text: var tlm=function(Le){'use strict';/**
       * @license
       * Copyright 2019 Google LLC. All Rights Reserved.
       * Licensed under the Apache License, Version 2.0 (the "License");
       * you may not use this file except in compliance with the License.
       * You may obtain a copy of the License at
       *
       * http://www.apache.org/licenses/LICENSE-2.0
       *
       * Unless required by applicable law or agreed to in writing, software
       * distributed under the License is distributed on an "AS IS" BASIS,
       * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       * See the License for the specific language governing permissions and
       * limitations under the License.
       * =============================================================================
       */var uf=Math.pow,cf=String.fromCharCode,hf=Number.isFinite,mf=Math.log,gf=Number.NEGATIVE_INFINITY,ff=Math.sin,yf=Math.cos,bf=Math.PI,xf=Number.MAX_SAFE_INTEGER,vf=Number.MIN_SAFE_INTEGER,Cf=Math.floor,Sf=Math.abs,Nf=Number.isInteger,If=Math.round,kf=Math.ceil,Tf=Math.sqrt,Rf=Math.exp,Ef=Math.max,wf=Math.min;function Fe(t,e){function a(){this.constructor=t}Af(t,e),t.prototype=null===e?Object.create(e):(a.prototype=e.prototype,new a)}function Be(p,t,e,d){return new(e||(e=Promise))(function(n,r){function a(e){try{s(d.next(e))}catch(e){r(e)}}function o(e){try{s(d.throw(e))}catch(e){r(e)}}function s(r){r.done?n(r.value):new e(function(t){t(r.value)}).then(a,o)}s((d=d.apply(p,t||[])).next())})}function Me(p,t){function e(e){return function(a){return function(e){if(d)throw new TypeError("Generator is already executing.");for(;s;)try{if(d=1,l&&(u=2&e[0]?l.return:e[0]?l.throw||((u=l.return)&&u.call(l),0):l.next)&&!(u=u.call(l,e[1])).done)return u;switch(l=0,u&&(e=[2&e[0],u.value]),e[0]){case 0:case 1:u=e;break;case 4:return s.label++,{value:e[1],done:!1};case 5:s.label++,l=e[1],e=[0];continue;case 7:e=s.ops.pop(),s.trys.pop();continue;default:if(!(u=0<(u=s.trys).length&&u[u.length-1])&&(6===e[0]||2===e[0])){s=0;continue}if(3===e[0]&&(!u||e[1]>u[0]&&e[1]<u[3])){s.label=e[1];break}if(6===e[0]&&s.label<u[1]){s.label=u[1],u=e;break}if(u&&s.label<u[2]){s.label=u[2],s.ops.push(e);break}u[2]&&s.ops.pop(),s.trys.pop();continue;}e=t.call(p,s)}catch(a){e=[6,a],l=0}finally{d=u=0}if(5&e[0])throw e[1];return{value:e[0]?e[1]:void 0,done:!0}}([e,a])}}var s={label:0,sent:function(){if(1&u[0])throw u[1];return u[1]},trys:[],ops:[]},d,l,u,c;return c={next:e(0),throw:e(1),return:e(2)},"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c}function n(a){var t={};return a.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,function(){for(var e=[],a=1;a<arguments.length;a++)e[a-1]=arguments[a];return function(a,t,e){a[decodeURIComponent(t)]=decodeURIComponent(e||"")}(t,e[0],e[1]),e.join("=")}),t}function a(e){_f=e}function r(a){for(var t=a.length,o=0,s=0;0<t;)s=0|Math.random()*t,o=a[--t],a[t]=a[s],a[s]=o}function l(a,t,e){return Ef(a,wf(t,e))}function s(e){return 0==e%2?e:e+1}function c(a){for(var t=0,r=0;r<a.length;r++)t+=a[r];return t}function Ue(a,t){if(!a)throw new Error("string"==typeof t?t:t())}function p(a,t,e){void 0===e&&(e=""),Ue(g(a,t),function(){return e+" Shapes "+a+" and "+t+" must match"})}function d(e){Ue(null!=e,function(){return"The input to the tensor constructor must be a non-null value."})}function v(a,t,o){if(void 0===t&&(t=[]),void 0===o&&(o=!1),null==t&&(t=[]),Array.isArray(a)||w(a)&&!o)for(var s=0;s<a.length;++s)v(a[s],t,o);else t.push(a);return t}function qe(a){if(0===a.length)return 1;for(var t=a[0],r=1;r<a.length;r++)t*=a[r];return t}function g(a,t){if(a===t)return!0;if(null==a||null==t)return!1;if(a.length!==t.length)return!1;for(var e=0;e<a.length;e++)if(a[e]!==t[e])return!1;return!0}function y(e){return 0==e%1}function h(a){var t=Math.tanh;if(null!=t)return t(a);if(a===1/0)return 1;if(a===-1/0)return-1;var n=Rf(2*a);return(n-1)/(n+1)}function m(a){var t=kf(Tf(a));return[t,kf(a/t)]}function f(a,t){return t<=a.length?a:a+" ".repeat(t-a.length)}function b(p,t,r){return void 0===t&&(t=function(){return 0}),new Promise(function(e,n){var o=0,d=function(){if(p())e();else{var a=t(++o);null!=r&&o>=r?n():setTimeout(d,a)}};d()})}function x(s,t){for(var e=1,i=-1,p=0;p<s.length;++p)if(0<=s[p])e*=s[p];else if(-1===s[p]){if(-1!=i)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+i+" and dim "+p);i=p}else if(0>s[p])throw Error("Shapes can not be < 0. Found "+s[p]+" at dim "+p);if(-1==i){if(0<t&&t!==e)throw Error("Size("+t+") must match the product of shape "+s);return s}if(0===e)throw Error("Cannot infer the missing size in ["+s+"] when there are 0 elements");if(0!=t%e)throw Error("The implicit shape can't be a fractional number. Got "+t+" / "+e);var d=s.slice();return d[i]=t/e,d}function C(a,r){var e=r.length;return Ue((a=null==a?r.map(function(a,t){return t}):[].concat(a)).every(function(a){return a>=-e&&a<e}),function(){return"All values in axis param must be in range [-"+e+", "+e+") but got axis "+a}),Ue(a.every(function(e){return y(e)}),function(){return"All values in axis param must be integers but got axis "+a}),a.map(function(a){return 0>a?e+a:a})}function I(s,t){for(var e=[],n=[],r=null==t?null:C(t,s).sort(),o=0,p=0;p<s.length;++p){if(null!=r){if(r[o]===p&&1!==s[p])throw new Error("Can't squeeze axis "+p+" since its dim '"+s[p]+"' is not 1");(null==r[o]||r[o]>p)&&1===s[p]&&(e.push(s[p]),n.push(p)),r[o]<=p&&o++}1!==s[p]&&(e.push(s[p]),n.push(p))}return{newShape:e,keptDims:n}}function S(a,t){var e=null;if(null==a||"float32"===a)e=new Float32Array(t);else if("int32"===a)e=new Int32Array(t);else{if("bool"!==a)throw new Error("Unknown data type "+a);e=new Uint8Array(t)}return e}function N(a,t){var e=null;if(null==a||"float32"===a)e=new Float32Array(t);else if("int32"===a)e=new Int32Array(t);else if("bool"===a)e=new Uint8Array(t);else{if("string"!==a)throw new Error("Unknown data type "+a);e=Array(t)}return e}function k(a,t,e){if("float32"===t)for(var n=0,s;n<a.length;n++)if(s=a[n],isNaN(s)||!isFinite(s))throw Error("The result of the '"+e+"' is "+s+".")}function R(a,t){for(var e=0,o;e<a.length;e++)if(o=a[e],isNaN(o)||!isFinite(o))throw Error("A tensor of type "+t+" being uploaded contains "+o+".")}function T(e){return"bool"===e||"complex64"===e||"float32"===e||"int32"===e||"string"===e}function E(a,t){return"complex64"!==t&&("float32"!==t||"complex64"===a)&&("int32"!==t||"float32"===a||"complex64"===a)&&("bool"!==t||"bool"!==a)}function w(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array}function A(e){if("float32"===e||"int32"===e)return 4;if("complex64"===e)return 8;if("bool"===e)return 1;throw new Error("Unknown dtype "+e)}function e(a){if(null==a)return 0;var n=0;return a.forEach(function(e){return n+=e.length}),n}function D(e){return"string"==typeof e||e instanceof String}function _(e){return"boolean"==typeof e}function O(e){return"number"==typeof e}function L(e){return Array.isArray(e)?L(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array?"int32":O(e)?"float32":D(e)?"string":_(e)?"bool":"float32"}function F(e){return!!(e&&e.constructor&&e.call&&e.apply)}function B(a,t){for(var e=t;e<a;++e)if(0==a%e)return e;return a}function z(a){var t=a.length;if(2>t)return[];var e=Array(t-1);e[t-2]=a[t-1];for(var n=t-3;0<=n;--n)e[n]=e[n+1]*a[n+1];return e}function P(a,s,e){if("string"===s)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(a)&&(a=v(a)),e&&R(a,s),function(a,t){return a instanceof Float32Array&&"float32"===t||a instanceof Int32Array&&"int32"===t||a instanceof Uint8Array&&"bool"===t}(a,s))return a;if(null==s||"float32"===s||"complex64"===s)return new Float32Array(a);if("int32"===s)return new Int32Array(a);if("bool"===s){for(var n=new Uint8Array(a.length),r=0;r<n.length;++r)0!==If(a[r])&&(n[r]=1);return n}throw new Error("Unknown data type "+s)}function M(a,t){if(0===a.length)return t[0];var e=a.reduce(function(a,t){return a*t});if(0===e)return[];if(e!==t.length)throw new Error("["+a+"] does not match the input size.");return function p(t,e,n){var r=[];if(1===e.length)for(var o=e[0],d=0;d<o;d++)r[d]=n[t+d];else{o=e[0];var l=e.slice(1),s=l.reduce(function(a,t){return a*t});for(d=0;d<o;d++)r[d]=p(t+d*s,l,n)}return r}(0,a,t)}function W(a,t){for(var e=V(a,t),n=0;n<e.length;n++)e[n]=1;return e}function V(a,t){if(null==t||"float32"===t||"complex64"===t)return new Float32Array(a);if("int32"===t)return new Int32Array(a);if("bool"===t)return new Uint8Array(a);throw new Error("Unknown data type "+t)}function U(){return _f.platform.now()}function G(e){e.forEach(function(t){Ue(Nf(t)&&0<=t,function(){return"Tensor must have a shape comprised of positive integers but got shape ["+e+"]."})})}function q(a,t){return void 0===t&&(t="utf-8"),t=t||"utf-8",_f.platform.encode(a,t)}function H(a,t){return void 0===t&&(t="utf-8"),t=t||"utf-8",_f.platform.decode(a,t)}function K(p,t,e,n){var r=z(t),o=function(p,t,e,n){var r=qe(t),o=n[n.length-1],a=Array(o).fill(0),i=t.length,s="complex64"===e?X(p):p;if(1<i)for(var d=0;d<r/o;d++)for(var u=d*o,c=0;c<o;c++)a[c]=Ef(a[c],j(s[u+c],0,e).length);return a}(p,t,e,r),a=t.length,i=function h(t,e,n,r,o,a){void 0===a&&(a=!0);var S="complex64"===n?2:1,s=e[0],u=e.length;if(0===u){if("complex64"===n){var l=X(t);return[j(l[0],0,n)]}return"bool"===n?[$(t[0])]:[t[0].toString()]}if(1===u){if(20<s){var c=Array.from(t.slice(0,3*S)),N=Array.from(t.slice(s-3*S,s));return"complex64"===n&&(c=X(c),N=X(N)),["["+c.map(function(a,t){return j(a,o[t],n)}).join(", ")+", ..., "+N.map(function(a,t){return j(a,o[s-3+t],n)}).join(", ")+"]"]}var I="complex64"===n?X(t):Array.from(t);return["["+I.map(function(a,t){return j(a,o[t],n)}).join(", ")+"]"]}var d=e.slice(1),v=r.slice(1),m=r[0]*S,g=[];if(20<s){for(var y=0;3>y;y++){var k=y*m,T=k+m;g.push.apply(g,h(t.slice(k,T),d,n,v,o,!1))}g.push("...");for(var y=s-3;y<s;y++){var k=y*m,T=k+m;g.push.apply(g,h(t.slice(k,T),d,n,v,o,y==s-1))}}else for(var y=0;y<s;y++){var k=y*m,T=k+m;g.push.apply(g,h(t.slice(k,T),d,n,v,o,y==s-1))}var R=2===u?",":"";g[0]="["+g[0]+R;for(var y=1;y<g.length-1;y++)g[y]=" "+g[y]+R;for(var C=",\n",y=2;y<u;y++)C+="\n";return g[g.length-1]=" "+g[g.length-1]+"]"+(a?"":C),g}(p,t,e,r,o),s=["Tensor"];return n&&(s.push("  dtype: "+e),s.push("  rank: "+a),s.push("  shape: ["+t+"]"),s.push("  values:")),s.push(i.map(function(e){return"    "+e}).join("\n")),s.join("\n")}function j(a,t,e){return f(Array.isArray(a)?parseFloat(a[0].toFixed(7))+" + "+parseFloat(a[1].toFixed(7))+"j":D(a)?"'"+a+"'":"bool"===e?$(a):parseFloat(a.toFixed(7)).toString(),t)}function $(e){return 0===e?"false":"true"}function X(a){for(var t=[],e=0;e<a.length;e+=2)t.push([a[e],a[e+1]]);return t}function Y(a,t){if("string"===a||"string"===t){if("string"===a&&"string"===t)return"string";throw new Error("Can not upcast "+a+" with "+t)}return Wf[a][t]}function He(e){return Y(e,"int32")}function Ke(a,t){if(a.dtype===t.dtype)return[a,t];var e=Y(a.dtype,t.dtype);return[a.cast(e),t.cast(e)]}function je(a,t){Ue(a.dtype===t.dtype,function(){return"The dtypes of the first("+a.dtype+") and second("+t.dtype+") input must match"})}function $e(a){var t=[];return function p(t,e,n){if(null!=t){if(t instanceof Lf)return void e.push(t);if(a=t,Array.isArray(a)||"object"==typeof a){var r=t,a;for(var d in r){var i=r[d];n.has(i)||(n.add(i),p(i,e,n))}}}}(a,t,new Set),t}function Xe(){return"undefined"!=typeof window&&null!=window.document||"undefined"!=typeof WorkerGlobalScope}function Ye(a,t){Vf[a]=t}function Ze(a){a in Vf||(Vf[a]=function(a){if(1!==a&&2!==a)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");var t=Qe(a);return(t.addEventListener("webglcontextlost",function(t){t.preventDefault(),delete Vf[a]},!1),1===a)?t.getContext("webgl",Ot)||t.getContext("experimental-webgl",Ot):t.getContext("webgl2",Ot)}(a));var t=Vf[a];return t.isContextLost()?(delete Vf[a],Ze(a)):(t.disable(t.DEPTH_TEST),t.disable(t.STENCIL_TEST),t.disable(t.BLEND),t.disable(t.DITHER),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SAMPLE_COVERAGE),t.enable(t.SCISSOR_TEST),t.enable(t.CULL_FACE),t.cullFace(t.BACK),Vf[a])}function Qe(e){if("undefined"!=typeof OffscreenCanvas&&2===e)return new OffscreenCanvas(300,150);if("undefined"!=typeof document)return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}function et(a,t){return[t,a]}function tt(a){var t=qe(a);return m(kf(t/4))}function at(a,t){return[Ef(1,kf(t/2)),Ef(1,kf(a/2))]}function nt(i,t){var e=i,p,d,m,g,f,y,b,x,v;return 2===_f.getNumber("WEBGL_VERSION")?(p=e.R32F,d=e.R16F,m=e.RGBA16F,g=e.RGBA32F,f=e.RED,y=4,b=1,x=e.HALF_FLOAT,v=e.FLOAT):(p=i.RGBA,d=i.RGBA,m=i.RGBA,g=e.RGBA,f=i.RGBA,y=4,b=4,x=null==t?null:t.HALF_FLOAT_OES,v=i.FLOAT),{internalFormatFloat:p,internalFormatHalfFloat:d,internalFormatPackedHalfFloat:m,internalFormatPackedFloat:g,textureFormatFloat:f,downloadTextureFormat:i.RGBA,downloadUnpackNumChannels:y,defaultNumChannels:b,textureTypeHalfFloat:x,textureTypeFloat:v}}function rt(a,t,e){var n=e();return t&&function(a){var t=a.getError();if(t!==a.NO_ERROR)throw new Error("WebGL Error: "+it(a,t))}(a),n}function ot(e){return!!(_f.getBool("WEBGL_RENDER_FLOAT32_ENABLED")||0===e||Gf<Sf(e)&&65504>Sf(e))}function it(a,t){return t===a.NO_ERROR?"NO_ERROR":t===a.INVALID_ENUM?"INVALID_ENUM":t===a.INVALID_VALUE?"INVALID_VALUE":t===a.INVALID_OPERATION?"INVALID_OPERATION":t===a.INVALID_FRAMEBUFFER_OPERATION?"INVALID_FRAMEBUFFER_OPERATION":t===a.OUT_OF_MEMORY?"OUT_OF_MEMORY":t===a.CONTEXT_LOST_WEBGL?"CONTEXT_LOST_WEBGL":"Unknown error code "+t}function bt(a,t,e){return ve(a,t,function(){return a.getExtension(e)},"Extension \""+e+"\" not supported on this browser.")}function Ct(a,t,e){var n=ve(a,t,function(){return a.createShader(a.VERTEX_SHADER)},"Unable to create vertex WebGLShader.");if(rt(a,t,function(){return a.shaderSource(n,e)}),rt(a,t,function(){return a.compileShader(n)}),!1===a.getShaderParameter(n,a.COMPILE_STATUS))throw console.log(a.getShaderInfoLog(n)),new Error("Failed to compile vertex shader.");return n}function Tt(a,t,e){var n=ve(a,t,function(){return a.createShader(a.FRAGMENT_SHADER)},"Unable to create fragment WebGLShader.");if(rt(a,t,function(){return a.shaderSource(n,e)}),rt(a,t,function(){return a.compileShader(n)}),!1===a.getShaderParameter(n,a.COMPILE_STATUS))throw function(p,t){var e=Gt.exec(t);if(null==e)return console.log("Couldn't parse line number in error: "+t),void console.log(p);for(var n=+e[1],r=p.split("\n"),o=r.length.toString().length+2,a=r.map(function(a,t){return f((t+1).toString(),o)+a}),i=0,d=0;d<a.length;d++)i=Ef(a[d].length,i);var m=a.slice(0,n-1),l=a.slice(n-1,n),c=a.slice(n);console.log(m.join("\n")),console.log(t.split("\n")[0]),console.log("%c "+f(l[0],i),"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(c.join("\n"))}(e,a.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}function Rt(a,t){return ve(a,t,function(){return a.createProgram()},"Unable to create WebGLProgram.")}function Et(a,t,e){if(rt(a,t,function(){return a.linkProgram(e)}),!1===a.getProgramParameter(e,a.LINK_STATUS))throw console.log(a.getProgramInfoLog(e)),new Error("Failed to link vertex and fragment shaders.")}function te(a,t,e){if(rt(a,t,function(){return a.validateProgram(e)}),!1===a.getProgramParameter(e,a.VALIDATE_STATUS))throw console.log(a.getProgramInfoLog(e)),new Error("Shader program validation failed.")}function ee(a,t,e){var n=ve(a,t,function(){return a.createBuffer()},"Unable to create WebGLBuffer");return rt(a,t,function(){return a.bindBuffer(a.ARRAY_BUFFER,n)}),rt(a,t,function(){return a.bufferData(a.ARRAY_BUFFER,e,a.STATIC_DRAW)}),n}function ne(a,t,e){var n=ve(a,t,function(){return a.createBuffer()},"Unable to create WebGLBuffer");return rt(a,t,function(){return a.bindBuffer(a.ELEMENT_ARRAY_BUFFER,n)}),rt(a,t,function(){return a.bufferData(a.ELEMENT_ARRAY_BUFFER,e,a.STATIC_DRAW)}),n}function re(a,t){return ve(a,t,function(){return a.createTexture()},"Unable to create WebGLTexture.")}function oe(a,t){var e=_f.getNumber("WEBGL_MAX_TEXTURE_SIZE");if(0>=a||0>=t){var n="["+a+"x"+t+"]";throw new Error("Requested texture size "+n+" is invalid.")}if(a>e||t>e)throw n="["+a+"x"+t+"]",new Error("Requested texture size "+n+" greater than WebGL maximum on this browser / GPU "+("["+e+"x"+e+"]."))}function ae(a,t){return ve(a,t,function(){return a.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function ie(p,t,e,n,r,o,a,i){var s=p.getAttribLocation(e,n);return-1!==s&&(rt(p,t,function(){return p.bindBuffer(p.ARRAY_BUFFER,r)}),rt(p,t,function(){return p.vertexAttribPointer(s,o,p.FLOAT,!1,a,i)}),rt(p,t,function(){return p.enableVertexAttribArray(s)}),!0)}function se(a,t,e,n){me(a,n),rt(a,t,function(){return a.activeTexture(a.TEXTURE0+n)}),rt(a,t,function(){return a.bindTexture(a.TEXTURE_2D,e)})}function ue(a,t,e,n){return ve(a,t,function(){return a.getUniformLocation(e,n)},"uniform \""+n+"\" not present in program.")}function le(a,t,e){return a.getUniformLocation(t,e)}function ce(s,t,e,n,r,o){rt(s,t,function(){return se(s,t,n,o)}),rt(s,t,function(){return s.uniform1i(r,o)})}function he(a,t,e,n){rt(a,t,function(){return a.bindFramebuffer(a.FRAMEBUFFER,n)}),rt(a,t,function(){return a.framebufferTexture2D(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,e,0)})}function fe(a,t,e){rt(a,t,function(){return a.bindFramebuffer(a.FRAMEBUFFER,e)}),rt(a,t,function(){return a.framebufferTexture2D(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,null,0)})}function pe(a){var t=a.checkFramebufferStatus(a.FRAMEBUFFER);if(t!==a.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+de(a,t))}function de(a,t){return t===a.FRAMEBUFFER_INCOMPLETE_ATTACHMENT?"FRAMEBUFFER_INCOMPLETE_ATTACHMENT":t===a.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT?"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT":t===a.FRAMEBUFFER_INCOMPLETE_DIMENSIONS?"FRAMEBUFFER_INCOMPLETE_DIMENSIONS":t===a.FRAMEBUFFER_UNSUPPORTED?"FRAMEBUFFER_UNSUPPORTED":"unknown error "+t}function ve(a,t,e,n){var r=rt(a,t,function(){return e()});if(null==r)throw new Error(n);return r}function me(a,t){var e=a.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,n=t+a.TEXTURE0;if(n<a.TEXTURE0||n>e)throw new Error("textureUnit must be in [gl.TEXTURE0, gl.TEXTURE"+e+"].")}function ge(a,t){return void 0===t&&(t=2),qe(a.slice(0,a.length-t))}function ye(e){if(0===e.length)throw Error("Cannot get rows and columns of an empty shape array.");return[1<e.length?e[e.length-2]:1,e[e.length-1]]}function xe(a){var t=[1,1,1];return 0===a.length||1===a.length&&1===a[0]||(t=[ge(a)].concat(ye(a))),t}function be(i,p){var d;void 0===p&&(p=!1);var c=_f.getNumber("WEBGL_MAX_TEXTURE_SIZE");if(p&&(c*=2,1===(i=i.map(function(t,e){return e>=i.length-2?s(i[e]):i[e]})).length&&(i=[2,i[0]])),2!==i.length){var h=I(i);i=h.newShape}var o=qe(i);if(1>=i.length&&o<=c)return[1,o];if(2===i.length&&i[0]<=c&&i[1]<=c)return i;if(3===i.length&&i[0]*i[1]<=c&&i[2]<=c)return[i[0]*i[1],i[2]];if(3===i.length&&i[0]<=c&&i[1]*i[2]<=c)return[i[0],i[1]*i[2]];if(4===i.length&&i[0]*i[1]*i[2]<=c&&i[3]<=c)return[i[0]*i[1]*i[2],i[3]];if(4===i.length&&i[0]<=c&&i[1]*i[2]*i[3]<=c)return[i[0],i[1]*i[2]*i[3]];if(p){var g=ge(i),f=2,y=2;return i.length&&(f=(d=ye(i))[0],y=d[1]),m(o=g*(f/2)*(y/2)).map(function(e){return 2*e})}return m(o)}function we(e){return 0==e%2}function Ce(a,o){if(g(a=a.slice(-2),o=o.slice(-2)))return!0;if(!a.length||!o.length)return!0;if(0===a[0]||0===a[1]||0===o[0]||0===o[1])return!0;if(a.length!==o.length){var s=a.slice(-1)[0],n=o.slice(-1)[0];if(s===n)return!0;if(we(s)&&we(n)&&(1===a[0]||1===o[0]))return!0}return a[1]===o[1]&&we(a[0])&&we(o[0])}function Ee(a){if(null==Oe){var t=Ze(a);Oe=t.getParameter(t.MAX_TEXTURE_SIZE)}return Oe}function Re(a){if(null==qf){var t=Ze(a);qf=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return wf(16,qf)}function Ie(a){if(0===a)return 0;var t=Ze(a);return Se(t,"EXT_disjoint_timer_query_webgl2")&&2===a?2:Se(t,"EXT_disjoint_timer_query")?1:0}function Se(a,t){return null!=a.getExtension(t)}function Ne(e){try{if(null!=Ze(e))return!0}catch(e){return!1}return!1}function ke(a){if(0===a)return!1;var t=Ze(a);if(1===a){if(!Se(t,"OES_texture_float"))return!1;}else if(!Se(t,"EXT_color_buffer_float"))return!1;return Te(t)}function Ae(a){if(0===a)return!1;var t=Ze(a);if(1!==a){if(Se(t,"EXT_color_buffer_float"))return Te(t);if(Se(t,"EXT_color_buffer_half_float")){var e=t.getExtension("EXT_color_buffer_half_float");return function(s,t){var e=nt(s,t),n=s.createTexture();s.bindTexture(s.TEXTURE_2D,n),s.texImage2D(s.TEXTURE_2D,0,e.internalFormatHalfFloat,1,1,0,e.textureFormatFloat,e.textureTypeHalfFloat,null);var r=s.createFramebuffer();s.bindFramebuffer(s.FRAMEBUFFER,r),s.framebufferTexture2D(s.FRAMEBUFFER,s.COLOR_ATTACHMENT0,s.TEXTURE_2D,n,0);var o=s.checkFramebufferStatus(s.FRAMEBUFFER)===s.FRAMEBUFFER_COMPLETE;return s.bindTexture(s.TEXTURE_2D,null),s.bindFramebuffer(s.FRAMEBUFFER,null),s.deleteTexture(n),s.deleteFramebuffer(r),o}(t,e)}return!1}return!!Se(t,"OES_texture_float")&&!!Se(t,"WEBGL_color_buffer_float")&&Te(t)}function Te(a){var t=nt(a),e=a.createTexture();a.bindTexture(a.TEXTURE_2D,e),a.texImage2D(a.TEXTURE_2D,0,t.internalFormatFloat,1,1,0,t.textureFormatFloat,t.textureTypeFloat,null);var n=a.createFramebuffer();a.bindFramebuffer(a.FRAMEBUFFER,n),a.framebufferTexture2D(a.FRAMEBUFFER,a.COLOR_ATTACHMENT0,a.TEXTURE_2D,e,0);var r=a.checkFramebufferStatus(a.FRAMEBUFFER)===a.FRAMEBUFFER_COMPLETE;return a.bindTexture(a.TEXTURE_2D,null),a.bindFramebuffer(a.FRAMEBUFFER,null),a.deleteTexture(e),a.deleteFramebuffer(n),r}function De(e){return 2===e&&null!=Ze(e).fenceSync}function _e(e){_f.getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function Pe(){return kt.memory()}function We(a,t){return kt.tidy(a,t)}function ze(e){$e(e).forEach(function(e){return e.dispose()})}function Ve(e){return kt.keep(e)}function Ge(){return kt.backend}function Je(){for(var a=[],t=0;t<arguments.length;t++)a[t]=arguments[t];_f.getBool("IS_TEST")||console.warn.apply(console,a)}function wt(a,t){var e=a;if(w(a))return"string"===t?[]:[a.length];if(!Array.isArray(a))return[];for(var o=[];Array.isArray(e)||w(e)&&"string"!==t;)o.push(e.length),e=e[0];return Array.isArray(a)&&_f.getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&function s(t,e,n){if(n=n||[],!Array.isArray(t)&&!w(t))return void Ue(0===e.length,function(){return"Element arr["+n.join("][")+"] is a primitive, but should be an array/TypedArray of "+e[0]+" elements"});Ue(0<e.length,function(){return"Element arr["+n.join("][")+"] should be a primitive, but is an array of "+t.length+" elements"}),Ue(t.length===e[0],function(){return"Element arr["+n.join("][")+"] should have "+e[0]+" elements, but has "+t.length+" elements"});for(var i=e.slice(1),o=0;o<t.length;++o)s(t[o],i,n.concat(o))}(a,o,[]),o}function zt(a,t,e,n){if(null!=a&&("numeric"!==a&&a!==t||"numeric"===a&&"string"===t))throw new Error("Argument '"+e+"' passed to '"+n+"' must be "+a+" tensor, but got "+t+" tensor")}function Lt(i,p,e,n){if(void 0===n&&(n="numeric"),i instanceof Lf)return zt(n,i.dtype,p,e),i;var d=L(i);if("string"!==d&&0<=["bool","int32","float32"].indexOf(n)&&(d=n),zt(n,d,p,e),null==i||!w(i)&&!Array.isArray(i)&&"number"!=typeof i&&"boolean"!=typeof i&&"string"!=typeof i){var l=null==i?"null":i.constructor.name;throw new Error("Argument '"+p+"' passed to '"+e+"' must be a Tensor or TensorLike, but got '"+l+"'")}var a=wt(i,d);w(i)||Array.isArray(i)||(i=[i]);var s="string"===d?v(i,[],!0):P(i,d,_f.getBool("DEBUG"));return Lf.make(a,{values:s},d)}function Bt(a,o,e,t){if(void 0===t&&(t="numeric"),!Array.isArray(a))throw new Error("Argument "+o+" passed to "+e+" must be a `Tensor[]` or `TensorLike[]`");return a.map(function(a,t){return Lt(a,o+"["+t+"]",e)},t)}function Pt(a,t){for(var e=0;e<a.length;++e)if(a[a.length-e-1]!==t-1-e)return!1;return!0}function Mt(p,t,e){for(var n=p.length+t.length,r=[],o=0,d=0,l=0;l<n;l++)-1===e.indexOf(l)?r.push(p[o++]):r.push(t[d++]);return r}function Wt(a,t){for(var e=[],n=a.length,r=0;r<n;r++)-1===t.indexOf(r)&&e.push(a[r]);return[e,t.map(function(t){return a[t]})]}function Vt(a,t){return Mt(a,t.map(function(){return 1}),t)}function Ut(a,t,e){Ue(Pt(t,e),function(){return a+" supports only inner-most axes for now. Got axes "+t+" and rank-"+e+" input."})}function qt(a,t){if(Pt(a,t))return null;for(var e=[],n=0;n<t;++n)-1===a.indexOf(n)&&e.push(n);return a.forEach(function(a){return e.push(a)}),e}function Ht(e){return e.map(function(a,t){return[t,a]}).sort(function(a,t){return a[1]-t[1]}).map(function(e){return e[0]})}function Kt(a,t){for(var e=[],n=t-a;n<t;++n)e.push(n);return e}function jt(a,s){var i=a[0].length;a.forEach(function(a,t){Ue(a.length===i,function(){return"Error in concat"+i+"D: rank of tensors["+t+"] must be the same as the rank of the rest ("+i+")"})}),Ue(0<=s&&s<i,function(){return"Error in concat"+i+"D: axis must be between 0 and "+(i-1)+"."});var e=a[0];a.forEach(function(n,t){for(var r=0;r<i;r++)Ue(r===s||n[r]===e[r],function(){return"Error in concat"+i+"D: Shape of tensors["+t+"] ("+n+") does not match the shape of the rest ("+e+") along the non-concatenated axis "+t+"."})})}function $t(a,t){for(var e=a[0].slice(),n=1;n<a.length;n++)e[t]+=a[n][t];return e}function Xt(a){var t=Object.keys(a);if(1!==t.length)throw new Error("Please provide an object with a single key (operation name) mapping to a function. Got an object with "+t.length+" keys.");var s=t[0],e=a[s];s.endsWith("_")&&(s=s.substring(0,s.length-1));var r=function(){for(var a=[],t=0;t<arguments.length;t++)a[t]=arguments[t];kt.startScope(s);try{var n=e.apply(void 0,a);return n instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),kt.endScope(n),n}catch(e){throw kt.endScope(null),e}};return Object.defineProperty(r,"name",{value:s,configurable:!0}),r}function Zt(a,t,e){return Ta(a,t,wt(a,e),e)}function Ta(i,p,d,n){if(null==n&&(n=L(i)),"complex64"===n)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!w(i)&&!Array.isArray(i)&&"number"!=typeof i&&"boolean"!=typeof i&&"string"!=typeof i)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!=p){G(p);var c=qe(p),o=qe(d);Ue(c===o,function(){return"Based on the provided shape, ["+p+"], the tensor should have "+c+" values but has "+o});for(var a=0;a<d.length;++a){var h=d[a],u=a!=d.length-1||h!==qe(p.slice(a));Ue(d[a]===p[a]||!u,function(){return"Error creating a new Tensor. Inferred shape ("+d+") does not match the provided shape ("+p+"). "})}}return w(i)||Array.isArray(i)||(i=[i]),p=p||d,i="string"===n?v(i,[],!0):P(i,n,_f.getBool("DEBUG")),Lf.make(p,{values:i},n)}function Da(a,t){if((w(a)&&"string"!==t||Array.isArray(a))&&"complex64"!==t)throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if("string"===t&&w(a)&&!(a instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Ta(a,[],[],t)}function en(a,t){d(a);var e=wt(a,t);if(1!==e.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Ta(a,null,e,t)}function tn(a,t,e){if(d(a),null!=t&&2!==t.length)throw new Error("tensor2d() requires shape to have two numbers");var n=wt(a,e);if(2!==n.length&&1!==n.length)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(1===n.length&&null==t)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Ta(a,t,n,e)}function an(a,t,e){if(d(a),null!=t&&3!==t.length)throw new Error("tensor3d() requires shape to have three numbers");var n=wt(a,e);if(3!==n.length&&1!==n.length)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(1===n.length&&null==t)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return Ta(a,t,n,e)}function nn(a,t,e){if(d(a),null!=t&&4!==t.length)throw new Error("tensor4d() requires shape to have four numbers");var n=wt(a,e);if(4!==n.length&&1!==n.length)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(1===n.length&&null==t)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return Ta(a,t,n,e)}function rn(a,t,e){if(d(a),null!=t&&5!==t.length)throw new Error("tensor5d() requires shape to have five numbers");var n=wt(a,e);if(5!==n.length&&1!==n.length)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(1===n.length&&null==t)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return Ta(a,t,n,e)}function on(a,t,o){if(d(a),null!=t&&6!==t.length)throw new Error("tensor6d() requires shape to have six numbers");var n=wt(a,o);if(6!==n.length&&1!==n.length)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(1===n.length&&null==t)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return Ta(a,t=t||n,n,o)}function sn(a,t){if(void 0===t&&(t="float32"),"complex64"===t){var s=sn(a,"float32"),n=pn(a,"float32");return Hf(s,n)}var r=W(qe(a),t);return Lf.make(a,{values:r},t)}function pn(a,t){if(void 0===t&&(t="float32"),"complex64"===t){var s=pn(a,"float32"),n=pn(a,"float32");return Hf(s,n)}var r=V(qe(a),t);return Lf.make(a,{values:r},t)}function dn(a,t,e){return kt.runKernel(function(n){return n.fill(a,t,e)},{})}function ln(a,t,e){if(0>=e)throw new Error("The number of values should be positive.");return kt.runKernel(function(n){return n.linspace(a,t,e)},{})}function un(s,t,e,i){if(void 0===e&&(e=1),void 0===i&&(i="float32"),0===e)throw new Error("Cannot have a step of zero");if(s===t||s<t&&0>e||t<s&&1<e)return pn([0],i);var p=V(Sf(kf((t-s)/e)),i);t<s&&1===e&&(e=-1),p[0]=s;for(var o=1;o<p.length;o++)p[o]=p[o-1]+e;return en(p,i)}function cn(a,t){return a(t={exports:{}},t.exports),t.exports}function hn(a,t,r){return void 0===t&&(t="float32"),t=t||"float32",G(a),new Z(a,t,r)}function mn(a,t){void 0===t&&(t=!1),console.log(a.toString(t))}function fn(s,t,e,n){void 0===n&&(n=!0);var p=[];if(n)(p=p.concat(t.slice(0))).push(s[0]/e),p=p.concat(s.slice(1));else{p=p.concat(s[0]);for(var d=t.length,a=0;a<d;++a)p=p.concat([s[a+1]/t[a],t[a]]);p=p.concat(s.slice(d+1))}return p}function bn(s,t,e){void 0===e&&(e=!0);var p=[];if(e){p.push(t);for(var r=t+1;r<s;++r)r<=2*t?(p.push(r),p.push(r-(t+1))):p.push(r)}else{var d=[],a=[];for(r=1;r<s;++r)r>=2*t+1||1==r%2?a.push(r):d.push(r);p.push.apply(p,d),p.push(0),p.push.apply(p,a)}return p}function vn(s,t,e,n){void 0===n&&(n=!0);var i=[];n?i.push(s[0]/e):i.push(s[0]*e);for(var o=1;o<s.length;++o)o<=t.length?n?i.push(t[o-1]*s[o]):i.push(s[o]/t[o-1]):i.push(s[o]);return i}function Cn(a,t){for(var e=[0],n=0;n<t;++n)e.push(a[n][0]);return e}function Sn(a,t,e){for(var n=a.slice(0,1),r=0;r<e;++r)n.push(a[r+1]-t[r][0]-t[r][1]);return n}function Nn(p,t){if(1>p.rank)throw new Error("tf.gatherND() expects the input to be rank 1 or higher, but the rank was "+p.rank+".");if(1>t.rank)throw new Error("tf.gatherND() expects the indices to be rank 1 or higher, but the rank was "+t.rank+".");if("int32"!==t.dtype)throw new Error("tf.gatherND() expects the indices to be int32 type, but the dtype was "+t.dtype+".");if(t.shape[t.rank-1]>p.rank)throw new Error("index innermost dimension length must be <= tensor rank; saw: "+t.shape[t.rank-1]+" vs. "+p.rank);if(0===p.size)throw new Error("Requested more than 0 entries, but input is empty. Input shape: "+p.shape+".");for(var e=t.shape,n=e[e.length-1],r=1,d=0;d<e.length-1;++d)r*=e[d];var c=p.shape,i=e.slice();i.pop();var s=1;for(d=n;d<p.rank;++d)s*=c[d],i.push(c[d]);var h=z(p.shape).map(function(e){return e/s}).concat([1]).slice(0,n);return[i,r,s,h]}function In(e){return 30>=e?e:B(e,Cf(Tf(e)))}function kn(a,t,e){if(1>t.rank)throw new Error("tf.scatterND() expects the indices to be rank 1 or higher, but the rank was "+t.rank+".");if(1>a.rank)throw new Error("tf.scatterND() expects the updates to be rank 1 or higher, but the rank was "+a.rank+".");if("int32"!==t.dtype)throw new Error("The dtype of 'indices' should be int32, but got dtype: "+t.dtype);if(1>e.length)throw new Error("Output rank must be greater or equal to 1, but got shape: "+e);if(0===e.length){if(0===t.size)throw new Error("Indices specified for empty output. indices shape: "+t.shape);if(0===a.size)throw new Error("Updates specified for empty output. updates shape: "+a.shape)}!function(s,t,e){var n=1<t.rank?t.shape[t.rank-1]:1,r=1<t.rank?t.rank-1:1,o="Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: "+e.shape+", indices.shape: "+t.shape+", shape: "+s+", sliceDim: "+n+", and batchDim: "+r+".";if(e.rank<r)throw new Error(o+" update.rank < "+r+". ");if(s.length<n+(e.rank-r))throw new Error(o+" Output shape length < "+(n+(e.rank-r)));if(e.rank!==r+s.length-n)throw new Error(o+" update.rank != "+(r+s.length-n));for(var a=0;a<r;++a)if(e.shape[a]!==t.shape[a])throw new Error(o+" updates.shape["+a+"] ("+e.shape[a]+") != indices.shape["+a+"] ("+t.shape[a]+").");for(a=0;a<e.rank-r;++a)if(e.shape[a+r]!==s[a+n])throw new Error(o+" updates.shape["+(a+r)+"] ("+e.shape[a+r]+") != shape["+(a+r)+"] ("+s[a+r]+")")}(e,t,a)}function Tn(p,t,e){for(var n=1<t.rank?t.shape[t.rank-1]:1,r=e.length,o=1,d=n;d<r;++d)o*=e[d];var l=1>n?1:n;return{sliceRank:n,numUpdates:t.size/l,sliceSize:o,strides:z(e.slice(0,n)).concat([1]),outputSize:qe(e)}}function Rn(d,t,e,n,r,m,g,y,b){if(void 0===r&&(r=0),void 0===m&&(m=0),void 0===g&&(g=0),void 0===y&&(y=0),void 0===b&&(b=0),0!==g)throw new Error("ellipsis mask is not yet supported");if(0!==y)throw new Error("new axis mask is not yet supported");for(var x=[],l=[],c=[],h=0;h<d.length;h++)x[h]=En(r,t,n,d,h),l[h]=wn(m,e,n,d,h),b&1<<h&&(l[h]=x[h]+1,c.push(h));var v=Array(d.length).fill(0);return v=v.map(function(r,t){for(var e=0,s=n[t]||1,o=x[t];0<s?!(o>=l[t]):!(o<=l[t]);o+=s)e+=1;return e}),[x,v,c]}function En(p,t,e,n,r){var o=t[r],d=e[r]||1;(p&1<<r||null==o)&&(o=0<d?vf:xf);var i=n[r];return 0>o&&(o+=i),o=l(0,o,i-1)}function wn(p,t,e,n,r){var o=t[r],d=e[r]||1;(p&1<<r||null==o)&&(o=0<d?xf:vf);var i=n[r];return 0>o&&(o+=i),o=0<d?l(0,o,i):l(-1,o,i-1)}function An(a,t,e){for(var n=e.length,s=0;s<e.length;s++)if(1<e[s]){n=s;break}for(s=n+1;s<e.length;s++)if(0<t[s]||e[s]!==a[s])return!1;return!0}function Dn(a,t){for(var e=0<a.length?a[a.length-1]:1,o=0;o<a.length-1;o++)e+=a[o]*t[o];return e}function _n(p,t){Ue(F(p),function(){return"The f passed in variableGrads(f) must be a function"}),Ue(null==t||Array.isArray(t)&&t.every(function(e){return e instanceof ht}),function(){return"The varList passed in variableGrads(f, varList) must be an array of variables"});var d=null!=t;if(!d)for(var n in t=[],kt.registeredVariables)t.push(kt.registeredVariables[n]);var r=d?t.filter(function(e){return!e.trainable}):null,o=t.length;Ue(0<(t=t.filter(function(e){return e.trainable})).length,function(){return"variableGrads() expects at least one of the input variables to be trainable, but none of the "+o+" variables is trainable."});var a=kt.gradients(p,t,null,!0),i=a.value,s=a.grads;Ue(s.some(function(e){return null!=e}),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()."}),Ue(0===i.rank,function(){return"The f passed in variableGrads(f) must return a scalar, but it returned a rank-"+i.rank+" tensor"});var u={};return t.forEach(function(a,t){null!=s[t]&&(u[a.name]=s[t])}),null!=r&&r.forEach(function(e){return u[e.name]=null}),{value:i,grads:u}}function On(e){return kt.customGrad(e)}function Vn(s,t){for(var e=s.length,n=[],r=0;r<e;r++){var p=e-1-r,a=s[p]||1;1<(t[t.length-1-r]||1)&&1===a&&n.unshift(p)}return n}function Zn(s,t){for(var e=[],n=0;n<t.length;n++){var p=s[s.length-n-1],o=t.length-n-1,a=t[o];(null==p||1===p&&1<a)&&e.unshift(o)}return e}function tr(s,t){for(var e=[],n=Ef(s.length,t.length),r=0,p;r<n;r++){p=s[s.length-r-1],null==p&&(p=1);var d=t[t.length-r-1];if(null==d&&(d=1),1==p)e.unshift(d);else if(1===d)e.unshift(p);else{if(p!==d)throw Error("Operands could not be broadcast together with shapes "+s+" and "+t+".");e.unshift(p)}}return e}function Sr(p,t,e,n,r,o,a){void 0===a&&(a="channelsLast");var d=Ar(t),u=d[0],l=d[1],c;if("channelsLast"===a)c=[u,l,p[3],p[3]];else{if("channelsFirst"!==a)throw new Error("Unknown dataFormat "+a);c=[u,l,p[1],p[1]]}return Nr(p,c,e,n,r,o,!1,a)}function Nr(p,t,e,n,r,o,a,x){void 0===a&&(a=!1),void 0===x&&(x="channelsLast");var _=[-1,-1,-1,-1],u=_[0],O=_[1],z=_[2],L=_[3];if("channelsLast"===x)u=p[0],O=p[1],z=p[2],L=p[3];else{if("channelsFirst"!==x)throw new Error("Unknown dataFormat "+x);u=p[0],L=p[1],O=p[2],z=p[3]}var F=t[0],v=t[1],m=t[3],g=Ar(e),B=g[0],b=g[1],w=Ar(n),C=w[0],E=w[1],R=_r(F,C),I=_r(v,E),S=function(p,t,e,n,r,o,a,i){var s,g,b;if("number"==typeof p){var x=0===p?"VALID":"NUMBER";s={top:p,bottom:p,left:p,right:p,type:x};var h=function(p,t,e,n,d){null==n&&(n=Tr(p,t,e));var o=p[0],a=p[1],i=Or((o-t+2*n)/e+1,d);Ue(y(i),function(){return"The output # of rows ("+i+") must be an integer. Change the stride and/or zero pad parameters"});var s=Or((a-t+2*n)/e+1,d);return Ue(y(s),function(){return"The output # of columns ("+s+") must be an integer. Change the stride and/or zero pad parameters"}),[i,s]}([t,e],o,n,p,i);g=h[0],b=h[1]}else if("same"===p){g=kf(t/n),b=kf(e/r);var f=Ef(0,(g-1)*n+o-t),d=Ef(0,(b-1)*r+a-e),v=Cf(f/2),m=Cf(d/2);s={top:v,bottom:f-v,left:m,right:d-m,type:"SAME"}}else{if("valid"!==p)throw Error("Unknown padding parameter: "+p);s={top:0,bottom:0,left:0,right:0,type:"VALID"},g=kf((t-o+1)/n),b=kf((e-a+1)/r)}return{padInfo:s,outHeight:g,outWidth:b}}(r,O,z,B,b,R,I,o),N=S.padInfo,k=S.outHeight,A=S.outWidth,T=a?m*L:m,D;return"channelsFirst"===x?D=[u,T,k,A]:"channelsLast"==x&&(D=[u,k,A,T]),{batchSize:u,dataFormat:x,inHeight:O,inWidth:z,inChannels:L,outHeight:k,outWidth:A,outChannels:T,padInfo:N,strideHeight:B,strideWidth:b,filterHeight:F,filterWidth:v,effectiveFilterHeight:R,effectiveFilterWidth:I,dilationHeight:C,dilationWidth:E,inShape:p,outShape:D,filterShape:t}}function kr(_,t,e,n,r,o,O){void 0===o&&(o=!1),void 0===O&&(O="channelsLast");var z=[-1,-1,-1,-1,-1],s=z[0],L=z[1],F=z[2],B=z[3],P=z[4];if("channelsLast"===O)s=_[0],L=_[1],F=_[2],B=_[3],P=_[4];else{if("channelsFirst"!==O)throw new Error("Unknown dataFormat "+O);s=_[0],P=_[1],L=_[2],F=_[3],B=_[4]}var M=t[0],d=t[1],v=t[2],m=t[4],g=Dr(e),y=g[0],x=g[1],b=g[2],w=Dr(n),C=w[0],E=w[1],R=w[2],I=function(y,t,e,n,r,o,a,i,s,u){var l,b,C,S;if("same"===y){b=kf(t/r),C=kf(e/o),S=kf(n/a);var N=(b-1)*r+i-t,d=(C-1)*o+s-e,v=(S-1)*a+u-n,m=Cf(N/2),g=Cf(d/2),x=Cf(v/2);l={top:g,bottom:d-g,left:x,right:v-x,front:m,back:N-m,type:"SAME"}}else{if("valid"!==y)throw Error("Unknown padding parameter: "+y);l={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},b=kf((t-i+1)/r),C=kf((e-s+1)/o),S=kf((n-u+1)/a)}return{padInfo:l,outDepth:b,outHeight:C,outWidth:S}}(r,L,F,B,y,x,b,_r(M,C),_r(d,E),_r(v,R)),S=I.padInfo,N=I.outDepth,k=I.outHeight,A=I.outWidth,T=o?m*P:m,D;return"channelsFirst"===O?D=[s,T,N,k,A]:"channelsLast"==O&&(D=[s,N,k,A,T]),{batchSize:s,dataFormat:O,inDepth:L,inHeight:F,inWidth:B,inChannels:P,outDepth:N,outHeight:k,outWidth:A,outChannels:T,padInfo:S,strideDepth:y,strideHeight:x,strideWidth:b,filterDepth:M,filterHeight:d,filterWidth:v,dilationDepth:C,dilationHeight:E,dilationWidth:R,inShape:_,outShape:D,filterShape:t}}function Tr(a,t,e,n){void 0===n&&(n=1);var s=_r(t,n);return Cf((a[0]*(e-1)-e+s)/2)}function Ar(e){return"number"==typeof e?[e,e]:e}function Dr(e){return"number"==typeof e?[e,e,e]:e}function _r(a,t){return 1>=t?a:a+(a-1)*(t-1)}function Or(a,t){if(!t)return a;switch(t){case"round":return If(a);case"ceil":return kf(a);case"floor":return Cf(a);default:throw new Error("Unknown roundingMode "+t);}}function zr(a){var t=Ar(a),e=t[0],n=t[1];return 1===e&&1===n}function Lr(a,t){return zr(a)||zr(t)}function Fr(p,t,e){if("complex64"===t){if("complex64"===p.dtype)return p.clone();var n=pn(p.shape),r=p.toFloat(),o=e.complex(r,n);return n.dispose(),r.dispose(),o}if(!E(p.dtype,t))return Lf.make(p.shape,{dataId:p.dataId},t);if("complex64"===p.dtype){var d=e.real(p);return o=d.cast(t),d.dispose(),o}if("int32"===t)return e.int(p);if("bool"===t){var i=Da(0,p.dtype);return o=e.notEqual(p,i),i.dispose(),o}throw new Error("Error in Cast: failed to cast "+p.dtype+" to "+t)}function Br(a,t){return Lf.make(t,{dataId:a.dataId},a.dtype)}function Pr(r,t,e){var n=V(e,"float32");n[0]=r;for(var o=1;o<n.length;o++)n[o]=n[o-1]+(t-r)/(e-1);return en(n,"float32")}function Mr(a,t){if(a.length!==t.length)throw new Error("Cannot merge real and imag arrays of different lengths. real:"+a.length+", imag: "+t.length+".");for(var e=new Float32Array(2*a.length),n=0;n<e.length;n+=2)e[n]=a[n/2],e[n+1]=t[n/2];return e}function Wr(a,t){return{real:a[2*t],imag:a[2*t+1]}}function Vr(a,t,e,n){a[2*n]=t,a[2*n+1]=e}function Ur(a,t,e){var n=(e?2:-2)*bf*(a/t);return{real:yf(n),imag:ff(n)}}function Gr(p,t,e,n,r){for(var o=Array.from(t).map(function(a,t){return{score:a,boxIndex:t}}).filter(function(e){return e.score>r}).sort(function(a,t){return t.score-a.score}),a=[],i=0;i<o.length;i++){var d=o[i],u=d.score,l=d.boxIndex;if(u<r)break;for(var c=!1,m=a.length-1;0<=m;--m)if(qr(p,l,a[m])>=n){c=!0;break}if(!c&&(a.push(l),a.length>=e))break}return en(a,"int32")}function qr(b,t,e){var n=b.subarray(4*t,4*t+4),r=b.subarray(4*e,4*e+4),o=wf(n[0],n[2]),a=wf(n[1],n[3]),i=Ef(n[0],n[2]),s=Ef(n[1],n[3]),u=wf(r[0],r[2]),l=wf(r[1],r[3]),c=Ef(r[0],r[2]),h=Ef(r[1],r[3]),f=(i-o)*(s-a),p=(c-u)*(h-l);if(0>=f||0>=p)return 0;var d=Ef(o,u),v=Ef(a,l),m=wf(i,c),g=wf(s,h),y=Ef(m-d,0)*Ef(g-v,0);return y/(f+p-y)}function Hr(s,t,i){var n=Array(s.rank).fill(0),r=s.shape.slice();return t.map(function(t){r[i]=t;var e=s.slice(n,r);return n[i]+=t,e})}function jr(p,t){for(var e=Array(p.rank),n=0;n<e.length;n++)e[n]=p.shape[n]*t[n];var d=hn(e,p.dtype);for(n=0;n<d.values.length;++n){for(var o=d.indexToLoc(n),a=Array(p.rank),i=0;i<a.length;i++)a[i]=o[i]%p.shape[i];var l=p.locToIndex(a);d.values[n]=p.values[l]}return d.toTensor()}function $r(o,t,e,n){for(var r=t[t.length-1],a=[o.length/r,r],i=a[0],s=a[1],u=S(e,i*n),l=S("int32",i*n),c=0;c<i;c++){for(var b=c*s,f=o.subarray(b,b+s),p=[],d=0;d<f.length;d++)p.push({value:f[d],index:d});p.sort(function(a,t){return t.value-a.value});var C=c*n,m=u.subarray(C,C+n),g=l.subarray(C,C+n);for(d=0;d<n;d++)m[d]=p[d].value,g[d]=p[d].index}var y=t.slice();return y[y.length-1]=n,[Zt(u,y,e),Zt(l,y,"int32")]}function Zr(p,t){for(var e=[],n=0;n<t.length;n++)t[n]&&e.push(n);var d=hn(p,"int32"),o=hn([e.length,p.length],"int32");for(n=0;n<e.length;n++){var a=d.indexToLoc(e[n]),i=n*p.length;o.values.set(a,i)}return o.toTensor()}function Qr(a,t){return["x","y","z","w","u","v"].slice(0,t).map(function(t){return a+"."+t})}function Jr(a,t){return 1===t?[a]:Qr(a,t)}function eo(){var i,p,d,h,m,g,f,y,b,x;return 2===_f.getNumber("WEBGL_VERSION")?(i="#version 300 es",p="in",d="out",h="in",m="texture",g="outputColor",f="out vec4 outputColor;",y="\n      bool isnan_custom(float val) {\n        return (val > 0. || val < 0. || val == 0.) ? false : true;\n      }\n    ",b="",x="\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    "):(i="",p="attribute",d="varying",h="varying",m="texture2D",g="gl_FragColor",f="",y="\n      bool isnan_custom(float val) {\n        return (val > 0. || val < 1. || val == 0.) ? false : true;\n      }\n    ",b="\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    ",x="\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:i,attribute:p,varyingVs:d,varyingFs:h,texture2D:m,output:g,defineOutput:f,defineSpecialNaN:y,defineSpecialInf:b,defineRound:x}}function to(a,t,s){void 0===s&&(s="index");var i=z(t);return i.map(function(t,e){return"int "+a[e]+" = "+s+" / "+t+"; "+(e===i.length-1?"int "+a[e+1]+" = "+s+" - "+a[e]+" * "+t:"index -= "+a[e]+" * "+t)+";"}).join("")}function ao(a){var t=z(a).map(function(e){return e.toString()});return"\n  int getFlatIndex(ivec3 coords) {\n    return coords.x * "+t[0]+" + coords.y * "+t[1]+" + coords.z;\n  }\n"}function no(p,d,e,n){var r=[];p.forEach(function(a){var t=qe(a.shapeInfo.logicalShape);a.shapeInfo.isUniform?r.push("uniform float "+a.name+(1<t?"["+t+"]":"")+";"):(r.push("uniform sampler2D "+a.name+";"),r.push("uniform int offset"+a.name+";"))});var t=r.join("\n"),o=p.map(function(e){return function(s,t,e){void 0===e&&(e=!1);var i="";i+=e?oo(s):ro(s);var p=s.shapeInfo.logicalShape,o=t.logicalShape;return p.length<=o.length&&(i+=e?function(a,t){var e=a.name,r=e.charAt(0).toUpperCase()+e.slice(1),o=a.shapeInfo.logicalShape.length,i=t.logicalShape.length,s=Vn(a.shapeInfo.logicalShape,t.logicalShape),u=po(i),l=i-o,c=["x","y","z","w","u","v"],h;h=0===o?"":2>i&&1<=s.length?"coords = 0;":s.map(function(e){return"coords."+c[e+l]+" = 0;"}).join("\n");var g="";g=2>i&&0<o?"coords":a.shapeInfo.logicalShape.map(function(a,t){return"coords."+c[t+l]}).join(", ");var b="return outputValue;",x=1===qe(a.shapeInfo.logicalShape),d=1===qe(t.logicalShape);if(!(1!==o||x||d))b="\n      return vec4(outputValue.xy, outputValue.xy);\n    ";else if(x&&!d)b=1===i?"\n        return vec4(outputValue.x, outputValue.x, 0., 0.);\n      ":"\n        return vec4(outputValue.x);\n      ";else if(s.length){var v=o-2,m=o-1;-1<s.indexOf(v)&&-1<s.indexOf(m)?b="return vec4(outputValue.x);":-1<s.indexOf(v)?b="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":-1<s.indexOf(m)&&(b="return vec4(outputValue.xx, outputValue.zz);")}return"\n    vec4 "+("get"+r+"AtOutCoords")+"() {\n      "+u+" coords = getOutputCoords();\n      "+h+"\n      vec4 outputValue = get"+r+"("+g+");\n      "+b+"\n    }\n  "}(s,t):function(m,t){var e=m.name,n=e.charAt(0).toUpperCase()+e.slice(1),r="get"+n+"AtOutCoords",o=t.texShape,a=m.shapeInfo.texShape,i=m.shapeInfo.logicalShape.length,s=t.logicalShape.length;if(!m.shapeInfo.isUniform&&i===s&&null==m.shapeInfo.flatOffset&&g(a,o))return"\n      float "+r+"() {\n        return sampleTexture("+e+", resultUV);\n      }\n    ";var u=po(s),c=Vn(m.shapeInfo.logicalShape,t.logicalShape),h=s-i,f=["x","y","z","w","u","v"],p;p=0===i?"":2>s&&1<=c.length?"coords = 0;":c.map(function(e){return"coords."+f[e+h]+" = 0;"}).join("\n");var y="";return y=2>s&&0<i?"coords":m.shapeInfo.logicalShape.map(function(a,t){return"coords."+f[t+h]}).join(", "),"\n    float "+r+"() {\n      "+u+" coords = getOutputCoords();\n      "+p+"\n      return get"+n+"("+y+");\n    }\n  "}(s,t)),i}(e,d,n)}).join("\n"),s=d.texShape,l=eo(),u=function(e){return"\n    float sampleTexture(sampler2D textureSampler, vec2 uv) {\n      return "+e.texture2D+"(textureSampler, uv).r;\n    }\n  "}(l),c=function(e){return e.version+"\n    precision highp float;\n    precision highp int;\n    precision highp sampler2D;\n    "+e.varyingFs+" vec2 resultUV;\n    "+e.defineOutput+"\n    const vec2 halfCR = vec2(0.5, 0.5);\n\n    struct ivec5\n    {\n      int x;\n      int y;\n      int z;\n      int w;\n      int u;\n    };\n\n    struct ivec6\n    {\n      int x;\n      int y;\n      int z;\n      int w;\n      int u;\n      int v;\n    };\n\n    uniform float NAN;\n    #define isnan(value) isnan_custom(value)\n    "+e.defineSpecialNaN+"\n    bvec4 isnan_custom(vec4 val) {\n      return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\n    }\n\n    "+e.defineSpecialInf+"\n    "+e.defineRound+"\n\n    int imod(int x, int y) {\n      return x - y * (x / y);\n    }\n\n    int idiv(int a, int b, float sign) {\n      int res = a / b;\n      int mod = imod(a, b);\n      if (sign < 0. && mod != 0) {\n        res -= 1;\n      }\n      return res;\n    }\n\n    //Based on the work of Dave Hoskins\n    //https://www.shadertoy.com/view/4djSRW\n    #define HASHSCALE1 443.8975\n    float random(float seed){\n      vec2 p = resultUV * seed;\n      vec3 p3  = fract(vec3(p.xyx) * HASHSCALE1);\n      p3 += dot(p3, p3.yzx + 19.19);\n      return fract((p3.x + p3.y) * p3.z);\n    }\n\n    "+Fo+"\n    "+Lo+"\n    "+Wo+"\n  "}(l),h,m;return d.isPacked?(h=function(s,t){switch(s.length){case 0:return"\n    int getOutputCoords() {\n      return 0;\n    }\n  ";case 1:return function(a,t){var e=[kf(t[0]/2),kf(t[1]/2)];return 1===e[0]?"\n      int getOutputCoords() {\n        return 2 * int(resultUV.x * "+e[1]+".0);\n      }\n    ":1===e[1]?"\n      int getOutputCoords() {\n        return 2 * 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 2 * (resTexRC.x * "+e[1]+" + resTexRC.y);\n    }\n  "}(0,t);case 2:return function(a,t){var e=[kf(t[0]/2),kf(t[1]/2)];if(g(a,t))return"\n      ivec2 getOutputCoords() {\n        return 2 * ivec2(resultUV.yx * vec2("+e[0]+", "+e[1]+"));\n      }\n    ";var n=kf(a[1]/2);return"\n    ivec2 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2("+e[0]+", "+e[1]+"));\n\n      int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n      int r = 2 * (index / "+n+");\n      int c = imod(index, "+n+") * 2;\n\n      return ivec2(r, c);\n    }\n  "}(s,t);case 3:return e=s,p=t,d=[kf(p[0]/2),kf(p[1]/2)],l=kf(e[2]/2),u=l*kf(e[1]/2),"\n    ivec3 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2("+d[0]+", "+d[1]+"));\n      int index = resTexRC.x * "+d[1]+" + resTexRC.y;\n\n      int b = index / "+u+";\n      index -= b * "+u+";\n\n      int r = 2 * (index / "+l+");\n      int c = imod(index, "+l+") * 2;\n\n      return ivec3(b, r, c);\n    }\n  ";default:return function(p,t){for(var e=[kf(t[0]/2),kf(t[1]/2)],n=kf(p[p.length-1]/2),r=n*kf(p[p.length-2]/2),o=r,d="",l="b, r, c",c=2;c<p.length-1;c++)o*=p[p.length-c-1],d="\n      int b"+c+" = index / "+o+";\n      index -= b"+c+" * "+o+";\n    "+d,l="b"+c+", "+l;return"\n    ivec"+p.length+" getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2("+e[0]+", "+e[1]+"));\n      int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n\n      "+d+"\n\n      int b = index / "+r+";\n      index -= b * "+r+";\n\n      int r = 2 * (index / "+n+");\n      int c = imod(index, "+n+") * 2;\n\n      return ivec"+p.length+"("+l+");\n    }\n  "}(s,t);}var e,p,d,l,u}(d.logicalShape,s),m=function(e){return"\n    void setOutput(vec4 val) {\n      "+e.output+" = val;\n    }\n  "}(l)):(h=function(a,t){switch(a.length){case 0:return"\n    int getOutputCoords() {\n      return 0;\n    }\n  ";case 1:return function(a,t){return 1===t[0]?"\n      int getOutputCoords() {\n        return int(resultUV.x * "+t[1]+".0);\n      }\n    ":1===t[1]?"\n      int getOutputCoords() {\n        return int(resultUV.y * "+t[0]+".0);\n      }\n    ":"\n    int getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2("+t[0]+", "+t[1]+"));\n      return resTexRC.x * "+t[1]+" + resTexRC.y;\n    }\n  "}(0,t);case 2:return function(a,t){return g(a,t)?"\n      ivec2 getOutputCoords() {\n        return ivec2(resultUV.yx * vec2("+t[0]+", "+t[1]+"));\n      }\n    ":1===a[1]?"\n      ivec2 getOutputCoords() {\n        ivec2 resTexRC = ivec2(resultUV.yx *\n                               vec2("+t[0]+", "+t[1]+"));\n        int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n        return ivec2(index, 0);\n      }\n    ":1===a[0]?"\n      ivec2 getOutputCoords() {\n        ivec2 resTexRC = ivec2(resultUV.yx *\n                               vec2("+t[0]+", "+t[1]+"));\n        int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n        return ivec2(0, index);\n      }\n    ":"\n    ivec2 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2("+t[0]+", "+t[1]+"));\n      int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n      int r = index / "+a[1]+";\n      int c = index - r * "+a[1]+";\n      return ivec2(r, c);\n    }\n  "}(a,t);case 3:return e=t,o=to(["r","c","d"],a),"\n    ivec3 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2("+e[0]+", "+e[1]+"));\n      int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n      "+o+"\n      return ivec3(r, c, d);\n    }\n  ";case 4:return function(a,t){var e=to(["r","c","d","d2"],a);return"\n    ivec4 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n        vec2("+t[0]+", "+t[1]+"));\n      int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n      "+e+"\n      return ivec4(r, c, d, d2);\n    }\n  "}(a,t);case 5:return function(a,t){var e=to(["r","c","d","d2","d3"],a);return"\n    ivec5 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx * vec2("+t[0]+",\n                             "+t[1]+"));\n\n      int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n\n      "+e+"\n\n      ivec5 outShape = ivec5(r, c, d, d2, d3);\n      return outShape;\n    }\n  "}(a,t);case 6:return function(a,t){var e=to(["r","c","d","d2","d3","d4"],a);return"\n    ivec6 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n        vec2("+t[0]+", "+t[1]+"));\n      int index = resTexRC.x * "+t[1]+" + resTexRC.y;\n\n      "+e+"\n\n      ivec6 result = ivec6(r, c, d, d2, d3, d4);\n      return result;\n    }\n  "}(a,t);default:throw new Error(a.length+"-D output sampling is not yet supported");}var e,o}(d.logicalShape,s),m=function(e){return"\n    void setOutput(float val) {\n      "+e.output+" = vec4(val, 0, 0, 0);\n    }\n  "}(l)),n&&(c+=Uo),[c,u,m,t,h,o,e].join("\n")}function ro(a){var t=a.shapeInfo.logicalShape;switch(t.length){case 0:return function(p){var t=p.name,e="get"+t.charAt(0).toUpperCase()+t.slice(1);if(p.shapeInfo.isUniform)return"float "+e+"() {return "+t+";}";var n=p.shapeInfo.texShape,r=n[0],o=n[1];if(1===r&&1===o)return"\n      float "+e+"() {\n        return sampleTexture("+t+", halfCR);\n      }\n    ";var a=p.shapeInfo.texShape,i=a[0],s=a[1],d=so(t);return"\n    float "+e+"() {\n      vec2 uv = uvFromFlat("+i+", "+s+", "+d+");\n      return sampleTexture("+t+", uv);\n    }\n  "}(a);case 1:return function(s){var t=s.name,e="get"+t.charAt(0).toUpperCase()+t.slice(1);if(s.shapeInfo.isUniform)return"\n      float "+e+"(int index) {\n        "+io(s)+"\n      }\n    ";var n=s.shapeInfo.texShape,r=n[0],o=n[1];if(1===o&&1===r)return"\n      float "+e+"(int index) {\n        return sampleTexture("+t+", halfCR);\n      }\n    ";var a=so(t);return 1===o?"\n      float "+e+"(int index) {\n        vec2 uv = vec2(0.5, (float(index + "+a+") + 0.5) / "+r+".0);\n        return sampleTexture("+t+", uv);\n      }\n    ":1===r?"\n      float "+e+"(int index) {\n        vec2 uv = vec2((float(index + "+a+") + 0.5) / "+o+".0, 0.5);\n        return sampleTexture("+t+", uv);\n      }\n    ":"\n    float "+e+"(int index) {\n      vec2 uv = uvFromFlat("+r+", "+o+", index + "+a+");\n      return sampleTexture("+t+", uv);\n    }\n  "}(a);case 2:return function(m){var t=m.shapeInfo.logicalShape,e=m.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1),r=m.shapeInfo.texShape;if(null!=r&&g(t,r)){var o=r[0],a=r[1];return"\n    float "+n+"(int row, int col) {\n      vec2 uv = (vec2(col, row) + halfCR) / vec2("+a+".0, "+o+".0);\n      return sampleTexture("+e+", uv);\n    }\n  "}var i=I(t),s=i.newShape,u=i.keptDims,l=s;if(l.length<t.length){var c=lo(m,l);return"\n      "+ro(c)+"\n      float "+n+"(int row, int col) {\n        return "+n+"("+uo(["row","col"],u)+");\n      }\n    "}if(m.shapeInfo.isUniform)return"\n      float "+n+"(int row, int col) {\n        int index = round(dot(vec2(row, col), vec2("+t[1]+", 1)));\n        "+io(m)+"\n      }\n    ";var h=r[0],f=r[1],p=so(e);return 1===f?"\n    float "+n+"(int row, int col) {\n      float index = dot(vec3(row, col, "+p+"), vec3("+t[1]+", 1, 1));\n      vec2 uv = vec2(0.5, (index + 0.5) / "+h+".0);\n      return sampleTexture("+e+", uv);\n    }\n  ":1===h?"\n    float "+n+"(int row, int col) {\n      float index = dot(vec3(row, col, "+p+"), vec3("+t[1]+", 1, 1));\n      vec2 uv = vec2((index + 0.5) / "+f+".0, 0.5);\n      return sampleTexture("+e+", uv);\n    }\n  ":"\n  float "+n+"(int row, int col) {\n    // Explicitly use integer operations as dot() only works on floats.\n    int index = row * "+t[1]+" + col + "+p+";\n    vec2 uv = uvFromFlat("+h+", "+f+", index);\n    return sampleTexture("+e+", uv);\n  }\n"}(a);case 3:return function(m){var t=m.shapeInfo.logicalShape,e=m.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1),r=t[1]*t[2],o=t[2],a=I(t),i=a.newShape,s=a.keptDims,u=i;if(u.length<t.length){var l=lo(m,u);return"\n        "+ro(l)+"\n        float "+n+"(int row, int col, int depth) {\n          return "+n+"("+uo(["row","col","depth"],s)+");\n        }\n      "}if(m.shapeInfo.isUniform)return"\n      float "+n+"(int row, int col, int depth) {\n        int index = round(dot(vec3(row, col, depth),\n                          vec3("+r+", "+o+", 1)));\n        "+io(m)+"\n      }\n    ";var c=m.shapeInfo.texShape,h=c[0],g=c[1],p=m.shapeInfo.flatOffset;if(g===r&&null==p)return"\n        float "+n+"(int row, int col, int depth) {\n          float texR = float(row);\n          float texC = dot(vec2(col, depth), vec2("+o+", 1));\n          vec2 uv = (vec2(texC, texR) + halfCR) /\n                     vec2("+g+".0, "+h+".0);\n          return sampleTexture("+e+", uv);\n        }\n      ";if(g===o&&null==p)return"\n    float "+n+"(int row, int col, int depth) {\n      float texR = dot(vec2(row, col), vec2("+t[1]+", 1));\n      float texC = float(depth);\n      vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+g+".0, "+h+".0);\n      return sampleTexture("+e+", uv);\n    }\n  ";var d=so(e);return"\n      float "+n+"(int row, int col, int depth) {\n        // Explicitly use integer operations as dot() only works on floats.\n        int index = row * "+r+" + col * "+o+" + depth + "+d+";\n        vec2 uv = uvFromFlat("+h+", "+g+", index);\n        return sampleTexture("+e+", uv);\n      }\n  "}(a);case 4:return function(m){var t=m.shapeInfo.logicalShape,e=m.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1),r=t[3],o=t[2]*r,a=t[1]*o,i=I(t),s=i.newShape,u=i.keptDims;if(s.length<t.length){var l=lo(m,s);return"\n      "+ro(l)+"\n      float "+n+"(int row, int col, int depth, int depth2) {\n        return "+n+"("+uo(["row","col","depth","depth2"],u)+");\n      }\n    "}if(m.shapeInfo.isUniform)return"\n      float "+n+"(int row, int col, int depth, int depth2) {\n        int index = round(dot(vec4(row, col, depth, depth2),\n                          vec4("+a+", "+o+", "+r+", 1)));\n        "+io(m)+"\n      }\n    ";var c=m.shapeInfo.flatOffset,h=m.shapeInfo.texShape,g=h[0],p=h[1];if(p===a&&null==c)return"\n      float "+n+"(int row, int col, int depth, int depth2) {\n        float texR = float(row);\n        float texC =\n            dot(vec3(col, depth, depth2),\n                vec3("+o+", "+r+", 1));\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                   vec2("+p+".0, "+g+".0);\n        return sampleTexture("+e+", uv);\n      }\n    ";if(p===r&&null==c)return"\n      float "+n+"(int row, int col, int depth, int depth2) {\n        float texR = dot(vec3(row, col, depth),\n                         vec3("+t[1]*t[2]+", "+t[2]+", 1));\n        float texC = float(depth2);\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                  vec2("+p+".0, "+g+".0);\n        return sampleTexture("+e+", uv);\n      }\n    ";var d=so(e);return"\n    float "+n+"(int row, int col, int depth, int depth2) {\n      // Explicitly use integer operations as dot() only works on floats.\n      int index = row * "+a+" + col * "+o+" +\n          depth * "+r+" + depth2;\n      vec2 uv = uvFromFlat("+g+", "+p+", index + "+d+");\n      return sampleTexture("+e+", uv);\n    }\n  "}(a);case 5:return function(g){var t=g.shapeInfo.logicalShape,e=g.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1),r=t[4],o=t[3]*r,a=t[2]*o,i=t[1]*a,s=I(t),u=s.newShape,l=s.keptDims;if(u.length<t.length){var c=lo(g,u);return"\n      "+ro(c)+"\n      float "+n+"(int row, int col, int depth, int depth2, int depth3) {\n        return "+n+"("+uo(["row","col","depth","depth2","depth3"],l)+");\n      }\n    "}if(g.shapeInfo.isUniform)return"\n      float "+n+"(int row, int col, int depth, int depth2, int depth3) {\n        float index = dot(\n          vec4(row, col, depth, depth2),\n          vec4("+i+", "+a+", "+o+", "+r+")) +\n          depth3;\n        "+io(g)+"\n      }\n    ";var h=g.shapeInfo.flatOffset,f=g.shapeInfo.texShape,p=f[0],d=f[1];if(d===i&&null==h)return"\n      float "+n+"(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("+a+", "+o+", "+r+", 1));\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                   vec2("+d+".0, "+p+".0);\n        return sampleTexture("+e+", uv);\n      }\n    ";if(d===r&&null==h)return"\n      float "+n+"(int row, int col, int depth, int depth2, int depth3) {\n        float texR = dot(\n          vec4(row, col, depth, depth2),\n          vec4("+t[1]*t[2]*t[3]+",\n               "+t[2]*t[3]+", "+t[3]+", 1));\n        int texC = depth3;\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                  vec2("+d+".0, "+p+".0);\n        return sampleTexture("+e+", uv);\n      }\n    ";var y=so(e);return"\n    float "+n+"(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 * "+i+" + col * "+a+" + depth * "+o+" +\n          depth2 * "+r+" + depth3 + "+y+";\n      vec2 uv = uvFromFlat("+p+", "+d+", index);\n      return sampleTexture("+e+", uv);\n    }\n  "}(a);case 6:return function(y){var t=y.shapeInfo.logicalShape,e=y.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1),r=I(t),o=r.newShape,a=r.keptDims;if(o.length<t.length){var i=lo(y,o);return"\n      "+ro(i)+"\n      float "+n+"(int row, int col, int depth,\n                    int depth2, int depth3, int depth4) {\n        return "+n+"("+uo(["row","col","depth","depth2","depth3","depth4"],a)+");\n      }\n    "}var s=t[5],u=t[4]*s,l=t[3]*u,c=t[2]*l,h=t[1]*c;if(y.shapeInfo.isUniform)return"\n      float "+n+"(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("+h+", "+c+", "+l+", "+u+")) +\n          dot(\n            vec2(depth3, depth4),\n            vec2("+s+", 1)));\n        "+io(y)+"\n      }\n    ";var f=y.shapeInfo.flatOffset,p=y.shapeInfo.texShape,d=p[0],b=p[1];if(b===h&&null==f)return"\n      float "+n+"(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("+b+".0, "+d+".0);\n        return sampleTexture("+e+", uv);\n      }\n    ";if(b===s&&null==f)return"\n      float "+n+"(int row, int col, int depth,\n                    int depth2, int depth3, int depth4) {\n        float texR = dot(vec4(row, col, depth, depth2),\n          vec4("+t[1]*t[2]*t[3]*t[4]+",\n               "+t[2]*t[3]*t[4]+",\n               "+t[3]*t[4]+",\n               "+t[4]+")) + float(depth3);\n        int texC = depth4;\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                  vec2("+b+".0, "+d+".0);\n        return sampleTexture("+e+", uv);\n      }\n    ";var m=so(e);return"\n    float "+n+"(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 * "+h+" + col * "+c+" + depth * "+l+" +\n          depth2 * "+u+" + depth3 * "+s+" + depth4 + "+m+";\n      vec2 uv = uvFromFlat("+d+", "+b+", index);\n      return sampleTexture("+e+", uv);\n    }\n  "}(a);default:throw new Error(t.length+"-D input sampling is not yet supported");}}function oo(a){var t,o,s;switch(a.shapeInfo.logicalShape.length){case 0:return t=a.name,o="get"+t.charAt(0).toUpperCase()+t.slice(1),s=eo(),"\n    vec4 "+o+"() {\n      return "+s.texture2D+"("+t+", halfCR);\n    }\n  ";case 1:return function(s){var t=s.name,e="get"+t.charAt(0).toUpperCase()+t.slice(1),n=s.shapeInfo.texShape,r=[kf(n[0]/2),kf(n[1]/2)],o=eo();return"\n    vec4 "+e+"(int index) {\n      vec2 uv = packedUVfrom1D(\n        "+r[0]+", "+r[1]+", index);\n      return "+o.texture2D+"("+t+", uv);\n    }\n  "}(a);case 2:return function(p){var t=p.shapeInfo.logicalShape,e=p.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1),r=p.shapeInfo.texShape,o=r[0],a=r[1],i=eo();if(null!=r&&g(t,r))return"\n      vec4 "+n+"(int row, int col) {\n        vec2 uv = (vec2(col, row) + halfCR) / vec2("+a+".0, "+o+".0);\n\n        return "+i.texture2D+"("+e+", uv);\n      }\n    ";var s=[kf(r[0]/2),kf(r[1]/2)],d=kf(t[1]/2);return"\n    vec4 "+n+"(int row, int col) {\n      vec2 uv = packedUVfrom2D("+d+", "+s[0]+", "+s[1]+", row, col);\n      return "+i.texture2D+"("+e+", uv);\n    }\n  "}(a);case 3:return function(p){var t=p.shapeInfo.logicalShape,e=p.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1),r=p.shapeInfo.texShape,o=[kf(r[0]/2),kf(r[1]/2)];if(1===t[0]){var a=t.slice(1),i=lo(p,a);return"\n        "+oo(i)+"\n        vec4 "+n+"(int b, int row, int col) {\n          return "+n+"("+uo(["b","row","col"],[1,2])+");\n        }\n      "}var s=o[0],d=o[1],l=kf(t[2]/2),u=l*kf(t[1]/2),c=eo();return"\n    vec4 "+n+"(int b, int row, int col) {\n      vec2 uv = packedUVfrom3D(\n        "+s+", "+d+", "+u+", "+l+", b, row, col);\n      return "+c.texture2D+"("+e+", uv);\n    }\n  "}(a);default:return function(m){for(var t=m.shapeInfo.logicalShape,e=t.length,n=m.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=m.shapeInfo.texShape,a=[kf(o[0]/2),kf(o[1]/2)],i=a[0],s=a[1],u=kf(t[e-1]/2),l=u*kf(t[e-2]/2),g="int b, int row, int col",y="b * "+l+" + (row / 2) * "+u+" + (col / 2)",b=2;b<e-1;b++)g="int b"+b+", "+g,l*=t[e-b-1],y="b"+b+" * "+l+" + "+y;var x=eo();return"\n    vec4 "+r+"("+g+") {\n      int index = "+y+";\n      int texR = index / "+s+";\n      int texC = index - texR * "+s+";\n      vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+s+", "+i+");\n      return "+x.texture2D+"("+n+", uv);\n    }\n  "}(a);}}function so(e){return"offset"+e}function io(a){var t=a.name,e=qe(a.shapeInfo.logicalShape);return 2>e?"return "+t+";":"\n    for (int i = 0; i < "+e+"; i++) {\n      if (i == index) {\n        return "+t+"[i];\n      }\n    }\n  "}function po(e){if(1>=e)return"int";if(2===e)return"ivec2";if(3===e)return"ivec3";if(4===e)return"ivec4";if(5===e)return"ivec5";if(6===e)return"ivec6";throw Error("GPU for rank "+e+" is not yet supported")}function lo(a,t){var e=JSON.parse(JSON.stringify(a));return e.shapeInfo.logicalShape=t,e}function uo(a,t){return t.map(function(t){return a[t]}).join(", ")}function co(a,t){if(1===a)return""+t;if(2===a)return t+".y";if(3===a)return t+".z";if(4===a)return t+".w";throw Error("Cumulative sum for rank "+a+" is not yet supported")}function Ca(a,t){var e=eo();return Ct(a,t,e.version+"\n    precision highp float;\n    "+e.attribute+" vec3 clipSpacePos;\n    "+e.attribute+" vec2 uv;\n    "+e.varyingVs+" vec2 resultUV;\n\n    void main() {\n      gl_Position = vec4(clipSpacePos, 1);\n      resultUV = uv;\n    }")}function La(a,t){return ee(a,t,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function Wa(a,t){return ne(a,t,new Uint16Array([0,1,2,2,1,3]))}function Ua(p,t,e,n,r,o,a){oe(e,n);var i=re(p,t),s=p.TEXTURE_2D;return rt(p,t,function(){return p.bindTexture(s,i)}),rt(p,t,function(){return p.texParameteri(s,p.TEXTURE_WRAP_S,p.CLAMP_TO_EDGE)}),rt(p,t,function(){return p.texParameteri(s,p.TEXTURE_WRAP_T,p.CLAMP_TO_EDGE)}),rt(p,t,function(){return p.texParameteri(s,p.TEXTURE_MIN_FILTER,p.NEAREST)}),rt(p,t,function(){return p.texParameteri(s,p.TEXTURE_MAG_FILTER,p.NEAREST)}),rt(p,t,function(){return p.texImage2D(s,0,r,e,n,0,o,a,null)}),rt(p,t,function(){return p.bindTexture(p.TEXTURE_2D,null)}),i}function za(s,t,e,n,r){var o=et(e,n);return Ua(s,t,o[0],o[1],r.internalFormatFloat,r.textureFormatFloat,s.FLOAT)}function Va(s,t,e,n,r){var o=et(e,n);return Ua(s,t,o[0],o[1],r.internalFormatHalfFloat,r.textureFormatFloat,r.textureTypeHalfFloat)}function Ga(o,t,e,n){var r=et(e,n);return Ua(o,t,r[0],r[1],o.RGBA,o.RGBA,o.UNSIGNED_BYTE)}function Ha(s,t,e,n,r){var o=at(e,n);return Ua(s,t,o[0],o[1],r.internalFormatPackedFloat,s.RGBA,s.FLOAT)}function qa(s,t,e,n,r){var o=at(e,n);return Ua(s,t,o[0],o[1],r.internalFormatPackedHalfFloat,s.RGBA,r.textureTypeHalfFloat)}function $a(a,t,e,n){return rt(a,t,function(){return a.bindBuffer(a.ARRAY_BUFFER,n)}),ie(a,t,e,"clipSpacePos",n,3,20,0)&&ie(a,t,e,"uv",n,2,20,12)}function ja(p,t,e,n,r,o,a){var i,d,c;rt(p,t,function(){return p.bindTexture(p.TEXTURE_2D,e)}),o instanceof Uint8Array?(i=new Uint8Array(4*(n*r)),d=p.UNSIGNED_BYTE,c=p.RGBA):(i=new Float32Array(4*(n*r)),d=p.FLOAT,c=a.internalFormatPackedFloat),i.set(o),rt(p,t,function(){return p.texImage2D(p.TEXTURE_2D,0,c,n,r,0,p.RGBA,d,i)}),rt(p,t,function(){return p.bindTexture(p.TEXTURE_2D,null)})}function Ka(a,t,e,n){rt(a,t,function(){return a.bindTexture(a.TEXTURE_2D,e)}),n.data instanceof Uint8Array?rt(a,t,function(){return a.texImage2D(a.TEXTURE_2D,0,a.RGBA,n.width,n.height,0,a.RGBA,a.UNSIGNED_BYTE,n.data)}):rt(a,t,function(){return a.texImage2D(a.TEXTURE_2D,0,a.RGBA,a.RGBA,a.UNSIGNED_BYTE,n)}),rt(a,t,function(){return a.bindTexture(a.TEXTURE_2D,null)})}function Xa(o,t,e,n){var r=o.createBuffer();rt(o,t,function(){return o.bindBuffer(o.PIXEL_PACK_BUFFER,r)});return rt(o,t,function(){return o.bufferData(o.PIXEL_PACK_BUFFER,16*e*n,o.STREAM_READ)}),rt(o,t,function(){return o.readPixels(0,0,n,e,o.RGBA,o.FLOAT,0)}),rt(o,t,function(){return o.bindBuffer(o.PIXEL_PACK_BUFFER,null)}),r}function Ya(a,t,e){var n=a,r=new Float32Array(e);return n.bindBuffer(n.PIXEL_PACK_BUFFER,t),n.getBufferSubData(n.PIXEL_PACK_BUFFER,0,r),n.bindBuffer(n.PIXEL_PACK_BUFFER,null),r}function Qa(p,t,e,n,r){var o=et(e,n),a=o[0],i=o[1],s=new Uint8Array(4*(e*n));return rt(p,t,function(){return p.readPixels(0,0,a,i,r.downloadTextureFormat,p.UNSIGNED_BYTE,s)}),new Float32Array(s.buffer)}function Ja(s,t,e,n,r,o,a){var i=s,p=new Float32Array(function(a,t){var e=at(a,t);return 4*(e[0]*e[1])}(o,a));return i.bindBuffer(i.PIXEL_PACK_BUFFER,t),i.getBufferSubData(i.PIXEL_PACK_BUFFER,0,p),i.bindBuffer(i.PIXEL_PACK_BUFFER,null),p}function Za(a,t,e,n){var r=new Float32Array(4*(e*n));return rt(a,t,function(){return a.readPixels(0,0,n,e,a.RGBA,a.FLOAT,r)}),r}function ho(a,p){if(a.length!==p.length)throw Error("Binary was compiled with "+a.length+" inputs, but was executed with "+p.length+" inputs");a.forEach(function(e,t){var n=e.logicalShape,r=p[t],o=r.shape;if(!g(n,o))throw Error("Binary was compiled with different shapes than the current args. Shapes "+n+" and "+o+" must match");if(!e.isUniform||!r.isUniform){var a=e.texShape,i=r.isUniform?null:r.texData.texShape;if(!g(a,i))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+a+" and "+i+" must match")}})}function mo(a,t){if(a===Ft.UPLOAD)return Uf.PACKED_2X2_FLOAT32;if(a===Ft.RENDER||null==a)return t?_f.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?Uf.PACKED_2X2_FLOAT32:Uf.PACKED_2X2_FLOAT16:_f.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?Uf.UNPACKED_FLOAT32:Uf.UNPACKED_FLOAT16;if(a===Ft.DOWNLOAD||a===Ft.PIXELS)return Uf.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+a)}function go(a,t,e){return a[0]+"_"+a[1]+"_"+t+"_"+e}function fo(a,t){if(void 0===t&&(t=!1),"linear"===a)return t?"return x;":"return x;";if("relu"===a)return t?"\n  vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n  bvec4 isNaN = isnan(x);\n\n  result.r = isNaN.r ? x.r : result.r;\n  result.g = isNaN.g ? x.g : result.g;\n  result.b = isNaN.b ? x.b : result.b;\n  result.a = isNaN.a ? x.a : result.a;\n\n  return result;\n":"if (isnan(x)) return x;\n  return (x < 0.0) ? 0.0 : x;\n";throw new Error("Activation "+a+" has not been implemented for the WebGL backend.")}function yo(p,t,e,n,r,o){var a=Lt(p,"x","batchNorm"),d=Lt(t,"mean","batchNorm"),l=Lt(e,"variance","batchNorm"),u,c;return null!=r&&(u=Lt(r,"scale","batchNorm")),null!=n&&(c=Lt(n,"offset","batchNorm")),Ue(2===a.rank,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+a.rank+"."}),Ue(2===d.rank||1===d.rank,function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank "+d.rank+"."}),Ue(2===l.rank||1===l.rank,function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank "+l.rank+"."}),null!=u&&Ue(2===u.rank||1===u.rank,function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank "+u.rank+"."}),null!=c&&Ue(2===c.rank||1===c.rank,function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank "+c.rank+"."}),Co(a,d,l,c,u,o)}function bo(p,t,e,n,r,o){var a=Lt(p,"x","batchNorm"),d=Lt(t,"mean","batchNorm"),l=Lt(e,"variance","batchNorm"),u,c;return null!=r&&(u=Lt(r,"scale","batchNorm")),null!=n&&(c=Lt(n,"offset","batchNorm")),Ue(3===a.rank,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+a.rank+"."}),Ue(3===d.rank||1===d.rank,function(){return"Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank "+d.rank+"."}),Ue(3===l.rank||1===l.rank,function(){return"Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank "+l.rank+"."}),null!=u&&Ue(3===u.rank||1===u.rank,function(){return"Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank "+u.rank+"."}),null!=c&&Ue(3===c.rank||1===c.rank,function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank "+c.rank+"."}),Co(a,d,l,c,u,o)}function xo(p,t,e,n,r,o){var a=Lt(p,"x","batchNorm"),d=Lt(t,"mean","batchNorm"),l=Lt(e,"variance","batchNorm"),u,c;return null!=r&&(u=Lt(r,"scale","batchNorm")),null!=n&&(c=Lt(n,"offset","batchNorm")),Ue(4===a.rank,function(){return"Error in batchNorm4D: x must be rank 4 but got rank "+a.rank+"."}),Ue(4===d.rank||1===d.rank,function(){return"Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank "+d.rank+"."}),Ue(4===l.rank||1===l.rank,function(){return"Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank "+l.rank+"."}),null!=u&&Ue(4===u.rank||1===u.rank,function(){return"Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank "+u.rank+"."}),null!=c&&Ue(4===c.rank||1===c.rank,function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank "+c.rank+"."}),Co(a,d,l,c,u,o)}function Co(p,t,e,n,r,g){null==g&&(g=.001);var o=Lt(p,"x","batchNorm"),d=Lt(t,"mean","batchNorm"),l=Lt(e,"variance","batchNorm"),c,h,y;return null!=r&&(c=Lt(r,"scale","batchNorm")),null!=n&&(h=Lt(n,"offset","batchNorm")),Ue(d.rank===l.rank,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."}),Ue(null==h||d.rank===h.rank,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."}),Ue(null==c||d.rank===c.rank,function(){return"Batch normalization gradient requires mean and scale to have equal ranks."}),y=0===o.rank||1===o.rank?o.as4D(1,1,1,o.size):2===o.rank?o.as4D(1,1,o.shape[0],o.shape[1]):3===o.rank?o.as4D(1,o.shape[0],o.shape[1],o.shape[2]):o,kt.runKernel(function(a,t){var e=a.batchNormalization(y,Io(d),Io(l),g,Io(c),Io(h));return t([o,d,l,c]),e},{$x:o,$mean:d,$variance:l,$scale:c,$offset:h},function(a,t){var e=t,n=e[0],r=e[1],o=e[2],i=e[3],s=null==i?Da(1):i,l=Zn(r.shape,y.shape),u=[];if(1===r.rank){for(var c=0;c<y.shape.length-1;++c)u.push(y.shape[c]);u.push(1)}var h=n.sub(r),p=a.mul(s),d=Is(o.add(Da(g))),b=d.mul(d).mul(d).mul(Da(-.5));return{$x:function(){return 1===r.rank?a.mul(wr(d.as4D(1,1,1,r.shape[0]),u)).mul(s).reshape(n.shape):a.mul(d).mul(s).reshape(n.shape)},$mean:function(){var e=d.mul(Da(-1)).mul(p);return 1===r.rank&&(e=e.sum(l)),e.reshape(r.shape)},$variance:function(){var e=b.mul(h).mul(p);return 1===r.rank&&(e=e.sum(l)),e.reshape(r.shape)},$scale:function(){var t=h.mul(d),e=a.mul(t);return 1===r.rank&&(e=e.sum(l)),e.reshape(r.shape)},$offset:function(){var t=a;return 1===r.rank&&(t=t.sum(l)),t.reshape(r.shape)}}}).reshape(o.shape)}function Io(e){return null==e?null:0===e.rank?e.as1D():1===e.rank?e:2===e.rank?e.as4D(1,1,e.shape[0],e.shape[1]):3===e.rank?e.as4D(1,e.shape[0],e.shape[1],e.shape[2]):e}function To(){_e("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon")}function Ro(p,t,d,e,r,o){Ue(p.length===t.rank,function(){return"Length of inShape ("+p.length+") and rank of dy ("+t.rank+") must match"});var a=p,n=t,m=!1;3===t.rank&&(m=!0,n=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]),a=[1,p[0],p[1],p[2]]);var g=a[3],l=n.shape[3];Ue(4===a.length,function(){return"Error in conv2dDerInput: inShape must be length 4, but got length "+a.length+"."}),Ue(4===n.rank,function(){return"Error in conv2dDerInput: dy must be rank 4, but got rank "+n.rank}),Ue(4===d.rank,function(){return"Error in conv2dDerInput: filter must be rank 4, but got rank "+d.rank}),Ue(g===d.shape[2],function(){return"Error in conv2dDerInput: depth of input ("+g+") must match input depth for filter "+d.shape[2]+"."}),Ue(l===d.shape[3],function(){return"Error in conv2dDerInput: depth of output ("+l+") must match output depth for filter "+d.shape[3]+"."}),null!=o&&Ue(y(r),function(){return"Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+"."});var c=Nr(a,d.shape,e,1,r,o),h=kt.runKernel(function(a,t){var e=a.conv2dDerInput(n,d,c);return t([d,n]),e},{dy4D:n,filter:d},function(a,t){var s=t[0],n=t[1];return{dy4D:function(){return ru(a,s,e,r,"NHWC",1,o)},filter:function(){return au(a,n,s.shape,e,r,o)}}});return m?h.as3D(h.shape[1],h.shape[2],h.shape[3]):h}function Eo(p,t,e,n,r,o){var a=p;3===p.rank&&(a=p.as4D(1,p.shape[0],p.shape[1],p.shape[2]));var d=t;3===d.rank&&(d=t.as4D(1,t.shape[0],t.shape[1],t.shape[2])),Ue(4===a.rank,function(){return"Error in conv2dDerFilter: input must be rank 4, but got shape "+a.shape+"."}),Ue(4===d.rank,function(){return"Error in conv2dDerFilter: dy must be rank 4, but got shape "+d.shape+"."}),Ue(4===e.length,function(){return"Error in conv2dDerFilter: filterShape must be length 4, but got "+e+"."}),Ue(a.shape[3]===e[2],function(){return"Error in conv2dDerFilter: depth of input "+a.shape[3]+") must match input depth in filter ("+e[2]+"."}),Ue(d.shape[3]===e[3],function(){return"Error in conv2dDerFilter: depth of dy ("+d.shape[3]+") must match output depth for filter ("+e[3]+")."}),null!=o&&Ue(y(r),function(){return"Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+"."});var l=Nr(a.shape,e,n,1,r,o);return kt.runKernel(function(e){return e.conv2dDerFilter(a,d,l)},{x4D:a,dy4D:d})}function wo(a){var t=function(e){return"number"==typeof e?[e,e,e]:2===e.length?[e[0],e[1],1]:e}(a),e=t[0],n=t[1],r=t[2];return 1===e&&1===n&&1===r}function Ao(p,d,e,n,h,t){var a=Lt(p,"x","maxPool"),o=a,i=!1;3===a.rank&&(i=!0,o=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),null==n&&(n=[1,1]),Ue(4===o.rank,function(){return"Error in maxPool: input must be rank 4 but got rank "+o.rank+"."}),Ue(Lr(e,n),function(){return"Error in maxPool: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+n+"'"}),null!=t&&Ue(y(h),function(){return"Error in maxPool: pad must be an integer when using, dimRoundingMode "+t+" but got pad "+h+"."});var m=Sr(o.shape,d,e,n,h,t),l=kt.runKernel(function(a,t){var e=a.maxPool(o,m);return t([o,e]),e},{x:o},function(r,t){var a=t[0],o=t[1];return{x:function(){return function(p,t,e,n,r,o,d,i){var s=Lt(p,"dy","maxPoolBackprop"),u=Lt(t,"input","maxPoolBackprop"),l=Lt(e,"output","maxPoolBackprop");Ue(u.rank===s.rank,function(){return"Rank of input ("+u.rank+") does not match rank of dy ("+s.rank+")"}),null==o&&(o=[1,1]),Ue(Lr(r,o),function(){return"Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+o+"'"}),Ue(4===s.rank,function(){return"Error in maxPoolBackprop: dy must be rank 4 but got rank "+s.rank+"."}),Ue(4===u.rank,function(){return"Error in maxPoolBackprop: input must be rank 4 but got rank "+u.rank+"."}),null!=i&&Ue(y(d),function(){return"Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+d+"."});var c=Sr(u.shape,n,r,o,d,i);return kt.runKernel(function(e){return e.maxPoolBackprop(s,u,l,c)},{$dy:s,$input:u})}(r,a,o,d,e,n,h)}}});return i?l.as3D(l.shape[1],l.shape[2],l.shape[3]):l}function Do(p,d,e,n,h,t){var a=Lt(p,"x","avgPool","float32");null==n&&(n=[1,1]),Ue(Lr(e,n),function(){return"Error in avgPool: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+n+"'"});var o=a,i=!1;3===a.rank&&(i=!0,o=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),Ue(4===o.rank,function(){return"Error in avgPool: x must be rank 4 but got rank "+o.rank+"."}),null!=t&&Ue(y(h),function(){return"Error in avgPool: pad must be an integer when using, dimRoundingMode "+t+" but got pad "+h+"."});var m=Sr(o.shape,d,e,n,h,t),l=kt.runKernel(function(e){return e.avgPool(o,m)},{x:o},function(a){return{x:function(){return function(p,t,e,n,r,d){var a=Lt(p,"dy","avgPoolBackprop"),i=Lt(t,"input","avgPoolBackprop");Ue(i.rank===a.rank,function(){return"Rank of input ("+i.rank+") does not match rank of dy ("+a.rank+")"}),null==r&&(r=[1,1]),Ue(Lr(n,r),function(){return"Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"});var s=i,m=a,g=!1;3===i.rank&&(g=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2]),m=a.as4D(1,a.shape[0],a.shape[1],a.shape[2])),Ue(4===m.rank,function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+m.rank+"."}),Ue(4===s.rank,function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+s.rank+"."});var y=Sr(s.shape,e,n,r,d),h=kt.runKernel(function(e){return e.avgPoolBackprop(m,s,y)},{dy4D:m,input4D:s});return g?h.as3D(h.shape[1],h.shape[2],h.shape[3]):h}(a,o,d,e,n,h)}}});return l=l.cast(a.dtype),i?l.as3D(l.shape[1],l.shape[2],l.shape[3]):l}function _o(a,s,i,n,p){return s.rank<i.rank&&(s=s.reshape(Vt(s.shape,n))),a.rank<i.rank&&(a=a.reshape(Vt(a.shape,n))),{$x:function(){var e=a.mul(i.equal(s).cast(a.dtype));return null==p?e:e.transpose(p)}}}function Oo(a,t){for(var e=[],n=a;n<t;++n)e.push(n);return e}function Bo(a){for(var t=[],e=0;e<a.length;++e)for(var o=0;o<a[e].length;++o)t.push(a[e][o]);return t}function Po(r,t,e){for(var n=new Float32Array(r),o=0,s;o<r;++o)s=2*bf*o/(r+(1-r%2)-1),n[o]=t-e*yf(s);return en(n,"float32")}function Mo(p,t){return void 0===t&&(t=!1),kt.tidy(function(){if(2!==p.shape.length)throw new Error("qr2d() requires a 2D Tensor, but got a "+p.shape.length+"D Tensor.");for(var g=p.shape[0],n=p.shape[1],r=ir(g),y=p.clone(),b=tn([[1]],[1,1]),i=b.clone(),e=g>=n?n:g,d=function(a){var t=y,o=i,s=r,p;p=kt.tidy(function(){var t=y.slice([a,a],[g-a,1]),e=t.norm(),o=y.slice([a,a],[1,1]),s=o.sign().neg(),l=o.sub(s.mul(e)),u=t.div(l);i=1===u.shape[0]?b.clone():b.concat(u.slice([1,0],[u.shape[0]-1,u.shape[1]]),0);var c=s.matMul(l).div(e).neg(),p=y.slice([a,0],[g-a,n]),d=c.mul(i);y=0===a?p.sub(d.matMul(i.transpose().matMul(p))):y.slice([0,0],[a,n]).concat(p.sub(d.matMul(i.transpose().matMul(p))),0);var h=r.slice([0,a],[g,r.shape[1]-a]);return r=0===a?h.sub(h.matMul(i).matMul(d.transpose())):r.slice([0,0],[g,a]).concat(h.sub(h.matMul(i).matMul(d.transpose())),1),[i,y,r]}),i=p[0],y=p[1],r=p[2],ze([t,o,s])},l=0;l<e;++l)d(l);return!t&&g>n&&(r=r.slice([0,0],[g,n]),y=y.slice([0,0],[n,n])),[r,y]})}function Vo(s,t,e,i,p){null==i&&(i=.5),null==p&&(p=gf);var d=s.shape[0];return e=wf(e,d),Ue(0<=i&&1>=i,function(){return"iouThreshold must be in [0, 1], but was '"+i+"'"}),Ue(2===s.rank,function(){return"boxes must be a 2D tensor, but was of rank '"+s.rank+"'"}),Ue(4===s.shape[1],function(){return"boxes must have 4 columns, but 2nd dimension was "+s.shape[1]}),Ue(1===t.rank,function(){return"scores must be a 1D tensor"}),Ue(t.shape[0]===d,function(){return"scores has incompatible shape with boxes. Expected "+d+", but was "+t.shape[0]}),{maxOutputSize:e,iouThreshold:i,scoreThreshold:p}}function Go(a,t,e){if("linear"===t)return a.linear(e);if("relu"===t)return a.relu(e);throw new Error("Activation "+t+" has not been implemented for the CPU backend.")}function qo(p,t){for(var g={},n=0,e=function(t){var e=t.name,r=t.dtype,a=t.shape,o=qe(a),s;if(("quantization"in t)){var i=t.quantization;if("uint8"!==i.dtype&&"uint16"!==i.dtype)throw new Error("Weight "+t.name+" has unknown quantization dtype "+i.dtype+". Supported quantization dtypes are: 'uint8' and 'uint16'.");var l=jf[i.dtype],c=p.slice(n,n+o*l),b="uint8"===i.dtype?new Uint8Array(c):new Uint16Array(c);if("float32"===r)s=Float32Array.from(b,function(e){return e*i.scale+i.min});else{if("int32"!==r)throw new Error("Unsupported dtype in weight '"+e+"': "+r);s=Int32Array.from(b,function(e){return If(e*i.scale+i.min)})}n+=o*l}else if("string"===r){var f=qe(t.shape);s=[];for(var x=0,C;x<f;x++){C=new Uint32Array(p.slice(n,n+4))[0],n+=4;var S=new Uint8Array(p.slice(n,n+C));s.push(S),n+=C}}else{var m=jf[r];if(c=p.slice(n,n+o*m),"float32"===r)s=new Float32Array(c);else if("int32"===r)s=new Int32Array(c);else{if("bool"!==r)throw new Error("Unsupported dtype in weight '"+e+"': "+r);s=new Uint8Array(c)}n+=o*m}g[e]=Zt(s,a,r)},o=0,s=t;o<s.length;o++)e(s[o]);return g}function Ho(a){if(null===a)throw new Error("Invalid input value: "+JSON.stringify(a));var s=0,i=[];a.forEach(function(e){if(s+=e.byteLength,i.push(e.byteLength===e.buffer.byteLength?e:new e.constructor(e)),!(e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array))throw new Error("Unsupported TypedArray subtype: "+e.constructor.name)});var n=new Uint8Array(s),r=0;return i.forEach(function(e){n.set(new Uint8Array(e.buffer),r),r+=e.byteLength}),n.buffer}function $o(e){return Mc?Buffer.byteLength(e):new Blob([e]).size}function Qo(a){var o=0;a.forEach(function(e){o+=e.byteLength});var s=new Uint8Array(o),n=0;return a.forEach(function(e){s.set(new Uint8Array(e),n),n+=e.byteLength}),s.buffer}function Jo(a){for(a=a.trim();a.endsWith("/");)a=a.slice(0,a.length-1);var n=a.split("/");return n[n.length-1]}function ns(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:null==e.modelTopology?0:$o(JSON.stringify(e.modelTopology)),weightSpecsBytes:null==e.weightSpecs?0:$o(JSON.stringify(e.weightSpecs)),weightDataBytes:null==e.weightData?0:e.weightData.byteLength}}function rs(e){if(-1===e.indexOf("://"))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+qc.getSchemes().join(","));return{scheme:e.split("://")[0],path:e.split("://")[1]}}function zs(p,t,e){return void 0===e&&(e=!1),Be(this,void 0,void 0,function(){var o,d,m,g,y,b,x,v,C;return Me(this,function(a){switch(a.label){case 0:return Ue(p!==t,function(){return"Old path and new path are the same: '"+p+"'"}),Ue(0<(o=Wc.getLoadHandlers(p)).length,function(){return"Copying failed because no load handler is found for source URL "+p+"."}),Ue(2>o.length,function(){return"Copying failed because more than one ("+o.length+") load handlers for source URL "+p+"."}),d=o[0],Ue(0<(m=Wc.getSaveHandlers(t)).length,function(){return"Copying failed because no save handler is found for destination URL "+t+"."}),Ue(2>m.length,function(){return"Copying failed because more than one ("+o.length+") save handlers for destination URL "+t+"."}),g=m[0],y=rs(p).scheme,b=rs(p).path,x=y===rs(p).scheme,[4,d.load()];case 1:return v=a.sent(),e&&x?[4,qc.getManager(y).removeModel(b)]:[3,3];case 2:a.sent(),a.label=3;case 3:return[4,g.save(v)];case 4:return C=a.sent(),!e||x?[3,6]:[4,qc.getManager(y).removeModel(b)];case 5:a.sent(),a.label=6;case 6:return[2,C.modelArtifactsInfo];}})})}function Vs(){if(!_f.getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var a=window,t=a.indexedDB||a.mozIndexedDB||a.webkitIndexedDB||a.msIndexedDB||a.shimIndexedDB;if(null==t)throw new Error("The current browser does not appear to support IndexedDB.");return t}function Us(a){var t=a.result;t.createObjectStore("models_store",{keyPath:"modelPath"}),t.createObjectStore("model_info_store",{keyPath:"modelPath"})}function Gs(e){return{info:["tensorflowjs_models",e,"info"].join("/"),topology:["tensorflowjs_models",e,"model_topology"].join("/"),weightSpecs:["tensorflowjs_models",e,"weight_specs"].join("/"),weightData:["tensorflowjs_models",e,"weight_data"].join("/"),modelMetadata:["tensorflowjs_models",e,"model_metadata"].join("/")}}function qs(a){var t=a.split("/");if(3>t.length)throw new Error("Invalid key format: "+a);return t.slice(1,t.length-1).join("/")}function Hs(e){return new Promise(function(e){return setTimeout(e)}).then(e)}function ti(s,t,e,p){!function(e){Ue(null!=e&&Array.isArray(e)&&0<e.length,function(){return"promises must be a none empty array"})}(s),function(a,t){Ue(0<=a&&1>=a,function(){return"Progress fraction must be in range [0, 1], but got startFraction "+a}),Ue(0<=t&&1>=t,function(){return"Progress fraction must be in range [0, 1], but got endFraction "+t}),Ue(t>=a,function(){return"startFraction must be no more than endFraction, but got startFraction "+a+" and endFraction "+t})}(e=null==e?0:e,p=null==p?1:p);var d=0;return Promise.all(s.map(function(n){return n.then(function(n){var a=e+ ++d/s.length*(p-e);return t(a),n}),n}))}function ri(i,p){return Be(this,void 0,void 0,function(){var e,t,d,m,g,y,b,x,v;return Me(this,function(a){switch(a.label){case 0:return null==p&&(p={}),e=null==p.fetchFunc?_f.platform.fetch:p.fetchFunc,t=i.map(function(a){return e(a,p.requestInit,{isBinary:!0})}),d=0,m=.5,null==p.onProgress?[4,Promise.all(t)]:[3,2];case 1:return g=a.sent(),[3,4];case 2:return[4,ti(t,p.onProgress,d,m)];case 3:g=a.sent(),a.label=4;case 4:return y=g.map(function(e){return e.arrayBuffer()}),b=.5,x=1,null==p.onProgress?[4,Promise.all(y)]:[3,6];case 5:return v=a.sent(),[3,8];case 6:return[4,ti(y,p.onProgress,b,x)];case 7:v=a.sent(),a.label=8;case 8:return[2,v];}})})}function Oi(m){var t=this;return function(g,n,y){return void 0===n&&(n=""),Be(t,void 0,void 0,function(){var a,b,o,i,t,x,v,C,S,N;return Me(this,function(e){switch(e.label){case 0:if(a=g.map(function(){return!1}),b={},o=null==y?[]:y.map(function(){return!1}),i=[],g.forEach(function(e,n){var r=0;e.weights.forEach(function(s){var e="quantization"in s?s.quantization.dtype:s.dtype,t=jf[e]*qe(s.shape),p=function(){a[n]=!0,null==b[n]&&(b[n]=[]),b[n].push({manifestEntry:s,groupOffset:r,sizeBytes:t})};null==y?p():y.forEach(function(t,e){t===s.name&&(p(),o[e]=!0)}),i.push(s.name),r+=t})}),!o.every(function(e){return e}))throw t=y.filter(function(a,t){return!o[t]}),new Error("Could not find weights in manifest with names: "+t.join(", ")+". \nManifest JSON has weights with names: "+i.join(", ")+".");return x=a.reduce(function(a,t,e){return t&&a.push(e),a},[]),v=[],x.forEach(function(e){g[e].paths.forEach(function(a){var t=n+(n.endsWith("/")?"":"/")+a;v.push(t)})}),[4,m(v)];case 1:return C=e.sent(),S={},N=0,x.forEach(function(n){for(var t=g[n].paths.length,e=0,o=0;o<t;o++)e+=C[N+o].byteLength;for(var p=new ArrayBuffer(e),i=new Uint8Array(p),s=0,d=0,h;d<t;d++)h=new Uint8Array(C[N+d]),i.set(h,s),s+=h.byteLength;b[n].forEach(function(a){var t=qo(p.slice(a.groupOffset,a.groupOffset+a.sizeBytes),[a.manifestEntry]);for(var e in t)S[e]=t[e]}),N+=t}),[2,S];}})})}}function Fi(e){return null!=e.match(xh.URL_SCHEME_REGEX)}function Vi(a,t){return new xh(a,t)}function Gi(e){Ue(null!=e.className,function(){return"Class being registered does not have the static className property defined."}),Ue("string"==typeof e.className,function(){return"className is required to be a string, but got type "+typeof e.className}),Ue(0<e.className.length,function(){return"Class being registered has an empty-string as its className, which is disallowed."}),Fh.register(e)}function Hi(){return 32===kt.backend.floatPrecision()?Ph:Lh}function Ki(p,t,e){var n=!0;if((w(p)||w(t))&&(n=!1),w(p)&&w(t)&&(n=!0),n){var d=p.constructor.name,o=t.constructor.name;if(d!==o)throw new Error("Arrays are of different type. Actual: "+d+". Expected: "+o)}if(Array.isArray(p)&&Array.isArray(t)){var a=wt(p),i=wt(t);if(!g(a,i))throw new Error("Arrays have different shapes. Actual: ["+a+"]. Expected: ["+i+"]")}var s=w(p)?p:v(p),u=w(t)?t:v(t);if(s.length!==u.length)throw new Error("Arrays have different lengths actual: "+s.length+" vs expected: "+u.length+".\nActual:   "+s+".\nExpected: "+u+".");for(var l=0;l<u.length;++l){var m=s[l],h=u[l];if(!e(m,h))throw new Error("Arrays differ: actual["+l+"] = "+m+", expected["+l+"] = "+h+".\nActual:   "+s+".\nExpected: "+u+".")}}function ji(a,t,e){return!isFinite(a)&&!isFinite(t)||!(isNaN(a)||isNaN(t)||Sf(a-t)>e)}function $i(){return new Promise(function(e){return ef(function(){return e()})})}function Xi(a,e){function t(){this.constructor=a}nf(a,e),a.prototype=null===e?Object.create(e):(t.prototype=e.prototype,new t)}function Yi(p,e,t,d){return new(t||(t=Promise))(function(n,r){function a(t){try{s(d.next(t))}catch(t){r(t)}}function o(t){try{s(d.throw(t))}catch(t){r(t)}}function s(r){r.done?n(r.value):new t(function(e){e(r.value)}).then(a,o)}s((d=d.apply(p,e||[])).next())})}function Qi(p,e){function t(t){return function(a){return function(t){if(d)throw new TypeError("Generator is already executing.");for(;s;)try{if(d=1,l&&(u=2&t[0]?l.return:t[0]?l.throw||((u=l.return)&&u.call(l),0):l.next)&&!(u=u.call(l,t[1])).done)return u;switch(l=0,u&&(t=[2&t[0],u.value]),t[0]){case 0:case 1:u=t;break;case 4:return s.label++,{value:t[1],done:!1};case 5:s.label++,l=t[1],t=[0];continue;case 7:t=s.ops.pop(),s.trys.pop();continue;default:if(!(u=0<(u=s.trys).length&&u[u.length-1])&&(6===t[0]||2===t[0])){s=0;continue}if(3===t[0]&&(!u||t[1]>u[0]&&t[1]<u[3])){s.label=t[1];break}if(6===t[0]&&s.label<u[1]){s.label=u[1],u=t;break}if(u&&s.label<u[2]){s.label=u[2],s.ops.push(t);break}u[2]&&s.ops.pop(),s.trys.pop();continue;}t=e.call(p,s)}catch(a){t=[6,a],l=0}finally{d=u=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}([t,a])}}var s={label:0,sent:function(){if(1&u[0])throw u[1];return u[1]},trys:[],ops:[]},d,l,u,c;return c={next:t(0),throw:t(1),return:t(2)},"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c}function Ji(){return null==ry&&(ry=Ge().epsilon()),ry}function ep(){return"channelsLast"}function tp(a,e){if(Array.isArray(a)){for(var t=[],o=0;o<e;o++)t=t.concat(a);return t}return(t=Array(e)).fill(a),t}function ap(a,e){if(!a)throw new Jf(e)}function np(a,e){for(var t=0,o=0,s=a;o<s.length;o++)s[o]===e&&t++;return t}function rp(t){return 1===t.length?t[0]:t}function op(t){return Array.isArray(t)?t:[t]}function sp(a){var e=a.replace(/(.)([A-Z][a-z0-9]+)/g,"$1_$2").replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();return"_"===e[0]?"private"+e:e}function ip(t){return 1>=t.length?t:-1===t.indexOf("_")?t:t.replace(/[_]+(\w|$)/g,function(a,e){return e.toUpperCase()})}function pp(a){if(null===a||void 0===a)return null;var e={};return e.className=a.getClassName(),e.config=a.getConfig(),e}function dp(a){if(null!=a&&"object"==typeof a)if(Array.isArray(a))a.forEach(function(t){return dp(t)});else for(var e=0,o=Object.keys(a);e<o.length;e++){var n=o[e],r=a[n];null!=r&&"object"==typeof r&&(Array.isArray(r)||"ndarray"!==r.type||"number"!=typeof r.value?dp(r):a[n]=r.value)}}function lp(x,e,N,I,k){var T,R,E;if(void 0===e&&(e={}),void 0===N&&(N={}),void 0===I&&(I="object"),void 0===k&&(k=!1),"string"==typeof x){var D=x,l;if(D in N)l=N[D];else if(D in ty)l=ty[D];else if(null==(l=e[D]))throw new Zf("Unknown "+I+": "+x+". This may be due to one of the following reasons:\n1. The "+I+" is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom "+I+" is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().");return l}var O=x;if(null==O.className||null==O.config)throw new Zf(I+": Improper config format: "+JSON.stringify(O)+".\n'className' and 'config' must set.");var c=O.className,p,L;if(c in N?(p=(T=N[c])[0],L=T[1]):c in ty?(p=(R=ty.className)[0],L=R[1]):c in e&&(p=(E=e[c])[0],L=E[1]),null==p)throw new Zf("Unknown "+I+": "+c+". This may be due to one of the following reasons:\n1. The "+I+" is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom "+I+" is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().");if(null!=L){for(var F={},f=0,B=Object.keys(ty);f<B.length;f++)F[z=B[f]]=ty[z];for(var m=0,P=Object.keys(N);m<P.length;m++)F[z=P[m]]=N[z];O.config.customObjects=F;for(var v=$f({},ty),M=0,W=Object.keys(N),z;M<W.length;M++)z=W[M],ty[z]=N[z];dp(O.config);var V=L(p,O.config,N,k);return ty=$f({},v),V}v=$f({},ty);for(var U=0,G=Object.keys(N);U<G.length;U++)z=G[U],ty[z]=N[z];return V=new p(O.config),ty=$f({},v),V}function up(a,e){return a<e?-1:a>e?1:0}function cp(a,e){return-1*up(a,e)}function hp(a){if(null==a)return a;for(var e=[],t=0,o=a,r;t<o.length;t++)r=o[t],-1===e.indexOf(r)&&e.push(r);return e}function mp(a){if(null==a)throw new Zf("Invalid value in obj: "+JSON.stringify(a));for(var e in a)if(a.hasOwnProperty(e))return!1;return!0}function gp(a,e,t){if(null!=t&&0>a.indexOf(t))throw new Zf(t+" is not a valid "+e+".  Valid values are "+a+" or null/undefined.")}function fp(a,o,e,t){return void 0===e&&(e=0),void 0===t&&(t=1/0),ap(0<=e),ap(t>=e),Array.isArray(a)&&a.length>=e&&a.length<=t&&a.every(function(t){return typeof t===o})}function yp(a,r){Array.isArray(a)?(Of.assert(0<a.length,function(){return r+" is unexpectedly an empty array."}),a.forEach(function(t,e){return yp(t,"element "+(e+1)+" of "+r)})):Of.assert(Nf(a)&&0<a,function(){return"Expected "+r+" to be a positive integer, but got "+bp(a)+"."})}function bp(t){return null===t?"null":Array.isArray(t)?"["+t.map(function(t){return bp(t)}).join(",")+"]":"string"==typeof t?"\""+t+"\"":""+t}function xp(s,e){var t=Of.now(),p;return function(){for(var n=[],r=0;r<arguments.length;r++)n[r]=arguments[r];var i=Of.now();return i-t<e?p:(t=i,p=s.apply(void 0,n))}}function vp(a,e){return We(function(){return Fs(Lu(fl(a,a),e,!0))})}function Cp(t){return pp(t)}function Sp(a,e){return void 0===e&&(e={}),lp(a,Mh.SerializationMap.getMap().classNameMap,e,"constraint")}function Np(t){return null==t?null:"string"==typeof t?Sp({className:t in py?py[t]:t,config:{}}):t instanceof ay?t:Sp(t)}function Ip(t){gp(ly,"DataFormat",t)}function kp(t){gp(uy,"PaddingMode",t)}function Tp(t){gp(cy,"PoolMode",t)}function Rp(a,e){gy.push(a);try{var t=e();return gy.pop(),t}catch(t){throw gy.pop(),t}}function Ep(){return 0===gy.length?"":gy.join("/")+"/"}function wp(t){if(!Dp(t))throw new Error("Not a valid tensor name: '"+t+"'");return Ep()+t}function Ap(a){if(!Dp(a))throw new Error("Not a valid tensor name: '"+a+"'");my.has(a)||my.set(a,0);var e=my.get(a);if(my.set(a,my.get(a)+1),0<e){var t=a+"_"+e;return my.set(t,1),t}return a}function Dp(t){return!!t.match(fy)}function _p(t){return t===parseInt(t.toString(),10)}function Op(a,e,o){null==e&&(e=0),null==o&&(o=a.length);for(var s=1,p=e;p<o;++p)s*=a[p];return s}function zp(t){return t=Array.isArray(t)?new Float32Array(t):t,en(t)}function Lp(t){return Bu(zp(t)).dataSync()[0]}function Fp(t){return Fu(zp(t)).dataSync()[0]}function Bp(a,e){if(e<a)throw new Zf("end ("+e+") < begin ("+a+") is forbidden.");for(var t=[],n=a;n<e;++n)t.push(n);return t}function Pp(a,e){return a.asType(e)}function Mp(a,e){void 0===e&&(e=-1);var r=a.shape.slice();return 0>e&&(e=r.length+e+1),r.splice(e,0,1),a.reshape(r)}function Wp(a,e){return We(function(){if(2!==a.shape.length)throw new Zf("repeat() expects a rank-2 tensor, but received a rank-"+a.shape.length+" tensor.");return $p(Mp(a,1),[1,e,1])})}function Vp(a){var e=[Op(a.shape)];return a.reshape(e)}function Up(a){if(1>=a.rank)throw new Zf("batchFlatten requires a minimum rank of 2. Got rank: "+a.rank+".");var e=[a.shape[0],Op(a.shape,1)];return a.reshape(e)}function Gp(a,e,t){return We(function(){switch(a.rank){case 1:return Ru(a,e,t);case 2:return Iu(a,[e,0],[t,a.shape[1]]);case 3:return Su(a,[e,0,0],[t,a.shape[1],a.shape[2]]);case 4:return Nu(a,[e,0,0,0],[t,a.shape[1],a.shape[2],a.shape[3]]);default:throw new Zf("sliceAlongFirstAxis() received an unsupported tensor rank: "+a.rank);}})}function qp(a,e,t){return We(function(){switch(a.rank){case 1:return Ru(a,e,t);case 2:return Iu(a,[0,e],[a.shape[0],t]);case 3:return Su(a,[0,0,e],[a.shape[0],a.shape[1],t]);case 4:return Nu(a,[0,0,0,e],[a.shape[0],a.shape[1],a.shape[2],t]);default:throw new Zf("sliceAlongLastAxis() received an unsupported tensor rank: "+a.rank);}})}function Hp(a,e,t,n){return We(function(){switch(a.rank){case 1:return Ru(a,e,t);case 2:switch(n){case 1:return Gp(a,e,t);case 2:return qp(a,e,t);default:throw new Zf("The axis is not within the rank of the tensor "+n);}case 3:switch(n){case 1:return Gp(a,e,t);case 2:return Su(a,[0,e,0],[a.shape[0],t,a.shape[2]]);case 3:return qp(a,e,t);default:throw new Zf("The axis is not within the rank of the tensor "+n);}case 4:switch(n){case 1:return Gp(a,e,t);case 2:return Nu(a,[0,e,0,0],[a.shape[0],t,a.shape[2],a.shape[3]]);case 3:return Nu(a,[0,0,e,0],[a.shape[0],a.shape[1],t,a.shape[3]]);case 4:return qp(a,e,t);default:throw new Zf("The axis is not within the rank of the tensor "+n);}default:throw new Zf("sliceAlongLastAxis() received an unsupported tensor rank: "+a.rank);}})}function Kp(a,e){var r;return void 0===e&&(e=-1),0>e&&(e=0===(r=a[0].rank)?0:r),e===a[0].rank&&(e=-1),Mn(a,e)}function jp(a,e){switch(a.rank){case 1:return Bn([a,e]);case 2:return Pn([a,e],0);case 3:return Ln([a,e],0);case 4:return Wn([a,e],0);default:throw new Zf("concatAlongFirstAxis() received an unsupported tensor rank: "+a.rank);}}function $p(a,e){if(Array.isArray(e)||(e=[e]),a.rank!==e.length)throw new Zf("The length of input n ("+e.length+") does not match the number of dimensions in input x ("+a.rank+")");return wr(a,e)}function Xp(a,e,o,s,r){return void 0===e&&(e=0),void 0===o&&(o=1),vr(a,e,o,s,r)}function Yp(m,g,f,n){if(2>m.rank||2>g.rank)throw new Qf("dot requires both inputs to be rank >= 2 but got x shape = "+m.shape+" and y shape = "+g.shape);if(3<=g.rank&&(o=m.shape.slice(-1)[0])!==(u=g.shape.slice(-2)[0]))throw new Qf("If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = "+m.shape+" and  y shape = "+g.shape);if(2===m.rank&&2===g.rank){var r=!1,y=!1;return Sc.matMul(m,g,r,y,n?Jp(m.rank,n,ep()):null,f)}var b=m.shape.slice(),o=b.pop();m=m.reshape([-1,o]);var x=g.shape.slice(),l=x.pop(),u=x.pop(),v=x.concat([l]),p=Array.from({length:g.rank},function(t,e){return 0===e?g.rank-2:e<=g.rank-2?e-1:e});g=g.transpose(p).reshape([u,-1]);var h=b.concat(v);return r=!1,y=!1,Sc.matMul(m,g,r,y,n?Jp(m.rank,n,ep()):null,f).reshape(h)}function Zp(a,e,r){return We(function(){return e=Array.isArray(e)?en(e,"int32"):e.toInt(),Ol(a,e,r)})}function Qp(t){return fl(t,t)}function Jp(a,e,t){var n=e.shape;if(1!==e.rank&&e.rank!==a)throw new Zf("Unexpected bias dimensions: "+e.rank+"; expected it to be 1 or "+a);if(5===a){if("channelsFirst"===t)return 1===n.length?e.reshape([1,n[0],1,1,1]):e.reshape([1,n[3],n[0],n[1],n[2]]);if("channelsLast"===t)return 1===n.length?e.reshape([1,1,1,1,n[0]]):e.reshape([1].concat(n))}else if(4===a){if("channelsFirst"===t)return 1===n.length?e.reshape([1,n[0],1,1]):e.reshape([1,n[2],n[0],n[1]]);if("channelsLast"===t)return 1===n.length?e.reshape([1,1,1,n[0]]):e.reshape([1].concat(n))}else if(3===a){if("channelsFirst"===t)return 1===n.length?e.reshape([1,n[0],1]):e.reshape([1,n[1],n[0]]);if("channelsLast"===t)return 1===n.length?e.reshape([1,1,n[0]]):e.reshape([1].concat(n))}else if(3>a)return e;throw new Zf("Unsupported input rank by biasAdd: "+e.rank)}function ed(a,e,t){return We(function(){return null==t&&(t=ep()),Ip(t),a.add(Jp(a.rank,e,t))})}function td(a,e){if(void 0===e&&(e=1),1!==e)throw new Qf("Support for alpha values other than 1 ("+e+") is not implemented yet.");return Il(a)}function ad(t){return We(function(){return nl(t,os(t).add(1))})}function nd(a,e,t,n){return We(function(){return Yl(a,e,t,n)})}function rd(a){return We(function(){var e=Ju(.5,hl(.2,a));return fs(e,0,1)})}function od(a,e,t){return void 0===t&&(t=!1),t?a():e()}function sd(t){gp(yy,"FanMode",t)}function id(t){gp(by,"Distribution",t)}function pd(o,e){var s,p;if(void 0===e&&(e="channelsLast"),Ip(e),2===o.length)s=o[0],p=o[1];else if(-1===[3,4,5].indexOf(o.length)){var d=Op(o);s=Tf(d),p=Tf(d)}else if("channelsFirst"===e){var a=Op(o,2);s=o[1]*a,p=o[0]*a}else"channelsLast"===e&&(a=Op(o,0,o.length-2),s=o[o.length-2]*a,p=o[o.length-1]*a);return[s,p]}function dd(a,e){return void 0===e&&(e={}),lp(a,Mh.SerializationMap.getMap().classNameMap,e,"initializer")}function ld(t){return pp(t)}function ud(a){if("string"==typeof a){var e=a in Ly?Ly[a]:a;if("GlorotNormal"===e)return new wy;if("GlorotUniform"===e)return new Ey;if("HeNormal"===e)return new Ay;if("HeUniform"===e)return new Dy;if("LeCunNormal"===e)return new _y;if("LeCunUniform"===e)return new Oy;var t={};return t.className=e,t.config={},dd(t)}return a instanceof xy?a:dd(a)}function cd(){return By++}function hd(t){return void 0===t&&(t=""),t in Py||(Py[t]=0),Py[t]+=1,t+Py[t].toString()}function md(t){return Array.isArray(t)&&Array.isArray(t[0])}function gd(t){return 0===t.length?[]:Array.isArray(t[0])?t:[t]}function fd(a){var e;if(Array.isArray(a)){if(1!==a.length)throw new Zf("Expected Tensor length to be 1; got "+a.length);e=a[0]}else e=a;return e}function yd(t){if(Array.isArray(t)&&Array.isArray(t[0])){if(1===t.length)return(t=t)[0];throw new Zf("Expected exactly 1 Shape; got "+t.length)}return t}function bd(a){for(var e=0,o=0,s=a,r;o<s.length;o++)r=s[o],e+=0===r.shape.length?1:r.shape.reduce(function(a,e){return a*e});return e}function xd(a,e){if(a.shape.toString()!==e.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(a.shape)+" vs. "+JSON.stringify(e.shape))}function vd(t){return t.map(function(t){return t.read()})}function Cd(t){t.forEach(function(t){t[0].write(t[1])})}function Sd(a){for(var o=[],t=0,s=a=op(a),r;t<s.length;t++)r=s[t],o.push(r.shape);return rp(o)}function Nd(){return"float32"}function Id(p,e,d){if((null==e||null!=d&&0<d)&&(e=p.sourceLayer,d=p.nodeIndex),0===e.inboundNodes.length)return[p];var u=e.inboundNodes[d];if(0===u.inboundLayers.length)return u.inputTensors;for(var r=[],i=0;i<u.inboundLayers.length;i++)for(var c=0,h=Id(u.inputTensors[i],u.inboundLayers[i],u.nodeIndices[i]),s;c<h.length;c++)s=h[c],-1===r.indexOf(s)&&r.push(s);return r}function kd(a){if(null==a.batchShape&&null==a.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!=a.batchShape&&null!=a.shape)throw new Zf("Please provide either a `shape` or `batchShape` argument to Input, but not both.");var e=a.batchShape;null!=a.shape&&null==e&&(e=[null].concat(a.shape));var r=a.dtype;return null==r&&(r="float32"),new jy({batchInputShape:e,name:a.name,dtype:r,sparse:a.sparse}).inboundNodes[0].outputTensors[0]}function Td(p){return Yi(this,void 0,void 0,function(){var e,d,c,u,h,m,g,f;return Qi(this,function(t){switch(t.label){case 0:if(null==p)return[2];for(u in e=[],d=[],c=[],p)"number"!=typeof(h=p[u])&&(m=h,e.push(m.data()),d.push(u),c.push(m));return 0<e.length?[4,Promise.all(e)]:[3,2];case 1:for(g=t.sent(),f=0;f<g.length;++f)p[d[f]]=g[f][0];ze(c),t.label=2;case 2:return[2];}})})}function Rd(a){if(null!=a)for(var e in a){var t=a[e];"number"!=typeof t&&t.dispose()}}function Ed(a,n){return null==a&&(a={}),a instanceof Xy?[a]:Array.isArray(a)&&a[0]instanceof Xy?a:op(a).map(function(t){return new Jy(t,n)})}function wd(d,e,t,n,r,i,a,o,s){var l=new Qy,u=[new Zy].concat(eb.createCallbacks(e));null!=d&&u.push.apply(u,d),u.push(l);var c=new Yy(u);return c.setParams({epochs:t,initialEpoch:n,samples:r,steps:i,batchSize:a,verbose:e,doValidation:o,metrics:s}),{callbackList:c,history:l}}function Ad(a,e,r){return void 0===e&&(e={}),void 0===r&&(r=!1),lp(a,Mh.SerializationMap.getMap().classNameMap,e,"layer",r)}function Dd(a,o){return We(function(){"float32"!==a.dtype&&(a=a.asType("float32"));var e=Lu(Qp(a),o,!0),t=dn(e.shape,Ji()),n=Fs(al(e,t));return nl(a,n)})}function _d(a,e){return We(function(){return Mu(Qp(gl(e,a)),-1)})}function Od(a,e){return We(function(){return Mu(os(gl(e,a)),-1)})}function zd(a,e){return We(function(){var t=gl(a,e),n=fs(os(a),Ji(),Number.MAX_VALUE),r=os(nl(t,n));return hl(100,Mu(r,-1))})}function Ld(a,e,o){return void 0===o&&(o=!1),We(function(){if(o)e=Ir(e);else{var t=Lu(e,e.shape.length-1,!0);e=nl(e,t)}return e=fs(e,Ji(),1-Ji()),Cs(Lu(hl(a.toFloat(),xs(e)),e.shape.length-1))})}function Fd(a,e){return We(function(){var t=ys(Vp(a)).toInt(),n=(e=fs(e,Ji(),1-Ji())).shape;return Ld(ur(t,n[n.length-1]).reshape(n),e,!1)})}function Bd(a,e){if(!Of.arraysEqual(a.shape,e.shape))throw new Zf("logits and labels must have the same shape, but got shapes "+JSON.stringify(a.shape)+" and "+JSON.stringify(e.shape));return We(function(){var t=e.relu(),n=e.abs().neg();return t.sub(e.mul(a)).add(n.exp().log1p())})}function Pd(a,e){return We(function(){var t;return t=fs(e,Ji(),1-Ji()),t=xs(nl(t,gl(1,t))),Mu(Bd(a,t),-1)})}function Md(a,e){return We(function(){var t=Dd(a,-1),n=Dd(e,-1),r=hl(t,n);return Cs(Lu(r,-1))})}function Wd(a){if("string"==typeof a){if(a in tb)return tb[a];var e="Unknown loss "+a;throw a.toLowerCase().includes("softmaxcrossentropy")&&(e="Unknown loss "+a+". Use \"categoricalCrossentropy\" as the string name for tf.losses.softmaxCrossEntropy"),new Zf(e)}return a}function Vd(a,e){return We(function(){var t=hl(.5,xn(e)),n=Pp(Vu(e,t),a.dtype);return Mu(Uu(a,n),-1)})}function Ud(a,e){return We(function(){return Pp(Uu(Du(a,-1),Du(e,-1)),"float32")})}function Gd(a,e){return We(function(){return xl(a.equal(1),e.equal(1)).sum().cast("float32")})}function qd(a,e){return We(function(){return xl(a.equal(1),e.equal(0)).sum().cast("float32")})}function Hd(a,e){return We(function(){return xl(a.equal(0),e.equal(1)).sum().cast("float32")})}function Kd(a,e){return We(function(){var t=Gd(a,e),n=Hd(a,e),r=t.add(n);return El(Vu(r,0),t.div(r),0).cast("float32")})}function jd(a,e){return We(function(){var t=Gd(a,e),n=qd(a,e),r=t.add(n);return El(Vu(r,0),t.div(r),0).cast("float32")})}function $d(a,e){return Pd(a,e)}function Xd(a,n){return a.rank===n.rank&&(a=a.squeeze([a.rank-1])),(n=n.argMax(-1)).dtype!==a.dtype&&(n=n.asType(a.dtype)),Uu(a,n).asType("float32")}function Yd(t){if("string"==typeof t&&t in rb)return rb[t];if("string"!=typeof t&&null!=t)return t;throw new Zf("Unknown metric "+t)}function Zd(s){if(ap(null!==s,"Unknown LossOrMetricFn "+s),"string"==typeof s)return s;for(var e=void 0,p=0,d=Object.keys(tb),r;p<d.length;p++)if(r=d[p],tb[r]===s){e=r;break}if(void 0!==e)return e;for(var l=0,u=Object.keys(rb);l<u.length;l++)if(r=u[l],rb[r]===s){e=r;break}return void 0===e?s.name:e}function Qd(a){var e={Adagrad:function(){return tf.adagrad(.01)},Adadelta:function(){return tf.adadelta(1,.95,Ji())},Adam:function(){return tf.adam(.001,.9,.999,Ji())},Adamax:function(){return tf.adamax(.002,.9,.999,Ji(),0)},RMSProp:function(){return tf.rmsprop(.001,.9,0,Ji())},SGD:function(){return tf.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,a in e)return e[a]();throw new Zf("Unknown Optimizer "+a)}function Jd(d,h,e,m){void 0===m&&(m=console.log);var g=Ml(d),a=["Layer (type)","Output shape","Param #"],o;if(g?(h=h||65,e=e||[.45,.85,1]):(h=h||98,e=e||[.33,.55,.67,1]),1>=e[e.length-1]&&(e=e.map(function(t){return Cf(h*t)})),!g)for(var f in a.push("Receives inputs"),o=[],d.nodesByDepth)o.push.apply(o,d.nodesByDepth[f]);m("_".repeat(h)),Jl(a,e,m),m("=".repeat(h));for(var s=d.layers,l=0;l<s.length;++l)g?eu(s[l],e,m):tu(s[l],e,o,m),m((l==s.length-1?"=":"_").repeat(h));d.checkTrainableWeightsConsistency();var y=Fl(d),c=bd(d.nonTrainableWeights);m("Total params: "+(y+c)),m("Trainable params: "+y),m("Non-trainable params: "+c),m("_".repeat(h))}function Fl(t){return null==t.collectedTrainableWeights?bd(t.trainableWeights):bd(t.collectedTrainableWeights)}function Ml(m){var e=!0,g=[],n=[];for(var r in m.nodesByDepth)g.push(m.nodesByDepth[r]);for(var i=0,f=g,o;i<f.length;i++){if(o=f[i],1<o.length||1===o.length&&1<o[0].inboundLayers.length){e=!1;break}n.push.apply(n,o)}if(e)for(var y=0,b=m.layers;y<b.length;y++){for(var u=!1,x=0,v=b[y].inboundNodes,h;x<v.length;x++)if(h=v[x],-1!==n.indexOf(h)){if(u){e=!1;break}u=!0}if(!e)break}return e}function Jl(a,e,t){void 0===t&&(t=console.log);for(var o="",s=0;s<a.length;++s)0<s&&(o=o.slice(0,o.length-1)+" "),o=(o+=a[s]).slice(0,e[s]),o+=" ".repeat(e[s]-o.length);t(o)}function eu(a,e,t){var n;try{n=JSON.stringify(a.outputShape)}catch(t){n="multiple"}Jl([a.name+" ("+a.getClassName()+")",n,a.countParams().toString()],e,t)}function tu(m,e,t,n){var r;try{r=JSON.stringify(m.outputShape)}catch(t){r="multiple"}for(var y=[],a=0,b=m.inboundNodes,s;a<b.length;a++)if(s=b[a],!(null!=t&&0<t.length&&-1===t.indexOf(s)))for(var x=0;x<s.inboundLayers.length;++x){var v=s.inboundLayers[x].name,c=s.nodeIndices[x],p=s.tensorIndices[x];y.push(v+"["+c+"]["+p+"]")}var h=m.name,d=m.getClassName(),f=0===y.length?"":y[0];for(Jl([h+" ("+d+")",r,m.countParams().toString(),f],e,n),x=1;x<y.length;++x)Jl(["","","",y[x]],e,n)}function nu(a,e,t){return("inboundNodes"===a||"outputLayers"===a||"inputLayers"===a)&&0===e&&"string"==typeof t}function bu(d,e){if(null===d)return null;if("string"==typeof d)return ip(d);if("number"==typeof d||"boolean"==typeof d)return d;if(d instanceof Array){for(var t=[],n=d.length,r=0,h;r<n;++r)h=d[r],nu(e,r,h)?t.push(h):t.push(bu(h,e));return t}for(var m={},o=0,g=Object.keys(d);o<g.length;o++){var l=g[o],u=d[l];if("name"===l&&"string"==typeof u)m[l]=u;else{var c=ip(l);m[c]=bu(u,c)}}return m}function xu(d,e){if(null===d||void 0===d)return null;if("string"==typeof d)return sp(d);if("number"==typeof d||"boolean"==typeof d)return d;if(d instanceof Array){for(var t=[],n=d.length,r=0,h;r<n;++r)h=d[r],nu(e,r,h)?t.push(h):t.push(xu(h,e));return t}for(var m={},o=0,g=Object.keys(d);o<g.length;o++){var l=g[o],u=d[l],c=sp(l);m[c]="name"!==l&&"className"!==l||"string"!=typeof u?xu(u,l):u}return m}function Au(a,e){if(null==a.dtype||a.dtype===e.dtype)return e;try{return er(e,a.dtype)}catch(t){throw new Zf("The dtype of the feed ("+e.dtype+") can not be cast to the dtype of the key '"+a.name+"' ("+a.dtype+").")}}function dc(F,e,t,B){for(var r=null!=t&&t.training,i=Array.isArray(F),a=i?F:[F],o=a.map(function(t){return t.name}),s=[],l=e.names(),u=0,P=o,p;u<P.length;u++)p=P[u],-1===l.indexOf(p)?s.push(null):s.push(e.getValue(p));null!=B&&(B.maxNumTensors=-1/0,B.minNumTensors=1/0);var W=o.join(",")+"|"+e.names().join(","),g,V;if(null==ib[W]){var U=yc(a,e);g=U.sorted,V=U.recipientCounts,ib[W]=g,pb[W]=V}g=ib[W],V={},r||Object.assign(V,pb[W]);for(var m=new sb(e),y=0;y<g.length;++y){if(null!=B){var G=Pe().numTensors;G>B.maxNumTensors&&(B.maxNumTensors=G),G<B.minNumTensors&&(B.minNumTensors=G)}var b=g[y],w=b.sourceLayer;if(!(w instanceof jy)){for(var z=[],S=[],A=[],_=!1,q=0,H=b.inputs;q<H.length;q++){var E=H[q],N=m.getValue(E),k=m.getMask(E);z.push(N),S.push(k),null!=k&&(_=!0),r||(V[E.name]--,0!==V[E.name]||e.hasKey(E)||-1!==o.indexOf(E.name)||N.isDisposed||!0===E.sourceLayer.stateful||A.push(N))}_&&((t=t||{}).mask=S[0]);var L=op(w.apply(z,t)),x=null;w.supportsMasking&&(x=w.computeMask(z,S));for(var K=Lc(b),D=Array.isArray(K)?K:[K],O=0;O<D.length;++O){m.hasKey(D[O])||m.add(D[O],L[O],Array.isArray(x)?x[0]:x);var j=o.indexOf(D[O].name);-1!==j&&(s[j]=L[O])}r||ze(A)}}return m.disposeMasks(),i?s:s[0]}function yc(m,e){Of.assert(null!=m&&0<m.length,function(){return"Expected at least one fetch, got none"});var t=[],y={};if(1===m.length){var b=zc(m[0],e);t=b.sorted,y=b.recipientMap}else for(var i=new Set,a=0,x=m;a<x.length;a++){for(var s=zc(x[a],e),l=s.sorted,u=s.recipientMap,c=0,v=l,h;c<v.length;c++)h=v[c],i.has(h.name)||(t.push(h),i.add(h.name));var C=function(a){null==y[a]&&(y[a]=new Set),u[a].forEach(function(e){return y[a].add(e)})};for(var f in u)C(f)}return{sorted:t,recipientCounts:Ac(y)}}function Ac(a){var e={};for(var t in a)e[t]=a[t].size;return e}function zc(m,e){for(var t=new Set,n=[],r={},i=0,g=e.names(),o;i<g.length;i++)o=g[i],t.add(o);var y=[],l=[];for(y.push(m);0<y.length;){var u=y[y.length-1];if(t.has(u.name))y.pop();else{var c=l[l.length-1]===y.length-1;if(0===u.inputs.length||c)y.pop(),n.push(u),t.add(u.name),c&&l.pop();else{l.push(y.length-1);for(var p=0,b=u.inputs,d;p<b.length;p++)d=b[p],null==r[d.name]&&(r[d.name]=new Set),r[d.name].add(u.name),t.has(d.name)||y.push(d)}}}return{sorted:n,recipientMap:r}}function Lc(o){var e;if(1===o.sourceLayer.inboundNodes.length)e=o.sourceLayer.output;else{for(var s=null,p=0;p<o.sourceLayer.inboundNodes.length;++p)for(var d=0,l=o.sourceLayer.inboundNodes[p].outputTensors;d<l.length;d++)if(l[d].id===o.id){s=p;break}e=o.sourceLayer.getOutputAt(s)}return e}function Bc(a,e,t){var n=e.length;if(null==a||Array.isArray(a)&&0===a.length)return e.map(function(){return null});if(1===n)return Array.isArray(a)&&1===a.length?a:"object"==typeof a&&e[0]in a?[a[e[0]]]:[a];if(Array.isArray(a)){if(a.length!==n)throw new Error("Provided "+t+" is an array of "+a.length+" element(s), but the model has "+n+" outputs. Make sure a set of weights is provided for each model output.");return a}if("object"==typeof a&&0<Object.keys(a).length&&"object"==typeof a[Object.keys(a)[0]]){var r=[];return e.forEach(function(e){e in a?r.push(a[e]):r.push(null)}),r}throw new Error("The model has multiple ("+n+") outputs, so "+t+" must be either an array with "+n+" elements or an object with "+e+" keys. Provided "+t+" not understood: "+JSON.stringify(a))}function Pc(a,e){return Bc(a,e,"classWeight")}function Vc(a,e,t,n){return Yi(this,void 0,void 0,function(){var r,p,d,c,h;return Qi(this,function(o){switch(o.label){case 0:if(null!=e||null!=n)throw new Error("Support sampleWeight is not implemented yet");return null==t?[3,2]:(r=We(function(){if(1===a.shape.length)return a.clone();if(2===a.shape.length){if(1<a.shape[1])return a.argMax(1);if(1===a.shape[1])return a.reshape([a.shape[0]]);throw new Error("Encountered unexpected last-dimension size ("+a.shape[1]+") during handling of class weights. The size is expected to be >= 1.")}throw new Error("Unexpected rank of target (y) tensor ("+a.rank+") during handling of class weights. The rank is expected to be 1 or 2.")}),c=(d=Array).from,[4,r.data()]);case 1:return p=c.apply(d,[o.sent()]),ze(r),h=[],p.forEach(function(a){if(null==t[a])throw new Error("classWeight must contain all classes in the training data. The class "+a+" exists in the data but not in classWeight");h.push(t[a])}),[2,en(h,"float32")];case 2:return[2,null];}})})}function Uc(a,e){return hl(a,e)}function Gc(d,e){var t=e,i,h;i=t.xs,h=t.ys,Of.assert(null!=i&&null!=h,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 m=Kc("input",d.inputNames,i),a=Kc("output",d.outputNames,h),o=m[0].shape[0];Of.assert(m.length===d.inputs.length,function(){return"LayersModel has "+d.inputs.length+" inputs, but the dataset provides "+m.length+" inputs.  (Expected input keys: "+JSON.stringify(d.inputNames)+")"}),Of.assert(a.length===d.outputs.length,function(){return"LayersModel has "+d.outputs.length+" outputs, but the dataset provides "+a.length+" outputs.  (Expected output keys: "+JSON.stringify(d.outputNames)+")"});var s=function(e){Of.assert(m[e].shape[0]===o,function(){return"Batch size mismatch: input "+d.inputNames[e]+" has "+m[e].shape[0]+"; expected  "+o+" based on input "+d.inputNames[0]+"."})};for(var l in m)s(l);var u=function(e){Of.assert(a[e].shape[0]===o,function(){return"Batch size mismatch: output "+d.outputNames[e]+" has "+a[e].shape[0]+"; expected  "+o+" based on input "+d.inputNames[0]+"."})};for(var c in a)u(c);return{xs:m,ys:a}}function Kc(s,e,t){if(t instanceof Lf)return[t];if(Array.isArray(t))return Of.assert(t.length===e.length,function(){return"Received an array of "+t.length+" Tensors, but expected "+e.length+" to match the "+s+" keys "+e+"."}),t;for(var n=[],r=0,p=e,a;r<p.length;r++){if(a=p[r],null==t[a])throw new Zf("The feature data generated by the dataset lacks the required "+s+" key '"+a+"'.");n.push(t[a])}return n}function jc(t){if(3===t.length)throw new Qf("Validation with sample weights is not implemented yet.");return{xs:t[0],ys:t[1]}}function Qc(F,e,t){return Yi(this,void 0,void 0,function(){var n,B,W,V,U,G,q,H,K,j,$,X,Y,Z,Q,J,ee,te,ae,ne,re,oe,se,ie,pe,de,le,P,ue,ce,he,me,ge,fe;return Qi(this,function(a){switch(a.label){case 0:if(n=null!=t.batchesPerEpoch,Of.assert(null!=F.optimizer,function(){return"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."}),Of.assert(null!=t,function(){return"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."}),Of.assert(null!=t.epochs&&0<t.epochs&&Nf(t.epochs),function(){return"For fitDataset(), config.epochs is expected to be a positive integer, but got "+t.epochs}),Of.assert(!n||0<t.batchesPerEpoch&&Nf(t.batchesPerEpoch),function(){return"For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got "+t.batchesPerEpoch}),Of.assert(null==t.validationSplit,function(){return"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."}),F.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");F.isTraining=!0,a.label=1;case 1:return a.trys.push([1,,26,27]),B=null!=t.validationData,W=void 0,V=void 0,B&&(ah(t.validationData)?Of.assert(null==t.validationBatches||0<t.validationBatches&&Nf(t.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 "+t.validationBatches}):(U=jc(t.validationData),W=U.xs,V=U.ys)),G=F.makeTrainFunction(),q=F.getDedupedMetricsNames(),H=void 0,H=B?q.slice().concat(q.map(function(t){return"val_"+t})):q.slice(),K=Ed(t.callbacks,t.yieldEvery),j=null==t.verbose?1:t.verbose,$=wd(K,j,t.epochs,null,null,Jc(e,t),null,B,H),X=$.callbackList,Y=$.history,X.setModel(F),F.history=Y,[4,X.onTrainBegin()];case 2:return a.sent(),F.stopTraining_=!1,Z=null==t.initialEpoch?0:t.initialEpoch,[4,e.iterator()];case 3:Q=a.sent(),a.label=4;case 4:return Z<t.epochs?(J={},[4,X.onEpochBegin(Z)]):[3,23];case 5:return a.sent(),ee=0,te=0,n?[3,7]:[4,e.iterator()];case 6:Q=a.sent(),a.label=7;case 7:return!n||ee<t.batchesPerEpoch?[4,Q.next()]:[3,21];case 8:return ae=a.sent(),n&&ae.done?(console.warn("You provided `batchesPerEpoch` as "+t.batchesPerEpoch+", but your dataset iterator ran out of data after "+ee+" batches; interrupting training. Make sure that your dataset can generate at least `batchesPerEpoch * epochs` batches (in this case, "+t.batchesPerEpoch*t.epochs+" batches). You may need to use the repeat() function when building your dataset."),[3,21]):null==ae.value?[3,15]:(ne=Gc(F,ae.value),re=ne.xs,oe=ne.ys,(se={}).batch=te,se.size=re[0].shape[0],[4,X.onBatchBegin(te,se)]);case 9:if(a.sent(),ie=[],null==t.classWeight)return[3,13];pe=Pc(t.classWeight,F.outputNames),fe=0,a.label=10;case 10:return fe<pe.length?(le=(de=ie).push,[4,Vc(oe[fe],null,pe[fe])]):[3,13];case 11:le.apply(de,[a.sent()]),a.label=12;case 12:return++fe,[3,10];case 13:for(P=re.concat(oe).concat(ie),ue=G(P),ze(P),fe=0;fe<q.length;++fe)ce=q[fe],he=ue[fe],se[ce]=he,Ve(he);return[4,X.onBatchEnd(te,se)];case 14:a.sent(),Rd(se),te++,ee++,a.label=15;case 15:return(n?ee>=t.batchesPerEpoch:ae.done)?B?(me=void 0,ah(t.validationData)?(ge=op,[4,F.evaluateDataset(t.validationData,{batches:t.validationBatches})]):[3,17]):[3,19]:[3,20];case 16:return me=ge.apply(void 0,[a.sent()]),[3,18];case 17:me=op(F.evaluate(W,V,{batchSize:null==t.validationBatchSize?32:t.validationBatchSize,verbose:0})),a.label=18;case 18:for(fe=0;fe<F.metricsNames.length;++fe)J["val_"+F.metricsNames[fe]]=me[fe];a.label=19;case 19:return[3,21];case 20:return F.stopTraining_?[3,21]:[3,7];case 21:return[4,X.onEpochEnd(Z,J)];case 22:return a.sent(),Z++,F.stopTraining_?[3,23]:[3,4];case 23:return[4,X.onTrainEnd()];case 24:return a.sent(),[4,F.history.syncData()];case 25:return a.sent(),[2,F.history];case 26:return F.isTraining=!1,[7];case 27:return[2];}})})}function Jc(a,e){var t=null;return null==e.batchesPerEpoch?hf(a.size)&&(t=a.size):t=e.batchesPerEpoch,t}function ah(t){return"function"==typeof t.iterator}function nh(t){return"function"==typeof t.next}function rh(m,e,g){return Yi(this,void 0,void 0,function(){var n,t,f,y,b,x,v,C,d,S;return Qi(this,function(a){switch(a.label){case 0:if(n=null!=(g=g||{}).batches,t=m.testFunction,f=[],0<g.verbose)throw new Qf("Verbose mode is not implemented yet.");return Of.assert(!n||0<g.batches&&Nf(g.batches),function(){return"Test loop expects `batches` to be a positive integer, but received "+JSON.stringify(g.batches)}),nh(e)?(b=e,[3,3]):[3,1];case 1:return[4,e.iterator()];case 2:b=a.sent(),a.label=3;case 3:y=b,x=0,v=0,C=function(){var e;return Qi(this,function(t){switch(t.label){case 0:return[4,y.next()];case 1:return e=t.sent(),f=We(function(){if(e.value){var a=Gc(m,e.value),n=a.xs,r=a.ys,o=n.concat(r),s=We(function(){return t(o)});if(ze(o),0===v)for(var i=0;i<s.length;++i)f.push(Da(0));var l=o[0].shape[0],u=function(a){var e=s[a],t=f[a];f[a]=We(function(){return Ju(f[a],hl(l,e))}),0<v&&ze(t)};for(i=0;i<s.length;++i)u(i);ze(s),x+=l,++v}return f}),e.done?(n&&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, "+g.batches+" batches). You may need to use the repeat() function when building your dataset."),[2,"break"]):[2];}})},a.label=4;case 4:return!n||v<g.batches?[5,C()]:[3,6];case 5:return"break"===a.sent()?[3,6]:[3,4];case 6:for(d=0;d<f.length;++d)S=f[d],f[d]=nl(f[d],x),ze(S);return[2,rp(f)];}})})}function oh(t){Of.assert(0<t&&Nf(t),function(){return"batchSize is required to be a positive integer, but got "+t})}function sh(a,r,t){return null==a?[null]:Array.isArray(a)?a.map(function(a){return Gp(a,r,t-r)}):Gp(a,r,t-r)}function ih(a,n){return We(function(){return null==a?null:Array.isArray(a)?a.map(function(t){return ih(t,n)}):Zp(a,"int32"===n.dtype?n:n.toInt())})}function dh(a,e){for(var t=[],n=0,o=null;n<a;)(o=n+e)>=a&&(o=a),t.push([n,o]),n=o;return t}function lh(x,e,t,n,r,C,N,I,s,l,u,k,p,T,d){return Yi(this,void 0,void 0,function(){var i,c,R,a,E,o,h,f;return Qi(this,function(m){switch(m.label){case 0:if(null==r&&(r=32),null==C&&(C=1),null==u&&(u=!0),null==p&&(p=0),i=!1,null!=s&&null!=l&&(i=!0),null!=d&&(i=!0,null==T))throw new Zf("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");return null!=(c=x.checkNumSamples(t,r,T,"steps_per_epoch"))&&(R=Bp(0,c)),null==N&&(N=1),a=wd(I,N,C,p,c,T,r,i,k),E=a.callbackList,o=a.history,E.setModel(x),x.history=o,[4,E.onTrainBegin()];case 1:m.sent(),x.stopTraining_=!1,h=function(d){var a,g,C,m,y;return Qi(this,function(o){switch(o.label){case 0:return[4,E.onEpochBegin(d)];case 1:if(o.sent(),a={},null==T)return[3,2];throw new Qf("stepsPerEpoch mode is not implemented yet.");case 2:if("batch"===u)throw new Qf("batch shuffling is not implemneted yet");u&&Of.shuffle(R),g=en(R),C=dh(c,r),m=function(o){var p;return Qi(this,function(d){switch(d.label){case 0:return p={},[4,E.onBatchBegin(o,p)];case 1:return d.sent(),We(function(){var u=C[o][0],c=C[o][1],d=Gp(g,u,c-u);p.batch=o,p.size=c-u;for(var h=ih(t,d),m=e(h),f=0;f<n.length;++f){var y=n[f],S=m[f];p[y]=S,Ve(S)}if(o===C.length-1&&i){var N=x.testLoop(s,l,r);for(f=0;f<n.length;++f)y=n[f],S=N[f],Ve(S),a["val_"+y]=S}}),[4,E.onBatchEnd(o,p)];case 2:return d.sent(),Rd(p),x.stopTraining_?[2,"break"]:[2];}})},y=0,o.label=3;case 3:return y<C.length?[5,m(y)]:[3,6];case 4:if("break"===o.sent())return[3,6];o.label=5;case 5:return++y,[3,3];case 6:g.dispose(),o.label=7;case 7:return[4,E.onEpochEnd(d,a)];case 8:return o.sent(),x.stopTraining_?[2,"break"]:[2];}})},f=p,m.label=2;case 2:return f<C?[5,h(f)]:[3,5];case 3:if("break"===m.sent())return[3,5];m.label=4;case 4:return++f,[3,2];case 5:return[4,E.onTrainEnd()];case 6:return m.sent(),[4,x.history.syncData()];case 7:return m.sent(),[2,x.history];}})})}function uh(x,e,t,n){return void 0===n&&(n={}),Yi(this,void 0,void 0,function(){var r,N,k,T,R,E,D,O,L,F,B,P,M,W,V,U,G,q,H,K,j,$;return Qi(this,function(a){switch(a.label){case 0:if(x.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");x.isTraining=!0,a.label=1;case 1:return a.trys.push([1,,7,8]),oh(O=null==n.batchSize?32:n.batchSize),L=!1,[4,x.standardizeUserData(e,t,n.sampleWeight,n.classWeight,L,O)];case 2:if(F=a.sent(),r=F[0],N=F[1],D=F[2],B=!1,P=void 0,!(null!=n.validationData&&0<n.validationData.length))return[3,4];if(B=!0,2!==n.validationData.length)throw 3===n.validationData.length?new Qf("validationData including sample weights is not supported yet."):new Zf("When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; "+n.validationData+" is invalid.");return k=n.validationData[0],T=n.validationData[1],M=!0,[4,x.standardizeUserData(k,T,null,null,M,O)];case 3:return W=a.sent(),R=W[0],E=W[1],P=R.concat(E),[3,5];case 4:null!=n.validationSplit&&0<n.validationSplit&&1>n.validationSplit?(B=!0,V=Cf(r[0].shape[0]*(1-n.validationSplit)),U=r[0].shape[0],R=sh(r,V,U),r=sh(r,0,V),E=sh(N,V,U),N=sh(N,0,V),P=R.concat(E)):null!=n.validationSteps&&(B=!0),a.label=5;case 5:return G=r.concat(N).concat(D),x.checkTrainableWeightsConsistency(),q=x.makeTrainFunction(),H=x.getDedupedMetricsNames(),K=void 0,j=void 0,B?(x.makeTestFunction(),K=x.testFunction,j=H.slice().concat(H.map(function(t){return"val_"+t}))):(K=null,P=[],j=H.slice()),$=Ed(n.callbacks,n.yieldEvery),[4,lh(x,q,G,H,O,n.epochs,n.verbose,$,K,P,n.shuffle,j,n.initialEpoch,null,null)];case 6:return[2,a.sent()];case 7:return x.isTraining=!1,mh(r,e),mh(N,t),mh(R,k),mh(E,T),null!=D&&ze(D),[7];case 8:return[2];}})})}function ch(a){var o=[];a instanceof Lf&&(a=[a]);for(var t=0,s;t<a.length;++t)if(s=a[t],1===s.rank)o.push(Mp(s,1));else{if(0===s.rank)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");o.push(s)}return o}function mh(p,e){if(null!=p){var t=[];if(e instanceof Lf)t.push(e.id);else if(Array.isArray(e))e.forEach(function(a){return t.push(a.id)});else if(null!=e)for(var n in e){var r=e[n];t.push(r.id)}var i=[];if(p instanceof Lf)-1===t.indexOf(p.id)&&i.push(p);else if(Array.isArray(p))p.forEach(function(a){-1===t.indexOf(a.id)&&i.push(a)});else if(null!=p)for(var a in p){var o=p[a];-1===t.indexOf(o.id)&&i.push(o)}i.forEach(function(t){t.isDisposed||t.dispose()})}}function gh(t){return t instanceof Lf}function bh(t){return Array.isArray(t)}function vh(t){return!gh(t)&&!bh(t)}function Ch(m,y,t,n,b){if(void 0===n&&(n=!0),void 0===b&&(b=""),null==y||0===y.length){if(null!=m){var x=!1;if(bh(m)&&0<m.length)x=!0;else if(vh(m)){for(var v in m)if(m.hasOwnProperty(v)){x=!0;break}}else x=!0;if(x)throw new Zf("Error when checking model "+b+" expected no data, but got "+m)}return[]}if(null==m)return y.map(function(){return null});var o;if(vh(m)){m=m,o=[];for(var C=0,S=y,u;C<S.length;C++){if(u=S[C],null==m[u])throw new Zf("No data provided for \""+u+"\". Need data for each key in: "+y);o.push(m[u])}}else if(bh(m)){if((m=m).length!==y.length)throw new Zf("Error when checking model "+b+": the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see "+y.length+" Tensor(s), but instead got the following list of Tensor(s): "+m);o=m}else{if(m=m,1<y.length)throw new Zf("The model "+b+" expects "+y.length+" Tensor(s), but only received one Tensor. Found: Tensor with shape "+m.shape);o=[m]}if(o=ch(o),null!=t)for(var N=0;N<y.length;++N)if(null!=t[N]){var I=o[N];if(I.shape.length!==t[N].length)throw new Zf("Error when checking "+b+": expected "+y[N]+" to have "+t[N].length+" dimension(s). but got array with shape "+I.shape);for(var h=0;h<t[N].length;++h)if(0!=h||n){var k=I.shape[h],f=t[N][h];if(null!=f&&0<=f&&k!==f)throw new Zf("Error when checking "+b+": expected "+y[N]+" to have shape ["+t[N]+"], but got array with shape ["+I.shape+"].")}}return o}function Sh(a,e){var t=hp(a.map(function(t){return t.shape[0]}));t.sort();var n=hp(e.map(function(t){return t.shape[0]}));if(n.sort(),1<t.length)throw new Zf("All input Tensors (x) should have the same number of samples. Got array shapes: "+JSON.stringify(a.map(function(t){return t.shape})));if(1<n.length)throw new Zf("All target Tensors (y) should have the same number of samples. Got array shapes: "+JSON.stringify(e.map(function(t){return t.shape})));if(0<t.length&&0<n.length&&!Of.arraysEqual(t,n))throw new Zf("Input Tensors should have the same number of samples as target Tensors. Found "+t[0]+" input sample(s) and "+n[0]+" target sample(s).")}function Rh(d,e,t){for(var n=[_d,Pd,Ld],r=0;r<d.length;++r){var m=d[r],a=e[r],o=t[r];if(null!=a){if(a===Ld&&1===m.shape[m.shape.length-1])throw new Zf("You are passing a target array of shape "+m.shape+" while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].");if(-1!==n.indexOf(a))for(var s=m.shape.slice(1),l=o.slice(1),u=0;u<s.length;++u){var g=s[u],p=l[u];if(null!=p&&g!==p)throw new Zf("A target Tensor with shape "+m.shape+" was passed for an output of shape "+o+", while using a loss function that expects targets to have the same shape as the output.")}}}}function wh(p,e,t,n,d){var h;if(void 0===n&&(n=!0),void 0===d&&(d=""),Array.isArray(p)){if(p.length!==e.length)throw new Zf("Error when checking model "+d+": 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 "+p.length+" Tensors(s).");h=p}else{if(1<e.length)throw new Zf("The model expects "+e.length+" "+d+" Tensors, but only received one Tensor. Found: array with shape "+JSON.stringify(p.shape)+".");h=[p]}if(null!=t)for(var m=0;m<e.length;++m)if(null!=t[m]){var g=h[m];if(g.shape.length!==t[m].length)throw new Zf("Error when checking "+d+": expected "+e[m]+" to have "+t[m].length+" dimension(s), but got array with shape "+JSON.stringify(g.shape));for(var s=0;s<t[m].length;++s)if(0!=s||n){var f=g.shape[s],u=t[m][s];if(null!=u&&u!==f)throw new Zf("Error when checking "+d+": expected "+e[m]+" to have shape "+JSON.stringify(t[m])+" but got array with shape "+JSON.stringify(g.shape)+".")}}}function zh(p,e){if(null==p||Array.isArray(p)&&0===p.length)return e.map(function(){return[]});var t;if("string"==typeof p||"function"==typeof p)t=[p];else{if(!Array.isArray(p)&&"object"!=typeof p)throw new TypeError("Type of metrics argument not understood. Expected an string,function, Array, or Object, found: "+p);t=p}if(Array.isArray(t))return e.map(function(){return t});for(var d=[],r=0,l=e;r<l.length;r++){var a=l[r],o=t.hasOwnProperty(a)?t[a]:[];Array.isArray(o)||(o=[o]),d.push(o)}return d}function Bh(a,r){return Yi(this,void 0,void 0,function(){var e;return Qi(this,function(){if(null==r&&(r={}),"string"==typeof a){if(0===(e=kh.getLoadHandlers(a,r.onProgress)).length)e.push(kh.browserHTTPRequest(a,r));else if(1<e.length)throw new Zf("Found more than one ("+e.length+") load handlers for URL '"+a+"'");a=e[0]}return[2,Vh(a,void 0,r)]})})}function Vh(d,e,t){return Yi(this,void 0,void 0,function(){var n,m,g,f,y,b,x,v,C;return Qi(this,function(a){switch(a.label){case 0:if(null==t&&(t={}),null==d.load)throw new Zf("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");return[4,d.load()];case 1:if(n=a.sent(),null!=(m=n.modelTopology).model_config&&(m=m.model_config),g=null==t.strict||t.strict,f=null!=n.weightData&&null!=n.weightSpecs&&g,y=Ad(bu(m),e,f),null!=(b=n.trainingConfig)&&y.loadTrainingConfig(b),null==n.weightData)return[3,4];if(null==n.weightSpecs)throw new Zf("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");return x=Uh(n.weightData,n.weightSpecs),v=x.modelWeights,C=x.optimizerWeights,y.loadWeights(v,g),null!=y.optimizer&&0<C.length?[4,y.optimizer.setWeights(C)]:[3,3];case 2:a.sent(),a.label=3;case 3:ze(v),ze(C.map(function(t){return t.tensor})),a.label=4;case 4:return[2,y];}})})}function Uh(a,e){var t=kh.decodeWeights(a,e),n={},r=[];return e.forEach(function(a){"optimizer"===a.group?r.push({name:a.name,tensor:t[a.name]}):n[a.name]=t[a.name]}),{modelWeights:n,optimizerWeights:r}}function Hh(a,e){return null==e&&(e={}),Bh(a,e)}function em(t){return t.getClassName()}function tm(a,e){return void 0===e&&(e={}),lp(a,Mh.SerializationMap.getMap().classNameMap,e,"activation")}function am(a){var e;return null==a?tm(e={className:"linear",config:{}}):"string"==typeof a?((e={}).className=a,e.config={},tm(e)):a instanceof cb?a:tm(a)}function nm(t){return new Tb({l1:null==t?null:t.l1,l2:0})}function rm(t){return new Tb({l2:null==t?null:t.l2,l1:0})}function om(t){return pp(t)}function sm(a,e){return void 0===e&&(e={}),lp(a,Mh.SerializationMap.getMap().classNameMap,e,"regularizer")}function im(t){return null==t?null:"string"==typeof t?sm({className:t in Rb?Rb[t]:t,config:{}}):t instanceof kb?t:sm(t)}function pm(a,e,t){if("number"==typeof a)return tp(a,e);if(a.length!==e)throw new Zf("The "+t+" argument must be an integer or tuple of "+e+" integers. Received: "+a.length+" elements.");for(var n=0,o;n<e;++n)if(o=a[n],!_p(o))throw new Zf("The "+t+" argument must be an integer or tuple of "+e+" integers. Received: "+JSON.stringify(a)+" including a non-integer number "+o);return a}function dm(o,e,t,n,r){return void 0===r&&(r=1),null==o?o:(s="same"===t?o:o-(e+(e-1)*(r-1))+1,Cf((s+n-1)/n));var s}function lm(a,o,t,n){if(null==a)return null;if("valid"===n)a=a*o+Fp([t-o,0]);else{if("same"!==n)throw new Zf("Unsupport padding mode: "+n+".");a*=o}return a}function um(a,e){return We(function(){return Ip(e),"channelsFirst"===e?Tl(a,[0,2,3,1]):a})}function cm(a,e){return We(function(){return Ip(e),"channelsFirst"===e?Tl(a,[0,2,3,4,1]):a})}function hm(p,d,t,n,l,u,c){return void 0===n&&(n=1),void 0===l&&(l="valid"),void 0===c&&(c=1),We(function(){if(null==u&&(u=ep()),Ip(u),3!==p.shape.length)throw new Zf("The input of a conv1dWithBias operation should be 3, but is "+p.shape.length+" instead.");if(3!==d.shape.length)throw new Zf("The kernel for a conv1dWithBias operation should be 3, but is "+d.shape.length+" instead");if(null!=t&&1!==t.shape.length)throw new Zf("The bias for a conv1dWithBias operation should be 1, but is "+d.shape.length+" instead");if("channelsFirst"===u&&(p=Tl(p,[0,2,1])),"causal"===l)throw new Qf("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");var e=Zs(p,d,n,"same"===l?"same":"valid","NWC",c);return null!=t&&(e=ed(e,t)),e})}function mm(p,e,t,n,d,l,u){return void 0===n&&(n=[1,1]),void 0===d&&(d="valid"),We(function(){if(null==l&&(l=ep()),Ip(l),3!==p.rank&&4!==p.rank)throw new Zf("conv2dWithBias expects input to be of rank 3 or 4, but received "+p.rank+".");if(3!==e.rank&&4!==e.rank)throw new Zf("conv2dWithBias expects kernel to be of rank 3 or 4, but received "+p.rank+".");var a=um(p,l);if("causal"===d)throw new Qf("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return a=ru(a,e,n,"same"===d?"same":"valid","NHWC",u),null!=t&&(a=ed(a,t)),"channelsFirst"===l&&(a=Tl(a,[0,3,1,2])),a})}function gm(p,e,t,n,d,l,u){return void 0===n&&(n=[1,1,1]),void 0===d&&(d="valid"),We(function(){if(null==l&&(l=ep()),Ip(l),4!==p.rank&&5!==p.rank)throw new Zf("conv3dWithBias expects input to be of rank 4 or 5, but received "+p.rank+".");if(4!==e.rank&&5!==e.rank)throw new Zf("conv3dWithBias expects kernel to be of rank 4 or 5, but received "+p.rank+".");var a=cm(p,l);if("causal"===d)throw new Qf("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return a=ou(a,e,n,"same"===d?"same":"valid","NDHWC",u),null!=t&&(a=ed(a,t)),"channelsFirst"===l&&(a=Tl(a,[0,4,1,2,3])),a})}function fm(s,e,t,p,d,l){return void 0===t&&(t=[1,1]),void 0===p&&(p="valid"),We(function(){null==d&&(d=ep()),Ip(d);var a=um(s,d);if(4!==s.rank)throw new Zf("Input for depthwiseConv2d is required to be 4-D, but is instead "+s.rank+"-D");if(4!==e.rank)throw new Zf("depthwiseKernel is required to be 4-D, but is instead "+e.rank+"-D");return a=su(a,e,t,"same"===p?"same":"valid","NHWC",l),"channelsFirst"===d&&(a=Tl(a,[0,3,1,2])),a})}function ym(t){return"relu"===t?"relu":"linear"===t?"linear":null}function bm(a,n){for(;0>a;)a+=n;return a}function xm(d,m,o){if(3<d.shape.length||3<m.shape.length)throw new Qf("batchDot is not implemented for tensors of 4D or higher rank yet");if(Of.assert(2<=d.shape.length,function(){return"batchDot requires the rank of x to be >= 2, but got "+d.shape.length}),Of.assert(2<=d.shape.length,function(){return"batchDot requires the rank of y to be >= 2, but got "+m.shape.length}),"number"==typeof o&&(o=[o,o]),"complex64"===d.dtype||"complex64"===m.dtype)throw new Qf("batchDot is not implemented for complex64-type Tensors yet.");var g=d.shape.length,r=m.shape.length;null==o&&(o=[g-1,r-2]);var i=o;return We(function(){var e,t;if(g>r){e=g-r;for(var a=[],f=0;f<e;++f)a.push(1);m=m.reshape(m.shape.concat(a))}else if(r>g){for(e=r-g,a=[],f=0;f<e;++f)a.push(1);d=d.reshape(d.shape.concat(a))}else e=0;if(2===d.shape.length&&2===m.shape.length)t=i[0]===i[1]?d.mulStrict(m).sum(i[0]):d.transpose([1,0]).mulStrict(m).sum(i[1]);else{var y=i[0]!==d.shape.length-1,u=i[1]===m.shape.length-1;t=d.matMul(m,y,u)}if(0<e){var c=[],h;for(f=h=g>r?g+r-3:g-1;f<h+e;++f)c.push(f);t=t.squeeze(c)}return 1===t.shape.length&&(t=t.expandDims(1)),t})}function vm(s,e,t,n,r,i){var p;if(void 0===i&&(i=.001),2===s.rank)p=Ys(s,e,t,n,r,i);else if(3===s.rank)p=Qs(s,e,t,n,r,i);else{if(4!==s.rank)throw new Qf("batchNormalization is not implemented for array of rank "+s.rank+" yet");p=Js(s,e,t,n,r,i)}return p}function Cm(p,e,t,n,r){return void 0===r&&(r=.001),We(function(){var i=Pu(p,n),a=i.mean,o=i.variance;return[vm(p,a,o,t,e,r),a,o]})}function Sm(m,e,t,n,r){return void 0===r&&(r=.001),We(function(){for(var i=Pu(m,n),a=i.mean,o=i.variance,s=[],l=0,y=Bp(0,m.rank),c;l<y.length;l++)c=y[l],-1===n.indexOf(c)?s.push(m.shape[c]):s.push(1);var b=a.reshape(s),h=o.reshape(s),d=null==e?null:e.reshape(s),f=null==t?null:t.reshape(s);return[vm(m,b,h,f,d,r),a,o]})}function Nm(a,e,t,n,r){return void 0===r&&(r=.001),Of.arraysEqual(n.slice().sort(),Bp(0,a.rank-1))?Cm(a,e,t,n,r):Sm(a,e,t,n,r)}function Im(a,e,o){return We(function(){if(4!==a.rank)throw new Zf("temporalPadding expects input tensor to be 4-D, but received a "+a.rank+"-D tensor.");if(null==e&&(e=[[1,1],[1,1]]),2!==e.length||2!==e[0].length||2!==e[1].length)throw new Zf("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(null==o&&(o=ep()),"channelsLast"!==o&&"channelsFirst"!==o)throw new Zf("Unknown data format: "+o+". Supported data formats are 'channelsLast' and 'channelsFirst.");var t;return t="channelsFirst"===o?[[0,0],[0,0],e[0],e[1]]:[[0,0],e[0],e[1],[0,0]],lr(a,t)})}function km(p,d,t,l,u,c){return We(function(){var e;Ip(u),Tp(c),kp(l),null==t&&(t=[1,1]),null==l&&(l="valid"),null==u&&(u=ep()),null==c&&(c="max"),p=um(p,u);var a="same"===l?"same":"valid";return e="max"===c?yu(p,d,t,a):wu(p,d,t,a),"channelsFirst"===u&&(e=Tl(e,[0,3,1,2])),e})}function Tm(a,o,s,p){function r(t){return null==t||Array.isArray(t)?t:[t]}if(Array.isArray(a)){if(null!=o||null!=s)throw new Zf("When inputs is an array, neither initialState or constants should be provided");null!=p&&(s=a.slice(a.length-p,a.length),a=a.slice(0,a.length-p)),1<a.length&&(o=a.slice(1,a.length)),a=a[0]}return{inputs:a,initialState:o=r(o),constants:s=r(s)}}function Rm(p,e,b,n,x,C,a,S){return void 0===n&&(n=!1),void 0===a&&(a=!1),void 0===S&&(S=!1),We(function(){var t=e.shape.length;if(3>t)throw new Zf("Input should be at least 3D, but is "+t+"D.");var r=[1,0].concat(Bp(2,t));if(e=Tl(e,r),null!=C)throw new Qf("The rnn() functoin of the deeplearn.js backend does not support constants yet.");a&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),null!=x&&((x=x.asType("bool").asType("float32")).rank===t-1&&(x=ar(x,-1)),x=Tl(x,r)),n&&(e=pu(e,0),null!=x&&(x=pu(x,0)));var o=[],s=b,i=e.shape[0],l=Er(e),u,h;null!=x&&(h=Er(x));for(var g=function(i){var e=l[i],d=We(function(){return p(e,s)});if(null==x)u=d[0],s=d[1];else{var t=We(function(){var a=h[i],e=xn(a).sub(a);return{output:d[0].mul(a).addStrict(s[0].mul(e)),newStates:s.map(function(n,t){return d[1][t].mul(a).addStrict(n.mul(e))})}});u=t.output,s=t.newStates}S&&o.push(u)},f=0,y;f<i;++f)g(f);return S&&(y=br(o,1)),[u,y,s]})}function Em(s,e,t,p){function d(){return nd(s(),e)}if(void 0===t&&(t=null),void 0===p&&(p=1),1<p){for(var i=[],a=0;a<p;a++)i.push(od(d,s,t));return i.map(function(t){return Ve(t.clone())})}return Ve(od(d,s,t).clone())}function wm(t){gp(hy,"BidirectionalMergeMode",t)}function Am(t){return new gx(t)}function Dm(t){return new bx(t)}function _m(t){return new Cx(t)}function Om(t){return new Ix(t)}function zm(t){return new mx(t)}function Lm(t){return new yx(t)}function Fm(a,e){return Vd(a,e)}function Bm(a,e){return $d(a,e)}function Pm(a,e){return Xd(a,e)}function Mm(a,e){return Ud(a,e)}function Wm(a,e){return ab(a,e)}function Vm(a,e){return Kd(a,e)}function Um(a,e){return jd(a,e)}function Gm(a,e){return Md(a,e)}function qm(a,e){return Od(a,e)}function Hm(a,e){return zd(a,e)}function Km(a,e){return zd(a,e)}function jm(a,e){return zd(a,e)}function $m(a,e){return _d(a,e)}function Xm(a,e){return _d(a,e)}function Ym(a,e){return _d(a,e)}function Zm(a,e){return a<e}function Qm(a,e){return a>e}function Jm(i,e,t,d){return new(t||(t=Promise))(function(a,n){function r(t){try{s(d.next(t))}catch(t){n(t)}}function o(t){try{s(d.throw(t))}catch(t){n(t)}}function s(n){n.done?a(n.value):new t(function(e){e(n.value)}).then(r,o)}s((d=d.apply(i,e||[])).next())})}function eg(i,e){function t(t){return function(a){return function(t){if(d)throw new TypeError("Generator is already executing.");for(;p;)try{if(d=1,l&&(u=2&t[0]?l.return:t[0]?l.throw||((u=l.return)&&u.call(l),0):l.next)&&!(u=u.call(l,t[1])).done)return u;switch(l=0,u&&(t=[2&t[0],u.value]),t[0]){case 0:case 1:u=t;break;case 4:return p.label++,{value:t[1],done:!1};case 5:p.label++,l=t[1],t=[0];continue;case 7:t=p.ops.pop(),p.trys.pop();continue;default:if(!(u=0<(u=p.trys).length&&u[u.length-1])&&(6===t[0]||2===t[0])){p=0;continue}if(3===t[0]&&(!u||t[1]>u[0]&&t[1]<u[3])){p.label=t[1];break}if(6===t[0]&&p.label<u[1]){p.label=u[1],u=t;break}if(u&&p.label<u[2]){p.label=u[2],p.ops.push(t);break}u[2]&&p.ops.pop(),p.trys.pop();continue;}t=e.call(i,p)}catch(a){t=[6,a],l=0}finally{d=u=0}if(5&t[0])throw t[1];return{value:t[0]?t[1]:void 0,done:!0}}([t,a])}}var p={label:0,sent:function(){if(1&u[0])throw u[1];return u[1]},trys:[],ops:[]},d,l,u,c;return c={next:t(0),throw:t(1),return:t(2)},"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c}function tg(a,e){qx[a]={tfOpName:a,category:"custom",inputs:[],attrs:[],customExecutor:e}}function ag(t){return qx[t]}function ng(i,e,t,a){var r=e.inputParams[i];if(r&&void 0!==r.inputIndexStart){var n=r.inputIndexStart,s=0===r.inputIndexEnd?void 0:void 0===r.inputIndexEnd?n+1:r.inputIndexEnd;if("tensor"===r.type)return rg(e.inputNames[r.inputIndexStart],t,a);if("tensors"===r.type)return e.inputNames.slice(n,s).map(function(n){return rg(n,t,a)});var o=Array.prototype.slice.call(rg(e.inputNames.slice(n)[0],t,a).dataSync());return"number"===r.type?o[0]:o}var p=e.attrParams[i];return p&&p.value}function rg(i,p,e){var t=pg(i),a=t[0],n=t[1],r=e.currentContextIds.find(function(t){return!!p[ig(a,t)]});return void 0===r?void 0:p[ig(a,r)][n]}function og(n,e,t){return e[ig(n,t.currentContextId)]}function sg(o,e){var t=pg(o),a=t[0],r=t[1];return[ig(a,e&&e.currentContextId),r]}function ig(a,e){return e?a+"-"+e:a}function pg(a){var e=a.lastIndexOf(":");return-1===e?[a,0]:[a.substring(0,e),+a.substring(e+1)]}function dg(n,e){for(var t=[],a=0;a<n.length;a+=e)t.push(n.slice(a,a+e));return t}function lg(a){var e=_f.global;if(void 0!==e.atob)return e.atob(a);if("undefined"!=typeof Buffer)return new Buffer(a,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}function ug(n,e){var t=Array.isArray(n)?cf.apply(null,n):lg(n);return e?t:t.toLowerCase()}function cg(o,e,t,a){void 0===a&&(a=!1);var s=o[e];return null==s?t:ug(s.s,a)}function hg(n,e,t){var a=n[e];return a?a.b:t}function mg(o,e,t){var a=o[e]||{},r=null==a.i?null==a.f?t:a.f:a.i;return"number"==typeof r?r:parseInt(r,10)}function gg(t){switch("string"==typeof t&&(t=Hx[t]),t){case Hx.DT_FLOAT:return"float32";case Hx.DT_INT32:return"int32";case Hx.DT_BOOL:return"bool";case Hx.DT_DOUBLE:return"float32";case Hx.DT_STRING:return"string";default:return null;}}function fg(n,e,t){var a=n[e];return a&&a.type?gg(a.type):t}function yg(n,e,t){var a=n[e];return a&&a.list&&a.list.type?a.list.type.map(function(t){return gg(t)}):t}function bg(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 xg(n,e,t){var a=n[e];return a&&a.shape?bg(a.shape):t}function vg(n,e,t){var a=n[e];return a?(a.list.f&&a.list.f.length?a.list.f:a.list.i).map(function(t){return"number"==typeof t?t:parseInt(t,10)}):t}function Cg(o,e,t,a){void 0===a&&(a=!1);var s=o[e];return s&&s.list&&s.list.s?s.list.s.map(function(t){return ug(t,a)}):t}function Sg(n,e,t){var a=n[e];return a&&a.list&&a.list.shape?a.list.shape.map(function(t){return bg(t)}):t}function Ng(n,e,t){var a=n[e];return a&&a.list&&a.list.b?a.list.b:t}function Ig(R,L,t){return Jm(this,void 0,void 0,function(){var e,a,B,W,U,G,q,H,K,$,X,Y,Z,Q,J,ee,te,ae,ne,re,oe,se,ie,pe,de,le,ue,ce,he,me,ge,fe,ye,be,xe;return eg(this,function(n){switch(n.label){case 0:switch(R.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,[ng("pred",R,L,t).clone()]];case 2:return e=ng("pred",R,L,t),a=ng("data",R,L,t),[4,e.data()];case 3:return[2,n.sent()[0]?[void 0,a.clone()]:[a.clone(),void 0]];case 4:return[2,(B=R.inputNames.find(function(a){return void 0!==rg(a,L,t)}))?[rg(B,L,t).clone()]:void 0];case 5:return W=ng("frameName",R,L,t),U=ng("tensor",R,L,t),t.enterFrame(W),[2,[U.clone()]];case 6:return G=ng("tensor",R,L,t),t.exitFrame(),[2,[G.clone()]];case 7:return q=ng("tensor",R,L,t),t.nextIteration(),[2,[q.clone()]];case 8:return H=ng("size",R,L,t),K=ng("dtype",R,L,t),$=ng("elementShape",R,L,t),X=ng("dynamicSize",R,L,t),Y=ng("clearAfterRead",R,L,t),Z=ng("identicalElementShapes",R,L,t),Q=ng("name",R,L,t),J=new hv(Q,K,H,$,Z,X,Y),t.addTensorArray(J),[2,[Da(J.id),Da(1)]];case 9:return ee=ng("tensorArrayId",R,L,t),te=ng("index",R,L,t),ae=ng("tensor",R,L,t),t.getTensorArray(ee).write(te,ae),[2,[Da(1)]];case 10:return ne=ng("tensorArrayId",R,L,t),re=ng("index",R,L,t),[2,[t.getTensorArray(ne).read(re)]];case 11:return oe=ng("tensorArrayId",R,L,t),se=ng("indices",R,L,t),ie=ng("dtype",R,L,t),[2,[t.getTensorArray(oe).gather(se,ie)]];case 12:return pe=ng("tensorArrayId",R,L,t),de=ng("indices",R,L,t),le=ng("tensor",R,L,t),t.getTensorArray(pe).scatter(de,le),[2,[Da(1)]];case 13:return ue=ng("tensorArrayId",R,L,t),ce=t.getTensorArray(ue),he=ng("dtype",R,L,t),[2,[ce.concat(he)]];case 14:return me=ng("tensorArrayId",R,L,t),ge=ng("tensor",R,L,t),fe=ng("lengths",R,L,t),t.getTensorArray(me).split(fe,ge),[2,[Da(1)]];case 15:return ye=ng("tensorArrayId",R,L,t),be=t.getTensorArray(ye),[2,[Da(be.size(),"int32")]];case 16:return xe=ng("tensorArrayId",R,L,t),t.getTensorArray(xe).clearAndClose(),[2,[]];case 17:throw TypeError("Node type "+R.op+" is not implemented");}})})}function kg(i,e,t){return Jm(this,void 0,void 0,function(){var a,d,l,c,h;return eg(this,function(n){switch(n.label){case 0:switch(i.op){case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":return[3,1];case"Where":return[3,3];case"ListDiff":return[3,5];}return[3,7];case 1:return a=ng("boxes",i,e,t),d=ng("scores",i,e,t),l=ng("maxOutputSize",i,e,t),c=ng("iouThreshold",i,e,t),h=ng("scoreThreshold",i,e,t),[4,Ec.nonMaxSuppressionAsync(a,d,l,c,h)];case 2:return[2,[n.sent()]];case 3:return[4,Rl(ng("condition",i,e,t))];case 4:return[2,[n.sent()]];case 5:return[4,Rr(ng("x",i,e,t),ng("y",i,e,t))];case 6:return[2,n.sent()];case 7:throw TypeError("Node type "+i.op+" is not implemented");}})})}function Tg(n,e,t){var a=function(n,e,t){switch(n.category){case"arithmetic":return uv(n,e,t);case"basic_math":return cv(n,e,t);case"control":return Ig(n,e,t);case"convolution":return mv(n,e,t);case"creation":return gv(n,e,t);case"dynamic":return kg(n,e,t);case"evaluation":return fv(n,e,t);case"image":return bv(n,e,t);case"graph":return yv(n,e,t);case"logical":return xv(n,e,t);case"matrices":return vv(n,e,t);case"normalization":return Cv(n,e,t);case"reduction":return Sv(n,e,t);case"slice_join":return Nv(n,e,t);case"spectral":return Iv(n,e,t);case"transformation":return kv(n,e,t);case"custom":var a=ag(n.op);if(a&&a.customExecutor)return a.customExecutor(new lv(n,e,t));throw TypeError("Custom op "+n.op+" is not registered.");default:throw TypeError("Unknown op '"+n.op+"'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()");}}(n,e,t);return a instanceof Promise?a.then(function(t){return[].concat(t)}):[].concat(a)}function Rg(d,e,t){for(var a=new Set,r=[],n=null,l=null,c=new Set,p=e.slice(),u;0<p.length;)u=p.pop(),(wg(u)||Ag(u))&&null==n&&(l=(n=u).children.map(function(t){return t.name}).filter(function(t){return a.has(t)})),a.add(u.name),null==t[u.name]&&null==d[u.name]&&(0===u.inputs.length?r.push(u.name):u.inputs.forEach(function(t){c.has(t.name)||(c.add(t.name),p.push(t))}));return{inputs:d,outputs:e,usedNodes:a,missingInputs:r,dynamicNode:n,syncInputs:l}}function Eg(i,e,t){var a=t.usedNodes,r=t.inputs,n=[];Object.keys(r).map(function(e){return i.nodes[e]}).forEach(function(t){a.has(t.name)&&n.push(t)}),i.weights.forEach(function(t){a.has(t.name)&&n.push(t)});for(var s=new Set,o=[],p;0<n.length;)p=n.pop(),s.add(p.name),e[p.name]||o.push(p),p.children.forEach(function(t){!s.has(t.name)&&a.has(t.name)&&t.inputs.every(function(t){return s.has(t.name)})&&n.push(t)});return o}function wg(t){return 0<=Rv.indexOf(t.op)}function Ag(t){return 0<=Ev.indexOf(t.op)}function Dg(b,e){var t=function(t){var a=b.nodes[t];if(null==a||"Add"!==a.op&&"AddV2"!==a.op||2!==a.inputNames.length)return"continue";var r=a.inputs.find(function(t){return"Relu"===t.op});if(null==r||1!==r.inputNames.length)return"continue";var n=a.inputs.find(function(t){return"Mul"===t.op});if(null==n||2!==n.inputNames.length)return"continue";var s=n.inputs.find(function(t){return"Const"===t.op}),o=n.inputs.find(function(t){return"Relu"===t.op});if(null==s||null==o||1!==o.inputNames.length)return"continue";var p=o.inputs[0];if(null==p||"Neg"!==p.op||1!==p.inputNames.length)return"continue";if(r.inputNames[0]!==p.inputNames[0])return"continue";var u=r.inputs[0],i=a.children,m=s.name+"_neg",c={name:m,inputNames:[],inputs:[],attrParams:{},category:"graph",children:[],op:"Const",inputParams:{},rawAttrs:{}};e[m]=[Cs(e[s.name][0])],b.weights.push(c);var l={name:a.name+"_Prelu",inputNames:[u.name,c.name],inputs:[u,c],attrParams:{},category:"custom",children:i,op:"Prelu",inputParams:{x:{inputIndexStart:0,type:"tensor"},alpha:{inputIndexStart:1,type:"tensor"}}};c.children.push(l);var d=s.children.indexOf(n);-1<d&&s.children.splice(d,1);var y=u.children.indexOf(r);-1<y&&u.children.splice(y,1);var f=u.children.indexOf(p);if(-1<f&&u.children.splice(f,1),u.children.push(l),i.forEach(function(n){var e=n.inputNames.indexOf(a.name);-1<e&&(n.inputNames[e]=l.name,n.inputs[e]=l)}),0===i.length){var h=b.outputs.indexOf(a);-1<h&&b.outputs.splice(h,1),b.outputs.push(l)}delete b.nodes[a.name],delete b.nodes[n.name],delete b.nodes[r.name],delete b.nodes[o.name],delete b.nodes[p.name],b.nodes[l.name]=l,b.nodes[c.name]=c};for(var a in b.nodes)t(a)}function _g(a,t){function e(){this.constructor=a}Dv(a,t),a.prototype=null===t?Object.create(t):(e.prototype=t.prototype,new e)}function Og(p,t,e,d){return new(e||(e=Promise))(function(n,r){function o(e){try{s(d.next(e))}catch(e){r(e)}}function a(e){try{s(d.throw(e))}catch(e){r(e)}}function s(r){r.done?n(r.value):new e(function(t){t(r.value)}).then(o,a)}s((d=d.apply(p,t||[])).next())})}function zg(p,t){function e(e){return function(a){return function(e){if(d)throw new TypeError("Generator is already executing.");for(;s;)try{if(d=1,l&&(u=2&e[0]?l.return:e[0]?l.throw||((u=l.return)&&u.call(l),0):l.next)&&!(u=u.call(l,e[1])).done)return u;switch(l=0,u&&(e=[2&e[0],u.value]),e[0]){case 0:case 1:u=e;break;case 4:return s.label++,{value:e[1],done:!1};case 5:s.label++,l=e[1],e=[0];continue;case 7:e=s.ops.pop(),s.trys.pop();continue;default:if(!(u=0<(u=s.trys).length&&u[u.length-1])&&(6===e[0]||2===e[0])){s=0;continue}if(3===e[0]&&(!u||e[1]>u[0]&&e[1]<u[3])){s.label=e[1];break}if(6===e[0]&&s.label<u[1]){s.label=u[1],u=e;break}if(u&&s.label<u[2]){s.label=u[2],s.ops.push(e);break}u[2]&&s.ops.pop(),s.trys.pop();continue;}e=t.call(p,s)}catch(a){e=[6,a],l=0}finally{d=u=0}if(5&e[0])throw e[1];return{value:e[0]?e[1]:void 0,done:!0}}([e,a])}}var s={label:0,sent:function(){if(1&u[0])throw u[1];return u[1]},trys:[],ops:[]},d,l,u,c;return c={next:e(0),throw:e(1),return:e(2)},"function"==typeof Symbol&&(c[Symbol.iterator]=function(){return this}),c}function Lg(a,t){return a(t={exports:{}},t.exports),t.exports}function Fg(a,t){return Bg(a,t)}function Bg(p,t,e,d){if(void 0===e&&(e=new Map),void 0===d&&(d=new Set),null==p)return null;if(d.has(p))throw new Error("Circular references are not supported.");if(e.has(p))return e.get(p);var l=t(p);if(l.recurse&&null!==l.value)throw new Error("A deep map function may not return both a value and recurse=true.");if(l.recurse){if(Ug(p)){var i=Array.isArray(p)?[]:{};for(var o in d.add(p),p){var a=Bg(p[o],t,e,d);i[o]=a}return d.delete(p),i}throw new Error("Can't recurse into non-iterable type: "+p)}return e.set(p,l.value),l.value}function Pg(a,t){return void 0===t&&(t=Wg),Mg(a,t)}function Mg(p,t,e){void 0===e&&(e=new Set);var d=p[0];if(e.has(d))throw new Error("Circular references are not supported.");var n=t(p);if(n.recurse&&null!==n.value)throw new Error("A deep zip function may not return both a value and recurse=true.");if(n.recurse){if(Ug(d)){var l=Array.isArray(d)?[]:{};e.add(d);var o=function(a){var n=Mg(p.map(function(e){return e[a]}),t,e);l[a]=n};for(var a in d)o(a);return e.delete(d),l}throw new Error("Can't recurse into non-iterable type: "+d)}return n.value}function Wg(e){return null===e?null:Ug(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}function Vg(p,t){return Og(this,void 0,void 0,function(){var e,d,l,c,h,m;return zg(this,function(a){switch(a.label){case 0:e=new Map,Bg(p,t,e),d=0,l=Array.from(e.keys()),a.label=1;case 1:return d<l.length?(c=l[d],(h=e.get(c))instanceof Promise?[4,h]:[3,3]):[3,4];case 2:m=a.sent(),e.set(c,m),a.label=3;case 3:return d++,[3,1];case 4:return[2,Bg(p,t,e)];}})})}function Ug(e){return null!=e&&(Array.isArray(e)||"object"==typeof e&&!(e instanceof Lf))}function Gg(e){return null==e||qg(e)||Array.isArray(e)||"object"==typeof e&&e instanceof Lf||Of.isTypedArray(e)}function qg(e){return null===e||"object"!=typeof e&&"function"!=typeof e}function Hg(e){return Fg(e,Kg)}function Kg(e){return e instanceof Lf?{value:e.clone(),recurse:!1}:Ug(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}function jg(e){return new Gv(e)}function $g(e){return new qv(e)}function Xg(a,t){return new tC(a,t)}function Yg(a,n){return void 0===n&&(n=null),new(function(e){function t(){var a=null!==e&&e.apply(this,arguments)||this;return a.size=n,a}return _g(t,e),t.prototype.iterator=function(){return Og(this,void 0,void 0,function(){return zg(this,function(){return[2,a()]})})},t}(sC))}function Zg(e){return null===e?null:Gg(e[0])?{value:Qg(e),recurse:!1}:{value:null,recurse:!0}}function Qg(e){if(0===e.length)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof Lf?br(e):Zt(e)}function Jg(p,t){return void 0===t&&(t={}),Og(this,void 0,void 0,function(){var e,d,l,u,c;return zg(this,function(a){switch(a.label){case 0:return"string"==typeof p?e=p:(e=p.url,d=kC(p)),[4,Of.fetch(e,d)];case 1:return(l=a.sent()).ok?(c=Uint8Array.bind,[4,l.arrayBuffer()]):[3,3];case 2:return u=new(c.apply(Uint8Array,[void 0,a.sent()])),[2,new IC(u,t)];case 3:throw new Error(l.statusText);}})})}function af(e){return"string"==typeof e&&"file://"===e.substr(0,7)}function rf(e){return[].concat(e).map(function(e){var t="undefined"==typeof e?"undefined":WC(e);if("string"===t)e={on:[e],show:e,use:e,focus:[0,0]};else if("object"===t){try{wC("Suggestion",e,"value"),AC("Suggestion",e,"value","string")}catch(t){if(t instanceof TypeError)throw t;try{wC("Suggestion",e,["on","show","use"])}catch(a){if(e.on||e.show||e.use)throw a;else throw t}AC("Suggestion",e,"on","string"),AC("Suggestion",e,"use","string"),AC("Suggestion",e,"show","string")}e.show=e.show||e.value,e.use=e.use||e.value,e.on=[e.show].concat(e.on||e.value),e.focus=e.focus||[0,0],e.focus.constructor!==Array&&(e.focus=[e.focus,e.focus])}return e})}function of(e){e&&!e.values&&(e={values:e});try{wC("SuggestionList",e,"trigger"),AC("Suggestion",e,"trigger","string")}catch(t){if(t instanceof TypeError)throw t}if(wC("SuggestionList",e,"values"),e.caseSensitive=!!e.caseSensitive,"function"==typeof e.values?this.getSuggestions=function(t,a){e.values(t,function(e){return a(rf(e))})}:(e.values.constructor===Array||"string"==typeof e.values)&&(e.values=rf(e.values),this.getSuggestions=function(t,a){var n=new RegExp("^"+t,e.caseSensitive?"":"i");a(e.values.filter(function(e){for(var a=!1,r=0;r<e.on.length&&!(e.on[r]!==t&&(a=n.test(e.on[r])));r++);return a}))}),this.trigger=e.trigger,this.trigger){var t="\\"+this.trigger.split("").join("\\");this.regex=new RegExp("(?:^|[^"+t+"]+?)"+t+"(\\S*)$")}else this.regex=/(?:^|\W+)(\w+)$/}function sf(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function pf(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function df(e,t,a){var n=e.slice(0,t),r=n.split(a||/\W/).pop(),o=r.length?n.slice(0,0-r.length):n;return r+=e.slice(t),{textAfterTrigger:r,textUptoTrigger:o}}// Invisible character
  function lf(e,t){if(PC(e,"isInput")){var a=LC(e),n=qC(a,1),r=n[0],o=df(e.value,r,t),s=o.textAfterTrigger,i=o.textUptoTrigger,p=document.createElement("pre");p.id="autosuggest-positionclone";var d=document.createElement("span");d.appendChild(document.createTextNode("\uFEFF")),p.appendChild(document.createTextNode(i.replace(/ /g,"\xA0"))),p.appendChild(d),p.appendChild(document.createTextNode(s.replace(/ /g,"\xA0"))),DC(e,p);var l=OC(e);p.style.opacity=0,p.style.position="absolute",p.style.top=l.top+"px",p.style.left=l.left+"px",document.body.appendChild(p),"INPUT"===e.tagName?(p.style.overflowX="auto",p.style.whiteSpace="nowrap",p.scrollLeft=r===e.value.length?p.scrollWidth-p.clientWidth:wf(zC(e),p.scrollWidth-p.clientWidth)):(p.style.maxWidth="100%",p.style.whiteSpace="pre-wrap",p.scrollTop=e.scrollTop,p.scrollLeft=e.scrollLeft);var u=OC(d);u.left-=p.scrollLeft;var c=parseFloat(_C(d,"line-height"));return u.top+=c-p.scrollTop,document.body.removeChild(p),u}var h=window.getSelection().getRangeAt(0),m=h.startContainer,g=h.startOffset,f=h.endContainer,y=h.endOffset,b=FC(),x=b.startContainer,v=b.startOffset,C=df(x.nodeValue,v,t),S=C.textAfterTrigger,N=C.textUptoTrigger,I=x.parentNode,k=x.nextSibling,T=document.createElement("span");if(T.appendChild(document.createTextNode("\uFEFF")),I.insertBefore(T,k),S){x.nodeValue=N;var R=document.createTextNode(S);I.insertBefore(R,k)}var E=OC(T),w=parseFloat(_C(T,"line-height"));E.top+=w,I.removeChild(T),S&&(I.removeChild(x.nextSibling),x.nodeValue=N+S);var A=window.getSelection().getRangeAt(0);return A.setStart(m,g),A.setEnd(f,y),E}var Af=function(t,e){return(Af=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,t){a.__proto__=t}||function(a,t){for(var e in t)t.hasOwnProperty(e)&&(a[e]=t[e])})(t,e)},Df=function(){function e(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.populateURLFlags()}return e.prototype.setPlatform=function(a,t){null!=this.platform&&console.warn("Platform "+this.platformName+" has already been set. Overwriting the platform with "+t+"."),this.platformName=a,this.platform=t},e.prototype.registerFlag=function(a,t,e){if(this.flagRegistry[a]={evaluationFn:t,setHook:e},null!=this.urlFlags[a]){var n=this.urlFlags[a];console.warn("Setting feature override from URL "+a+": "+n+"."),this.set(a,n)}},e.prototype.get=function(e){return e in this.flags?this.flags[e]:(this.flags[e]=this.evaluateFlag(e),this.flags[e])},e.prototype.getNumber=function(e){return this.get(e)},e.prototype.getBool=function(e){return this.get(e)},e.prototype.getFlags=function(){return this.flags},Object.defineProperty(e.prototype,"features",{get:function(){return this.flags},enumerable:!0,configurable:!0}),e.prototype.set=function(a,t){if(null==this.flagRegistry[a])throw new Error("Cannot set flag "+a+" as it has not been registered.");this.flags[a]=t,null!=this.flagRegistry[a].setHook&&this.flagRegistry[a].setHook(t)},e.prototype.evaluateFlag=function(e){if(null==this.flagRegistry[e])throw new Error("Cannot evaluate flag '"+e+"': no evaluation function found.");return this.flagRegistry[e].evaluationFn()},e.prototype.setFlags=function(e){this.flags=Object.assign({},e)},e.prototype.reset=function(){this.flags={},this.urlFlags={},this.populateURLFlags()},e.prototype.populateURLFlags=function(){var a=this;if(void 0!==this.global&&void 0!==this.global.location&&void 0!==this.global.location.search){var t=n(this.global.location.search);"tfjsflags"in t&&t.tfjsflags.split(",").forEach(function(t){var e=t.split(":"),n=e[0],r=e[1];a.urlFlags[n]=function(a,t){if("true"===(t=t.toLowerCase())||"false"===t)return"true"===t;if(""+ +t===t)return+t;throw new Error("Could not parse value flag value "+t+" for flag "+a+".")}(n,r)})}},e}(),_f=null,o=Object.freeze({Environment:Df,getQueryParams:n,get ENV(){return _f},setEnvironmentGlobal:a}),Of=Object.freeze({shuffle:r,clamp:l,nearestLargerEven:s,sum:c,randUniform:function(a,t){var e=Math.random();return t*e+(1-e)*a},distSquared:function(a,t){for(var e=0,s=0,i;s<a.length;s++)i=+a[s]-+t[s],e+=i*i;return e},assert:Ue,assertShapesMatch:p,assertNonNull:d,flatten:v,sizeFromShape:qe,isScalarShape:function(e){return 0===e.length},arraysEqual:g,isInt:y,tanh:h,sizeToSquarishShape:m,createShuffledIndices:function(a){for(var t=new Uint32Array(a),e=0;e<a;++e)t[e]=e;return r(t),t},rightPad:f,repeatedTry:b,inferFromImplicitShape:x,parseAxisParam:C,squeezeShape:I,getTypedArrayFromDType:S,getArrayFromDType:N,checkComputationForErrors:k,checkConversionForErrors:R,isValidDtype:T,hasEncodingLoss:E,isTypedArray:w,bytesPerElement:A,bytesFromStringArray:e,isString:D,isBoolean:_,isNumber:O,inferDtype:L,isFunction:F,nearestDivisor:B,computeStrides:z,toTypedArray:P,toNestedArray:M,makeOnesTypedArray:W,makeZerosTypedArray:V,now:U,assertNonNegativeIntegerDimensions:G,fetch:function(a,t){return _f.platform.fetch(a,t)},encodeString:q,decodeString:H}),u=function(){function e(a,t){this.backendTimer=a,this.logger=t,null==t&&(this.logger=new Q)}return e.prototype.profileKernel=function(s,t){var i=this,a=this.backendTimer.time(function(){e=t()}),e;return(Array.isArray(e)?e:[e]).forEach(function(t){var e=t.dataSync();k(e,t.dtype,s),a.then(function(n){var r="";null!=n.getExtraProfileInfo&&(r=n.getExtraProfileInfo()),i.logger.logKernelProfile(s,t,e,n.kernelMs,r)})}),e},e}(),Q=function(){function e(){}return e.prototype.logKernelProfile=function(p,t,e,n,r){var o=f(n+"ms",9),a=f(p,25),i=t.rank,s=t.size,d=f(t.shape.toString(),14);console.log("%c"+a+"\t%c"+o+"\t%c"+i+"D "+d+"\t%c"+s+"\t%c"+r,"font-weight:bold","color:red","color:blue","color: orange","color: green")},e}(),Z=function(){function e(a,t,e){var n=this;if(this.dtype=t,this.shape=a.slice(),this.size=qe(a),null!=e){var r=e.length;Ue(r===this.size,function(){return"Length of values '"+r+"' does not match the size inferred by the shape '"+n.size+"'."})}if("complex64"===t)throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=e||N(t,this.size),this.strides=z(a)}return e.prototype.set=function(a){for(var t=this,e=[],s=1;s<arguments.length;s++)e[s-1]=arguments[s];0===e.length&&(e=[0]),Ue(e.length===this.rank,function(){return"The number of provided coordinates ("+e.length+") must match the rank ("+t.rank+")"});var i=this.locToIndex(e);this.values[i]=a},e.prototype.get=function(){for(var p=[],d=0;d<arguments.length;d++)p[d]=arguments[d];0===p.length&&(p=[0]);for(var l=0,c=0,h=p,o;c<h.length;c++){if(o=h[c],0>o||o>=this.shape[l]){var m="Requested out of range element at "+p+".   Buffer shape="+this.shape;throw new Error(m)}l++}for(var i=p[p.length-1],g=0;g<p.length-1;++g)i+=this.strides[g]*p[g];return this.values[i]},e.prototype.locToIndex=function(a){if(0===this.rank)return 0;if(1===this.rank)return a[0];for(var t=a[a.length-1],r=0;r<a.length-1;++r)t+=this.strides[r]*a[r];return t},e.prototype.indexToLoc=function(a){if(0===this.rank)return[];if(1===this.rank)return[a];for(var r=Array(this.shape.length),e=0;e<r.length-1;++e)r[e]=Cf(a/this.strides[e]),a-=r[e]*this.strides[e];return r[r.length-1]=a,r},Object.defineProperty(e.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),e.prototype.toTensor=function(){return Lf.make(this.shape,{values:this.values},this.dtype)},e}(),J=null,st=null,zf=null,Lf=function(){function s(a,t,e,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=a.slice(),this.dtype=t||"float32",this.size=qe(a),this.strides=z(a),this.dataId=null==n?{}:n,this.id=J().nextTensorId(),this.rankType=5>this.rank?this.rank.toString():"higher",J().registerTensor(this,r),null!=e&&J().write(r,this.dataId,e)}return s.make=function(t,e,n,r){var o=e.values;return null!=e.values&&"string"===n&&D(e.values[0])&&(o=e.values.map(function(e){return q(e)})),new s(t,n,o,e.dataId,r)},s.prototype.flatten=function(){return this.throwIfDisposed(),this.as1D()},s.prototype.asScalar=function(){return this.throwIfDisposed(),Ue(1===this.size,function(){return"The array must have only 1 element."}),this.reshape([])},s.prototype.as1D=function(){return this.throwIfDisposed(),this.reshape([this.size])},s.prototype.as2D=function(a,t){return this.throwIfDisposed(),this.reshape([a,t])},s.prototype.as3D=function(a,t,e){return this.throwIfDisposed(),this.reshape([a,t,e])},s.prototype.as4D=function(a,t,e,n){return this.throwIfDisposed(),this.reshape([a,t,e,n])},s.prototype.as5D=function(a,t,e,n,r){return this.throwIfDisposed(),this.reshape([a,t,e,n,r])},s.prototype.asType=function(e){return this.throwIfDisposed(),st.cast(this,e)},Object.defineProperty(s.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),s.prototype.buffer=function(){return Be(this,void 0,void 0,function(){var a;return Me(this,function(t){switch(t.label){case 0:return[4,this.data()];case 1:return a=t.sent(),[2,st.buffer(this.shape,this.dtype,a)];}})})},s.prototype.bufferSync=function(){return st.buffer(this.shape,this.dtype,this.dataSync())},s.prototype.array=function(){return Be(this,void 0,void 0,function(){var a;return Me(this,function(t){switch(t.label){case 0:return[4,this.data()];case 1:return a=t.sent(),[2,M(this.shape,a)];}})})},s.prototype.arraySync=function(){return M(this.shape,this.dataSync())},s.prototype.data=function(){return Be(this,void 0,void 0,function(){var a,r;return Me(this,function(e){switch(e.label){case 0:return this.throwIfDisposed(),a=J().read(this.dataId),"string"===this.dtype?[4,a]:[3,2];case 1:r=e.sent();try{return[2,r.map(function(e){return H(e)})]}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}e.label=2;case 2:return[2,a];}})})},s.prototype.dataSync=function(){this.throwIfDisposed();var e=J().readSync(this.dataId);if("string"===this.dtype)try{return e.map(function(e){return H(e)})}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e},s.prototype.bytes=function(){return Be(this,void 0,void 0,function(){var a;return Me(this,function(t){switch(t.label){case 0:return this.throwIfDisposed(),[4,J().read(this.dataId)];case 1:return a=t.sent(),"string"===this.dtype?[2,a]:[2,new Uint8Array(a.buffer)];}})})},s.prototype.dispose=function(){this.isDisposed||(J().disposeTensor(this),this.isDisposedInternal=!0)},Object.defineProperty(s.prototype,"isDisposed",{get:function(){return this.isDisposedInternal},enumerable:!0,configurable:!0}),s.prototype.throwIfDisposed=function(){if(this.isDisposed)throw new Error("Tensor is disposed.")},s.prototype.toFloat=function(){return this.asType("float32")},s.prototype.toInt=function(){return this.asType("int32")},s.prototype.toBool=function(){return this.asType("bool")},s.prototype.print=function(e){return void 0===e&&(e=!1),st.print(this,e)},s.prototype.reshape=function(e){return this.throwIfDisposed(),st.reshape(this,e)},s.prototype.reshapeAs=function(e){return this.throwIfDisposed(),this.reshape(e.shape)},s.prototype.expandDims=function(e){return void 0===e&&(e=0),st.expandDims(this,e)},s.prototype.cumsum=function(a,r,o){return void 0===a&&(a=0),void 0===r&&(r=!1),void 0===o&&(o=!1),st.cumsum(this,a,r,o)},s.prototype.squeeze=function(e){return this.throwIfDisposed(),st.squeeze(this,e)},s.prototype.clone=function(){return this.throwIfDisposed(),st.clone(this)},s.prototype.oneHot=function(a,t,e){return this.throwIfDisposed(),st.oneHot(this,a,t,e)},s.prototype.toString=function(e){return void 0===e&&(e=!1),K(this.dataSync(),this.shape,this.dtype,e)},s.prototype.tile=function(e){return this.throwIfDisposed(),st.tile(this,e)},s.prototype.gather=function(a,t){return void 0===t&&(t=0),this.throwIfDisposed(),st.gather(this,a,t)},s.prototype.matMul=function(a,t,r){return void 0===t&&(t=!1),void 0===r&&(r=!1),this.throwIfDisposed(),st.matMul(this,a,t,r)},s.prototype.dot=function(e){return this.throwIfDisposed(),st.dot(this,e)},s.prototype.norm=function(a,r,o){return void 0===a&&(a="euclidean"),void 0===r&&(r=null),void 0===o&&(o=!1),this.throwIfDisposed(),st.norm(this,a,r,o)},s.prototype.slice=function(a,t){return this.throwIfDisposed(),st.slice(this,a,t)},s.prototype.reverse=function(e){return this.throwIfDisposed(),st.reverse(this,e)},s.prototype.concat=function(t,a){return void 0===a&&(a=0),this.throwIfDisposed(),t instanceof s&&(t=[t]),st.concat([this].concat(t),a)},s.prototype.split=function(a,t){return void 0===t&&(t=0),this.throwIfDisposed(),st.split(this,a,t)},s.prototype.stack=function(a,t){return void 0===t&&(t=0),st.stack([this,a],t)},s.prototype.unstack=function(e){return void 0===e&&(e=0),st.unstack(this,e)},s.prototype.pad=function(a,t){return void 0===t&&(t=0),st.pad(this,a,t)},s.prototype.batchNormalization=function(a,t,e,s,r){return void 0===e&&(e=.001),zf("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon"),this.batchNorm(a,t,r,s,e)},s.prototype.batchNorm=function(a,t,e,n,r){return void 0===r&&(r=.001),this.throwIfDisposed(),st.batchNorm(this,a,t,e,n,r)},s.prototype.all=function(a,n){return void 0===a&&(a=null),void 0===n&&(n=!1),this.throwIfDisposed(),st.all(this,a,n)},s.prototype.any=function(a,n){return void 0===a&&(a=null),void 0===n&&(n=!1),this.throwIfDisposed(),st.any(this,a,n)},s.prototype.logSumExp=function(a,n){return void 0===a&&(a=null),void 0===n&&(n=!1),this.throwIfDisposed(),st.logSumExp(this,a,n)},s.prototype.sum=function(a,n){return void 0===a&&(a=null),void 0===n&&(n=!1),this.throwIfDisposed(),st.sum(this,a,n)},s.prototype.prod=function(a,n){return void 0===a&&(a=null),void 0===n&&(n=!1),this.throwIfDisposed(),st.prod(this,a,n)},s.prototype.mean=function(a,n){return void 0===a&&(a=null),void 0===n&&(n=!1),this.throwIfDisposed(),st.mean(this,a,n)},s.prototype.min=function(a,n){return void 0===a&&(a=null),void 0===n&&(n=!1),this.throwIfDisposed(),st.min(this,a,n)},s.prototype.max=function(a,n){return void 0===a&&(a=null),void 0===n&&(n=!1),this.throwIfDisposed(),st.max(this,a,n)},s.prototype.argMin=function(e){return void 0===e&&(e=null),this.throwIfDisposed(),st.argMin(this,e)},s.prototype.argMax=function(e){return void 0===e&&(e=null),this.throwIfDisposed(),st.argMax(this,e)},s.prototype.cast=function(e){return this.throwIfDisposed(),st.cast(this,e)},s.prototype.add=function(e){return this.throwIfDisposed(),st.add(this,e)},s.prototype.addStrict=function(e){return this.throwIfDisposed(),st.addStrict(this,e)},s.prototype.atan2=function(e){return this.throwIfDisposed(),st.atan2(this,e)},s.prototype.sub=function(e){return this.throwIfDisposed(),st.sub(this,e)},s.prototype.subStrict=function(e){return this.throwIfDisposed(),st.subStrict(this,e)},s.prototype.pow=function(e){return this.throwIfDisposed(),st.pow(this,e)},s.prototype.powStrict=function(e){return this.throwIfDisposed(),st.powStrict(this,e)},s.prototype.mul=function(e){return this.throwIfDisposed(),st.mul(this,e)},s.prototype.mulStrict=function(e){return this.throwIfDisposed(),st.mulStrict(this,e)},s.prototype.div=function(e){return this.throwIfDisposed(),st.div(this,e)},s.prototype.floorDiv=function(e){return this.throwIfDisposed(),st.floorDiv(this,e)},s.prototype.divStrict=function(e){return this.throwIfDisposed(),st.divStrict(this,e)},s.prototype.minimum=function(e){return this.throwIfDisposed(),st.minimum(this,e)},s.prototype.minimumStrict=function(e){return this.throwIfDisposed(),st.minimumStrict(this,e)},s.prototype.maximum=function(e){return this.throwIfDisposed(),st.maximum(this,e)},s.prototype.maximumStrict=function(e){return this.throwIfDisposed(),st.maximumStrict(this,e)},s.prototype.mod=function(e){return this.throwIfDisposed(),st.mod(this,e)},s.prototype.modStrict=function(e){return this.throwIfDisposed(),st.modStrict(this,e)},s.prototype.squaredDifference=function(e){return this.throwIfDisposed(),st.squaredDifference(this,e)},s.prototype.squaredDifferenceStrict=function(e){return this.throwIfDisposed(),st.squaredDifferenceStrict(this,e)},s.prototype.transpose=function(e){return this.throwIfDisposed(),st.transpose(this,e)},s.prototype.notEqual=function(e){return this.throwIfDisposed(),st.notEqual(this,e)},s.prototype.notEqualStrict=function(e){return this.throwIfDisposed(),st.notEqualStrict(this,e)},s.prototype.less=function(e){return this.throwIfDisposed(),st.less(this,e)},s.prototype.lessStrict=function(e){return this.throwIfDisposed(),st.lessStrict(this,e)},s.prototype.equal=function(e){return this.throwIfDisposed(),st.equal(this,e)},s.prototype.equalStrict=function(e){return this.throwIfDisposed(),st.equalStrict(this,e)},s.prototype.lessEqual=function(e){return this.throwIfDisposed(),st.lessEqual(this,e)},s.prototype.lessEqualStrict=function(e){return this.throwIfDisposed(),st.lessEqualStrict(this,e)},s.prototype.greater=function(e){return this.throwIfDisposed(),st.greater(this,e)},s.prototype.greaterStrict=function(e){return this.throwIfDisposed(),st.greaterStrict(this,e)},s.prototype.greaterEqual=function(e){return this.throwIfDisposed(),st.greaterEqual(this,e)},s.prototype.greaterEqualStrict=function(e){return this.throwIfDisposed(),st.greaterEqualStrict(this,e)},s.prototype.logicalAnd=function(e){return this.throwIfDisposed(),st.logicalAnd(this,e)},s.prototype.logicalOr=function(e){return this.throwIfDisposed(),st.logicalOr(this,e)},s.prototype.logicalNot=function(){return this.throwIfDisposed(),st.logicalNot(this)},s.prototype.logicalXor=function(e){return this.throwIfDisposed(),st.logicalXor(this,e)},s.prototype.where=function(a,t){return this.throwIfDisposed(),st.where(a,this,t)},s.prototype.neg=function(){return this.throwIfDisposed(),st.neg(this)},s.prototype.ceil=function(){return this.throwIfDisposed(),st.ceil(this)},s.prototype.floor=function(){return this.throwIfDisposed(),st.floor(this)},s.prototype.sign=function(){return this.throwIfDisposed(),st.sign(this)},s.prototype.isNaN=function(){return this.throwIfDisposed(),st.isNaN(this)},s.prototype.isInf=function(){return this.throwIfDisposed(),st.isInf(this)},s.prototype.isFinite=function(){return this.throwIfDisposed(),st.isFinite(this)},s.prototype.exp=function(){return this.throwIfDisposed(),st.exp(this)},s.prototype.expm1=function(){return this.throwIfDisposed(),st.expm1(this)},s.prototype.log=function(){return this.throwIfDisposed(),st.log(this)},s.prototype.log1p=function(){return this.throwIfDisposed(),st.log1p(this)},s.prototype.sqrt=function(){return this.throwIfDisposed(),st.sqrt(this)},s.prototype.rsqrt=function(){return this.throwIfDisposed(),st.rsqrt(this)},s.prototype.square=function(){return this.throwIfDisposed(),st.square(this)},s.prototype.reciprocal=function(){return this.throwIfDisposed(),st.reciprocal(this)},s.prototype.abs=function(){return this.throwIfDisposed(),st.abs(this)},s.prototype.clipByValue=function(a,t){return this.throwIfDisposed(),st.clipByValue(this,a,t)},s.prototype.relu=function(){return this.throwIfDisposed(),st.relu(this)},s.prototype.elu=function(){return this.throwIfDisposed(),st.elu(this)},s.prototype.selu=function(){return this.throwIfDisposed(),st.selu(this)},s.prototype.leakyRelu=function(e){return void 0===e&&(e=.2),this.throwIfDisposed(),st.leakyRelu(this,e)},s.prototype.prelu=function(e){return this.throwIfDisposed(),st.prelu(this,e)},s.prototype.sigmoid=function(){return this.throwIfDisposed(),st.sigmoid(this)},s.prototype.logSigmoid=function(){return this.throwIfDisposed(),st.logSigmoid(this)},s.prototype.softplus=function(){return this.throwIfDisposed(),st.softplus(this)},s.prototype.zerosLike=function(){return this.throwIfDisposed(),st.zerosLike(this)},s.prototype.onesLike=function(){return this.throwIfDisposed(),st.onesLike(this)},s.prototype.sin=function(){return this.throwIfDisposed(),st.sin(this)},s.prototype.cos=function(){return this.throwIfDisposed(),st.cos(this)},s.prototype.tan=function(){return this.throwIfDisposed(),st.tan(this)},s.prototype.asin=function(){return this.throwIfDisposed(),st.asin(this)},s.prototype.acos=function(){return this.throwIfDisposed(),st.acos(this)},s.prototype.atan=function(){return this.throwIfDisposed(),st.atan(this)},s.prototype.sinh=function(){return this.throwIfDisposed(),st.sinh(this)},s.prototype.cosh=function(){return this.throwIfDisposed(),st.cosh(this)},s.prototype.tanh=function(){return this.throwIfDisposed(),st.tanh(this)},s.prototype.asinh=function(){return this.throwIfDisposed(),st.asinh(this)},s.prototype.acosh=function(){return this.throwIfDisposed(),st.acosh(this)},s.prototype.atanh=function(){return this.throwIfDisposed(),st.atanh(this)},s.prototype.erf=function(){return this.throwIfDisposed(),st.erf(this)},s.prototype.round=function(){return this.throwIfDisposed(),st.round(this)},s.prototype.step=function(e){return void 0===e&&(e=0),this.throwIfDisposed(),st.step(this,e)},s.prototype.softmax=function(e){return void 0===e&&(e=-1),this.throwIfDisposed(),st.softmax(this,e)},s.prototype.logSoftmax=function(e){return void 0===e&&(e=-1),this.throwIfDisposed(),st.logSoftmax(this,e)},s.prototype.resizeBilinear=function(a,t){return void 0===t&&(t=!1),this.throwIfDisposed(),st.image.resizeBilinear(this,a,t)},s.prototype.resizeNearestNeighbor=function(a,t){return void 0===t&&(t=!1),this.throwIfDisposed(),st.image.resizeNearestNeighbor(this,a,t)},s.prototype.conv1d=function(s,t,e,n,i,p){return void 0===n&&(n="NWC"),void 0===i&&(i=1),this.throwIfDisposed(),st.conv1d(this,s,t,e,n,i,p)},s.prototype.conv2d=function(s,t,e,n,i,p){return void 0===n&&(n="NHWC"),void 0===i&&(i=[1,1]),this.throwIfDisposed(),st.conv2d(this,s,t,e,n,i,p)},s.prototype.conv2dTranspose=function(a,t,e,n,r){return this.throwIfDisposed(),st.conv2dTranspose(this,a,t,e,n,r)},s.prototype.depthwiseConv2D=function(s,t,e,n,i,p){return void 0===n&&(n="NHWC"),void 0===i&&(i=[1,1]),this.throwIfDisposed(),st.depthwiseConv2d(this,s,t,e,n,i,p)},s.prototype.separableConv2d=function(s,t,e,n,r,i){return void 0===r&&(r=[1,1]),void 0===i&&(i="NHWC"),this.throwIfDisposed(),st.separableConv2d(this,s,t,e,n,r,i)},s.prototype.avgPool=function(a,t,e,n){return this.throwIfDisposed(),st.avgPool(this,a,t,e,n)},s.prototype.maxPool=function(a,t,e,n){return this.throwIfDisposed(),st.maxPool(this,a,t,e,n)},s.prototype.localResponseNormalization=function(a,o,s,i){return void 0===a&&(a=5),void 0===o&&(o=1),void 0===s&&(s=1),void 0===i&&(i=.5),st.localResponseNormalization(this,a,o,s,i)},s.prototype.pool=function(a,t,e,n,r){return this.throwIfDisposed(),st.pool(this,a,t,e,n,r)},s.prototype.variable=function(a,r,e){return void 0===a&&(a=!0),this.throwIfDisposed(),ht.variable(this,a,r,e)},s.prototype.unsortedSegmentSum=function(a,t){return this.throwIfDisposed(),st.unsortedSegmentSum(this,a,t)},s.prototype.batchToSpaceND=function(a,t){return this.throwIfDisposed(),st.batchToSpaceND(this,a,t)},s.prototype.spaceToBatchND=function(a,t){return this.throwIfDisposed(),st.spaceToBatchND(this,a,t)},s.prototype.topk=function(a,n){return void 0===a&&(a=1),void 0===n&&(n=!0),this.throwIfDisposed(),st.topk(this,a,n)},s.prototype.stridedSlice=function(p,t,e,n,d,l,u,c){return void 0===n&&(n=0),void 0===d&&(d=0),void 0===l&&(l=0),void 0===u&&(u=0),void 0===c&&(c=0),this.throwIfDisposed(),st.stridedSlice(this,p,t,e,n,d,l,u,c)},s.prototype.depthToSpace=function(a,t){return this.throwIfDisposed(),st.depthToSpace(this,a,t)},s.prototype.fft=function(){return this.throwIfDisposed(),st.spectral.fft(this)},s.prototype.ifft=function(){return this.throwIfDisposed(),st.spectral.ifft(this)},s.prototype.rfft=function(){return this.throwIfDisposed(),st.spectral.rfft(this)},s.prototype.irfft=function(){return this.throwIfDisposed(),st.spectral.irfft(this)},s}();Object.defineProperty(Lf,Symbol.hasInstance,{value:function(e){return!!e&&null!=e.dataId&&null!=e.shape&&null!=e.dtype}});var ht=function(a){function s(t,e,s){void 0===e&&(e=!0);var r=a.call(this,t.shape,t.dtype,null,t.dataId)||this;r.trainable=e,r.name=s,null==r.name&&(r.name=J().nextVariableId().toString());try{J().registerVariable(r)}catch(e){throw J().disposeTensor(r),e}return r}return Fe(s,a),s.variable=function(a,n,i,r){return void 0===n&&(n=!0),null!=r&&r!==a.dtype&&(a=a.asType(r)),new s(a,n,i)},s.prototype.assign=function(e){if(e.dtype!==this.dtype)throw new Error("dtype of the new value ("+e.dtype+") and previous value ("+this.dtype+") must match");if(!g(e.shape,this.shape))throw new Error("shape of the new value ("+e.shape+") and previous value ("+this.shape+") must match");J().disposeTensor(this),this.dataId=e.dataId,J().registerTensor(this)},s.prototype.dispose=function(){J().disposeVariable(this),this.isDisposedInternal=!0},s}(Lf);Object.defineProperty(ht,Symbol.hasInstance,{value:function(e){return e instanceof Lf&&null!=e.assign&&e.assign instanceof Function}});var ft=ht.variable,yt,Ff,Bf,Pf,Mf;!function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"}(yt||(yt={})),function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"}(Ff||(Ff={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"}(Bf||(Bf={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"}(Pf||(Pf={})),function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"}(Mf||(Mf={}));var Wf={float32:Pf,int32:Ff,bool:Bf,complex64:Mf},xt=Object.freeze({makeTypesMatch:Ke,assertTypesMatch:je,isTensorInList:function(a,t){for(var e=0;e<t.length;e++)if(t[e].id===a.id)return!0;return!1},getTensorsInContainer:$e}),St=function(){function e(){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.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null}}return e.prototype.dispose=function(){for(var e in this.registeredVariables)this.registeredVariables[e].dispose()},e}(),Nt=function(){function a(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new St}return a.prototype.ready=function(){return Be(this,void 0,void 0,function(){var a,o,s;return Me(this,function(e){switch(e.label){case 0:if(null!=this.pendingBackendInit)return[2,this.pendingBackendInit.then(function(){})];if(null!=this.backendInstance)return[2];a=this.getSortedBackends(),o=0,e.label=1;case 1:return o<a.length?(s=a[o],[4,this.initializeBackend(s).success]):[3,5];case 2:return e.sent()?[4,this.setBackend(s)]:[3,4];case 3:return e.sent(),[2];case 4:return o++,[3,1];case 5:throw new Error("Could not initialize any backends, all backend initializations failed.");}})})},Object.defineProperty(a.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() before calling other methods");if(null==this.backendInstance){var a=this.initializeBackendsAndReturnBest(),t=a.name;if(a.asyncInit)throw new Error("The highest priority backend '"+t+"' has not yet been initialized. Make sure to await tf.ready() before calling other methods");this.setBackend(t)}return this.backendInstance},enumerable:!0,configurable:!0}),a.prototype.backendNames=function(){return Object.keys(this.registryFactory)},a.prototype.findBackend=function(e){if(!(e in this.registry)){if(!(e in this.registryFactory))return null;if(this.initializeBackend(e).asyncInit)return null}return this.registry[e]},a.prototype.findBackendFactory=function(e){return e in this.registryFactory?this.registryFactory[e].factory:null},a.prototype.registerBackend=function(a,t,e){return void 0===e&&(e=1),a in this.registryFactory?(console.warn(a+" backend was already registered. Reusing existing backend factory."),!1):(this.registryFactory[a]={factory:t,priority:e},!0)},a.prototype.setBackend=function(a){return Be(this,void 0,void 0,function(){var t,s,i;return Me(this,function(e){switch(e.label){case 0:if(null==this.registryFactory[a])throw new Error("Backend name '"+a+"' not found in registry");return this.backendName=a,null==this.registry[a]?(this.backendInstance=null,t=this.initializeBackend(a),s=t.success,t.asyncInit?[4,s]:[3,2]):[3,4];case 1:return i=e.sent(),[3,3];case 2:i=s,e.label=3;case 3:if(!i)return[2,!1];e.label=4;case 4:return this.backendInstance=this.registry[a],this.profiler=new u(this.backendInstance),[2,!0];}})})},a.prototype.initializeBackend=function(s){var t=this,e=this.registryFactory[s];if(null==e)throw new Error("Cannot initialize backend "+s+", no registration found.");try{var n=e.factory();if(Promise.resolve(n)===n){var r=++this.pendingBackendInitId,o=n.then(function(e){return!(r<t.pendingBackendInitId)&&(t.registry[s]=e,t.pendingBackendInit=null,!0)}).catch(function(e){return!(r<t.pendingBackendInitId)&&(t.pendingBackendInit=null,console.warn("Initialization of backend "+s+" failed"),console.warn(e.stack||e.message),!1)});return this.pendingBackendInit=o,{success:o,asyncInit:!0}}return this.registry[s]=n,{success:!0,asyncInit:!1}}catch(t){return console.warn("Initialization of backend "+s+" failed"),console.warn(t.stack||t.message),{success:!1,asyncInit:!1}}},a.prototype.removeBackend=function(e){if(!(e in this.registryFactory))throw new Error(e+" backend not found in registry");this.backendName===e&&null!=this.pendingBackendInit&&this.pendingBackendInitId++,e in this.registry&&(this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)},a.prototype.getSortedBackends=function(){var a=this;if(0===Object.keys(this.registryFactory).length)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort(function(t,e){return a.registryFactory[e].priority-a.registryFactory[t].priority})},a.prototype.initializeBackendsAndReturnBest=function(){for(var s=this.getSortedBackends(),t=0;t<s.length;t++){var i=s[t],n=this.initializeBackend(i),r=n.success,o=n.asyncInit;if(o||r)return{name:i,asyncInit:o}}throw new Error("Could not initialize any backends, all backend initializations failed.")},a.prototype.moveData=function(a,t){this.write(a,t,this.readSync(t))},a.prototype.tidy=function(a,t){var s=this,r=null,i;if(null==t){if("function"!=typeof a)throw new Error("Please provide a function to tidy()");t=a}else{if("string"!=typeof a&&!(a instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!=typeof t)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");r=a}return this.scopedRun(function(){return s.startScope(r)},function(){return s.endScope(i)},function(){return(i=t())instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),i})},a.prototype.scopedRun=function(a,o,e){a();try{var t=e();return o(),t}catch(e){throw o(),e}},a.prototype.nextTensorId=function(){return a.nextTensorId++},a.prototype.nextVariableId=function(){return a.nextVariableId++},a.prototype.clone=function(a){var t=Lf.make(a.shape,{dataId:a.dataId},a.dtype);return this.addTapeNode([a],t,function(e){return[e.toFloat()]}),t},a.prototype.runKernel=function(p,d,e){var n=this,o=[],m=this.isTapeOn(),t=null==this.state.activeScope?"":this.state.activeScope.name,s=function(e){m&&(o=e.map(function(e){return n.keep(n.clone(e))}))},i=this.state.numBytes,l=this.state.numTensors,u;if(this.scopedRun(function(){return n.state.kernelDepth++},function(){return n.state.kernelDepth--},function(){u=n.ENV.getBool("DEBUG")?n.profiler.profileKernel(t,function(){return p(n.backend,s)}):p(n.backend,s)}),m){var c={id:this.state.nextTapeNodeId++,name:t,inputs:d,outputs:Array.isArray(u)?u:[u],saved:o};null!=e&&(c.gradient=function(a){return e(a,o)}),this.state.activeTape.push(c)}return this.state.profiling&&this.state.activeProfile.kernels.push({name:t,bytesAdded:this.state.numBytes-i,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-l,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(d).map(function(e){return d[e].shape}),outputShape:Array.isArray(u)?u.map(function(e){return e.shape}):u.shape}),u},a.prototype.registerTensor=function(a,t){var e=this.state.tensorInfo.has(a.dataId)?this.state.tensorInfo.get(a.dataId).refCount:0;if(this.state.numTensors++,"string"===a.dtype&&this.state.numStringTensors++,0===e){this.state.numDataBuffers++;var n=0;"complex64"!==a.dtype&&"string"!==a.dtype&&(n=a.size*A(a.dtype)),this.state.tensorInfo.set(a.dataId,{backend:null==t?this.backend:t,dtype:a.dtype,shape:a.shape,bytes:n,refCount:0}),this.state.numBytes+=n,null==t?this.backend.register(a.dataId,a.shape,a.dtype):t.register(a.dataId,a.shape,a.dtype)}this.state.tensorInfo.get(a.dataId).refCount++,a instanceof ht||this.track(a)},a.prototype.registerVariable=function(e){if(null!=this.state.registeredVariables[e.name])throw new Error("Variable with name "+e.name+" was already registered");this.state.registeredVariables[e.name]=e},a.prototype.disposeTensor=function(a){if(this.state.tensorInfo.has(a.dataId)){this.state.numTensors--,"string"===a.dtype&&this.state.numStringTensors--;var t=this.state.tensorInfo.get(a.dataId);1>=t.refCount?("complex64"!==a.dtype&&(this.state.numBytes-=t.bytes),this.state.numDataBuffers--,t.backend.disposeData(a.dataId),this.state.tensorInfo.delete(a.dataId)):this.state.tensorInfo.get(a.dataId).refCount--}},a.prototype.disposeVariables=function(){for(var a in this.state.registeredVariables){var t=this.state.registeredVariables[a];this.disposeVariable(t)}},a.prototype.disposeVariable=function(e){this.disposeTensor(e),null!=this.state.registeredVariables[e.name]&&delete this.state.registeredVariables[e.name]},a.prototype.memory=function(){var e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,0<this.state.numStringTensors&&(e.unreliable=!0,null==e.reasons&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e},a.prototype.profile=function(a){return Be(this,void 0,void 0,function(){var t,r;return Me(this,function(){return this.state.profiling=!0,t=this.state.numBytes,r=this.state.numTensors,this.state.activeProfile.kernels=[],this.state.activeProfile.result=a(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Ef.apply(Math,this.state.activeProfile.kernels.map(function(e){return e.totalBytesSnapshot})),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-r,[2,this.state.activeProfile]})})},a.prototype.isTapeOn=function(){return 0<this.state.gradientDepth&&0===this.state.kernelDepth},a.prototype.addTapeNode=function(a,t,s){var n={};a.forEach(function(a,t){n[t]=a});var e={id:this.state.nextTapeNodeId++,name:this.state.activeScope.name,inputs:n,outputs:[t],gradient:function(a){var t=s(a),n={};return t.forEach(function(a,t){n[t]=function(){return a}}),n}};this.state.activeTape.push(e)},a.prototype.keep=function(e){return e.kept=!0,e},a.prototype.startTape=function(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++},a.prototype.endTape=function(){this.state.gradientDepth--},a.prototype.startScope=function(a){var t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};a&&(t.name=a),this.state.scopeStack.push(t),this.state.activeScope=t},a.prototype.endScope=function(s){for(var p=this,e=$e(s),t=new Set(e.map(function(e){return e.id})),n=0,r;n<this.state.activeScope.track.length;n++)r=this.state.activeScope.track[n],r.kept||t.has(r.id)||r.dispose();var d=this.state.scopeStack.pop();this.state.activeScope=0===this.state.scopeStack.length?null:this.state.scopeStack[this.state.scopeStack.length-1],e.forEach(function(e){e.kept||e.scopeId!==d.id||p.track(e)})},a.prototype.gradients=function(s,p,e,t){var n=this;if(void 0===t&&(t=!1),Ue(0<p.length,function(){return"gradients() received an empty list of xs."}),null!=e&&"float32"!==e.dtype)throw new Error("dy must have 'float32' dtype, but has '"+e.dtype+"'");var o=this.scopedRun(function(){return n.startTape()},function(){return n.endTape()},function(){return n.tidy("forward",s)});Ue(o instanceof Lf,function(){return"The result y returned by f() must be a tensor."});var a=function(y,t,e){for(var n={},r={},o=0;o<t.length;o++)n[t[o].id]=!0;for(o=0;o<y.length;o++){var b=(p=y[o]).inputs;for(var x in b){for(var C=b[x],u=!1,S=0;S<t.length;S++)if(n[C.id]){p.outputs.forEach(function(e){return n[e.id]=!0}),u=!0,r[p.id]=!0;break}if(u)break}}var N={};N[e.id]=!0;var h={};for(o=y.length-1;0<=o;o--)for(b=(p=y[o]).inputs,S=0;S<p.outputs.length;S++)if(N[p.outputs[S].id]){for(var x in b)N[b[x].id]=!0,h[p.id]=!0;break}var f=[];for(o=0;o<y.length;o++){var p;if(r[(p=y[o]).id]&&h[p.id]){var I={};for(var x in p.inputs){var v=p.inputs[x];n[v.id]&&(I[x]=v)}var m=Object.assign({},p);m.inputs=I,m.outputs=p.outputs,f.push(m)}}return f}(this.state.activeTape,p,o);if(!t&&0===a.length&&0<p.length)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 i={},s,d;i[o.id]=null==e?(s=o.shape,d=W(qe(s),"float32"),Lf.make(s,{values:d})):e,function(p,t,d){for(var e=function(e){var n=t[e],o=[];if(n.outputs.forEach(function(t){var e=p[t.id];if(null!=e)o.push(e);else{var a=Lf.make(t.shape,{values:V(t.size,t.dtype)},t.dtype);o.push(a)}}),null==n.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+n.name+".");var l=n.gradient(1===n.outputs.length?o[0]:o),a=function(t){if(!(t in l))throw new Error("Cannot backprop through input "+t+". Available gradients found: "+Object.keys(l)+".");var e=d(function(){return l[t]()});if("float32"!==e.dtype)throw new Error("Error in gradient for op "+n.name+". The gradient of input "+t+" must have 'float32' dtype, but has '"+e.dtype+"'");var r=n.inputs[t];if(!g(e.shape,r.shape))throw new Error("Error in gradient for op "+n.name+". The gradient of input '"+t+"' has shape '"+e.shape+"', which does not match the shape of the input '"+r.shape+"'");if(null==p[r.id])p[r.id]=e;else{var a=p[r.id];p[r.id]=a.add(e),a.dispose()}};for(var r in n.inputs)a(r)},a=t.length-1;0<=a;a--)e(a)}(i,a,function(e){return n.tidy(e)});var l=p.map(function(e){return i[e.id]});return 0===n.state.gradientDepth&&(n.state.activeTape.forEach(function(a){for(var t in a.saved)a.saved[t].dispose()}),n.state.activeTape=null),{value:o,grads:l}})},a.prototype.customGrad=function(a){var t=this;return Ue(F(a),function(){return"The f passed in customGrad(f) must be a function."}),function(){for(var s=[],e=0,r;e<arguments.length;e++)s[e]=arguments[e];Ue(s.every(function(e){return e instanceof Lf}),function(){return"The args passed in customGrad(f)(x1, x2,...) must all be tensors"});var i={};return s.forEach(function(a,t){i[t]=a}),t.runKernel(function(t,e){return Ue((r=a.apply(void 0,s.concat([e]))).value instanceof Lf,function(){return"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"}),Ue(F(r.gradFunc),function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."}),r.value},i,function(n,t){var e=r.gradFunc(n,t),o=Array.isArray(e)?e:[e];Ue(o.length===s.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(...)."}),Ue(o.every(function(e){return e instanceof Lf}),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 a={};return o.forEach(function(n,t){a[t]=function(){return n}}),a})}},a.prototype.write=function(s,i,p){var n=this.state.tensorInfo.get(i),r=n.backend;if(s=s||this.backend,"string"===n.dtype){var o=e(p);this.state.numBytes+=o-n.bytes,n.bytes=o}s!==r&&(r.disposeData(i),n.backend=s,s.register(i,n.shape,n.dtype)),s.write(i,p)},a.prototype.readSync=function(e){return this.state.tensorInfo.get(e).backend.readSync(e)},a.prototype.read=function(e){return this.state.tensorInfo.get(e).backend.read(e)},a.prototype.fromPixels=function(a,t){return this.backend.fromPixels(a,t)},a.prototype.time=function(a){return Be(this,void 0,void 0,function(){var t,o;return Me(this,function(e){switch(e.label){case 0:return t=U(),[4,this.backend.time(a)];case 1:return(o=e.sent()).wallMs=U()-t,[2,o];}})})},a.prototype.track=function(e){return null!=this.state.activeScope&&(e.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(e)),e},Object.defineProperty(a.prototype,"registeredVariables",{get:function(){return this.state.registeredVariables},enumerable:!0,configurable:!0}),a.prototype.reset=function(){for(var e in this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new St,this.registry)this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null},a.nextTensorId=0,a.nextVariableId=0,a}(),kt=function(){var n=function(){if(null==At){var e;if("undefined"!=typeof window)e=window;else if("undefined"!=typeof global)e=global;else if("undefined"!=typeof process)e=process;else{if("undefined"==typeof self)throw new Error("Could not find a global object");e=self}At=e}return At}();if(null==n._tfengine){var t=new Df(n);n._tfengine=new Nt(t)}return a(n._tfengine.ENV),J=function(){return n._tfengine},n._tfengine}(),At;_f.registerFlag("DEBUG",function(){return!1},function(e){e&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")}),_f.registerFlag("IS_BROWSER",function(){return Xe()}),_f.registerFlag("IS_NODE",function(){return"undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node}),_f.registerFlag("IS_CHROME",function(){return"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)}),_f.registerFlag("PROD",function(){return!1}),_f.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",function(){return _f.getBool("DEBUG")}),_f.registerFlag("DEPRECATION_WARNINGS_ENABLED",function(){return!0}),_f.registerFlag("IS_TEST",function(){return!1});var Vf={},Ot={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0},Ft,Uf;!function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"}(Ft||(Ft={})),function(e){e[e.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",e[e.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",e[e.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",e[e.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",e[e.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"}(Uf||(Uf={}));var Gf=5.96e-8,Gt=/ERROR: [0-9]+:([0-9]+):/g,Jt=Object.freeze({callAndCheck:rt,canBeRepresented:ot,getWebGLErrorMessage:it,getExtensionOrThrow:bt,createVertexShader:Ct,createFragmentShader:Tt,createProgram:Rt,linkProgram:Et,validateProgram:te,createStaticVertexBuffer:ee,createStaticIndexBuffer:ne,getNumChannels:function(){return 2===_f.getNumber("WEBGL_VERSION")?1:4},createTexture:re,validateTextureSize:oe,createFramebuffer:ae,bindVertexBufferToProgramAttribute:ie,bindTextureUnit:se,unbindTextureUnit:function(a,t,e){me(a,e),rt(a,t,function(){return a.activeTexture(a.TEXTURE0+e)}),rt(a,t,function(){return a.bindTexture(a.TEXTURE_2D,null)})},getProgramUniformLocationOrThrow:ue,getProgramUniformLocation:le,bindTextureToProgramUniformSampler:ce,bindCanvasToFramebuffer:function(a,t){rt(a,t,function(){return a.bindFramebuffer(a.FRAMEBUFFER,null)}),rt(a,t,function(){return a.viewport(0,0,a.canvas.width,a.canvas.height)}),rt(a,t,function(){return a.scissor(0,0,a.canvas.width,a.canvas.height)})},bindColorTextureToFramebuffer:he,unbindColorTextureFromFramebuffer:fe,validateFramebuffer:pe,getFramebufferErrorMessage:de,getBatchDim:ge,getRowsCols:ye,getShapeAs3D:xe,getTextureShapeFromLogicalShape:be,isReshapeFree:Ce,getWebGLMaxTextureSize:Ee,resetMaxTextureSize:function(){Oe=null},resetMaxTexturesInShader:function(){qf=null},getMaxTexturesInShader:Re,getWebGLDisjointQueryTimerVersion:Ie,hasExtension:Se,isWebGLVersionEnabled:Ne,isRenderToFloatTextureEnabled:ke,isDownloadFloatTextureEnabled:Ae,isWebGLFenceEnabled:De}),Oe,qf;_f.registerFlag("HAS_WEBGL",function(){return 0<_f.getNumber("WEBGL_VERSION")}),_f.registerFlag("WEBGL_VERSION",function(){return Ne(2)?2:Ne(1)?1:0}),_f.registerFlag("WEBGL_BUFFER_SUPPORTED",function(){return 2===_f.get("WEBGL_VERSION")}),_f.registerFlag("WEBGL_CPU_FORWARD",function(){return!0}),_f.registerFlag("WEBGL_PACK",function(){return _f.getBool("HAS_WEBGL")}),_f.registerFlag("WEBGL_PACK_NORMALIZATION",function(){return _f.getBool("WEBGL_PACK")}),_f.registerFlag("WEBGL_PACK_CLIP",function(){return _f.getBool("WEBGL_PACK")}),_f.registerFlag("WEBGL_PACK_DEPTHWISECONV",function(){return!1}),_f.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",function(){return _f.getBool("WEBGL_PACK")}),_f.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",function(){return _f.getBool("WEBGL_PACK")}),_f.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",function(){return _f.getBool("WEBGL_PACK")}),_f.registerFlag("WEBGL_PACK_REDUCE",function(){return _f.getBool("WEBGL_PACK")}),_f.registerFlag("WEBGL_LAZILY_UNPACK",function(){return _f.getBool("WEBGL_PACK")}),_f.registerFlag("WEBGL_CONV_IM2COL",function(){return _f.getBool("WEBGL_PACK")}),_f.registerFlag("WEBGL_MAX_TEXTURE_SIZE",function(){return Ee(_f.getNumber("WEBGL_VERSION"))}),_f.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",function(){return Re(_f.getNumber("WEBGL_VERSION"))}),_f.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",function(){var e=_f.getNumber("WEBGL_VERSION");return 0===e?0:Ie(e)}),_f.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",function(){return 0<_f.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")&&(e=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(e)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4))));var e}),_f.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",function(){return ke(_f.getNumber("WEBGL_VERSION"))}),_f.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",function(){return Ae(_f.getNumber("WEBGL_VERSION"))}),_f.registerFlag("WEBGL_FENCE_API_ENABLED",function(){return De(_f.getNumber("WEBGL_VERSION"))}),_f.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",function(){return _f.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0}),zf=_e;var Hf=Xt({complex_:function(a,t){var e=Lt(a,"real","complex"),n=Lt(t,"imag","complex");return p(e.shape,n.shape,"real and imag shapes, "+e.shape+" and "+n.shape+", must match in call to tf.complex()."),kt.runKernel(function(a){return a.complex(e,n)},{$real:e,$imag:n})}}),gn=Xt({real_:function(a){var n=Lt(a,"input","real");return kt.runKernel(function(e){return e.real(n)},{$input:n})}}),yn=Xt({imag_:function(a){var n=Lt(a,"input","imag");return kt.runKernel(function(e){return e.imag(n)},{$input:n})}}),xn=Xt({onesLike_:function(a){var o=Lt(a,"x","onesLike");if("complex64"===o.dtype){var e=xn(gn(o)),t=Fn(yn(o));return Hf(e,t)}return kt.runKernel(function(e){return e.onesLike(o)},{$x:o},function(e){return{$x:function(){return Fn(e)}}})}}),Fn=Xt({zerosLike_:function(a){var n=Lt(a,"x","zerosLike");return kt.runKernel(function(e){return e.zerosLike(n)},{$x:n},function(e){return{$x:function(){return Fn(e)}}})}}),Mn=Xt({concat_:function(s,i){void 0===i&&(i=0),Ue(1<=s.length,function(){return"Pass at least one tensor to concat"});var p=Bt(s,"tensors","concat");i=C(i,p[0].shape)[0];var t=$t(p.map(function(e){return e.shape}),i);if(0===qe(t))return Zt([],t);if(1===(p=p.filter(function(e){return 0<e.size})).length)return p[0];var r=p.map(function(e){return e.shape});jt(r,i);var o=p;return kt.runKernel(function(e){return e.concat(p,i)},o,function(e){var t=r.map(function(e){return e[i]});return Un(e,t,i).map(function(e){return function(){return e}})})}}),Bn=Xt({concat1d_:function(e){return Mn(e,0)}}),Pn=Xt({concat2d_:function(a,t){return Mn(a,t)}}),Ln=Xt({concat3d_:function(a,t){return Mn(a,t)}}),Wn=Xt({concat4d_:function(a,t){return Mn(a,t)}}),Un=Xt({split_:function(a,t,e){void 0===e&&(e=0);var s=Lt(a,"x","split"),o;return e=C(e,s.shape)[0],"number"==typeof t?(Ue(0==s.shape[e]%t,function(){return"Number of splits must evenly divide the axis."}),o=Array(t).fill(s.shape[e]/t)):(Ue(s.shape[e]===t.reduce(function(a,t){return a+t}),function(){return"The sum of sizes must match the size of the axis dimension."}),o=t),kt.runKernel(function(a){return a.split(s,o,e)},{$x:s},function(a){return{$x:function(){return Mn(a,e)}}})}}),zn=cn(function(e){!function(s,t,e){function p(a){var o=this,t=(s=4022871197,function(e){e=e.toString();for(var a=0,o;a<e.length;a++)o=.02519603282416938*(s+=e.charCodeAt(a)),o-=s=o>>>0,s=(o*=s)>>>0,s+=4294967296*(o-=s);return 23283064365386963e-26*(s>>>0)}),s;o.next=function(){var e=2091639*o.s0+23283064365386963e-26*o.c;return o.s0=o.s1,o.s1=o.s2,o.s2=e-(o.c=0|e)},o.c=1,o.s0=t(" "),o.s1=t(" "),o.s2=t(" "),o.s0-=t(a),0>o.s0&&(o.s0+=1),o.s1-=t(a),0>o.s1&&(o.s1+=1),o.s2-=t(a),0>o.s2&&(o.s2+=1),t=null}function r(a,t){return t.c=a.c,t.s0=a.s0,t.s1=a.s1,t.s2=a.s2,t}function n(o,t){var e=new p(o),n=t&&t.state,a=e.next;return a.int32=function(){return 0|4294967296*e.next()},a.double=function(){return a()+11102230246251565e-32*(0|2097152*a())},a.quick=a,n&&("object"==typeof n&&r(n,e),a.state=function(){return r(e,{})}),a}t&&t.exports?t.exports=n:e&&e.amd?e(function(){return n}):this.alea=n}(0,e,!1)}),Gn=cn(function(e){!function(s,t,e){function p(a){var o=this,e="";o.x=0,o.y=0,o.z=0,o.w=0,o.next=function(){var e=o.x^o.x<<11;return o.x=o.y,o.y=o.z,o.z=o.w,o.w^=o.w>>>19^e^e>>>8},a===(0|a)?o.x=a:e+=a;for(var t=0;t<e.length+64;t++)o.x^=0|e.charCodeAt(t),o.next()}function r(a,t){return t.x=a.x,t.y=a.y,t.z=a.z,t.w=a.w,t}function n(o,t){var e=new p(o),n=t&&t.state,a=function(){return(e.next()>>>0)/4294967296};return a.double=function(){do var a=((e.next()>>>11)+(e.next()>>>0)/4294967296)/2097152;while(0===a);return a},a.int32=e.next,a.quick=a,n&&("object"==typeof n&&r(n,e),a.state=function(){return r(e,{})}),a}t&&t.exports?t.exports=n:e&&e.amd?e(function(){return n}):this.xor128=n}(0,e,!1)}),Hn=cn(function(e){!function(s,t,e){function p(a){var o=this,e="";o.next=function(){var e=o.x^o.x>>>2;return o.x=o.y,o.y=o.z,o.z=o.w,o.w=o.v,0|(o.d=0|o.d+362437)+(o.v=o.v^o.v<<4^e^e<<1)},o.x=0,o.y=0,o.z=0,o.w=0,o.v=0,a===(0|a)?o.x=a:e+=a;for(var t=0;t<e.length+64;t++)o.x^=0|e.charCodeAt(t),t==e.length&&(o.d=o.x<<10^o.x>>>4),o.next()}function r(a,t){return t.x=a.x,t.y=a.y,t.z=a.z,t.w=a.w,t.v=a.v,t.d=a.d,t}function n(o,t){var e=new p(o),n=t&&t.state,a=function(){return(e.next()>>>0)/4294967296};return a.double=function(){do var a=((e.next()>>>11)+(e.next()>>>0)/4294967296)/2097152;while(0===a);return a},a.int32=e.next,a.quick=a,n&&("object"==typeof n&&r(n,e),a.state=function(){return r(e,{})}),a}t&&t.exports?t.exports=n:e&&e.amd?e(function(){return n}):this.xorwow=n}(0,e,!1)}),qn=cn(function(e){!function(s,t,e){function p(a){var s=this;s.next=function(){var e=s.x,a=s.i,r,o;return r=e[a],o=(r^=r>>>7)^r<<24,o^=(r=e[7&a+1])^r>>>10,o^=(r=e[7&a+3])^r>>>3,o^=(r=e[7&a+4])^r<<7,r=e[7&a+7],o^=(r^=r<<13)^r<<9,e[a]=o,s.i=7&a+1,o},function(a,t){var o=[],r;if(t===(0|t))o[0]=t;else for(t=""+t,r=0;r<t.length;++r)o[7&r]=o[7&r]<<15^t.charCodeAt(r)+o[7&r+1]<<13;for(;8>o.length;)o.push(0);for(r=0;8>r&&0===o[r];++r);for(8==r?o[7]=-1:o[r],a.x=o,a.i=0,r=256;0<r;--r)a.next()}(s,a)}function r(a,t){return t.x=a.x.slice(),t.i=a.i,t}function n(o,s){null==o&&(o=+new Date);var e=new p(o),n=s&&s.state,a=function(){return(e.next()>>>0)/4294967296};return a.double=function(){do var a=((e.next()>>>11)+(e.next()>>>0)/4294967296)/2097152;while(0===a);return a},a.int32=e.next,a.quick=a,n&&(n.x&&r(n,e),a.state=function(){return r(e,{})}),a}t&&t.exports?t.exports=n:e&&e.amd?e(function(){return n}):this.xorshift7=n}(0,e,!1)}),$n=cn(function(e){!function(s,t,e){function p(a){var s=this;s.next=function(){var e=s.w,i=s.X,o=s.i,p,d;return s.w=e=0|e+1640531527,d=i[127&o+34],p=i[o=127&o+1],d^=d<<13,p^=p<<17,d^=d>>>15,p^=p>>>12,d=i[o]=d^p,s.i=o,0|d+(e^e>>>16)},function(p,t){var d=[],s=128,l,c,h,m,g;for(t===(0|t)?(c=t,t=null):(t+="\0",c=0,s=Ef(s,t.length)),h=0,m=-32;m<s;++m)t&&(c^=t.charCodeAt((m+32)%t.length)),0===m&&(g=c),c^=c<<10,c^=c>>>15,c^=c<<4,c^=c>>>13,0<=m&&(g=0|g+1640531527,h=0==(l=d[127&m]^=c+g)?h+1:0);for(128<=h&&(d[127&(t&&t.length||0)]=-1),h=127,m=512;0<m;--m)c=d[127&h+34],l=d[h=127&h+1],c^=c<<13,l^=l<<17,c^=c>>>15,l^=l>>>12,d[h]=c^l;p.w=g,p.X=d,p.i=h}(s,a)}function r(a,t){return t.i=a.i,t.w=a.w,t.X=a.X.slice(),t}function n(o,s){null==o&&(o=+new Date);var e=new p(o),n=s&&s.state,a=function(){return(e.next()>>>0)/4294967296};return a.double=function(){do var a=((e.next()>>>11)+(e.next()>>>0)/4294967296)/2097152;while(0===a);return a},a.int32=e.next,a.quick=a,n&&(n.X&&r(n,e),a.state=function(){return r(e,{})}),a}t&&t.exports?t.exports=n:e&&e.amd?e(function(){return n}):this.xor4096=n}(0,e,!1)}),jn=cn(function(e){!function(s,t,e){function p(a){var s=this,e="";s.next=function(){var e=s.b,a=s.c,i=s.d,p=s.a;return e=e<<25^e>>>7^a,a=0|a-i,i=i<<24^i>>>8^p,p=0|p-e,s.b=e=e<<20^e>>>12^a,s.c=a=0|a-i,s.d=i<<16^a>>>16^p,s.a=0|p-e},s.a=0,s.b=0,s.c=-1640531527,s.d=1367130551,a===Cf(a)?(s.a=0|a/4294967296,s.b=0|a):e+=a;for(var t=0;t<e.length+20;t++)s.b^=0|e.charCodeAt(t),s.next()}function r(a,t){return t.a=a.a,t.b=a.b,t.c=a.c,t.d=a.d,t}function n(o,t){var e=new p(o),n=t&&t.state,a=function(){return(e.next()>>>0)/4294967296};return a.double=function(){do var a=((e.next()>>>11)+(e.next()>>>0)/4294967296)/2097152;while(0===a);return a},a.int32=e.next,a.quick=a,n&&("object"==typeof n&&r(n,e),a.state=function(){return r(e,{})}),a}t&&t.exports?t.exports=n:e&&e.amd?e(function(){return n}):this.tychei=n}(0,e,!1)}),Kn=cn(function(a){!function(s,i){function e(e,t,a){var r=[],m=d(function s(t,e){var n=[],o=typeof t,a;if(e&&"object"==o)for(a in t)try{n.push(s(t[a],e-1))}catch(e){}return n.length?n:"string"==o?t:t+"\0"}((t=1==t?{entropy:!0}:t||{}).entropy?[e,v(s)]:null==e?function(){try{var e;return c&&(e=c.randomBytes)?e=e(256):(e=new Uint8Array(256),(h.crypto||h.msCrypto).getRandomValues(e)),v(e)}catch(e){var a=h.navigator,n=a&&a.plugins;return[+new Date,h,n,h.screen,v(s)]}}():e,3),r),g=new n(r),f=function(){for(var a=g.g(6),r=o,s=0;a<u;)a=256*(a+s),r*=256,s=g.g(1);for(;a>=l;)a/=2,r/=2,s>>>=1;return(a+s)/r};return f.int32=function(){return 0|g.g(4)},f.quick=function(){return g.g(4)/4294967296},f.double=f,d(v(g.S),s),(t.pass||a||function(a,t,e,n){return n&&(n.S&&p(n,g),a.state=function(){return p(g,{})}),e?(i.random=a,t):a})(f,m,"global"in t?t.global:this==i,t.state)}function n(a){var p=a.length,d=this,r=0,l=d.i=d.j=0,u=d.S=[],s;for(p||(a=[p++]);256>r;)u[r]=r++;for(r=0;256>r;r++)u[r]=u[l=255&l+a[r%p]+(s=u[r])],u[l]=s;(d.g=function(a){for(var r=0,p=d.i,l=d.j,u=d.S,s;a--;)s=u[p=255&p+1],r=256*r+u[255&(u[p]=u[l=255&l+s])+(u[l]=s)];return d.i=p,d.j=l,r})(256)}function p(a,t){return t.i=a.i,t.j=a.j,t.S=a.S.slice(),t}function d(a,t){for(var e=a+"",r=0,s;r<e.length;)t[255&r]=255&(s^=19*t[255&r])+e.charCodeAt(r++);return v(t)}function v(e){return cf.apply(0,e)}var h=this,o=i.pow(256,6),u=i.pow(2,52),l=2*u,c;if(i.seedrandom=e,d(i.random(),s),a.exports){a.exports=e;try{c=require("crypto")}catch(e){}}}([],Math)});Kn.alea=zn,Kn.xor128=Gn,Kn.xorwow=Hn,Kn.xorshift7=qn,Kn.xor4096=$n,Kn.tychei=jn;var Xn=Kn.alea,Yn=function(){function e(s,t,e,n,r){this.mean=s,this.stdDev=t,this.dtype=e,this.nextVal=NaN,this.truncated=n,this.truncated&&(this.upper=this.mean+2*this.stdDev,this.lower=this.mean-2*this.stdDev);var o=r||Math.random();this.random=Xn(o.toString())}return e.prototype.nextValue=function(){if(!isNaN(this.nextVal)){var p=this.nextVal;return this.nextVal=NaN,p}for(var t=!1,d,l;!t;){var u=void 0,c=void 0,h=void 0;do h=(u=2*this.random()-1)*u+(c=2*this.random()-1)*c;while(1<=h||0===h);var m=Tf(-2*mf(h)/h);d=this.mean+this.stdDev*u*m,l=this.mean+this.stdDev*c*m,this.truncated&&!this.isValidTruncated(d)||(t=!0)}return this.truncated&&!this.isValidTruncated(l)||(this.nextVal=this.convertValue(l)),this.convertValue(d)},e.prototype.convertValue=function(e){return null==this.dtype||"float32"===this.dtype?e:If(e)},e.prototype.isValidTruncated=function(e){return e<=this.upper&&e>=this.lower},e}(),Qn=function(){function e(a,s,i,n){void 0===a&&(a=0),void 0===s&&(s=1);var p=this;if(this.canReturnFloat=function(){return null==p.dtype||"float32"===p.dtype},this.min=a,this.range=s-a,this.dtype=i,null==n&&(n=Math.random()),"number"==typeof n&&(n=n.toString()),!this.canReturnFloat()&&1>=this.range)throw new Error("The difference between "+a+" - "+s+" <= 1 and dtype is not float");this.random=Xn(n)}return e.prototype.convertValue=function(e){return this.canReturnFloat()?e:If(e)},e.prototype.nextValue=function(){return this.convertValue(this.min+this.range*this.random())},e}(),Jn=Xt({batchToSpaceND_:function(a,s,e){var n=Lt(a,"x","batchToSpaceND"),t=s.reduce(function(a,t){return a*t});return Ue(n.rank>=1+s.length,function(){return"input rank is "+n.rank+" but should be > than blockShape.length "+s.length}),Ue(e.length===s.length,function(){return"crops.length is "+e.length+" but should be equal to blockShape.length  "+s.length}),Ue(0==n.shape[0]%t,function(){return"input tensor batch is "+n.shape[0]+" but is not divisible by the product of the elements of blockShape "+s.join(" * ")+" === "+t}),kt.runKernel(function(a){return a.batchToSpaceND(n,s,e)},{$x:n},function(a){return{$x:function(){return a.spaceToBatchND(s,e)}}})}}),er=Xt({cast_:function(a,r){var e=Lt(a,"x","cast");if(!T(r))throw new Error("Failed to cast to unknown dtype "+r);if("string"===r&&"string"!==e.dtype||"string"!==r&&"string"===e.dtype)throw new Error("Only strings can be casted to strings");return kt.runKernel(function(a){return a.cast(e,r)},{$x:e},function(e){return{$x:function(){return e.clone()}}})}}),nr=Xt({clone_:function(a){var t=Lt(a,"x","clone",null);return kt.runKernel(function(){return Lf.make(t.shape,{dataId:t.dataId},t.dtype)},{$x:t},function(e){return{$x:function(){return e.toFloat()}}})}}),rr=Xt({cumsum_:function(p,d,l,c){void 0===d&&(d=0),void 0===l&&(l=!1),void 0===c&&(c=!1);var t=Lt(p,"x","cumsum"),o=qt([d|=0],t.rank),a=t;null!=o&&(a=t.transpose(o));var h=Kt(1,t.rank)[0],s=kt.runKernel(function(e){return e.cumsum(a,h,l,c)},{permutedX:a},function(e){return{permutedX:function(){return e.cumsum(d,l,!c)}}});return null!=o&&(s=s.transpose(o)),s}}),or=Xt({depthToSpace_:function(s,p,e){void 0===e&&(e="NHWC");var d=Lt(s,"x","depthToSpace"),t="NHWC"===e?d.shape[1]:d.shape[2],r="NHWC"===e?d.shape[2]:d.shape[3],a="NHWC"===e?d.shape[3]:d.shape[1];return Ue(0<=t*p,function(){return"Negative dimension size caused by overflow when multiplying\n      "+t+" and "+p+"  for depthToSpace with input shape\n      "+d.shape}),Ue(0<=r*p,function(){return"Negative dimension size caused by overflow when multiplying\n      "+r+" and "+p+" for depthToSpace with input shape\n          "+d.shape}),Ue(0==a%(p*p),function(){return"Dimension size must be evenly divisible by "+p*p+" but is "+a+" for depthToSpace with input shape "+d.shape}),kt.runKernel(function(a){return a.depthToSpace(d,p,e)},{$x:d})}}),ar=Xt({expandDims_:function(a,t){void 0===t&&(t=0);var o=Lt(a,"x","expandDims",null);Ue(t<=o.rank,function(){return"Axis must be <= rank of the tensor"});var n=o.shape.slice();return 0>t&&(Ue(-(o.rank+1)<=t,function(){return"Axis must be in the interval ["+-(o.rank+1)+", "+o.rank+"]"}),t=o.rank+t+1),n.splice(t,0,1),gr(o,n)}}),ir=Xt({eye_:function(p,t,d,n){void 0===n&&(n="float32"),null==t&&(t=p);for(var l=hn([p,t],n),o=p<=t?p:t,a=0;a<o;++a)l.set(1,a,a);var u=l.toTensor().as2D(p,t);if(null==d)return u;if(1===d.length)return wr(ar(u,0),[d[0],1,1]);if(2===d.length)return wr(ar(ar(u,0),0),[d[0],d[1],1,1]);if(3===d.length)return wr(ar(ar(ar(u,0),0),0),[d[0],d[1],d[2],1,1]);throw new Error("eye() currently supports only 1D and 2D batchShapes, but received "+d.length+"D.")}}),sr=Xt({multinomial_:function(p,d,e,l){void 0===l&&(l=!1);var t=Lt(p,"logits","multinomial"),o=t.size,a=t.rank;if(2>o)throw new Error("Error in multinomial: you need at least 2 outcomes, but got "+o+".");if(2<a)throw new Error("Rank of probabilities must be 1 or 2, but is "+a);e=e||Math.random();var i=1===a?t.as2D(1,-1):t,s=kt.runKernel(function(a){return a.multinomial(i,l,d,e)},{logits2D:i});return 1===a?s.as1D():s}}),ur=Xt({oneHot_:function(s,i,e,p){if(void 0===e&&(e=1),void 0===p&&(p=0),2>i)throw new Error("Error in oneHot: depth must be >=2, but it is "+i);var d=Lt(s,"indices","oneHot","int32"),t=d.shape.concat([i]);return d=d.flatten(),kt.runKernel(function(a){return a.oneHot(d,i,e,p)},{$indices:d},function(){return{$indices:function(){return pn(d.shape,"float32")}}}).reshape(t)}}),lr=Xt({pad_:function(a,s,e){void 0===e&&(e=0);var i=Lt(a,"x","pad");if(0===i.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var r=s.map(function(e){return e[0]});return kt.runKernel(function(a){return a.pad(i,s,e)},{$x:i},function(e){return{$x:function(){return e.slice(r,i.shape)}}})}}),cr=Xt({pad1d_:function(a,t,e){return void 0===e&&(e=0),Ue(2===t.length,function(){return"Invalid number of paddings. Must be length of 2."}),lr(a,[t],e)}}),hr=Xt({pad2d_:function(a,t,e){return void 0===e&&(e=0),Ue(2===t.length&&2===t[0].length&&2===t[1].length,function(){return"Invalid number of paddings. Must be length of 2 each."}),lr(a,t,e)}}),fr=Xt({pad3d_:function(a,t,e){return void 0===e&&(e=0),Ue(3===t.length&&2===t[0].length&&2===t[1].length&&2===t[2].length,function(){return"Invalid number of paddings. Must be length of 2 each."}),lr(a,t,e)}}),pr=Xt({pad4d_:function(a,t,e){return void 0===e&&(e=0),Ue(4===t.length&&2===t[0].length&&2===t[1].length&&2===t[2].length&&2===t[3].length,function(){return"Invalid number of paddings. Must be length of 2 each."}),lr(a,t,e)}}),dr=Xt({rand_:function(s,t,e){var n=qe(s),r=null;if(null==e||"float32"===e)r=new Float32Array(n);else if("int32"===e)r=new Int32Array(n);else{if("bool"!==e)throw new Error("Unknown data type "+e);r=new Uint8Array(n)}for(var i=0;i<n;i++)r[i]=t();return Lf.make(s,{values:r},e)}}),vr=Xt({randomNormal_:function(p,t,d,l,r){if(void 0===t&&(t=0),void 0===d&&(d=1),null!=l&&"bool"===l)throw new Error("Unsupported data type "+l);for(var o=new Yn(t,d,l,!1,r),a=hn(p,l),i=0;i<a.values.length;i++)a.values[i]=o.nextValue();return a.toTensor()}}),mr=Xt({randomUniform_:function(p,t,d,l,u){void 0===t&&(t=0),void 0===d&&(d=1),void 0===l&&(l="float32");for(var o=hn(p,l),a=new Qn(t,d,null,u),i=0;i<o.values.length;i++)o.values[i]=a.nextValue();return o.toTensor()}}),gr=Xt({reshape_:function(a,r){var o=Lt(a,"x","reshape",null);return r=x(r,o.size),Ue(o.size===qe(r),function(){return"new shape and old shape must have the same number of elements."}),kt.runKernel(function(e){return e.reshape(o,r)},{$x:o},function(e){return{$x:function(){return e.reshape(o.shape)}}})}}),yr=Xt({spaceToBatchND_:function(a,s,e){var n=Lt(a,"x","spaceToBatchND");return Ue(n.rank>=1+s.length,function(){return"input rank "+n.rank+" should be > than [blockShape] "+s.length}),Ue(e.length===s.length,function(){return"paddings.shape[0] "+e.length+" must be equal to [blockShape] "+s.length}),Ue(n.shape.reduce(function(a,t,n){return 0<n&&n<=s.length?a&&0==(t+e[n-1][0]+e[n-1][1])%s[n-1]:a},!0),function(){return"input spatial dimensions "+n.shape.slice(1)+" with paddings "+e.toString()+" must be divisible by blockShapes "+s.toString()}),kt.runKernel(function(a){return a.spaceToBatchND(n,s,e)},{$x:n},function(a){return{$x:function(){return a.batchToSpaceND(s,e)}}})}}),xr=Xt({squeeze_:function(a,t){var e=Lt(a,"x","squeeze");return gr(e,I(e.shape,t).newShape)}}),br=Xt({stack_:function(s,d){void 0===d&&(d=0);var t=Bt(s,"tensors","stack");if(Ue(1<=t.length,function(){return"Pass at least one tensor to tf.stack"}),1===t.length)return t[0].expandDims(d);var n=t[0].rank,r=t[0].shape,o=t[0].dtype;Ue(d<=n,function(){return"Axis must be <= rank of the tensor"}),t.forEach(function(e){p(r,e.shape,"All tensors passed to stack must have matching shapes")}),t.forEach(function(e){Ue(o===e.dtype,function(){return"All tensors passed to stack must have matching dtypes"})});var a=t.map(function(e){return e.expandDims(d)});return Mn(a,d)}}),wr=Xt({tile_:function(a,p){var e=Lt(a,"x","tile",null);return Ue(e.rank===p.length,function(){return"Error in transpose: rank of input "+e.rank+" must match length of reps "+p+"."}),kt.runKernel(function(a,t){var n=a.tile(e,p);return t([e]),n},{$x:e},function(e,t){var d=t[0];return{$x:function(){var t=Fn(d);if(1===d.rank)for(var r=0;r<p[0];++r)t=t.add(e.slice([r*d.shape[0]],[d.shape[0]]));else if(2===d.rank)for(r=0;r<p[0];++r)for(var l=0;l<p[1];++l)t=t.add(e.slice([r*d.shape[0],l*d.shape[1]],[d.shape[0],d.shape[1]]));else if(3===d.rank)for(r=0;r<p[0];++r)for(l=0;l<p[1];++l)for(var u=0;u<p[2];++u)t=t.add(e.slice([r*d.shape[0],l*d.shape[1],u*d.shape[2]],[d.shape[0],d.shape[1],d.shape[2]]));else{if(4!==d.rank)throw new Error("Gradient for tile operation is not implemented for rank-"+d.rank+" tensors yet.");for(r=0;r<p[0];++r)for(l=0;l<p[1];++l)for(u=0;u<p[2];++u)for(var c=0;c<p[3];++c)t=t.add(e.slice([r*d.shape[0],l*d.shape[1],u*d.shape[2],c*d.shape[3]],[d.shape[0],d.shape[1],d.shape[2],d.shape[3]]))}return t}}})}}),Cr=Xt({truncatedNormal_:function(p,t,d,l,r){if(void 0===t&&(t=0),void 0===d&&(d=1),null!=l&&"bool"===l)throw new Error("Unsupported data type "+l);for(var o=new Yn(t,d,l,!0,r),a=hn(p,l),i=0;i<a.values.length;i++)a.values[i]=o.nextValue();return a.toTensor()}}),Er=Xt({unstack_:function(a,r){void 0===r&&(r=0),r=r||0;var o=Lt(a,"x","unstack");return Ue(r>=-o.shape.length&&r<o.shape.length,function(){return"Axis = "+r+" is not in [-"+o.shape.length+", "+o.shape.length+")"}),0>r&&(r+=o.shape.length),kt.runKernel(function(e){return e.unstack(o,r)},{$x:o},function(e){return{$x:function(){return br(e,r)}}})}}),Rr=function(p,t){return Be(this,void 0,void 0,function(){var e,d,m,g,y,b,x,v,C,r;return Me(this,function(a){switch(a.label){case 0:return e=Lt(p,"x","setdiff1d"),d=Lt(t,"y","setdiff1d"),Ue(e.dtype===d.dtype,function(){return"x and y should have the same dtype, but got x ("+e.dtype+") and y ("+d.dtype+")."}),Ue(1===e.rank,function(){return"x should be 1D tensor, but got x ("+e.shape+")."}),Ue(1===d.rank,function(){return"y should be 1D tensor, but got y ("+d.shape+")."}),[4,e.data()];case 1:return m=a.sent(),[4,d.data()];case 2:for(g=a.sent(),y=new Set(g),b=0,C=0;C<m.length;C++)y.has(m[C])||b++;for(x=new Z([b],e.dtype),v=new Z([b],"int32"),C=0,r=0;C<m.length;C++)y.has(m[C])||(x.values[r]=m[C],v.values[r]=C,r++);return[2,[x.toTensor(),v.toTensor()]];}})})},Ir=Xt({softmax_:function(a,s){void 0===s&&(s=-1);var t=Lt(a,"logits","softmax");if(-1===s&&(s=t.rank-1),s!==t.rank-1)throw Error("Softmax along a non-last dimension is not yet supported. Logits was rank "+t.rank+" and dim was "+s);return On(function(e,t){var a=e.logSumExp([s],!0),n=e.toFloat().sub(a).exp();return t([n]),{value:n,gradFunc:function(e,t){var a=t[0],n=e.mul(a);return n.sub(n.sum([s],!0).mul(a))}}})(t)}}),Kr=Xt({logSoftmax_:function(a,s){void 0===s&&(s=-1);var t=Lt(a,"logits","logSoftmax");if(-1===s&&(s=t.rank-1),s!==t.rank-1)throw Error("Log Softmax along a non-last dimension is not yet supported. Logits was rank "+t.rank+" and axis was "+s);return On(function(e,t){var n=e.max(s,!0),r=e.sub(n),o=r.toFloat().sub(r.exp().sum(s,!0).log());return t([o]),{value:o,gradFunc:function(e,t){var a=t[0].exp();return e.sub(e.sum(s,!0).mul(a))}}})(t)}}),Xr=function(){function e(a,t){this.backend=a,this.dataMover=t,this.data=new WeakMap}return e.prototype.get=function(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)},e.prototype.set=function(a,t){this.data.set(a,t)},e.prototype.has=function(e){return this.data.has(e)},e.prototype.delete=function(e){return this.data.delete(e)},e}(),Yr=Object.freeze({castTensor:Fr,reshapeTensor:Br,linspaceImpl:Pr,upcastType:Y,axesAreInnerMostDims:Pt,combineLocations:Mt,computeOutAndReduceShapes:Wt,expandShapeToKeepDim:Vt,assertAxesAreInnerMostDims:Ut,getAxesPermutation:qt,getUndoAxesPermutation:Ht,getInnerMostAxes:Kt,getBroadcastDims:Vn,getReductionAxes:Zn,assertAndGetBroadcastShape:tr,assertParamsConsistent:jt,computeOutShape:$t,computePool2DInfo:Sr,computeConv2DInfo:Nr,computeConv3DInfo:kr,computeDefaultPad:Tr,tupleValuesAreOne:zr,eitherStridesOrDilationsAreOne:Lr}),vo=function(){return function(a,t){this.outputShape=[],this.outputShape=a,this.variableNames=t.map(function(a,t){return"T"+t});var e=[];this.variableNames.forEach(function(a){e.push("float v"+a+" = get"+a+"AtOutCoords();")});var n=this.variableNames.map(function(e){return"v"+e}).join(" + ");this.userCode="\n      void main() {\n        "+e.join("\n        ")+"\n\n        float result = "+n+";\n        setOutput(result);\n      }\n    "}}(),So=function(){return function(a,t){this.outputShape=[],this.usesPackedTextures=!0,this.outputShape=a,this.variableNames=t.map(function(a,t){return"T"+t});var e=[];this.variableNames.forEach(function(a){e.push("vec4 v"+a+" = get"+a+"AtOutCoords();")});var n=this.variableNames.map(function(e){return"v"+e}).join(" + ");this.userCode="\n      void main() {\n        "+e.join("\n        ")+"\n\n        vec4 result = "+n+";\n        setOutput(result);\n      }\n    "}}(),No=function(){return function(p,t,e){this.variableNames=["A"];var n=p.windowSize,r=p.batchSize,o=p.inSize,a=kf(o/n);e||this.variableNames.push("bestIndicesA"),this.outputShape=[r,a];var i="max"===t?">":"<",s=e?"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 * "+n+";\n\n        int bestIndex = inOffset;\n        float bestValue = getA(batch, bestIndex);\n\n        for (int i = 0; i < "+n+"; i++) {\n          int inIdx = "+s+";\n          float candidate = getA(batch, inIdx);\n          if (candidate "+i+" bestValue) {\n            bestValue = candidate;\n            bestIndex = inIdx;\n          }\n        }\n        setOutput(float(bestIndex));\n      }\n    "}}(),ko="\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",Fo="\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",Lo="\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",Wo="\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",Uo="\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",zo=function(){return function(p,t,e,n){this.variableNames=["A"],this.usesPackedTextures=!0,Ue(2<p.length,function(){return"Packed arg"+(e.charAt(0).toUpperCase()+e.slice(1))+" supports only inputs with rank above 2."});var r=p[p.length-1],o=kf(r/t);this.outputShape=p.slice(0,-1),1<o&&this.outputShape.push(o),n||this.variableNames.push("bestIndicesA");var a=this.outputShape,u=a.length,l=po(u),c=Jr("coords",u),h,S;if(1===o){var N=po(S=u+1);h="\n        "+N+" sourceLocR = "+N+"("+c.join()+", 0);\n        ++"+c[u-1]+";\n        "+N+" sourceLocG = "+N+"("+c.join()+", 0);\n        ++"+c[u-2]+";\n        "+N+" sourceLocA = "+N+"("+c.join()+", 0);\n        --"+c[u-1]+";\n        "+N+" sourceLocB = "+N+"("+c.join()+", 0);\n        --"+c[u-2]+";"}else S=u,h="\n        "+l+" sourceLocR = coords;\n        ++"+c[u-1]+";\n        "+l+" sourceLocG = coords;\n        ++"+c[u-2]+";\n        "+l+" sourceLocA = coords;\n        --"+c[u-1]+";\n        "+l+" sourceLocB = coords;\n        --"+c[u-2]+";";var f=["x","y","z","w","u","v"].slice(0,S),d="."+f[S-1],v=f.map(function(e){return"int "+e}),m=Jr("sourceLocR",S-1).concat("inIdx.r"),g=Jr("sourceLocG",S-1).concat("inIdx.g"),y=Jr("sourceLocB",S-1).concat("inIdx.b"),x=Jr("sourceLocA",S-1).concat("inIdx.a"),b="max"===e?"greaterThan":"lessThan",I=n?"":"\n          inIdx = round(vec4(getBestIndicesAChannel("+m.join()+"),\n                             getBestIndicesAChannel("+g.join()+"),\n                             getBestIndicesAChannel("+y.join()+"),\n                             getBestIndicesAChannel("+x.join()+")));",C="vec4(\n            getAChannel("+m.join()+"),\n            hasNextCol ? getAChannel("+g.join()+") : 0.,\n            hasNextRow ? getAChannel("+y.join()+") : 0.,\n            hasNextRow && hasNextCol ? getAChannel("+x.join()+") : 0.)",k=n?"":"\n      float getBestIndicesAChannel("+v.join()+") {\n        return getChannel(getBestIndicesA("+f.join()+"),\n                                          vec2("+f.slice(-2).join()+"));\n      }";this.userCode="\n      float getAChannel("+v.join()+") {\n        return getChannel(getA("+f.join()+"),\n                               vec2("+f.slice(-2).join()+"));\n      }\n      "+k+"\n      void main() {\n        "+l+" coords = getOutputCoords();\n        bool hasNextCol = "+c[u-1]+" < "+(a[u-1]-1)+";\n        bool hasNextRow = "+c[u-2]+" < "+(a[u-2]-1)+";\n        "+h+"\n        ivec4 srcIdx = ivec4(sourceLocR"+d+", sourceLocG"+d+",\n          sourceLocB"+d+", sourceLocA"+d+") * "+t+";\n        ivec4 inIdx = srcIdx;\n        vec4 bestIndex = vec4(inIdx);\n        vec4 bestValue = "+C+";\n\n        for (int i = 0; i < "+t+"; i++) {\n          inIdx = srcIdx;\n          "+I+"\n          vec4 candidate = "+C+";\n          bvec4 nan = isnan(candidate);\n          bvec4 replace = bvec4(\n            vec4("+b+"(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    "}}(),jo=function(){return function(p){this.variableNames=["dy"],this.outputShape=p.inShape;var t=p.filterHeight,e=p.filterWidth,n=p.strideHeight,r=p.strideWidth,o=p.dilationHeight,a=p.dilationWidth,i=p.effectiveFilterHeight,s=p.effectiveFilterWidth,d=i-1-p.padInfo.top,l=s-1-p.padInfo.left;this.userCode="\n      const ivec2 pads = ivec2("+d+", "+l+");\n      const float avgMultiplier = float("+1/(t*e)+");\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 < "+i+";\n            wR += "+o+") {\n          float dyR = float(dyRCorner + wR) / "+n+".0;\n\n          if (dyR < 0.0 || dyR >= "+p.outHeight+".0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          for (int wC = 0; wC < "+s+";\n            wC+= "+a+") {\n            float dyC = float(dyCCorner + wC) / "+r+".0;\n\n            if (dyC < 0.0 || dyC >= "+p.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    "}}(),Ko=function(){return function(p,t,e,n,r,o){this.outputShape=[],this.variableNames=["x","mean","variance"],tr(p,t),tr(p,e);var a="0.0";null!=n&&(tr(p,n),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");var d="1.0";null!=r&&(tr(p,r),this.variableNames.push("scale"),d="getScaleAtOutCoords()"),this.outputShape=p,this.userCode="\n      void main() {\n        float x = getXAtOutCoords();\n        float mean = getMeanAtOutCoords();\n        float variance = getVarianceAtOutCoords();\n        float offset = "+a+";\n        float scale = "+d+";\n        float inv = scale * inversesqrt(variance + float("+o+"));\n        setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n      }\n    "}}(),Xo=function(){return function(p,t,e,n,r,o){this.usesPackedTextures=!0,this.variableNames=["x","mean","variance"],tr(p,t),tr(p,e);var a="vec4(0.0)";null!=n&&(tr(p,n),this.variableNames.push("offset"),a="getOffsetAtOutCoords()");var d="vec4(1.0)";null!=r&&(tr(p,r),this.variableNames.push("scale"),d="getScaleAtOutCoords()"),this.outputShape=p,this.userCode="\n      void main() {\n        vec4 offset = "+a+";\n        vec4 scale = "+d+";\n\n        vec4 x = getXAtOutCoords();\n        vec4 mean = getMeanAtOutCoords();\n        vec4 variance = getVarianceAtOutCoords();\n\n        vec4 inv = scale * inversesqrt(variance + vec4("+o+"));\n\n        setOutput((x - mean) * inv + offset);\n      }\n    "}}(),Yo=function(){return function(a,t,e){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=tr(t,e),this.userCode="\n      float binaryOpComplex(\n          float areal, float aimag, float breal, float bimag) {\n        "+a+"\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    "}}(),Zo="return a + b;",ta="return a - b;",ea="return a * b;",na=function(){return function(a,t,e){this.variableNames=["A","B"],this.outputShape=tr(t,e),this.userCode="\n      float binaryOperation(float a, float b) {\n        "+a+"\n      }\n\n      void main() {\n        float a = getAAtOutCoords();\n        float b = getBAtOutCoords();\n        setOutput(binaryOperation(a, b));\n      }\n    "}}(),ra=function(){return function(s,t,e,n){void 0===n&&(n=!1),this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.usesPackedTextures=!0,this.outputShape=tr(t,e);var p=this.outputShape.length,o="";if(n)if(0===p||1===qe(this.outputShape))o="\n          result.y = 0.;\n          result.z = 0.;\n          result.w = 0.;\n        ";else if(o="\n          "+po(p)+" coords = getOutputCoords();\n        ",1===p)o+="\n            result.y = (coords + 1) >= "+this.outputShape[0]+" ? 0. : result.y;\n            result.z = 0.;\n            result.w = 0.;\n          ";else{var d=Jr("coords",p);o+="\n            bool nextRowOutOfBounds =\n              ("+d[p-2]+" + 1) >= "+this.outputShape[p-2]+";\n            bool nextColOutOfBounds =\n              ("+d[p-1]+" + 1) >= "+this.outputShape[p-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        "+s+"\n      }\n\n      void main() {\n        vec4 a = getAAtOutCoords();\n        vec4 b = getBAtOutCoords();\n\n        vec4 result = binaryOperation(a, b);\n        "+o+"\n\n        setOutput(result);\n      }\n    "}}(),oa=function(){function e(e){this.variableNames=["A"],this.outputShape=e,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 e.prototype.getCustomSetupFunc=function(a,t){var e=this;return function(n,r){null==e.minLoc&&(e.minLoc=n.getUniformLocationNoThrow(r,"minVal"),e.maxLoc=n.getUniformLocationNoThrow(r,"maxVal")),n.gl.uniform1f(e.minLoc,a),n.gl.uniform1f(e.maxLoc,t)}},e}(),aa=function(){function e(e){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=e,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 e.prototype.getCustomSetupFunc=function(a,t){var e=this;return function(n,r){null==e.minLoc&&(e.minLoc=n.getUniformLocationNoThrow(r,"minVal"),e.maxLoc=n.getUniformLocationNoThrow(r,"maxVal")),n.gl.uniform1f(e.minLoc,a),n.gl.uniform1f(e.maxLoc,t)}},e}(),ia=function(){return function(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode="\n      void main() {\n        float re = abs(getRealAtOutCoords());\n        float im = abs(getImagAtOutCoords());\n        float mx = max(re, im);\n\n        // sadly the length function in glsl is not underflow-safe\n        // (at least not on Intel GPUs). So the safe solution is\n        // to ensure underflow-safety in all cases.\n        setOutput(\n          mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))\n        );\n      }\n    "}}(),sa=function(){return function(s){this.outputShape=[],this.outputShape=$t(s,1),this.variableNames=s.map(function(a,t){return"T"+t});var t=Array(s.length-1);t[0]=s[0][1];for(var e=1;e<t.length;e++)t[e]=t[e-1]+s[e][1];var p=["if (yC < "+t[0]+") setOutput(getT0(yR, yC));"];for(e=1;e<t.length;e++){var r=t[e-1];p.push("else if (yC < "+t[e]+") setOutput(getT"+e+"(yR, yC-"+r+"));")}var o=t.length,a=t[t.length-1];p.push("else setOutput(getT"+o+"(yR, yC-"+a+"));"),this.userCode="\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int yR = coords.x;\n        int yC = coords.y;\n\n        "+p.join("\n        ")+"\n      }\n    "}}(),ua=function(){return function(m,t){this.usesPackedTextures=!0,this.outputShape=[],this.outputShape=$t(m,t);var e=this.outputShape,n=e.length,r=po(n),o=Jr("coords",n),a=["x","y","z","w","u","v"].slice(0,n);this.variableNames=m.map(function(a,t){return"T"+t});var i=Array(m.length-1);i[0]=m[0][t];for(var s=1;s<i.length;s++)i[s]=i[s-1]+m[s][t];var g=a[t],l="vec2("+a.slice(-2).join()+")",c=a.join(),h="if ("+g+" < "+i[0]+")\n          return getChannel(getT0("+c+"), "+l+");";for(s=1;s<i.length;s++){var y=i[s-1];h+="\n        else if ("+g+" < "+i[s]+") {\n          "+g+" -= "+y+";\n          return getChannel(getT"+s+"("+c+"), "+l+");\n        }"}var p=i.length;h+="\n        else {\n          "+g+" -= "+i[i.length-1]+";\n          return getChannel(getT"+p+"("+c+"), "+l+");\n        }",this.userCode="\n      float getValue("+a.map(function(e){return"int "+e})+") {\n        "+h+"\n      }\n\n      void main() {\n        "+r+" coords = getOutputCoords();\n        vec4 result = vec4(getValue("+o+"), 0., 0., 0.);\n        if (++"+o[n-1]+" < "+e[n-1]+") {\n          result.g = getValue("+o+");\n        }\n        if (++"+o[n-2]+" < "+e[n-2]+") {\n          result.a = getValue("+o+");\n        }\n        if ("+o[n-2]+" < "+e[n-2]+" &&\n            --"+o[n-1]+" < "+e[n-1]+") {\n          result.b = getValue("+o+");\n        }\n        setOutput(result);\n      }\n    "}}(),la=function(){return function(a){this.variableNames=["x","dy"],this.outputShape=a.filterShape;var t=a.strideHeight,e=a.strideWidth,n=a.padInfo.top,r=a.padInfo.left;this.userCode="\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int wR = coords.x;\n        int wC = coords.y;\n        int d1 = coords.z;\n        int d2 = coords.w;\n\n        // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n\n        for (int b = 0; b < "+a.batchSize+"; b++) {\n          for (int yR = 0; yR < "+a.outHeight+"; yR++) {\n            int xR = wR + yR * "+t+" - "+n+";\n\n            if (xR < 0 || xR >= "+a.inHeight+") {\n              continue;\n            }\n\n            for (int yC = 0; yC < "+a.outWidth+"; yC++) {\n              int xC = wC + yC * "+e+" - "+r+";\n\n              if (xC < 0 || xC >= "+a.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    "}}(),ca=function(){return function(s){this.variableNames=["dy","W"],this.outputShape=s.inShape;var t=s.filterHeight,e=s.filterWidth,n=s.strideHeight,r=s.strideWidth,o=t-1-s.padInfo.top,a=e-1-s.padInfo.left;this.userCode="\n      const ivec2 pads = ivec2("+o+", "+a+");\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d1 = coords[3];\n\n        ivec2 dyCorner = coords.yz - pads;\n        int dyRCorner = dyCorner.x;\n        int dyCCorner = dyCorner.y;\n\n        // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        for (int wR = 0; wR < "+t+"; wR++) {\n          float dyR = float(dyRCorner + wR) / "+n+".0;\n\n          if (dyR < 0.0 || dyR >= "+s.outHeight+".0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          int wRPerm = "+t+" - 1 - wR;\n\n          for (int wC = 0; wC < "+e+"; wC++) {\n            float dyC = float(dyCCorner + wC) / "+r+".0;\n\n            if (dyC < 0.0 || dyC >= "+s.outWidth+".0 ||\n                fract(dyC) > 0.0) {\n              continue;\n            }\n            int idyC = int(dyC);\n\n            int wCPerm = "+e+" - 1 - wC;\n\n            for (int d2 = 0; d2 < "+s.outChannels+"; d2++) {\n              float xValue = getDy(batch, idyR, idyC, d2);\n              float wValue = getW(wRPerm, wCPerm, d1, d2);\n              dotProd += xValue * wValue;\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    "}}(),ha=function(){return function(s){this.variableNames=["x","dy"],this.outputShape=s.filterShape;var t=s.strideDepth,e=s.strideHeight,n=s.strideWidth,r=s.padInfo.front,o=s.padInfo.top,a=s.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 < "+s.batchSize+"; b++) {\n          for (int yF = 0; yF < "+s.outDepth+"; yF++) {\n            int xF = wF + yF * "+t+" - "+r+";\n\n            if (xF < 0 || xF >= "+s.inDepth+") {\n              continue;\n            }\n\n            for (int yR = 0; yR < "+s.outHeight+"; yR++) {\n              int xR = wR + yR * "+e+" - "+o+";\n\n              if (xR < 0 || xR >= "+s.inHeight+") {\n                continue;\n              }\n\n              for (int yC = 0; yC < "+s.outWidth+"; yC++) {\n                int xC = wC + yC * "+n+" - "+a+";\n\n                if (xC < 0 || xC >= "+s.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    "}}(),fa=function(){return function(p){this.variableNames=["dy","W"],this.outputShape=p.inShape;var t=p.filterDepth,e=p.filterHeight,n=p.filterWidth,r=p.strideDepth,o=p.strideHeight,a=p.strideWidth,i=t-1-p.padInfo.front,s=e-1-p.padInfo.top,d=n-1-p.padInfo.left;this.userCode="\n      const ivec3 pads = ivec3("+i+", "+s+", "+d+");\n\n      void main() {\n        ivec5 coords = getOutputCoords();\n        int batch = coords.x;\n        int d1 = coords.u;\n\n\n        ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n        int dyFCorner = dyCorner.x;\n        int dyRCorner = dyCorner.y;\n        int dyCCorner = dyCorner.z;\n\n        float dotProd = 0.0;\n        for (int wF = 0; wF < "+t+"; wF++) {\n          float dyF = float(dyFCorner + wF) / "+r+".0;\n\n          if (dyF < 0.0 || dyF >= "+p.outDepth+".0 || fract(dyF) > 0.0) {\n            continue;\n          }\n          int idyF = int(dyF);\n\n          int wFPerm = "+t+" - 1 - wF;\n\n          for (int wR = 0; wR < "+e+"; wR++) {\n            float dyR = float(dyRCorner + wR) / "+o+".0;\n\n            if (dyR < 0.0 || dyR >= "+p.outHeight+".0 ||\n              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 >= "+p.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 < "+p.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    "}}(),pa=function(){return function(s){this.variableNames=["x","dy"],this.outputShape=s.filterShape;var t=s.strideHeight,e=s.strideWidth,n=s.padInfo.top,r=s.padInfo.left,o=s.outChannels/s.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 * "+o+" + dm;\n\n        float dotProd = 0.0;\n\n        // TODO: Vec4 over the batch size\n        for (int b = 0; b < "+s.batchSize+"; b++) {\n          for (int yR = 0; yR < "+s.outHeight+"; yR++) {\n            int xR = wR + yR * "+t+" - "+n+";\n\n            if (xR < 0 || xR >= "+s.inHeight+") {\n              continue;\n            }\n\n            for (int yC = 0; yC < "+s.outWidth+"; yC++) {\n              int xC = wC + yC * "+e+" - "+r+";\n\n              if (xC < 0 || xC >= "+s.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    "}}(),da=function(){return function(p){this.variableNames=["dy","W"],this.outputShape=p.inShape;var t=p.filterHeight,e=p.filterWidth,n=p.strideHeight,r=p.strideWidth,o=t-1-p.padInfo.top,a=e-1-p.padInfo.left,i=p.outChannels/p.inChannels;this.userCode="\n      const ivec2 pads = ivec2("+o+", "+a+");\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d1 = coords[3];\n        ivec2 dyCorner = coords.yz - pads;\n        int dyRCorner = dyCorner.x;\n        int dyCCorner = dyCorner.y;\n\n        float dotProd = 0.0;\n\n        for (int wR = 0; wR < "+t+"; wR++) {\n          float dyR = float(dyRCorner + wR) / "+n+".0;\n\n          if (dyR < 0.0 || dyR >= "+p.outHeight+".0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          int wRPerm = "+t+" - 1 - wR;\n\n          for (int wC = 0; wC < "+e+"; wC++) {\n            float dyC = float(dyCCorner + wC) / "+r+".0;\n\n            if (dyC < 0.0 || dyC >= "+p.outWidth+".0 ||\n                fract(dyC) > 0.0) {\n              continue;\n            }\n            int idyC = int(dyC);\n\n            int wCPerm = "+e+" - 1 - wC;\n\n            // TODO: Vec4 over the channelMul\n            for (int dm = 0; dm < "+i+"; dm++) {\n              int d2 = d1 * "+i+" + 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    "}}(),va=function(){return function(m,t,g){void 0===t&&(t=!1),void 0===g&&(g=null),this.variableNames=["x","W"],this.outputShape=m.outShape;var y=m.padInfo.top,r=m.padInfo.left,o=m.strideHeight,a=m.strideWidth,i=m.dilationHeight,s=m.dilationWidth,u=m.filterHeight,l=m.filterWidth,c=4*Cf(m.inChannels/4),h=m.inChannels%4,f="",b="";g&&(f="\n        float activation(float x) {\n          "+g+"\n        }\n      ",b="result = activation(result);");var x=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),this.userCode="\n      "+f+"\n\n      const ivec2 strides = ivec2("+o+", "+a+");\n      const ivec2 pads = ivec2("+y+", "+r+");\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d2 = coords[3];\n\n        ivec2 xRCCorner = coords.yz * strides - pads;\n        int xRCorner = xRCCorner.x;\n        int xCCorner = xRCCorner.y;\n\n        // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        for (int wR = 0; wR < "+u+"; wR++) {\n          int xR = xRCorner + wR * "+i+";\n\n          if (xR < 0 || xR >= "+m.inHeight+") {\n            continue;\n          }\n\n          for (int wC = 0; wC < "+l+"; wC++) {\n            int xC = xCCorner + wC * "+s+";\n\n            if (xC < 0 || xC >= "+m.inWidth+") {\n              continue;\n            }\n\n            for (int d1 = 0; d1 < "+c+"; d1 += 4) {\n              vec4 xValues = vec4(\n                getX(batch, xR, xC, d1),\n                getX(batch, xR, xC, d1 + 1),\n                getX(batch, xR, xC, d1 + 2),\n                getX(batch, xR, xC, d1 + 3)\n              );\n              vec4 wValues = vec4(\n                getW(wR, wC, d1, d2),\n                getW(wR, wC, d1 + 1, d2),\n                getW(wR, wC, d1 + 2, d2),\n                getW(wR, wC, d1 + 3, d2)\n              );\n\n              dotProd += dot(xValues, wValues);\n            }\n\n            if ("+(1==h)+") {\n              dotProd +=\n                getX(batch, xR, xC, "+c+") *\n                getW(wR, wC, "+c+", d2);\n            } else if ("+(2==h)+") {\n              vec2 xValues = vec2(\n                getX(batch, xR, xC, "+c+"),\n                getX(batch, xR, xC, "+c+" + 1)\n              );\n              vec2 wValues = vec2(\n                getW(wR, wC, "+c+", d2),\n                getW(wR, wC, "+c+" + 1, d2)\n              );\n              dotProd += dot(xValues, wValues);\n            } else if ("+(3==h)+") {\n              vec3 xValues = vec3(\n                getX(batch, xR, xC, "+c+"),\n                getX(batch, xR, xC, "+c+" + 1),\n                getX(batch, xR, xC, "+c+" + 2)\n              );\n              vec3 wValues = vec3(\n                getW(wR, wC, "+c+", d2),\n                getW(wR, wC, "+c+" + 1, d2),\n                getW(wR, wC, "+c+" + 2, d2)\n              );\n              dotProd += dot(xValues, wValues);\n            }\n          }\n        }\n\n        float result = dotProd;\n        "+x+"\n        "+b+"\n        setOutput(result);\n      }\n    "}}(),ma=function(){return function(m){this.variableNames=["x","W"],this.outputShape=m.outShape;var t=m.padInfo.front,e=m.padInfo.top,n=m.padInfo.left,r=m.strideDepth,o=m.strideHeight,a=m.strideWidth,i=m.dilationDepth,s=m.dilationHeight,u=m.dilationWidth,l=m.filterDepth,c=m.filterHeight,h=m.filterWidth,g=4*Cf(m.inChannels/4),p=m.inChannels%4;this.userCode="\n      const ivec3 strides = ivec3("+r+", "+o+", "+a+");\n      const ivec3 pads = ivec3("+t+", "+e+", "+n+");\n\n      void main() {\n        ivec5 coords = getOutputCoords();\n        int batch = coords.x;\n        int d2 = coords.u;\n\n        ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n        int xFCorner = xFRCCorner.x;\n        int xRCorner = xFRCCorner.y;\n        int xCCorner = xFRCCorner.z;\n\n        // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get\n        // y(yF, yR, yC, d2). ? = to be determined. : = across all\n        // values in that axis.\n        float dotProd = 0.0;\n        for (int wF = 0; wF < "+l+"; wF++) {\n          int xF = xFCorner + wF * "+i+";\n\n          if (xF < 0 || xF >= "+m.inDepth+") {\n            continue;\n          }\n\n          for (int wR = 0; wR < "+c+"; wR++) {\n            int xR = xRCorner + wR * "+s+";\n\n            if (xR < 0 || xR >= "+m.inHeight+") {\n              continue;\n            }\n\n            for (int wC = 0; wC < "+h+"; wC++) {\n              int xC = xCCorner + wC * "+u+";\n\n              if (xC < 0 || xC >= "+m.inWidth+") {\n                continue;\n              }\n\n              for (int d1 = 0; d1 < "+g+"; 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==p)+") {\n                dotProd +=\n                  getX(batch, xF, xR, xC, "+g+") *\n                  getW(wF, wR, wC, "+g+", d2);\n              } else if ("+(2==p)+") {\n                vec2 xValues = vec2(\n                  getX(batch, xF, xR, xC, "+g+"),\n                  getX(batch, xF, xR, xC, "+g+" + 1)\n                );\n                vec2 wValues = vec2(\n                  getW(wF, wR, wC, "+g+", d2),\n                  getW(wF, wR, wC, "+g+" + 1, d2)\n                );\n                dotProd += dot(xValues, wValues);\n              } else if ("+(3==p)+") {\n                vec3 xValues = vec3(\n                  getX(batch, xF, xR, xC, "+g+"),\n                  getX(batch, xF, xR, xC, "+g+" + 1),\n                  getX(batch, xF, xR, xC, "+g+" + 2)\n                );\n                vec3 wValues = vec3(\n                  getW(wF, wR, wC, "+g+", d2),\n                  getW(wF, wR, wC, "+g+" + 1, d2),\n                  getW(wF, wR, wC, "+g+" + 2, d2)\n                );\n                dotProd += dot(xValues, wValues);\n              }\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    "}}(),ga=function(){return function(p){this.variableNames=["x","W"],this.outputShape=p.outShape;var t=p.inHeight,e=p.inWidth,n=p.padInfo.top,r=p.padInfo.left,o=p.strideHeight,a=p.strideWidth,i=p.dilationHeight,s=p.dilationWidth,d=p.filterHeight,l=p.filterWidth,u=p.outChannels/p.inChannels;this.userCode="\n      const ivec2 strides = ivec2("+o+", "+a+");\n      const ivec2 pads = ivec2("+n+", "+r+");\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 / "+u+";\n        int q = d2 - d1 * "+u+";\n\n        int xRCorner = xRCCorner.x;\n        int xCCorner = xRCCorner.y;\n\n        // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        // TODO(dsmilkov): Flatten the two for loops and vec4 the operations.\n        for (int wR = 0; wR < "+d+"; wR++) {\n          int xR = xRCorner + wR * "+i+";\n\n          if (xR < 0 || xR >= "+t+") {\n            continue;\n          }\n\n          for (int wC = 0; wC < "+l+"; wC++) {\n            int xC = xCCorner + wC * "+s+";\n\n            if (xC < 0 || xC >= "+e+") {\n              continue;\n            }\n\n            float xVal = getX(batch, xR, xC, d1);\n            float wVal = getW(wR, wC, d1, q);\n            dotProd += xVal * wVal;\n          }\n        }\n        setOutput(dotProd);\n      }\n    "}}(),ya=function(){return function(h){this.variableNames=["x","W"],this.usesPackedTextures=!0,this.outputShape=h.outShape;for(var t=h.inHeight,e=h.inWidth,n=h.padInfo.top,r=h.padInfo.left,o=h.strideHeight,a=h.strideWidth,i=h.dilationHeight,y=h.dilationWidth,u=h.filterHeight,l=h.filterWidth,c=l,f="int xR; int xC; int xCOffset;",b=0;b<u;b++)for(var x=0;x<l;x++)f+="\n          vec4 xTexelR"+b+"C"+2*x+" = vec4(0.);\n          vec4 wR"+b+"C"+x+" = vec4(0.);\n          vec4 xR"+b+"C"+x+" = vec4(0.);";for(b=0;b<u;b++)for(var C=0;C<c;C++){if(f+="\n          xR = xRCorner + "+b*i+";\n          xC = xCCorner + "+(x=2*C)*y+";\n        ",1!==a)x<l&&(f+="\n              if(xR >= 0 && xR < "+t+") {\n            ",1==r%2?(f+="\n                xCOffset = xC + 1 - "+a+";\n                if(xCOffset >= 0 && xCOffset < "+e+") {\n                  xTexelR"+b+"C"+x+" = getX(batch, xR, xCOffset, d1);\n                } else {\n                  xTexelR"+b+"C"+x+" = vec4(0.);\n                }\n\n                if(xC + 1 >= 0 && xC + 1 < "+e+") {\n                  xTexelR"+b+"C"+(x+2)+" = getX(batch, xR, xC + 1, d1);\n                } else {\n                  xTexelR"+b+"C"+(x+2)+" = vec4(0.);\n                }\n\n                xR"+b+"C"+x+" = vec4(\n                  xTexelR"+b+"C"+x+".zw, xTexelR"+b+"C"+(x+2)+".zw);\n              ",x+1<l&&(f+="\n                  vec4 final = vec4(0.);\n                  xCOffset = xC + 1 + "+a+";\n                  if(xCOffset >= 0 && xCOffset < "+e+") {\n                    final = getX(batch, xR, xCOffset, d1);\n                  }\n                  xR"+b+"C"+(x+1)+" = vec4(xTexelR"+b+"C"+(x+2)+".xy, final.xy);\n                ")):(f+="\n                if(xC >= 0 && xC < "+e+") {\n                  xTexelR"+b+"C"+x+" = getX(batch, xR, xC, d1);\n                } else {\n                  xTexelR"+b+"C"+x+" = vec4(0.);\n                }\n\n                xCOffset = xC + "+a+";\n                if(xCOffset >= 0 && xCOffset < "+e+") {\n                  xTexelR"+b+"C"+(x+2)+" = getX(batch, xR, xCOffset, d1);\n                } else {\n                  xTexelR"+b+"C"+(x+2)+" = vec4(0.);\n                }\n\n                xR"+b+"C"+x+" = vec4(\n                  xTexelR"+b+"C"+x+".xy, xTexelR"+b+"C"+(x+2)+".xy);\n              ",x+1<l&&(f+="\n                  xR"+b+"C"+(x+1)+" = vec4(\n                    xTexelR"+b+"C"+x+".zw, xTexelR"+b+"C"+(x+2)+".zw);\n                ")),f+="}");else if(x<l&&(f+=1==r%2?"\n                xCOffset = xC + 1;\n                if(xR >= 0 && xR < "+t+" && xCOffset >= 0 && xCOffset < "+e+") {\n                  xTexelR"+b+"C"+x+" = getX(batch, xR, xCOffset, d1);\n                } else {\n                  xTexelR"+b+"C"+x+" = vec4(0.);\n                }\n\n                xCOffset = xC + 1 - 2;\n                if(xR >= 0 && xR < "+t+" && xCOffset >= 0 && xCOffset < "+e+") {\n                  vec4 previous = getX(batch, xR, xCOffset, d1);\n                  xR"+b+"C"+x+" = vec4(previous.zw, xTexelR"+b+"C"+x+".xy);\n                } else {\n                  xR"+b+"C"+x+" = vec4(0, 0, xTexelR"+b+"C"+x+".xy);\n                }\n              ":"\n                if(xR >= 0 && xR < "+t+" && xC >= 0 && xC < "+e+") {\n                  xTexelR"+b+"C"+x+" = getX(batch, xR, xC, d1);\n                } else {\n                  xTexelR"+b+"C"+x+" = vec4(0.);\n                }\n\n                xR"+b+"C"+x+" = xTexelR"+b+"C"+x+";\n              ",x+1<l)){var S=0==r%2?s(y):y;0==y%2&&1==r%2||0!=y%2&&1!=r%2?(f+="\n                  xCOffset = xC + "+r%2+" + "+S+";\n\n                  if(xR >= 0 && xR < "+t+" &&\n                    xCOffset >= 0 && xCOffset < "+e+") {\n                    xTexelR"+b+"C"+(x+2)+" = getX(batch, xR, xCOffset, d1);\n                  }\n                ",1<y&&(f+="\n                    xCOffset -= 2;\n                    if(xR >= 0 && xR < "+t+" &&\n                      xCOffset >= 0 && xCOffset < "+e+") {\n                      xTexelR"+b+"C"+x+" = getX(batch, xR, xCOffset, d1);\n                    } else {\n                      xTexelR"+b+"C"+x+" = vec4(0.);\n                    }\n                  "),f+="\n                  xR"+b+"C"+(x+1)+" = vec4(\n                    xTexelR"+b+"C"+x+".zw, xTexelR"+b+"C"+(x+2)+".xy);\n                "):f+="\n                  xCOffset = xC + "+S+";\n\n                  if(xR >= 0 && xR < "+t+" &&\n                    xCOffset >= 0 && xCOffset < "+e+") {\n                    xTexelR"+b+"C"+(x+2)+" = getX(batch, xR, xCOffset, d1);\n                  }\n\n                  xR"+b+"C"+(x+1)+" = xTexelR"+b+"C"+(x+2)+";\n                "}x<l&&(f+="\n            vec4 wTexelR"+b+"C"+x+" = getW("+b+", "+x+", d1, q);\n            wR"+b+"C"+x+" = vec4(wTexelR"+b+"C"+x+".xz, wTexelR"+b+"C"+x+".xz);\n          ",x+1<l&&(f+="\n              vec4 wTexelR"+b+"C"+(x+1)+" = getW("+b+", "+(x+1)+", d1, q);\n              wR"+b+"C"+(x+1)+" =\n                vec4(wTexelR"+b+"C"+(x+1)+".xz, wTexelR"+b+"C"+(x+1)+".xz);"))}for(b=0;b<u;b++)for(x=0;x<l;x++)f+="result += xR"+b+"C"+x+" * wR"+b+"C"+x+";";this.userCode="\n      const ivec2 strides = ivec2("+o+", "+a+");\n      const ivec2 pads = ivec2("+n+", "+r+");\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 result = vec4(0.);\n\n        "+f+"\n\n        setOutput(result);\n      }\n    "}}(),xa=function(){return function(S,t,e,n,r){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];var o=S[0],a=S[1],i=S[2],s=S[3],u=t[0],l=e[0],c=e[1];this.outputShape=[u,l,c,s];var h="bilinear"===n?1:0,f=[a-1+".0",i-1+".0"],p=f[0],d=f[1],v=1<l?[""+(a-1)/(l-1),"(y2-y1) * height_ratio","y1*"+p+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+p],m=v[0],g=v[1],y=v[2],x=1<c?[""+(i-1)/(c-1),"(x2-x1) * width_ratio","x1*"+d+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+d],b=x[0],N=x[1],C=x[2];this.userCode="\n      const float height_ratio = float("+m+");\n      const float width_ratio = float("+b+");\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int y = coords[1];\n        int x = coords[2];\n        int d = coords[3];\n\n        // get box vals\n        float y1 = getBoxes(b,0);\n        float x1 = getBoxes(b,1);\n        float y2 = getBoxes(b,2);\n        float x2 = getBoxes(b,3);\n\n        // get image in batch index\n        int bInd = round(getBoxInd(b));\n        if(bInd < 0 || bInd >= "+o+") {\n          return;\n        }\n\n        float height_scale = "+g+";\n        float width_scale = "+N+";\n\n        float in_y = "+y+";\n        if( in_y < 0.0 || in_y > "+p+" ) {\n          setOutput(float("+r+"));\n          return;\n        }\n        float in_x = "+C+";\n        if( in_x < 0.0 || in_x > "+d+" ) {\n          setOutput(float("+r+"));\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    "}}(),ba=function(){return function(s,t,e){this.variableNames=["x"],this.outputShape=s;var n=s.length,r=s[s.length-1],o=e?"<":">";this.userCode="\n      int getIndex(int i) {\n        "+(e?"return "+r+" -i - 1;":"return i;")+"\n      }\n\n      void main() {\n        "+po(n)+" coords = getOutputCoords();\n        int end = "+co(n,"coords")+";\n        float val = 0.0;\n        for (int i = "+r+" - 1; i >= 0; i -= 1) {\n          int idx = getIndex(i);\n          if (idx "+o+" end) {\n            continue;\n          }\n          if (idx == end && "+t+") {\n            continue;\n          }\n          "+co(n,"coords")+" = idx;\n          val += getX("+function(a,t){if(1===a)return""+t;if(2===a)return t+".x, "+t+".y";if(3===a)return t+".x, "+t+".y, "+t+".z";if(4===a)return t+".x, "+t+".y, "+t+".z, "+t+".w";throw Error("Cumulative sum for rank "+a+" is not yet supported")}(n,"coords")+");\n        }\n        setOutput(val);\n      }\n    "}}(),wa=function(){return function(a,t){this.variableNames=["A"];var e=eo();this.outputShape=a,this.userCode="\n      ivec3 outCoordsFromFlatIndex(int index) {\n        "+to(["r","c","d"],a)+"\n        return ivec3(r, c, d);\n      }\n\n      void main() {\n        ivec2 resTexRC = ivec2(resultUV.yx *\n          vec2("+t[0]+", "+t[1]+"));\n        int index = 4 * (resTexRC.x * "+t[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        "+e.output+" = result;\n      }\n    "}}(),Ea=function(){return function(a,t){this.variableNames=["A"],this.usesPackedTextures=!0;var e=eo();this.outputShape=a,this.userCode="\n      ivec3 outCoordsFromFlatIndex(int index) {\n        "+to(["r","c","d"],a)+"\n        return ivec3(r, c, d);\n      }\n\n      void main() {\n        ivec2 resTexRC = ivec2(resultUV.yx *\n          vec2("+t[0]+", "+t[1]+"));\n        int index = 4 * (resTexRC.x * "+t[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        "+e.output+" = result;\n      }\n    "}}(),Ra=function(){function e(a,t,e){this.variableNames=["x"],this.outputShape=[],this.outputShape=a,this.blockSize=t,this.dataFormat=e,this.userCode="\n    void main() {\n      ivec4 coords = getOutputCoords();\n      int b = coords[0];\n      int h = "+this.getHeightCoordString()+";\n      int w = "+this.getWidthCoordString()+";\n      int d = "+this.getDepthCoordString()+";\n\n      int in_h = h / "+t+";\n      int offset_h = imod(h, "+t+");\n      int in_w = w / "+t+";\n      int offset_w = imod(w, "+t+");\n      int offset_d = (offset_h * "+t+" + offset_w) *\n        "+this.getOutputDepthSize()+";\n      int in_d = d + offset_d;\n\n      float result = "+this.getInputSamplingString()+";\n      setOutput(result);\n    }\n  "}return e.prototype.getHeightCoordString=function(){return"NHWC"===this.dataFormat?"coords[1]":"coords[2]"},e.prototype.getWidthCoordString=function(){return"NHWC"===this.dataFormat?"coords[2]":"coords[3]"},e.prototype.getDepthCoordString=function(){return"NHWC"===this.dataFormat?"coords[3]":"coords[1]"},e.prototype.getOutputDepthSize=function(){return"NHWC"===this.dataFormat?this.outputShape[3]:this.outputShape[1]},e.prototype.getInputSamplingString=function(){return"NHWC"===this.dataFormat?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"},e}(),Ia=function(){return function(a){this.variableNames=["A"];var t=eo();this.outputShape=a,this.userCode="\n      "+ko+"\n\n      void main() {\n        float x = getAAtOutCoords();\n        "+t.output+" = encode_float(x);\n      }\n    "}}(),Sa=function(){return function(a){this.variableNames=["A"],this.usesPackedTextures=!0;var t=eo();this.outputShape=a,this.userCode="\n      "+ko+"\n\n      void main() {\n        ivec3 coords = getOutputCoords();\n        float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\n        "+t.output+" = encode_float(x);\n      }\n    "}}(),Na=function(){return function(s,t,e){void 0===e&&(e=!1),this.variableNames=["A"];var p=eo(),r=t[0],o=t[1];this.outputShape=s;var a="result";e&&(a="floor(result * 255. + 0.5)"),this.userCode="\n      "+ao(s)+"\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 / "+o+";\n        int c = imod(flatIndex, "+o+");\n        vec2 uv = (vec2(c, r) + halfCR) / vec2("+o+".0, "+r+".0);\n        vec4 values = "+p.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        "+p.output+" = vec4("+a+", 0., 0., 0.);\n      }\n    "}}(),ka=function(){return function(p,t,e){void 0===e&&(e=!1),this.variableNames=["A"];var d=eo(),r=t[0],o=t[1];this.outputShape=p;var a="",h="result";e&&(h="floor(result * 255. + 0.5)");for(var m=0;1>=m;m++)for(var g=0,f;1>=g;g++)f=2*m+g,a+="\n          localCoords = coords;\n          if(localCoords[2] + "+g+" < "+p[2]+") {\n            localCoords[2] += "+g+";\n            if(localCoords[1] + "+m+" < "+p[1]+") {\n              localCoords[1] += "+m+";\n\n              flatIndex = getFlatIndex(localCoords);\n              offset = imod(flatIndex, 4);\n    \n              flatIndex = idiv(flatIndex, 4, 1.);\n\n              r = flatIndex / "+o+";\n              c = imod(flatIndex, "+o+");\n              uv = (vec2(c, r) + halfCR) / vec2("+o+".0, "+r+".0);\n              values = "+d.texture2D+"(A, uv);\n\n              if(offset == 0) {\n                result["+f+"] = values[0];\n              } else if(offset == 1) {\n                result["+f+"] = values[1];\n              } else if(offset == 2) {\n                result["+f+"] = values[2];\n              } else {\n                result["+f+"] = values[3];\n              }\n            }\n          }\n        ";this.userCode="\n      "+ao(p)+"\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        "+a+"\n\n        "+d.output+" = "+h+";\n      }\n    "}}(),Aa=function(){return function(s,t,e){this.variableNames=["real","imag"];var n=t[1];this.outputShape=t;var r=e?"2.0 * "+bf:"-2.0 * "+bf,o=e?n+".0":"1.0";this.userCode="\n      const float exponentMultiplier = "+r+";\n\n      float unaryOpComplex(float real, float expR, float imag, float expI) {\n        "+s+"\n      }\n\n      float mulMatDFT(int batch, int index) {\n        float indexRatio = float(index) / float("+n+");\n        float exponentMultiplierTimesIndexRatio =\n            exponentMultiplier * indexRatio;\n\n        float result = 0.0;\n\n        for (int i = 0; i < "+n+"; 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) / "+o+";\n        }\n\n        return result;\n      }\n\n      void main() {\n        ivec2 coords = getOutputCoords();\n        setOutput(mulMatDFT(coords[0], coords[1]));\n      }\n    "}}(),_a=function(){function e(e){this.outputShape=[],this.variableNames=["x"],this.outputShape=e,this.userCode="\n      uniform float value;\n      void main() {\n        // Input can be obtained from uniform value.\n        setOutput(value);\n      }\n    "}return e.prototype.getCustomSetupFunc=function(a){var t=this;return function(e,n){null==t.valueLoc&&(t.valueLoc=e.getUniformLocationNoThrow(n,"value")),e.gl.uniform1f(t.valueLoc,a)}},e}(),Oa=function(){return function(a){this.variableNames=["A"];var t=eo(),e=a[0],n=a[1];this.outputShape=a,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("+n+".0, "+e+".0);\n\n        vec4 values = "+t.texture2D+"(A, uv);\n        float value;\n        if (depth == 0) {\n          value = values.r;\n        } else if (depth == 1) {\n          value = values.g;\n        } else if (depth == 2) {\n          value = values.b;\n        } else if (depth == 3) {\n          value = values.a;\n        }\n\n        setOutput(floor(value * 255.0 + 0.5));\n      }\n    "}}(),Fa=function(){return function(a){this.variableNames=["A"];var t=eo(),e=a[0],n=a[1];this.outputShape=a,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) / vec2("+n+".0, "+e+".0);\n            vec4 values = "+t.texture2D+"(A, uv);\n            float value;\n            if (depth == 0) {\n              value = values.r;\n            } else if (depth == 1) {\n              value = values.g;\n            } else if (depth == 2) {\n              value = values.b;\n            } else if (depth == 3) {\n              value = values.a;\n            }\n\n            result[row * 2 + col] = floor(value * 255.0 + 0.5);\n          }\n        }\n\n        "+t.output+" = result;\n      }\n    "}}(),Ma=function(){return function(s,t,e){this.variableNames=["A","indices"];var n=s.slice();n[e]=t,this.outputShape=n,this.rank=n.length;var r=po(this.rank),o=function(s,t){var e=s.length;if(4<e)throw Error("Gather for rank "+e+" is not yet supported");if(1===e)return"int(getIndices(resRC))";for(var n=["resRC.x","resRC.y","resRC.z","resRC.w"],r=[],o=0;o<s.length;o++)o===t?r.push("int(getIndices("+n[o]+"))"):r.push(""+n[o]);return r.join()}(s,e);this.userCode="\n      void main() {\n        "+r+" resRC = getOutputCoords();\n        setOutput(getA("+o+"));\n      }\n    "}}(),Ba=function(){return function(s,t,e){this.sliceDim=s,this.strides=t,this.variableNames=["x","indices"],this.outputShape=e;var n=po(t.length),r=po(e.length),o=1<this.sliceDim?"strides[j]":"strides";this.userCode="\n        "+n+" strides = "+n+"("+this.strides+");\n         void main() {\n          "+r+" 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 * "+o+";\n          }\n          setOutput(getX(flattenIndex, coords[1]));\n        }\n      "}}(),Pa=Object.freeze({createVertexShader:Ca,createVertexBuffer:La,createIndexBuffer:Wa,createFloat32MatrixTexture:za,createFloat16MatrixTexture:Va,createUnsignedBytesMatrixTexture:Ga,createPackedMatrixTexture:Ha,createFloat16PackedMatrixTexture:qa,bindVertexProgramAttributeStreams:$a,uploadDenseMatrixToTexture:ja,uploadPixelDataToTexture:Ka,createBufferFromOutputTexture:Xa,downloadFloat32MatrixFromBuffer:Ya,downloadByteEncodedFloatMatrixFromOutputTexture:Qa,downloadPackedMatrixFromBuffer:Ja,downloadMatrixFromPackedOutputTexture:Za}),ei=function(){function e(a){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];var t=_f.getNumber("WEBGL_VERSION");if(null==a?this.gl=Ze(t):(this.gl=a,Ye(t,a)),1===_f.getNumber("WEBGL_VERSION"))this.textureFloatExtension=bt(this.gl,this.debug,"OES_texture_float"),this.colorBufferFloatExtension=this.gl.getExtension("WEBGL_color_buffer_float"),_f.getBool("WEBGL_RENDER_FLOAT32_ENABLED")||(this.textureHalfFloatExtension=bt(this.gl,this.debug,"OES_texture_half_float"),this.colorBufferHalfFloatExtension=this.gl.getExtension("EXT_color_buffer_half_float"));else if(Se(this.gl,"EXT_color_buffer_float"))this.colorBufferFloatExtension=this.gl.getExtension("EXT_color_buffer_float");else{if(!Se(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=La(this.gl,this.debug),this.indexBuffer=Wa(this.gl,this.debug),this.framebuffer=ae(this.gl,this.debug),this.textureConfig=nt(this.gl,this.textureHalfFloatExtension)}return Object.defineProperty(e.prototype,"debug",{get:function(){return _f.getBool("DEBUG")},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){var a=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 t=this.gl;rt(t,this.debug,function(){return t.finish()}),rt(t,this.debug,function(){return t.bindFramebuffer(t.FRAMEBUFFER,null)}),rt(t,this.debug,function(){return t.deleteFramebuffer(a.framebuffer)}),rt(t,this.debug,function(){return t.bindBuffer(t.ARRAY_BUFFER,null)}),rt(t,this.debug,function(){return t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,null)}),rt(t,this.debug,function(){return t.deleteBuffer(a.indexBuffer)}),this.disposed=!0}},e.prototype.createFloat32MatrixTexture=function(a,t){return this.throwIfDisposed(),za(this.gl,this.debug,a,t,this.textureConfig)},e.prototype.createFloat16MatrixTexture=function(a,t){return this.throwIfDisposed(),Va(this.gl,this.debug,a,t,this.textureConfig)},e.prototype.createUnsignedBytesMatrixTexture=function(a,t){return this.throwIfDisposed(),Ga(this.gl,this.debug,a,t,this.textureConfig)},e.prototype.uploadPixelDataToTexture=function(a,t){this.throwIfDisposed(),Ka(this.gl,this.debug,a,t)},e.prototype.uploadDenseMatrixToTexture=function(a,t,e,n){this.throwIfDisposed(),ja(this.gl,this.debug,a,t,e,n,this.textureConfig)},e.prototype.createFloat16PackedMatrixTexture=function(a,t){return this.throwIfDisposed(),qa(this.gl,this.debug,a,t,this.textureConfig)},e.prototype.createPackedMatrixTexture=function(a,t){return this.throwIfDisposed(),Ha(this.gl,this.debug,a,t,this.textureConfig)},e.prototype.deleteMatrixTexture=function(a){var t=this;this.throwIfDisposed(),this.outputTexture===a&&(fe(this.gl,this.debug,this.framebuffer),this.outputTexture=null),rt(this.gl,this.debug,function(){return t.gl.deleteTexture(a)})},e.prototype.downloadByteEncodedFloatMatrixFromOutputTexture=function(a,t,e){var n=this;return this.downloadMatrixDriver(a,function(){return Qa(n.gl,n.debug,t,e,n.textureConfig)})},e.prototype.downloadPackedMatrixFromBuffer=function(s,t,e,n,r,o){return Ja(this.gl,s,0,0,0,r,o,this.textureConfig)},e.prototype.downloadFloat32MatrixFromBuffer=function(a,t){return Ya(this.gl,a,t)},e.prototype.createBufferFromTexture=function(a,t,e){this.bindTextureToFrameBuffer(a);var n=Xa(this.gl,this.debug,t,e,this.textureConfig);return this.unbindTextureToFrameBuffer(),n},e.prototype.createAndWaitForFence=function(){var e=this.createFence(this.gl);return this.pollFence(e)},e.prototype.createFence=function(s){var t=this,r,i;if(_f.getBool("WEBGL_FENCE_API_ENABLED")){var p=s,o=p.fenceSync(p.SYNC_GPU_COMMANDS_COMPLETE,0);s.flush(),i=function(){var e=p.clientWaitSync(o,0,0);return e===p.ALREADY_SIGNALED||e===p.CONDITION_SATISFIED},r=o}else 0<_f.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?(r=this.beginQuery(),this.endQuery(),i=function(){return t.isQueryAvailable(r,_f.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}):i=function(){return!0};return{query:r,isFencePassed:i}},e.prototype.downloadMatrixFromPackedTexture=function(a,t,e){var n=this;return this.downloadMatrixDriver(a,function(){return Za(n.gl,n.debug,t,e)})},e.prototype.createProgram=function(a){this.throwIfDisposed();var t=this.gl,e=Tt(t,this.debug,a),n=Ca(t,this.debug),r=Rt(t,this.debug);return rt(t,this.debug,function(){return t.attachShader(r,n)}),rt(t,this.debug,function(){return t.attachShader(r,e)}),Et(t,this.debug,r),this.debug&&te(t,this.debug,r),this.vertexAttrsAreBound||(this.setProgram(r),this.vertexAttrsAreBound=$a(t,this.debug,this.program,this.vertexBuffer)),r},e.prototype.deleteProgram=function(a){var t=this;this.throwIfDisposed(),a===this.program&&(this.program=null),null!=a&&rt(this.gl,this.debug,function(){return t.gl.deleteProgram(a)})},e.prototype.setProgram=function(a){var t=this;this.throwIfDisposed(),this.program=a,null!=this.program&&this.debug&&te(this.gl,this.debug,this.program),rt(this.gl,this.debug,function(){return t.gl.useProgram(a)})},e.prototype.getUniformLocation=function(a,t,e){return void 0===e&&(e=!0),this.throwIfDisposed(),e?ue(this.gl,this.debug,a,t):le(this.gl,a,t)},e.prototype.getAttributeLocation=function(a,t){var e=this;return this.throwIfDisposed(),rt(this.gl,this.debug,function(){return e.gl.getAttribLocation(a,t)})},e.prototype.getUniformLocationNoThrow=function(a,t){return this.throwIfDisposed(),this.gl.getUniformLocation(a,t)},e.prototype.setInputMatrixTexture=function(a,t,e){this.throwIfDisposed(),this.throwIfNoProgram(),ce(this.gl,this.debug,this.program,a,t,e)},e.prototype.setOutputMatrixTexture=function(a,t,e){this.setOutputMatrixTextureDriver(a,e,t)},e.prototype.setOutputPackedMatrixTexture=function(s,t,e){this.throwIfDisposed();var n=at(t,e),r=n[0],o=n[1];this.setOutputMatrixTextureDriver(s,r,o)},e.prototype.setOutputMatrixWriteRegion=function(a,t,e,n){this.setOutputMatrixWriteRegionDriver(e,a,n,t)},e.prototype.setOutputPackedMatrixWriteRegion=function(){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")},e.prototype.debugValidate=function(){null!=this.program&&te(this.gl,this.debug,this.program),pe(this.gl)},e.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var e=this.gl;this.debug&&this.debugValidate(),rt(e,this.debug,function(){return e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0)})},e.prototype.blockUntilAllProgramsCompleted=function(){var e=this;this.throwIfDisposed(),rt(this.gl,this.debug,function(){return e.gl.finish()})},e.prototype.getQueryTimerExtension=function(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=bt(this.gl,this.debug,2===_f.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension},e.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension()},e.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension()},e.prototype.beginQuery=function(){if(2===_f.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var a=this.gl,t=this.getQueryTimerExtensionWebGL2(),e=a.createQuery();return a.beginQuery(t.TIME_ELAPSED_EXT,e),e}var n=this.getQueryTimerExtensionWebGL1(),r=n.createQueryEXT();return n.beginQueryEXT(n.TIME_ELAPSED_EXT,r),r},e.prototype.endQuery=function(){if(2!==_f.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var a=this.getQueryTimerExtensionWebGL1();a.endQueryEXT(a.TIME_ELAPSED_EXT)}else{var t=this.gl,e=this.getQueryTimerExtensionWebGL2();t.endQuery(e.TIME_ELAPSED_EXT)}},e.prototype.waitForQueryAndGetTime=function(a){return Be(this,void 0,void 0,function(){var t=this;return Me(this,function(e){switch(e.label){case 0:return[4,b(function(){return t.disposed||t.isQueryAvailable(a,_f.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))})];case 1:return e.sent(),[2,this.getQueryTime(a,_f.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))];}})})},e.prototype.getQueryTime=function(a,t){if(0===t)return null;if(2===t){var e=this.gl;return e.getQueryParameter(a,e.QUERY_RESULT)/1e6}var n=this.getQueryTimerExtensionWebGL1();return n.getQueryObjectEXT(a,n.QUERY_RESULT_EXT)/1e6},e.prototype.isQueryAvailable=function(a,t){if(0===t)return!0;if(2===t){var e=this.gl,n=this.getQueryTimerExtensionWebGL2(),s=e.getQueryParameter(a,e.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),s&&!this.disjoint}return s=(n=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(a,n.QUERY_RESULT_AVAILABLE_EXT),null==this.disjoint&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),s&&!this.disjoint},e.prototype.pollFence=function(a){var t=this;return new Promise(function(e){t.addItemToPoll(function(){return a.isFencePassed()},function(){return e()})})},e.prototype.pollItems=function(){for(var a=function(a){for(var t=0,r;t<a.length&&(r=a[t](),!!r);++t);return t-1}(this.itemsToPoll.map(function(e){return e.isDoneFn})),t=0;t<=a;++t)(0,this.itemsToPoll[t].resolveFn)();this.itemsToPoll=this.itemsToPoll.slice(a+1)},e.prototype.addItemToPoll=function(a,t){var e=this;this.itemsToPoll.push({isDoneFn:a,resolveFn:t}),1<this.itemsToPoll.length||b(function(){return e.pollItems(),0===e.itemsToPoll.length})},e.prototype.bindTextureToFrameBuffer=function(e){this.throwIfDisposed(),he(this.gl,this.debug,e,this.framebuffer),this.debug&&pe(this.gl)},e.prototype.unbindTextureToFrameBuffer=function(){null==this.outputTexture?fe(this.gl,this.debug,this.framebuffer):(he(this.gl,this.debug,this.outputTexture,this.framebuffer),this.debug&&pe(this.gl))},e.prototype.downloadMatrixDriver=function(a,t){this.bindTextureToFrameBuffer(a);var e=t();return this.unbindTextureToFrameBuffer(),e},e.prototype.setOutputMatrixTextureDriver=function(a,t,e){this.throwIfDisposed();var n=this.gl;he(n,this.debug,a,this.framebuffer),this.debug&&pe(n),this.outputTexture=a,rt(n,this.debug,function(){return n.viewport(0,0,t,e)}),rt(n,this.debug,function(){return n.scissor(0,0,t,e)})},e.prototype.setOutputMatrixWriteRegionDriver=function(a,t,e,n){var r=this;this.throwIfDisposed(),rt(this.gl,this.debug,function(){return r.gl.scissor(a,t,e,n)})},e.prototype.throwIfDisposed=function(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")},e.prototype.throwIfNoProgram=function(){if(null==this.program)throw new Error("No GPU program is currently set.")},e}(),ni=function(){return function(y,t,e){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=y;for(var n=e.filterWidth,r=e.inChannels,o=e.strideWidth,a=e.strideHeight,i=e.padInfo,s=e.outWidth,u=e.dilationWidth,l=e.dilationHeight,c=i.left,h=i.top,f=r*n,p=eo(),d="",b=0;1>=b;b++)for(var x=0;1>=x;x++)d+="\n          blockIndex = rc.y + "+x+";\n          pos = rc.x + "+b+";\n          \n          if(blockIndex < "+y[1]+" && pos < "+y[0]+") {\n            offsetY = int(blockIndex / ("+s+")) * "+a+" - "+h+";\n            d0 = offsetY + "+l+" * (pos / "+f+");\n  \n            if(d0 < "+t[0]+" && d0 >= 0) {\n              offsetX = int(mod(float(blockIndex), "+s+".) * "+o+". - "+c+".);\n              d1 = offsetX + "+u+" * (int(mod(float(pos), "+f+".) / "+r+".));\n    \n              if(d1 < "+t[1]+" && d1 >= 0) {\n                innerDims = vec2(d1, int(mod(float(pos), "+r+".)));\n                result["+(2*b+x)+"] = getChannel(getA(d0, 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;\n        vec2 innerDims;\n\n        "+d+"\n\n        "+p.output+" = result;\n      }\n    "}}(),oi=function(){return function(p,t,e,n,r){this.variableNames=["x"],this.outputShape=[];var o=t,i=p[3]-1,s;this.outputShape=p;var d="float("+e+") + float("+n+") * sum";s=.5===r?"inversesqrt("+d+")":1===r?"1.0/("+d+")":"exp(log("+d+") * float(-"+r+"));",this.userCode="\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int r = coords[1];\n        int c = coords[2];\n        int d = coords[3];\n        float x = getX(b, r, c, d);\n        float sum = 0.0;\n        for (int j = -"+o+"; j <= "+o+"; j++) {\n          int idx = d + j;\n          if (idx >= 0 && idx <=  "+i+") {\n            float z = getX(b, r, c, idx);\n            sum += z * z;\n          }\n        }\n        float val = x * "+s+";\n        setOutput(val);\n      }\n    "}}(),ai=function(){return function(a,t,e,n,r){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=a,this.depth=a[3],this.depthRadius=t,this.bias=e,this.alpha=n,this.beta=r,this.userCode="\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int r = coords[1];\n        int c = coords[2];\n\n        float result = 0.0;\n        for (int d = 0; d < "+this.depth+"; ++d) {\n          int depthBegin = int(max(0.0, float(d - "+t+")));\n          int depthEnd = int(min(float("+this.depth+"),\n              float(d + "+t+" + 1)));\n\n          const int MIN_DEPTH_BEGIN = 0;\n          const int MAX_DEPTH_END = "+this.depth+";\n\n          float norm = 0.0;\n          for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {\n            if (k < depthBegin){\n              continue;\n            }\n            else if (k >= depthBegin && k < depthEnd) {\n              norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);\n            }\n            else {\n              break;\n            }\n          }\n\n          norm = float("+n+") * norm + float("+e+");\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("+n+")\n                * float("+r+")\n                * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)\n                / norm;\n              if (k == d) {\n                dyi += pow(norm, -1.0 * "+r+");\n              }\n              if (k == coords[3]) {\n                dyi *= getDy(b, r, c, d);\n                result += dyi;\n              }\n            }\n            else {\n              break;\n            }\n          }\n      }\n      setOutput(result);\n      }\n    "}}(),ii=function(){return function(p,t,e,n,r){this.variableNames=["x"],this.outputShape=[],this.usesPackedTextures=!0;var o=t,i=p[3]-1,s;this.outputShape=p;var d="float("+e+") + float("+n+") * sum";s=.5===r?"inversesqrt("+d+")":1===r?"1.0/("+d+")":"exp(log("+d+") * float(-"+r+"));",this.userCode="\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords.x;\n        int r = coords.y;\n        int c = coords.z;\n        int d = coords.w;\n\n        bool hasNextCol = d < "+this.outputShape[3]+";\n        bool hasNextRow = c < "+this.outputShape[2]+";\n\n        vec4 sum = vec4(0.);\n        vec4 xFragAtOutputCoords = getX(b, r, c, d);\n\n        vec4 xAtOutputCoords = vec4(\n          getChannel(xFragAtOutputCoords, vec2(c, d)),\n          hasNextCol ?\n            getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,\n          hasNextRow ?\n            getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0\n        );\n\n        int firstChannel = d - "+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("+i+"));\n\n          bool depthInRange = aboveLowerBound.x && belowUpperBound.x;\n          bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;\n\n          if(depthInRange || depthPlusOneInRange){\n            vec4 z = vec4(0.);\n            vec4 xFragAtCurrentDepth;\n            z.xz = cache.xy;\n            if(depthPlusOneInRange && hasNextCol){\n              xFragAtCurrentDepth = idx.y != d ?\n                getX(b, r, c, idx.y) : xFragAtOutputCoords;\n              z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));\n              if(hasNextRow){\n                z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));\n              }\n            }\n            cache.xy = z.yw;\n            sum += z * z;\n          }\n        }\n        vec4 result = xAtOutputCoords * "+s+";\n        setOutput(result);\n      }\n    "}}(),si=function(){return function(p){this.variableNames=["dy","maxPos"],this.outputShape=p.inShape;var t=p.strideHeight,e=p.strideWidth,n=p.dilationHeight,r=p.effectiveFilterHeight,o=p.effectiveFilterWidth,a=r-1-p.padInfo.top,i=o-1-p.padInfo.left;this.userCode="\n      const ivec2 pads = ivec2("+a+", "+i+");\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n\n        ivec2 dyRCCorner = coords.yz - pads;\n        int dyRCorner = dyRCCorner.x;\n        int dyCCorner = dyRCCorner.y;\n\n        // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        for (int wR = 0; wR < "+r+";\n          wR += "+n+") {\n          float dyR = float(dyRCorner + wR) / "+t+".0;\n\n          if (dyR < 0.0 || dyR >= "+p.outHeight+".0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          for (int wC = 0; wC < "+o+"; wC++) {\n            float dyC = float(dyCCorner + wC) / "+e+".0;\n\n            if (dyC < 0.0 || dyC >= "+p.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 = "+(r*o-1)+" - 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 * "+o+" + wC;\n            float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n            dotProd += dyValue * mask;\n          }\n        }\n        setOutput(dotProd);\n      }\n    "}}(),ui=function(){return function(m,t,e,g,y,b){void 0===e&&(e=!1),void 0===g&&(g=!1),void 0===y&&(y=!1),void 0===b&&(b=null),this.variableNames=["matrixA","matrixB"],this.usesPackedTextures=!0,this.outputShape=t;var x=e?m[1]:m[2],i=kf(x/2),s=e?"i * 2, rc.y":"rc.y, i * 2",u=g?"rc.z, i * 2":"i * 2, rc.z",l=e?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],c=g?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],h="",v="";b&&(h="vec4 activation(vec4 x) {\n        "+b+"\n      }",v="result = activation(result);");var C=y?"result += getBiasAtOutCoords();":"";y&&this.variableNames.push("bias"),this.userCode="\n      "+h+"\n\n      const float sharedDimension = "+i+".0;\n\n      vec4 dot2x2ARowBCol(ivec3 rc) {\n        vec4 result = vec4(0);\n        for (int i = 0; i < "+i+"; i++) {\n          vec4 a = getMatrixA(rc.x, "+s+");\n          vec4 b = getMatrixB(rc.x, "+u+");\n\n          // These swizzled products need to be separately added.\n          // See: https://github.com/tensorflow/tfjs/issues/1735\n          result += ("+l[0]+" * "+c[0]+");\n          result += ("+l[1]+" * "+c[1]+");\n        }\n        return result;\n      }\n\n      void main() {\n        ivec3 rc = getOutputCoords();\n        vec4 result = dot2x2ARowBCol(rc);\n\n        "+C+"\n\n        "+v+"\n\n        setOutput(result);\n      }\n    "}}(),li=function(){function e(a,t,e){this.variableNames=["probs"],this.outputShape=[a,e],this.userCode="\n      uniform float seed;\n\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int batch = coords[0];\n\n        float r = random(seed);\n        float cdf = 0.0;\n\n        for (int i = 0; i < "+(t-1)+"; i++) {\n          cdf += getProbs(batch, i);\n\n          if (r < cdf) {\n            setOutput(float(i));\n            return;\n          }\n        }\n\n        // If no other event happened, last event happened.\n        setOutput(float("+(t-1)+"));\n      }\n    "}return e.prototype.getCustomSetupFunc=function(a){var t=this;return function(e,n){null==t.seedLoc&&(t.seedLoc=e.getUniformLocation(n,"seed")),e.gl.uniform1f(t.seedLoc,a)}},e}(),ci=function(){return function(a,t,e,n){this.variableNames=["indices"],this.outputShape=[a,t],this.userCode="\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int index = round(getIndices(coords.x));\n        setOutput(mix(float("+n+"), float("+e+"),\n                      float(index == coords.y)));\n      }\n    "}}(),hi=function(){return function(s){this.variableNames=["A"],this.outputShape=s;var t=s.length;if(0===t)this.userCode="\n        void main() {\n          setOutput(vec4(getA(), 0., 0., 0.));\n        }\n      ";else{var e=Jr("rc",t),n=po(t),r=function(a,t,e){if(1===a)return"rc > "+t[0];for(var n="",s=a-2;s<a;s++)n+=e[s]+" >= "+t[s],s<a-1&&(n+="||");return n}(t,s,e),o=function(a,t,e,n){if(1===a)return"";var r=n.slice(-2);return"\n    int r = "+r[0]+";\n    int c = "+r[1]+";\n    int rp1 = r + 1;\n    int cp1 = c + 1;\n\n    bool cEdge = cp1 >= "+t+";\n    bool rEdge = rp1 >= "+e+";\n  "}(t,s[s.length-1],s[s.length-2],e),a=function(a,t){var e=a.length,n=function(s,t){for(var e=[],n=0;1>=n;n++)for(var p=0;1>=p;p++){for(var d=(0==n?"r":"rp1")+", "+(0==p?"c":"cp1"),l=2;l<s;l++)d=t[t.length-1-l]+","+d;e.push(d)}return e}(e,t);return 1===e?"getA(rc),\n            rc + 1 >= "+a[0]+" ? 0. : getA(rc + 1),\n            0, 0":"getA("+n[0]+"),\n          cEdge ? 0. : getA("+n[1]+"),\n          rEdge ? 0. : getA("+n[2]+"),\n          rEdge || cEdge ? 0. : getA("+n[3]+")"}(s,e);this.userCode="\n        void main() {\n          "+n+" rc = getOutputCoords();\n\n          if("+r+") {\n            setOutput(vec4(0));\n          } else {\n            "+o+"\n\n            setOutput(vec4("+a+"));\n          }\n        }\n      "}}}(),fi=function(){return function(p,t,e){this.variableNames=["x"],this.outputShape=t.map(function(t,e){return t[0]+p[e]+t[1]});var n=p.length,r=po(n),o=t.map(function(e){return e[0]}).join(","),a=t.map(function(t,e){return t[0]+p[e]}).join(","),i=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,n);this.userCode=1===n?"\n        int start = "+o+";\n        int end = "+a+";\n\n        void main() {\n          int outC = getOutputCoords();\n          if (outC < start || outC >= end) {\n            setOutput(float("+e+"));\n          } else {\n            setOutput(getX(outC - start));\n          }\n        }\n      ":"\n      "+r+" start = "+r+"("+o+");\n      "+r+" end = "+r+"("+a+");\n\n      void main() {\n        "+r+" outC = getOutputCoords();\n        if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n          setOutput(float("+e+"));\n        } else {\n          "+r+" coords = outC - start;\n          setOutput(getX("+i+"));\n        }\n      }\n    "}}(),pi=function(){return function(m,t,e){this.variableNames=["x"],this.usesPackedTextures=!0,this.outputShape=t.map(function(t,e){return t[0]+m[e]+t[1]});for(var n=m.length,r=po(n),o=t.map(function(e){return e[0]}).join(","),a=t.map(function(t,e){return t[0]+m[e]}).join(","),i=Jr("rc",n),s=Jr("source",n),u=i[n-1]+" < "+this.outputShape[n-1],l=1===n?"source":"vec2("+s.slice(-2).join()+")",c=[r+" rc = outputLoc;",i[n-1]+" += 1;\n       if("+u+") {\n      ",1===n?"":"}\n       rc = outputLoc;\n       "+i[n-2]+" += 1;\n       if("+i[n-2]+" < "+this.outputShape[n-2]+") {",1===n?"":"  "+i[n-1]+" += 1;\n         if("+u+") {"],h=1===n?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",g="",f=0,y=1===n?2:4;f<y;f++)g+="\n        "+c[f]+"\n        if ("+h+") {\n          result["+f+"] = float("+e+");\n        } else {\n          "+r+" source = rc - start;\n          result["+f+"] = getChannel(getX("+s.join()+"), "+l+");\n        }\n      ";g+=1===n?"} ":"}}",this.userCode="\n      const "+r+" start = "+r+"("+o+");\n      const "+r+" end = "+r+"("+a+");\n\n      void main() {\n        "+r+" outputLoc = getOutputCoords();\n        vec4 result = vec4(0.);\n        "+g+"\n        setOutput(result);\n      }\n    "}}(),di=function(){return function(y,t,e){if(this.variableNames=["x"],"avg"===t&&e)throw new Error("Cannot compute positions for average pool.");var n=y.filterWidth,r=y.strideHeight,o=y.strideWidth,a=y.dilationHeight,i=y.dilationWidth,s=y.effectiveFilterHeight,u=y.effectiveFilterWidth,l=y.padInfo.top,c=y.padInfo.left;this.outputShape=y.outShape;var h="avg"===t,f="0.0";if(h||(f="-1.0 / 1e-20"),e)this.userCode="\n        const ivec2 strides = ivec2("+r+", "+o+");\n        const ivec2 pads = ivec2("+l+", "+c+");\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 < "+s+";\n              wR += "+a+") {\n            int xR = xRCorner + wR;\n\n            if (xR < 0 || xR >= "+y.inHeight+") {\n              continue;\n            }\n\n            for (int wC = 0; wC < "+u+";\n                wC += "+i+") {\n              int xC = xCCorner + wC;\n\n              if (xC < 0 || xC >= "+y.inWidth+") {\n                continue;\n              }\n\n              float value = getX(batch, xR, xC, d);\n\n              // If a min / max value has already been found, use it. If not,\n              // use the current value.\n              float currMinMaxValue = mix(\n                  value, minMaxValue, minMaxValueFound);\n              if (value >= currMinMaxValue) {\n                minMaxValue = value;\n                minMaxValueFound = 1.0;\n                minMaxPosition = wR * "+u+" + wC;\n              }\n            }\n          }\n          setOutput(float(minMaxPosition));\n        }\n      ";else{var b=t+"("+t+"("+t+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===t&&(b="avgValue / count");var x=4*Cf(n/4),v=n%4,m="\n      if ("+h+") {\n        avgValue += dot(values, ones);\n      } else {\n        minMaxValue = max(values, minMaxValue);\n      }\n    ";this.userCode="\n      const ivec2 strides = ivec2("+r+", "+o+");\n      const ivec2 pads = ivec2("+l+", "+c+");\n      const float initializationValue = "+f+";\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 >= "+y.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("+f+");\n        float avgValue = 0.0;\n        count = 0.0;\n\n        for (int wR = 0; wR < "+s+";\n            wR += "+a+") {\n          int xR = xRCorner + wR;\n\n          if (xR < 0 || xR >= "+y.inHeight+") {\n            continue;\n          }\n\n          for (int wC = 0; wC < "+x+"; wC += 4) {\n            int xC = xCCorner + wC * "+i+";\n\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              getValue(batch, xR, xC + "+i+", d),\n              getValue(batch, xR, xC + 2 * "+i+", d),\n              getValue(batch, xR, xC + 3 * "+i+", d)\n            );\n\n            "+m+"\n          }\n\n          int xC = xCCorner + "+x+";\n          if ("+(1==v)+") {\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              initializationValue,\n              initializationValue,\n              initializationValue\n            );\n\n            "+m+"\n          } else if ("+(2==v)+") {\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              getValue(batch, xR, xC + "+i+", d),\n              initializationValue,\n              initializationValue\n            );\n\n            "+m+"\n          } else if ("+(3==v)+") {\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              getValue(batch, xR, xC + "+i+", d),\n              getValue(batch, xR, xC + 2 * "+i+", d),\n              initializationValue\n            );\n\n            "+m+"\n          }\n        }\n        setOutput("+b+");\n      }\n    "}}}(),vi=function(){return function(d,t){this.variableNames=["x"];var e=d.windowSize,n=d.batchSize,r=d.inSize,o=kf(r/e);this.outputShape=[n,o];var a="0.0",m="";"prod"===t?a="1.0":"min"===t?(a="1.0 / 1e-20",m="min"):"max"==t&&(a="-1.0 / 1e-20",m="max");var g=t+"("+t+"("+t+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"sum"===t?g="sumValue":"prod"===t?g="prodValue":"all"===t?g="allValue":"any"==t&&(g="anyValue");var y=4*Cf(e/4),l=e%4,c="\n      if ("+("sum"===t)+") {\n        sumValue += dot(values, ones);\n      } else if ("+("prod"===t)+") {\n        vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n        prodValue *= tmp[0] * tmp[1];\n      } else {\n        minMaxValue = "+m+"(values, minMaxValue);\n      }\n    ",b="vec4";"all"===t?(a="1.0",c="\n        bool reducedAllValue = all(values);\n        float floatedReducedAllValue = float(reducedAllValue);\n        allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n      ",b="bvec4"):"any"==t&&(a="0.0",c="\n        bool reducedAnyValue = any(values);\n        float floatedReducedAnyValue = float(reducedAnyValue);\n        anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n      ",b="bvec4");var x="";0<r%e&&(x="\n        if (inIdx < 0 || inIdx >= "+r+") {\n          return initializationValue;\n        }\n      "),this.userCode="\n      const float initializationValue = "+a+";\n      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n      float getValue(int batch, int inIdx) {\n        "+x+"\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 * "+e+";\n\n        vec4 minMaxValue = vec4("+a+");\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 < "+y+"; i += 4) {\n          int inIdx = inOffset + i;\n          "+b+" values = "+b+"(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            getValue(batch, inIdx + 3)\n          );\n\n          "+c+"\n        }\n\n        int inIdx = inOffset + "+y+";\n        if ("+(1==l)+") {\n          "+b+" values = "+b+"(\n            getValue(batch, inIdx),\n            initializationValue,\n            initializationValue,\n            initializationValue\n          );\n\n          "+c+"\n        } else if ("+(2==l)+") {\n          "+b+" values = "+b+"(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            initializationValue,\n            initializationValue\n          );\n\n          "+c+"\n        } else if ("+(3==l)+") {\n          "+b+" values = "+b+"(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            initializationValue\n          );\n\n          "+c+"\n        }\n        setOutput("+g+");\n      }\n    "}}(),mi=function(){return function(a,t){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=a;for(var e="",s=0,i;4>s;s++)i="thisRC = rc;",1==s%2&&(i+="thisRC.z += 1;"),1<s&&(i+="thisRC.y += 1;"),e+="\n        "+i+"\n        "+(0<s?"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["+s+"] =\n            getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n        "+(0<s?"}":"")+"\n      ";this.userCode="\n      \n    ivec3 inputCoordsFromReshapedOutCoords(int index) {\n      "+to(["r","c","d"],t)+"\n      return ivec3(r, c, d);\n    }\n  \n      "+ao(a)+"\n\n      void main() {\n        ivec3 rc = getOutputCoords();\n\n        vec4 result = vec4(0.);\n\n        ivec3 thisRC;\n        int rows = "+a[1]+";\n        int cols = "+a[2]+";\n\n        "+e+"\n\n        setOutput(result);\n      }\n    "}}(),gi=function(){return function(g,t,e){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;var n=t.shape,r=n[1],o=n[2],a=g.shape,i=a[1],s=a[2],u=[e&&1<i?r-1:r,e&&1<s?o-1:o],l=[e&&1<i?i-1:i,e&&1<s?s-1:s],c=u[0]/l[0],h=u[1]/l[1],f=1/c,p=1/h,d=2*kf(f)+2,y=2*kf(p)+2;this.userCode="\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n        int r = coords[1];\n        int c = coords[2];\n\n        float accumulator = 0.0;\n\n        const float heightScale = float("+c+");\n        const float widthScale = float("+h+");\n\n        const float invHeightScale = float("+f+");\n        const float invWidthScale = float("+p+");\n\n        const int winHeight = int("+d+");\n        const int winWidth = int("+y+");\n\n        // Compute bounds for where in dy we will look\n        float startRLerp = floor(float(r) * invHeightScale);\n        int startDyR = int(startRLerp - float(winHeight / 2));\n\n        float startCLerp = floor(float(c) * invWidthScale);\n        int startDyC = int(startCLerp - float(winWidth / 2));\n\n        // Loop over dy\n        for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n          int dyR = dyROffset + startDyR;\n\n          // Guard against the window exceeding the bounds of dy\n          if (dyR < 0 || dyR >= "+i+") {\n            continue;\n          }\n\n          for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n            int dyC = dyCOffset + startDyC;\n\n            // Guard against the window exceeding the bounds of dy\n            if (dyC < 0 || dyC >= "+s+") {\n              continue;\n            }\n\n            float dxR = float(dyR) * heightScale;\n            int topDxRIndex = int(floor(dxR));\n            int bottomDxRIndex = int(min(ceil(dxR), "+(r-1)+".0));\n            float dxRLerp = dxR - float(topDxRIndex);\n            float inverseDxRLerp = 1.0 - dxRLerp;\n\n            float dxC = float(dyC) * widthScale;\n            int leftDxCIndex = int(floor(dxC));\n            int rightDxCIndex = int(min(ceil(dxC), "+(o-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    "}}(),yi=function(){return function(p,t,e,n){this.variableNames=["A"],this.outputShape=[];var r=p[0],o=p[1],a=p[2],i=p[3];this.outputShape=[r,t,e,i];var s=[n&&1<t?o-1:o,n&&1<e?a-1:a],d=[n&&1<t?t-1:t,n&&1<e?e-1:e];this.userCode="\n      const vec2 effectiveInputOverOutputRatioRC = vec2(\n          "+s[0]/d[0]+",\n          "+s[1]/d[1]+");\n      const vec2 inputShapeRC = vec2("+o+".0, "+a+".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    "}}(),xi=function(){return function(p,t,e,n){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=[];var r=p[0],o=p[1],a=p[2],i=p[3];this.outputShape=[r,t,e,i];var s=[n&&1<t?o-1:o,n&&1<e?a-1:a],d=[n&&1<t?t-1:t,n&&1<e?e-1:e];this.userCode="\n      const vec3 effectiveInputOverOutputRatioRC = vec3(\n          "+s[0]/d[0]+",\n          "+s[1]/d[1]+",\n          "+s[1]/d[1]+");\n      const vec3 inputShapeRC = vec3("+o+".0, "+a+".0,\n                                     "+a+".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 < "+(i-1)+"; \n        bool hasNextRow = coords.z < "+(e-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    "}}(),bi=function(){return function(g,t,e){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t.shape;var n=t.shape,r=n[1],o=n[2],a=g.shape,i=a[1],s=a[2],u=[e&&1<i?r-1:r,e&&1<s?o-1:o],l=[e&&1<i?i-1:i,e&&1<s?s-1:s],c=u[0]/l[0],h=u[1]/l[1],f=1/c,p=1/h,d=2*kf(f)+2,y=2*kf(p)+2;this.userCode="\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n        int r = coords[1];\n        int c = coords[2];\n\n        float accumulator = 0.0;\n\n        const float heightScale = float("+c+");\n        const float widthScale = float("+h+");\n\n        const float invHeightScale = float("+f+");\n        const float invWidthScale = float("+p+");\n\n        const int winHeight = int("+d+");\n        const int winWidth = int("+y+");\n\n        // Compute bounds for where in dy we will look\n        float startRLerp = floor(float(r) * invHeightScale);\n        int startDyR = int(floor(startRLerp - float(winHeight / 2)));\n\n        float startCLerp = floor(float(c) * invWidthScale);\n        int startDyC = int(floor(startCLerp - float(winWidth / 2)));\n\n        // Loop over dy\n        for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n          int dyR = dyROffset + startDyR;\n\n          // Guard against the window exceeding the bounds of dy\n          if (dyR < 0 || dyR >= "+i+") {\n            continue;\n          }\n\n          for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n            int dyC = dyCOffset + startDyC;\n\n            // Guard against the window exceeding the bounds of dy\n            if (dyC < 0 || dyC >= "+s+") {\n              continue;\n            }\n\n            float sourceFracRow =\n              float("+u[0]+") *\n                (float(dyR) / float("+l[0]+"));\n\n            float sourceFracCol =\n                float("+u[1]+") *\n                  (float(dyC) / float("+l[1]+"));\n\n            int sourceNearestRow = int(min(\n                float(int("+r+") - 1),\n                "+e+" ? float(round(sourceFracRow)) :\n                                  float(floor(sourceFracRow))));\n\n            int sourceNearestCol = int(min(\n                float(int("+o+") - 1),\n                "+e+" ? 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    "}}(),wi=function(){return function(p,t,e,n){this.variableNames=["A"],this.outputShape=[];var r=p[0],o=p[1],a=p[2],i=p[3];this.outputShape=[r,t,e,i];var s=[n&&1<t?o-1:o,n&&1<e?a-1:a],d=[n&&1<t?t-1:t,n&&1<e?e-1:e],l=n?"0.5":"0.0";this.userCode="\n      const vec2 effectiveInputOverOutputRatioRC = vec2(\n          "+s[0]/d[0]+",\n          "+s[1]/d[1]+");\n      const vec2 inputShapeRC = vec2("+o+".0, "+a+".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 + "+l+")));\n\n        float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n        setOutput(newValue);\n      }\n    "}}(),Ci=function(){return function(a,t){this.variableNames=["x"];var e=a.length;if(4<e)throw new Error("WebGL backend: Reverse of rank-"+e+" tensor is not yet supported");if(this.outputShape=a,1!==e){var n=a.map(function(e,n){return function(e){return-1!==t.indexOf(e)&&1!==a[e]?a[e]+" - coords["+e+"] - 1":"coords["+e+"]"}(n)}).join(","),r=po(e);this.userCode="\n      void main() {\n        "+r+" coords = getOutputCoords();\n        setOutput(getX("+n+"));\n      }\n    "}else this.userCode="\n        void main() {\n          int coord = getOutputCoords();\n          setOutput(getX("+a[0]+" - coord - 1));\n        }\n      "}}(),Ei=function(){return function(p,t){function e(e){var a=p.map(function(a,n){return function(e,a){return-1!==t.indexOf(e)&&1!==p[e]?p[e]+" - "+a[e]+" - 1":""+a[e]}(n,e)});return"getChannel(getX("+a.join(",")+"), vec2("+a.slice(-2).join(",")+"))"}this.variableNames=["x"],this.usesPackedTextures=!0;var s=p.length;if(4<s)throw new Error("WebGL backend: Reverse of rank-"+s+" tensor is not yet supported");this.outputShape=p;var n=Jr("rc",s),r=n[s-1]+" + 1 < "+this.outputShape[s-1],o=n[s-2]+" + 1 < "+this.outputShape[s-2],a=po(s);this.userCode=1===s?"\n        void main(){\n          int rc = getOutputCoords();\n          vec4 result = vec4(0.);\n          result.r = getChannel(getX("+p[0]+" - rc - 1),\n            "+p[0]+" - rc - 1);\n          if("+r+"){\n              result.g = getChannel(getX("+p[0]+" - (rc  + 1) - 1),\n                "+p[0]+" - (rc  + 1) - 1);\n          }\n          setOutput(result);\n        }\n      ":"\n        void main() {\n          "+a+" rc = getOutputCoords();\n          vec4 result = vec4(0.);\n          result.r = "+function(a){return e(a)}(n.slice())+";\n          if("+r+"){\n            result.g = "+function(a){return a[s-1]="("+a[s-1]+" + 1)",e(a)}(n.slice())+";\n          }\n          if("+o+") {\n            result.b = "+function(a){return a[s-2]="("+a[s-2]+" + 1)",e(a)}(n.slice())+";\n            if("+r+") {\n              result.a = "+function(a){return a[s-1]="("+a[s-1]+" + 1)",a[s-2]="("+a[s-2]+" + 1)",e(a)}(n.slice())+";\n            }\n          }\n          setOutput(result);\n        }\n    "}}(),Ri=function(){return function(i,t,e,n,r,o){this.variableNames=["updates","indices","defaultValue"],this.outputShape=o;var a=po(r.length),s=po(o.length),d="";1===e?d="i":2==e&&(d="i, j");var u="getIndices("+d+")",c="";1===n?c="i":2==n&&(c="i, coords[1]");var m="getUpdates("+c+")",g=1<t?"strides[j]":"strides";this.userCode="\n        "+a+" strides = "+a+"("+r+");\n\n        void main() {\n          "+s+" coords = getOutputCoords();\n          float sum = 0.0;\n          bool found = false;\n          for (int i = 0; i < "+i+"; i++) {\n            int flattenedIndex = 0;\n            for (int j = 0; j < "+t+"; j++) {\n              int index = round("+u+");\n              flattenedIndex += index * "+g+";\n            }\n            if (flattenedIndex == coords[0]) {\n              sum += "+m+";\n              found = true;\n            }\n          }\n          setOutput(mix(getDefaultValue(), sum, float(found)));\n        }\n      "}}(),Ii=function(){return function(e){this.variableNames=["x","segmentIds"];var t=e.windowSize,n=e.batchSize,r=e.inSize,o=e.numSegments,a=o*kf(r/t);this.outputShape=[n,a];var i=4*Cf(t/4),s=t%4,p="";0<r%t&&(p="\n        if (inIdx < 0 || inIdx >= "+r+") {\n          return initializationValue;\n        }\n      ");var d="";0<r%t&&(d="\n        if (inIdx < 0 || inIdx >= "+r+") {\n          return -1.0;\n        }\n      "),this.userCode="\n      const float initializationValue = 0.0;\n\n      float getValue(int batch, int inIdx) {\n        "+p+"\n        return getX(batch, inIdx);\n      }\n\n      float getSegmentIdAtIndex(int inIdx) {\n        "+d+"\n        return getSegmentIds(inIdx);\n      }\n\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int batch = coords[0];\n        int outIdx = coords[1];\n        int inOffset = int(floor(float(outIdx) / float(\n          "+o+")) * float("+t+"));\n        int currentSeg = int(mod(float(outIdx), float("+o+")));\n\n        float sumValue = 0.0;\n\n        for (int i = 0; i < "+i+"; i += 4) {\n          int inIdx = inOffset + i;\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            getValue(batch, inIdx + 3)\n          );\n\n          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          \n        sumValue += dot(values, segFilter);\n    \n        }\n\n        int inIdx = inOffset + "+i+";\n        if ("+(1==s)+") {\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          \n        sumValue += dot(values, segFilter);\n    \n        } else if ("+(2==s)+") {\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          \n        sumValue += dot(values, segFilter);\n    \n        } else if ("+(3==s)+") {\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          \n        sumValue += dot(values, segFilter);\n    \n        }\n        setOutput(sumValue);\n      }\n    "}}(),Si=function(){return function(p,t,e){var n,d;if(this.variableNames=["c","a","b"],this.outputShape=t,4<e)throw Error("Where for rank "+e+" is not yet supported");if(1===e)d="resRC",n="resRC";else{for(var c=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[],i=[],s=0;s<t.length;s++)i.push(""+c[s]),s<p&&a.push(""+c[s]);n=a.join(),d=i.join()}var h=po(e);this.userCode="\n      void main() {\n        "+h+" resRC = getOutputCoords();\n        float cVal = getC("+n+");\n        if (cVal >= 1.0) {\n          setOutput(getA("+d+"));\n        } else {\n          setOutput(getB("+d+"));\n        }\n      }\n    "}}(),Ni=function(){function e(a){this.variableNames=["source"],this.outputShape=a,this.rank=a.length;var t=po(this.rank),n="uniform int start["+this.rank+"];",r=function(e){if(1===e)return"sourceLoc";if(6>=e)return ki.slice(0,e).map(function(e){return"sourceLoc."+e}).join(",");throw Error("Slicing for rank "+e+" is not yet supported")}(this.rank),o;o="\n        "+t+" sourceLoc;\n        "+t+" coords = getOutputCoords();\n        "+a.map(function(a,t){return"sourceLoc."+ki[t]+" = start["+t+"] + coords."+ki[t]+";"}).join("\n")+"\n      ",this.userCode="\n      "+n+"\n      void main() {\n        "+o+"\n        setOutput(getSource("+r+"));\n      }\n    "}return e.prototype.getCustomSetupFunc=function(a){var t=this;if(a.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+a.length+")");return function(e,n){null==t.startLoc&&(t.startLoc=e.getUniformLocationNoThrow(n,"start"),null==t.startLoc)||e.gl.uniform1iv(t.startLoc,a)}},e}(),ki=["x","y","z","w","u","v"],Ai=function(){function e(p){this.variableNames=["source"],this.usesPackedTextures=!0,this.outputShape=p,this.rank=p.length;var t=po(this.rank),d=Jr("coords",this.rank),n=Jr("sourceLoc",this.rank),e=1===this.rank?"sourceLoc":"vec2("+n.slice(-2).join()+")",r="getChannel(getSource("+n.join()+"), "+e+")",a="\n      result.x = "+r+";\n      if (++"+d[this.rank-1]+" < "+p[this.rank-1]+") {\n        ++"+n[this.rank-1]+";\n        result.y = "+r+";\n        --"+n[this.rank-1]+";\n      }\n    ",o=1===this.rank?"":"\n      --"+d[this.rank-1]+";\n      if (++"+d[this.rank-2]+" < "+p[this.rank-2]+") {\n        ++"+n[this.rank-2]+";\n        result.z = "+r+";\n        if (++"+d[this.rank-1]+" < "+p[this.rank-1]+") {\n          ++"+n[this.rank-1]+";\n          result.w = "+r+";\n        }\n      }\n    ",s=4>=this.rank?"sourceLoc = coords +\n            "+t+"("+p.map(function(a,t){return"start["+t+"]"}).join()+");":p.map(function(a,t){return n[t]+" = "+d[t]+" + start["+t+"];"}).join("\n");this.userCode="\n      uniform int start["+this.rank+"];\n      void main() {\n        "+t+" coords = getOutputCoords();\n        "+t+" sourceLoc;\n        "+s+" \n        vec4 result = vec4(0.);\n        "+a+"\n        "+o+"\n        setOutput(result);\n      }\n    "}return e.prototype.getCustomSetupFunc=function(a){var t=this;if(a.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+a.length+")");return function(e,n){null==t.startLoc&&(t.startLoc=e.getUniformLocationNoThrow(n,"start"),null==t.startLoc)||e.gl.uniform1iv(t.startLoc,a)}},e}(),Ti=function(){return function(p,t,e,n){this.variableNames=["x"];var r=e.filter(function(a,t){return-1===n.indexOf(t)});this.outputShape=r;var o=e.length,a=po(e.length),i=po(r.length),s="";if(1===o)s="coords * strides + begin";else{var d=0;s=e.map(function(a,t){return-1===n.indexOf(t)?(d++,1===r.length?"coords * strides["+t+"] + begin["+t+"]":"coords["+(d-1)+"] * strides["+t+"] + begin["+t+"]"):"begin["+t+"]"}).join(",")}this.userCode="\n      "+a+" begin = "+a+"("+p+");\n      "+a+" strides = "+a+"("+t+");\n\n      void main() {\n        "+i+" coords = getOutputCoords();\n        setOutput(getX("+s+"));\n      }\n    "}}(),Di=function(){function e(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}return e.prototype.acquireTexture=function(s,t,e){var n=mo(t,e),o=go(s,n,e),a;if(o in this.freeTextures||(this.freeTextures[o]=[]),o in this.usedTextures||(this.usedTextures[o]=[]),0<this.freeTextures[o].length){this.numFreeTextures--,this.numUsedTextures++,this.log();var p=this.freeTextures[o].shift();return this.usedTextures[o].push(p),p}return this.numUsedTextures++,this.log(),n===Uf.PACKED_2X2_FLOAT32?a=this.gpgpu.createPackedMatrixTexture(s[0],s[1]):n===Uf.PACKED_2X2_FLOAT16?a=this.gpgpu.createFloat16PackedMatrixTexture(s[0],s[1]):n===Uf.UNPACKED_FLOAT32?a=this.gpgpu.createFloat32MatrixTexture(s[0],s[1]):n===Uf.UNPACKED_FLOAT16?a=this.gpgpu.createFloat16MatrixTexture(s[0],s[1]):n===Uf.PACKED_4X1_UNSIGNED_BYTE&&(a=this.gpgpu.createUnsignedBytesMatrixTexture(s[0],s[1])),this.usedTextures[o].push(a),a},e.prototype.releaseTexture=function(s,t,e,n){if(null!=this.freeTextures){var r=go(t,mo(e,n),n);r in this.freeTextures||(this.freeTextures[r]=[]),this.freeTextures[r].push(s),this.numFreeTextures++,this.numUsedTextures--;var o=this.usedTextures[r],a=o.indexOf(s);if(0>a)throw new Error("Cannot release a texture that was never provided by this texture manager");o.splice(a,1),this.log()}},e.prototype.log=function(){if(this.logEnabled){var e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+e+")")}},e.prototype.getNumUsedTextures=function(){return this.numUsedTextures},e.prototype.getNumFreeTextures=function(){return this.numFreeTextures},e.prototype.dispose=function(){var a=this;if(null!=this.freeTextures){for(var t in this.freeTextures)this.freeTextures[t].forEach(function(t){a.gpgpu.deleteMatrixTexture(t)});for(var t in this.usedTextures)this.usedTextures[t].forEach(function(t){a.gpgpu.deleteMatrixTexture(t)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0}},e}(),_i=function(){return function(s,t){this.variableNames=["A"];for(var e=Array(s.length),n=0;n<e.length;n++)e[n]=s[n]*t[n];this.outputShape=e,this.rank=e.length;var i=po(this.rank),o=function(a){var t=a.length;if(5<t)throw Error("Tile for rank "+t+" is not yet supported");if(1===t)return"imod(resRC, "+a[0]+")";for(var e=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],n=[],r=0;r<a.length;r++)n.push("imod("+e[r]+", "+a[r]+")");return n.join()}(s);this.userCode="\n      void main() {\n        "+i+" resRC = getOutputCoords();\n        setOutput(getA("+o+"));\n      }\n    "}}(),Mi=function(){return function(s,t){this.variableNames=["A"];for(var e=Array(s.length),n=0;n<e.length;n++)e[n]=s[t[n]];this.outputShape=e,this.rank=e.length;var i=po(this.rank),o=function(a){var t=a.length;if(6<t)throw Error("Transpose for rank "+t+" is not yet supported");for(var e=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],n=Array(t),r=0;r<a.length;r++)n[a[r]]=e[r];return n.join()}(t);this.userCode="\n    void main() {\n      "+i+" resRC = getOutputCoords();\n      setOutput(getA("+o+"));\n    }\n    "}}(),Bi=function(){return function(p,t){this.variableNames=["A"],this.usesPackedTextures=!0;for(var e=Array(p.length),n=0;n<e.length;n++)e[n]=p[t[n]];if(this.outputShape=e,this.rank=e.length,6<this.rank)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");var d=po(this.rank),o=Qr("rc",this.rank),a=Array(this.rank);for(n=0;n<t.length;n++)a[t[n]]=o[n];var i="vec2("+a.slice(-2).join()+")",s="++"+o[this.rank-1]+" < "+e[this.rank-1],u="getChannel(getA("+a.join()+"), "+i+")";this.userCode="\n    void main() {\n      "+d+" rc = getOutputCoords();\n      vec4 result = vec4(0.);\n      result[0] = "+u+";\n      if("+s+") {\n        result[1] = "+u+";\n      }\n      --"+o[this.rank-1]+";\n      if(++"+o[this.rank-2]+" < "+e[this.rank-2]+") {\n        result[2] = "+u+";\n        if("+s+") {\n          result[3] = "+u+";\n        }\n      }  \n      setOutput(result);\n    }\n    "}}(),Pi=1.7580993408473768,Li=1.0507009873554805,Wi=function(){return function(a,t){this.variableNames=["A"],this.outputShape=a,this.userCode="\n      float unaryOperation(float x) {\n        "+t+"\n      }\n\n      void main() {\n        float x = getAAtOutCoords();\n        float y = unaryOperation(x);\n\n        setOutput(y);\n      }\n    "}}(),Ui="if (isnan(x)) return x;",zi="return exp(x);",qi=function(){return function(a,t){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=a,this.userCode="\n      vec4 unaryOperation(vec4 x) {\n        "+t+"\n      }\n\n      void main() {\n        vec4 x = getAAtOutCoords();\n        vec4 y = unaryOperation(x);\n\n        setOutput(y);\n      }\n    "}}(),Zi=function(){return function(s){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=s;var t=s.length,e=Jr("rc",t),n=po(t),r=function(a,t){if(1===a)return"rc";for(var e="",o=0;o<a;o++)e+=t[o],o<a-1&&(e+=",");return e}(t,e),o=e.slice(-2),a=1>=t?"rc":"vec2("+o.join(",")+")";this.userCode="\n      void main() {\n        "+n+" rc = getOutputCoords();\n        vec4 packedInput = getA("+r+");\n\n        setOutput(getChannel(packedInput, "+a+"));\n      }\n    "}}(),ts={},es=function(){function e(a){if(this.gpgpu=a,this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.warnedAboutMemory=!1,this.disposed=!1,!_f.getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(null==a){var t=Ze(_f.getNumber("WEBGL_VERSION"));this.binaryCache=(e=_f.getNumber("WEBGL_VERSION"))in ts?ts[e]:(ts[e]={},ts[e]),this.gpgpu=new ei(t),this.canvas=t.canvas,this.gpgpuCreatedLocally=!0}else this.binaryCache={},this.gpgpuCreatedLocally=!1,this.canvas=a.gl.canvas;var e;this.textureManager=new Di(this.gpgpu),this.numMBBeforeWarning=null==_f.global.screen?1024:_f.global.screen.height*_f.global.screen.width*window.devicePixelRatio*600/1024/1024,this.texData=new Xr(this,kt)}return e.prototype.register=function(a,t,e){if(this.texData.has(a))throw new Error("Data buffer is already registered");this.texData.set(a,{shape:t,dtype:e})},e.prototype.fromPixels=function(i,d){if(null==i)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var e=[i.height,i.width],n=[i.height,i.width,d],r="undefined"!=typeof OffscreenCanvas&&i instanceof OffscreenCanvas||"undefined"!=typeof HTMLCanvasElement&&i instanceof HTMLCanvasElement,o=i.data instanceof Uint8Array,a="undefined"!=typeof ImageData&&i instanceof ImageData,s="undefined"!=typeof HTMLVideoElement&&i instanceof HTMLVideoElement,u="undefined"!=typeof HTMLImageElement&&i instanceof HTMLImageElement;if(!(r||o||a||s||u))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 "+i.constructor.name);if(u||s){if(null==this.fromPixels2DContext){if("complete"!==document.readyState)throw new Error("The DOM is not ready yet. Please call tf.browser.fromPixels() once the DOM is ready. One way to do that is to add an event listener for `DOMContentLoaded` on the document object");this.fromPixels2DContext=Qe(_f.getNumber("WEBGL_VERSION")).getContext("2d")}this.fromPixels2DContext.canvas.width=i.width,this.fromPixels2DContext.canvas.height=i.height,this.fromPixels2DContext.drawImage(i,0,0,i.width,i.height),i=this.fromPixels2DContext.canvas}var l=this.makeTensorHandle(e,"int32"),m,g;if(this.texData.get(l.dataId).usage=Ft.PIXELS,this.gpgpu.uploadPixelDataToTexture(this.getTexture(l.dataId),i),_f.getBool("WEBGL_PACK")){m=new Fa(n);var f=this.makePackedTensor(m.outputShape,l.dtype);g=this.compileAndRun(m,[l],f)}else m=new Oa(n),g=this.compileAndRun(m,[l]);return this.disposeData(l.dataId),g},e.prototype.makeTensorHandle=function(a,t){var e={};return this.register(e,a,t),{dataId:e,shape:a,dtype:t}},e.prototype.write=function(a,t){if(null==t)throw new Error("MathBackendWebGL.write(): values can not be null");if(_f.getBool("DEBUG"))for(var e=0,s;e<t.length;e++)if(s=t[e],!ot(s))throw Error("The value "+s+" cannot be represented on this device.");var i=this.texData.get(a);if("complex64"===i.dtype)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.releaseGPUData(a),i.usage=Ft.UPLOAD,i.values=t},e.prototype.readSync=function(p){var t=this.texData.get(p),e=t.values,n=t.dtype,r=t.complexTensors,o=t.slice,a=t.shape;if(null!=o){var i=new Wi(a,"return x;"),s=this.compileAndRun(i,[{dataId:p,shape:a,dtype:n}]),d=this.readSync(s.dataId);return s.dispose(),d}if(null!=e)return this.convertAndCacheOnCPU(p);if("string"===n)return e;var l=null!=this.activeTimers,u,m;return m=(l&&(u=U()),"complex64"===n)?Mr(r.real.dataSync(),r.imag.dataSync()):this.getValuesFromTexture(p),l&&(this.downloadWaitMs+=U()-u),this.convertAndCacheOnCPU(p,m)},e.prototype.read=function(i){return Be(this,void 0,void 0,function(){var t,g,S,N,I,k,T,A,D,_,O,z,L,F,B,P,M,W,V,U,G;return Me(this,function(e){switch(e.label){case 0:if(this.pendingRead.has(i))return g=this.pendingRead.get(i),[2,new Promise(function(e){return g.push(e)})];if(S=this.texData.get(i),N=S.values,I=S.shape,k=S.slice,T=S.dtype,A=S.complexTensors,null!=k)return D=new Wi(I,"return x;"),_=this.compileAndRun(D,[{dataId:i,shape:I,dtype:T}]),O=this.read(_.dataId),_.dispose(),[2,O];if(null!=N)return[2,this.convertAndCacheOnCPU(i)];if(!_f.getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===_f.getNumber("WEBGL_VERSION"))throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");return z=null,"complex64"!==T&&_f.get("WEBGL_BUFFER_SUPPORTED")&&(L=this.decode(i),i=L.dataId,F=this.texData.get(L.dataId),z=(t=this.gpgpu).createBufferFromTexture.apply(t,[F.texture].concat(tt(I)))),this.pendingRead.set(i,[]),"complex64"===T?[3,2]:[4,this.gpgpu.createAndWaitForFence()];case 1:e.sent(),e.label=2;case 2:return"complex64"===T?[4,Promise.all([A.real.data(),A.imag.data()])]:[3,4];case 3:return P=e.sent(),M=P[0],W=P[1],B=Mr(M,W),[3,5];case 4:null==z?B=this.getValuesFromTexture(i):(V=qe(I),B=this.gpgpu.downloadFloat32MatrixFromBuffer(z,V),this.disposeData(i)),e.label=5;case 5:return U=this.convertAndCacheOnCPU(i,B),G=this.pendingRead.get(i),this.pendingRead.delete(i),G.forEach(function(e){return e(U)}),this.pendingDisposal.has(i)&&(this.pendingDisposal.delete(i),this.disposeData(i)),[2,U];}})})},e.prototype.getValuesFromTexture=function(i){var t=this,n=this.texData.get(i),r=n.shape,o=n.dtype,a=n.isPacked,s=qe(r),u;if(_f.getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){var g=this.decode(i),l=this.texData.get(g.dataId),c=(u=this.gpgpu).downloadMatrixFromPackedTexture.apply(u,[l.texture].concat(tt(r))).subarray(0,s);return this.disposeData(g.dataId),c}var h=_f.getBool("WEBGL_PACK")&&!0===a,f=h?xe(r):r,p=this.makeTensorHandle(f,"float32");p.size=qe(r),this.texData.get(p.dataId).usage=Ft.DOWNLOAD;var d=We(function(){var a=h?new Sa(f):new Ia(f);return t.compileAndRun(a,[{shape:f,dtype:o,dataId:i}],p,null)}),b=this.texData.get(d.dataId),m=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(b.texture,b.texShape[0],b.texShape[1]).subarray(0,s);return this.disposeData(p.dataId),m},e.prototype.time=function(p){return Be(this,void 0,void 0,function(){var t,d,l,h,m,g,f;return Me(this,function(e){switch(e.label){case 0:return t=this.activeTimers,d=[],l=!1,null==this.programTimersStack?(this.programTimersStack=d,l=!0):this.activeTimers.push(d),this.activeTimers=d,p(),h=v(this.activeTimers.map(function(e){return e.query})).filter(function(e){return null!=e}),m=v(this.activeTimers.map(function(e){return e.name})).filter(function(e){return null!=e}),this.activeTimers=t,l&&(this.programTimersStack=null),[4,Promise.all(h)];case 1:return g=e.sent(),f={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:c(g),getExtraProfileInfo:function(){return g.map(function(a,t){return{name:m[t],ms:a}}).map(function(e){return e.name+": "+e.ms}).join(", ")},wallMs:null},this.uploadWaitMs=0,this.downloadWaitMs=0,[2,f];}})})},e.prototype.memory=function(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU}},e.prototype.startTimer=function(){return 0<_f.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?this.gpgpu.beginQuery():{startMs:U(),endMs:null}},e.prototype.endTimer=function(e){return 0<_f.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?(this.gpgpu.endQuery(),e):(e.endMs=U(),e)},e.prototype.getQueryTime=function(a){return Be(this,void 0,void 0,function(){var t;return Me(this,function(){return 0<_f.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?[2,this.gpgpu.waitForQueryAndGetTime(a)]:[2,(t=a).endMs-t.startMs]})})},e.prototype.disposeData=function(a){if(!this.pendingDisposal.has(a))if(this.pendingRead.has(a))this.pendingDisposal.add(a);else if(this.texData.has(a)){this.releaseGPUData(a);var t=this.texData.get(a).complexTensors;null!=t&&(t.real.dispose(),t.imag.dispose()),this.texData.delete(a)}},e.prototype.releaseGPUData=function(p){var t=this.texData.get(p),e=t.texture,n=t.dtype,r=t.texShape,o=t.usage,a=t.isPacked,i=t.slice,s=i&&i.origDataId||p,d=this.dataRefCount.get(s);1<d?this.dataRefCount.set(s,d-1):(this.dataRefCount.delete(s),null!=e&&(this.numBytesInGPU-=this.computeBytes(r,n),this.textureManager.releaseTexture(e,r,o,a)));var l=this.texData.get(p);l.texture=null,l.texShape=null,l.isPacked=!1,l.slice=null},e.prototype.getTexture=function(e){return this.uploadToGPU(e),this.texData.get(e).texture},e.prototype.getCPUBackend=function(){return _f.getBool("WEBGL_CPU_FORWARD")?(null==this.cpuBackend&&(this.cpuBackend=kt.findBackend("cpu")),this.cpuBackend):null},e.prototype.shouldExecuteOnCPU=function(a,r){var o=this;return void 0===r&&(r=128),null!=this.getCPUBackend()&&a.every(function(e){return null==o.texData.get(e.dataId).texture&&e.size<r})},e.prototype.getGPGPUContext=function(){return this.gpgpu},e.prototype.complex=function(a,t){var e=this.makeOutputArray(a.shape,"complex64");return this.texData.get(e.dataId).complexTensors={real:kt.keep(a.clone()),imag:kt.keep(t.clone())},e},e.prototype.real=function(e){return this.texData.get(e.dataId).complexTensors.real.clone()},e.prototype.imag=function(e){return this.texData.get(e.dataId).complexTensors.imag.clone()},e.prototype.slice=function(i,t,e){if(this.shouldExecuteOnCPU([i]))return this.cpuBackend.slice(i,t,e);if(0===qe(e))return Zt([],e,i.dtype);var n=this.texData.get(i.dataId).isPacked,r=An(i.shape,t,e);if(n||!r){var o=_f.getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Ai(e):new Ni(e),a=o.getCustomSetupFunc(t);return this.compileAndRun(o,[i],null,a)}return this.uploadToGPU(i.dataId),this.shallowSlice(i,t,e)},e.prototype.shallowSlice=function(p,t,e){var n=this.texData.get(p.dataId),r=Lf.make(e,{},p.dtype,this),o=this.texData.get(r.dataId);Object.assign(o,n),o.shape=e,o.dtype=p.dtype;var a=Dn(t,p.strides);n.slice&&(a+=n.slice.flatOffset),o.slice={flatOffset:a,origDataId:n.slice&&n.slice.origDataId||p.dataId};var d=this.dataRefCount.get(o.slice.origDataId)||1;return this.dataRefCount.set(o.slice.origDataId,d+1),r},e.prototype.stridedSlice=function(m,t,e,n,r,o,a,i,s){if(this.shouldExecuteOnCPU([m]))return this.cpuBackend.stridedSlice(m,t,e,n,r,o,a,i,s);var u=Rn(m.shape,t,e,n,r,o,a,i,s),l=u[0],c=u[1],h=u[2],g=c.filter(function(a,t){return-1===h.indexOf(t)});if(g.some(function(e){return 0===e}))return Zt([],g);var p=new Ti(l,n,c,h);return this.compileAndRun(p,[m])},e.prototype.reverse=function(a,t){var e=_f.getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Ei(a.shape,t):new Ci(a.shape,t);return this.compileAndRun(e,[a])},e.prototype.concat=function(i,p){if(this.shouldExecuteOnCPU(i))return this.cpuBackend.concat(i,p);if(1===i.length)return i[0];if(i.length>_f.getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var e=Cf(i.length/2),t=this.concat(i.slice(0,e),p),n=this.concat(i.slice(e),p);return this.concat([t,n],p)}if(_f.getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&1<i[0].rank){var r=new ua(i.map(function(e){return e.shape}),p);return this.compileAndRun(r,i)}var a=$t(i.map(function(e){return e.shape}),p),o=i.map(function(e){return e.as2D(-1,qe(e.shape.slice(p)))}),s=new sa(o.map(function(e){return e.shape}));return this.compileAndRun(s,o).reshape(a)},e.prototype.neg=function(a){var t=new Wi(a.shape,"return -x;");return this.compileAndRun(t,[a])},e.prototype.batchMatMul=function(d,m,g,n){var r=g?d.shape[2]:d.shape[1],o=n?m.shape[1]:m.shape[2],a=g?d.shape[1]:d.shape[2],i=d.shape[0];if((1===r||1===o)&&1e3<a){g&&(d=d.transpose([0,2,1])),n&&(m=m.transpose([0,2,1]));var s=1===o?d:d.as3D(i,a,1),u=1===o?2:1,l=1===o?m.as3D(i,1,a):m;return this.multiply(s,l).sum(u,!0)}var c=Y(d.dtype,m.dtype),h=new ui(d.shape,[i,r,o],g,n),f=this.makePackedTensor(h.outputShape,c);return this.compileAndRun(h,[d,m],f)},e.prototype.fusedBatchMatMul=function(c,t,e,n,r,o){var a=e?c.shape[2]:c.shape[1],i=n?t.shape[1]:t.shape[2],s=c.shape[0],u=Y(c.dtype,t.dtype),l=o?fo(o,!0):null,h=new ui(c.shape,[s,a,i],e,n,null!=r,l),m=this.makePackedTensor(h.outputShape,u),p=[c,t];return r&&p.push(r),this.compileAndRun(h,p,m)},e.prototype.multiply=function(i,t){if("complex64"===i.dtype){var e=this.texData.get(i.dataId),n=this.texData.get(t.dataId),r=new Yo("return areal * breal - aimag * bimag;",i.shape,t.shape),o=new Yo("return areal * bimag + aimag * breal;",i.shape,t.shape),a=[this.makeComplexComponentTensorHandle(i,e.complexTensors.real),this.makeComplexComponentTensorHandle(i,e.complexTensors.imag),this.makeComplexComponentTensorHandle(t,n.complexTensors.real),this.makeComplexComponentTensorHandle(t,n.complexTensors.imag)],s=this.compileAndRun(r,a),p=this.compileAndRun(o,a),d=this.complex(s,p);return s.dispose(),p.dispose(),d}if(this.shouldExecuteOnCPU([i,t]))return this.cpuBackend.multiply(i,t);if(_f.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(i,t,ea,i.dtype);var l=new na(ea,i.shape,t.shape),u=this.makeOutputArray(l.outputShape,i.dtype);return this.compileAndRun(l,[i,t],u)},e.prototype.batchNormalization=function(i,t,e,n,r,o){var a=[i,t,e],s=null;null!=o&&(s=o.shape,a.push(o));var p=null;if(null!=r&&(p=r.shape,a.push(r)),_f.getBool("WEBGL_PACK_NORMALIZATION")){var d=new Xo(i.shape,t.shape,e.shape,s,p,n);return this.compileAndRun(d,a)}var c=new Ko(i.shape,t.shape,e.shape,s,p,n);return this.compileAndRun(c,a)},e.prototype.localResponseNormalization4D=function(s,t,e,n,r){var o=_f.getBool("WEBGL_PACK_NORMALIZATION")?new ii(s.shape,t,e,n,r):new oi(s.shape,t,e,n,r);return this.compileAndRun(o,[s])},e.prototype.LRNGrad=function(p,t,e,n,r,o,a){var i=new ai(t.shape,n,r,o,a);return this.compileAndRun(i,[t,e,p])},e.prototype.tile=function(a,t){if("string"===a.dtype){var e=this.readSync(a.dataId).map(function(e){return H(e)});return jr(hn(a.shape,a.dtype,e),t)}var n=new _i(a.shape,t);return this.compileAndRun(n,[a])},e.prototype.pad=function(a,t,e){var n=_f.getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new pi(a.shape,t,e):new fi(a.shape,t,e);return this.compileAndRun(n,[a])},e.prototype.transpose=function(a,t){if(this.shouldExecuteOnCPU([a]))return this.cpuBackend.transpose(a,t);var e=_f.getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Bi(a.shape,t):new Mi(a.shape,t);return this.compileAndRun(e,[a])},e.prototype.gather=function(a,t,e){if(this.shouldExecuteOnCPU([a,t]))return this.cpuBackend.gather(a,t,e);var n=new Ma(a.shape,t.size,e);return this.compileAndRun(n,[a,t])},e.prototype.batchToSpaceND=function(p,t,e){Ue(4>=p.rank,function(){return"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"});var n=t.reduce(function(a,t){return a*t}),r=fn(p.shape,t,n),o=bn(r.length,t.length),a=vn(p.shape,t,n),i=Cn(e,t.length),s=Sn(a,e,t.length);return p.reshape(r).transpose(o).reshape(a).slice(i,s)},e.prototype.spaceToBatchND=function(p,t,e){Ue(4>=p.rank,function(){return"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"});var n=t.reduce(function(a,t){return a*t}),r=[[0,0]];r.push.apply(r,e);for(var o=1+t.length;o<p.shape.length;++o)r.push([0,0]);var d=p.pad(r),i=fn(d.shape,t,n,!1),s=bn(i.length,t.length,!1),u=vn(d.shape,t,n,!1);return d.reshape(i).transpose(s).reshape(u)},e.prototype.reduce=function(p,t,e){var n=p.shape[0],r=p.shape[1],o=In(r),a=new vi({windowSize:o,inSize:r,batchSize:n},t),i=a.outputShape,s=i[0],d=i[1],l=this.makeOutputArray([s,d],e);return this.compileAndRun(a,[p],l),1===l.shape[1]?l:this.reduce(l,t,e)},e.prototype.argReduce=function(p,t,e){void 0===e&&(e=null);var d=p.shape[0],m=p.shape[1];null!=e&&(d=e.shape[0],m=e.shape[1]);var g=In(m),a=new No({windowSize:g,inSize:m,batchSize:d},t,null==e),i=a.outputShape,s=i[0],u=i[1],l=this.makeOutputArray([s,u],"int32"),c=[p];return null!=e&&c.push(e),this.compileAndRun(a,c,l),1===l.shape[1]?l:this.argReduce(p,t,l)},e.prototype.argReducePacked=function(p,t,e){void 0===e&&(e=null);var d=null==e?p.shape:e.shape,r=In(d[d.length-1]),o=new zo(d,r,t,null==e),a=this.makePackedTensor(o.outputShape,"int32"),i=null==e?[p]:[p,e];return this.compileAndRun(o,i,a),a.rank===p.rank?this.argReducePacked(p,t,a):a},e.prototype.sum=function(s,t){Ut("sum",t,s.rank);var e=Wt(s.shape,t),n=e[0],r=qe(e[1]),o=s.as2D(-1,r),a=He(s.dtype);return this.reduce(o,"sum",a).reshape(n)},e.prototype.prod=function(s,t){if(this.shouldExecuteOnCPU([s]))return this.cpuBackend.prod(s,t);var e=Wt(s.shape,t),n=e[0],r=qe(e[1]),o=s.as2D(-1,r),a=He(s.dtype);return this.reduce(o,"prod",a).reshape(n)},e.prototype.unsortedSegmentSum=function(p,t,e){var n=0,d=qt([n],p.rank),o=p;null!=d&&(o=p.transpose(d),n=Kt(1,p.rank)[0]);var h=function(s,t,e){for(var n=[],r=s.length,o=0;o<r;o++)o===t?n.push(e):n.push(s[o]);return n}(o.shape,n,e),i=qe([o.shape[n]]),s=o.as2D(-1,i),u=He(p.dtype),l=this.segOpCompute(s,"unsortedSegmentSum",t,u,e).reshape(h);return null!=d&&(l=l.transpose(Ht(d))),l},e.prototype.segOpCompute=function(p,t,e,d,r){var o=p.shape[0],a=p.shape[1],i=function(a,t){var e=!1,o;for(a<=30?(o=a,e=!0):o=B(a,Cf(Tf(a)));!e;)o>t||o===a?e=!0:o=B(a,o+1);return o}(a,r),s=new Ii({windowSize:i,inSize:a,batchSize:o,numSegments:r},t),u=s.outputShape,l=u[0],c=u[1],h=this.makeOutputArray([l,c],d);return this.compileAndRun(s,[p,e],h),h.shape[1]===r?h:(e=un(0,r).tile([a/i]),this.segOpCompute(h,t,e,d,r))},e.prototype.argMinMaxReduce=function(i,t,e){var n=[t];if(Ut("arg"+e.charAt(0).toUpperCase()+e.slice(1),n,i.rank),!_f.getBool("WEBGL_PACK_REDUCE")||2>=i.rank){var r=Wt(i.shape,n),o=r[0],a=qe(r[1]),s=i.as2D(-1,a);return this.argReduce(s,e).reshape(o)}return this.argReducePacked(i,e)},e.prototype.argMin=function(a,t){return this.argMinMaxReduce(a,t,"min")},e.prototype.argMax=function(a,t){return this.argMinMaxReduce(a,t,"max")},e.prototype.cumsum=function(a,t,e,n){if(t!==a.rank-1)throw new Error("WebGL cumsum shader expects an inner-most axis="+(a.rank-1)+" but got axis="+t);var r=new ba(a.shape,e,n);return this.compileAndRun(r,[a])},e.prototype.equal=function(a,t){if(_f.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(a,t,"\n  return vec4(equal(a, b));\n","bool");var e=new na("return float(a == b);",a.shape,t.shape),n=this.makeOutputArray(e.outputShape,"bool");return this.compileAndRun(e,[a,t],n)},e.prototype.notEqual=function(a,t){if(_f.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(a,t,"\n  return vec4(notEqual(a, b));\n","bool");var e=new na("return float(a != b);",a.shape,t.shape),n=this.makeOutputArray(e.outputShape,"bool");return this.compileAndRun(e,[a,t],n)},e.prototype.less=function(a,t){if(this.shouldExecuteOnCPU([a,t]))return this.cpuBackend.less(a,t);if(_f.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(a,t,"\n  return vec4(lessThan(a, b));\n","bool");var e=new na("return float(a < b);",a.shape,t.shape),n=this.makeOutputArray(e.outputShape,"bool");return this.compileAndRun(e,[a,t],n)},e.prototype.lessEqual=function(a,t){if(_f.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(a,t,"\n  return vec4(lessThanEqual(a, b));\n","bool");var e=new na("return float(a <= b);",a.shape,t.shape),n=this.makeOutputArray(e.outputShape,"bool");return this.compileAndRun(e,[a,t],n)},e.prototype.greater=function(a,t){if(this.shouldExecuteOnCPU([a,t]))return this.cpuBackend.greater(a,t);if(_f.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(a,t,"\n  return vec4(greaterThan(a, b));\n","bool");var e=new na("return float(a > b);",a.shape,t.shape),n=this.makeOutputArray(e.outputShape,"bool");return this.compileAndRun(e,[a,t],n)},e.prototype.greaterEqual=function(a,t){if(_f.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(a,t,"\n  return vec4(greaterThanEqual(a, b));\n","bool");var e=new na("return float(a >= b);",a.shape,t.shape),n=this.makeOutputArray(e.outputShape,"bool");return this.compileAndRun(e,[a,t],n)},e.prototype.logicalNot=function(a){var t=new Wi(a.shape,"return float(!(x >= 1.0));");return this.compileAndRun(t,[a])},e.prototype.logicalAnd=function(a,t){if(_f.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(a,t,"\n  return vec4(\n    vec4(greaterThanEqual(a, vec4(1.0))) *\n    vec4(greaterThanEqual(b, vec4(1.0))));\n","bool");var e=new na("return float(a >= 1.0 && b >= 1.0);",a.shape,t.shape),n=this.makeOutputArray(e.outputShape,"bool");return this.compileAndRun(e,[a,t],n)},e.prototype.logicalOr=function(a,t){if(_f.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(a,t,"\n  return min(\n    vec4(greaterThanEqual(a, vec4(1.0))) +\n    vec4(greaterThanEqual(b, vec4(1.0))),\n    vec4(1.0));\n","bool");var e=new na("return float(a >= 1.0 || b >= 1.0);",a.shape,t.shape),n=this.makeOutputArray(e.outputShape,"bool");return this.compileAndRun(e,[a,t],n)},e.prototype.select=function(a,t,e){var n=new Si(a.rank,t.shape,t.rank),r=this.makeOutputArray(n.outputShape,Y(t.dtype,e.dtype));return this.compileAndRun(n,[a,t,e],r)},e.prototype.where=function(a){Je("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var t=a.dataSync();return Zr(a.shape,t)},e.prototype.topk=function(a,t){return $r(a.dataSync(),a.shape,a.dtype,t)},e.prototype.min=function(s,t){Ut("min",t,s.rank);var e=Wt(s.shape,t),n=e[0],r=qe(e[1]),o=s.as2D(-1,r);return this.reduce(o,"min",o.dtype).reshape(n)},e.prototype.minimum=function(a,t){if(this.shouldExecuteOnCPU([a,t]))return this.cpuBackend.minimum(a,t);var e=_f.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ra("\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",a.shape,t.shape):new na("\n  if (isnan(a)) return a;\n  if (isnan(b)) return b;\n\n  return min(a, b);\n",a.shape,t.shape);return this.compileAndRun(e,[a,t])},e.prototype.mod=function(a,t){var e=_f.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ra("\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",a.shape,t.shape):new na("if (b == 0.0) return NAN;\n  return mod(a, b);",a.shape,t.shape);return this.compileAndRun(e,[a,t])},e.prototype.max=function(s,t){if(this.shouldExecuteOnCPU([s]))return this.cpuBackend.max(s,t);Ut("max",t,s.rank);var e=Wt(s.shape,t),n=e[0],r=qe(e[1]),o=s.as2D(-1,r);return this.reduce(o,"max",o.dtype).reshape(n)},e.prototype.maximum=function(a,t){if(this.shouldExecuteOnCPU([a,t]))return this.cpuBackend.maximum(a,t);var e=_f.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ra("\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",a.shape,t.shape):new na("\n  if (isnan(a)) return a;\n  if (isnan(b)) return b;\n\n  return max(a, b);\n",a.shape,t.shape);return this.compileAndRun(e,[a,t])},e.prototype.all=function(s,t){Ut("all",t,s.rank);var e=Wt(s.shape,t),n=e[0],r=qe(e[1]),o=s.as2D(-1,r);return this.reduce(o,"all",o.dtype).reshape(n)},e.prototype.any=function(s,t){Ut("any",t,s.rank);var e=Wt(s.shape,t),n=e[0],r=qe(e[1]),o=s.as2D(-1,r);return this.reduce(o,"any",o.dtype).reshape(n)},e.prototype.squaredDifference=function(a,t){var e=_f.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ra("return (a - b) * (a - b);",a.shape,t.shape):new na("return (a - b) * (a - b);",a.shape,t.shape);return this.compileAndRun(e,[a,t])},e.prototype.realDivide=function(a,t){if(_f.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(a,t,"\n  // vec4 one = vec4(equal(a, b));\n  // return one + (vec4(1.0) - one) * a / b;\n  vec4 result = a / b;\n  if(b.x == 0.0) {\n    result.x = NAN;\n  } else if(a.x == b.x) {\n    result.x = 1.;\n  }\n  if(b.y == 0.0) {\n    result.y = NAN;\n  } else if(a.y == b.y) {\n    result.y = 1.;\n  }\n  if(b.z == 0.0) {\n    result.z = NAN;\n  } else if(a.z == b.z) {\n    result.z = 1.;\n  }\n  if(b.w == 0.0) {\n    result.w = NAN;\n  } else if(a.w == b.w) {\n    result.w = 1.;\n  }\n\n  return result;\n","float32",!0);var e=new na("\nif (b == 0.0) {\n  return NAN;\n}\nif (a == b) {\n  return 1.0;\n};\nreturn a / b;",a.shape,t.shape),n=this.makeOutputArray(e.outputShape,"float32");return this.compileAndRun(e,[a,t],n)},e.prototype.floorDiv=function(a,t){if(_f.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(a,t,"\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 e=new na("\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",a.shape,t.shape),n=this.makeOutputArray(e.outputShape,"int32");return this.compileAndRun(e,[a,t],n)},e.prototype.add=function(a,t){if("complex64"===a.dtype&&"complex64"===t.dtype)return this.complexSeparableBinaryOp(a,t,Zo);if(this.shouldExecuteOnCPU([a,t]))return this.cpuBackend.add(a,t);var e=Y(a.dtype,t.dtype);if(_f.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(a,t,Zo,e);var n=new na(Zo,a.shape,t.shape),r=this.makeOutputArray(n.outputShape,e);return this.compileAndRun(n,[a,t],r)},e.prototype.packedBinaryOp=function(s,t,e,n,r){void 0===r&&(r=!1);var p=new ra(e,s.shape,t.shape,r),a=this.makePackedTensor(p.outputShape,n);return this.compileAndRun(p,[s,t],a)},e.prototype.complexSeparableBinaryOp=function(p,t,e){var n=this,r=this.texData.get(p.dataId),o=this.texData.get(t.dataId),a=[[r.complexTensors.real,o.complexTensors.real],[r.complexTensors.imag,o.complexTensors.imag]].map(function(r){var o=r[0],a=r[1],i=n.makeComplexComponentTensorHandle(p,o),s=n.makeComplexComponentTensorHandle(t,a),d=new na(e,p.shape,t.shape),l=n.makeOutputArray(d.outputShape,Y(o.dtype,a.dtype));return n.compileAndRun(d,[i,s],l)}),i=a[0],s=a[1],d=this.complex(i,s);return i.dispose(),s.dispose(),d},e.prototype.makeComplexComponentTensorHandle=function(a,t){return{dataId:t.dataId,dtype:t.dtype,shape:a.shape}},e.prototype.addN=function(i){if(1===i.length)return i[0];if(i.length>_f.get("WEBGL_MAX_TEXTURES_IN_SHADER")){var t=Cf(i.length/2),e=this.addN(i.slice(0,t)),n=this.addN(i.slice(t));return this.addN([e,n])}var r=i.map(function(e){return e.dtype}).reduce(function(a,t){return Y(a,t)}),o=i.map(function(e){return e.shape}),a=_f.getBool("WEBGL_PACK"),s=a?new So(i[0].shape,o):new vo(i[0].shape,o),p=a?this.makePackedTensor(s.outputShape,r):this.makeOutputArray(s.outputShape,r);return this.compileAndRun(s,i,p)},e.prototype.subtract=function(a,t){if("complex64"===a.dtype&&"complex64"===t.dtype)return this.complexSeparableBinaryOp(a,t,ta);if(this.shouldExecuteOnCPU([a,t]))return this.cpuBackend.subtract(a,t);var e=Y(a.dtype,t.dtype);if(_f.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(a,t,ta,a.dtype);var n=new na(ta,a.shape,t.shape),r=this.makeOutputArray(n.outputShape,e);return this.compileAndRun(n,[a,t],r)},e.prototype.pow=function(s,t){var e=_f.getBool("WEBGL_PACK_BINARY_OPERATIONS"),n=e?new ra("\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",s.shape,t.shape):new na("\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",s.shape,t.shape),r=Y(s.dtype,t.dtype),o=e?this.makePackedTensor(n.outputShape,r):this.makeOutputArray(n.outputShape,r);return this.compileAndRun(n,[s,t],o)},e.prototype.ceil=function(a){var t=new Wi(a.shape,"return ceil(x);");return this.compileAndRun(t,[a])},e.prototype.floor=function(a){var t=new Wi(a.shape,"return floor(x);");return this.compileAndRun(t,[a])},e.prototype.sign=function(a){var t=new Wi(a.shape,"\n  if (isnan(x)) { return 0.0; }\n  return sign(x);\n");return this.compileAndRun(t,[a])},e.prototype.isNaN=function(a){var t=new Wi(a.shape,"return float(isnan(x));"),e=this.makeOutputArray(t.outputShape,"bool");return this.compileAndRun(t,[a],e)},e.prototype.isInf=function(a){var t=new Wi(a.shape,"return float(isinf(x));"),e=this.makeOutputArray(t.outputShape,"bool");return this.compileAndRun(t,[a],e)},e.prototype.isFinite=function(a){var t=new Wi(a.shape,"return float(!isnan(x) && !isinf(x));"),e=this.makeOutputArray(t.outputShape,"bool");return this.compileAndRun(t,[a],e)},e.prototype.round=function(a){var t=new Wi(a.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(t,[a])},e.prototype.exp=function(a){var t;return t=_f.getBool("WEBGL_PACK")?new qi(a.shape,zi):new Wi(a.shape,zi),this.compileAndRun(t,[a])},e.prototype.expm1=function(a){var t=new Wi(a.shape,"return exp(x) - 1.0;");return this.compileAndRun(t,[a])},e.prototype.log=function(a){var t;return t=_f.getBool("WEBGL_PACK")?new qi(a.shape,"\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"):new Wi(a.shape,"if (x < 0.0) return NAN;\n  return log(x);"),this.compileAndRun(t,[a])},e.prototype.log1p=function(a){var t=new Wi(a.shape,"return log(1.0 + x);");return this.compileAndRun(t,[a])},e.prototype.sqrt=function(a){var t=new Wi(a.shape,"return sqrt(x);");return this.compileAndRun(t,[a])},e.prototype.rsqrt=function(a){if(this.shouldExecuteOnCPU([a]))return this.cpuBackend.rsqrt(a);var t=new Wi(a.shape,"return inversesqrt(x);");return this.compileAndRun(t,[a])},e.prototype.square=function(a){var t=new Wi(a.shape,"return x * x;");return this.compileAndRun(t,[a])},e.prototype.reciprocal=function(a){var t=new Wi(a.shape,"return 1.0 / x;");return this.compileAndRun(t,[a])},e.prototype.relu=function(a){var t;return t=_f.getBool("WEBGL_PACK")?new qi(a.shape,"\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"):new Wi(a.shape,Ui+"\n  return (x < 0.0) ? 0.0 : x;\n"),this.compileAndRun(t,[a])},e.prototype.prelu=function(a,t){var e=_f.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ra("\n  vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n  return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",a.shape,t.shape):new na("return (a < 0.) ? b * a : a;",a.shape,t.shape);return this.compileAndRun(e,[a,t])},e.prototype.elu=function(a){var t=new Wi(a.shape,"return (x >= 0.0) ? x : (exp(x) - 1.0);");return this.compileAndRun(t,[a])},e.prototype.eluDer=function(a,t){var e=_f.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ra("\n  vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n  return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n",a.shape,t.shape):new na("return (b >= 1.0) ? a : a * (b + 1.0);",a.shape,t.shape);return this.compileAndRun(e,[a,t])},e.prototype.selu=function(a){var t=new Wi(a.shape,"\n  // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n  // see: https://arxiv.org/abs/1706.02515\n  float scaleAlpha = "+Pi+";\n  float scale = "+Li+";\n  return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n");return this.compileAndRun(t,[a])},e.prototype.int=function(a){var t=new Wi(a.shape,"return float(int(x));"),e=this.makeOutputArray(t.outputShape,"int32");return this.compileAndRun(t,[a],e)},e.prototype.clip=function(a,t,e){var n=(o=_f.getBool("WEBGL_PACK_CLIP")?new aa(a.shape):new oa(a.shape)).getCustomSetupFunc(t,e),o;return this.compileAndRun(o,[a],null,n)},e.prototype.abs=function(a){var t=new Wi(a.shape,"return abs(x);");return this.compileAndRun(t,[a])},e.prototype.complexAbs=function(a){var t=this.texData.get(a.dataId),e=new ia(a.shape),n=[this.makeComplexComponentTensorHandle(a,t.complexTensors.real),this.makeComplexComponentTensorHandle(a,t.complexTensors.imag)];return this.compileAndRun(e,n)},e.prototype.sigmoid=function(a){var t=new Wi(a.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(t,[a])},e.prototype.softplus=function(a){var t=new Wi(a.shape,"\n  float epsilon = 1.1920928955078125e-7;\n  float threshold = log(epsilon) + 2.0;\n\n  bool too_large = x > -threshold;\n  bool too_small = x < threshold;\n\n  float result;\n  float exp_x = exp(x);\n\n  if (too_large){\n    result = x;\n  }\n  else if (too_small){\n    result = exp_x;\n  }\n  else{\n    result = log(exp_x + 1.0);\n  }\n  return result;\n");return this.compileAndRun(t,[a])},e.prototype.sin=function(a){var t=new Wi(a.shape,Ui+"\n  return sin(x);\n");return this.compileAndRun(t,[a])},e.prototype.cos=function(a){var t=new Wi(a.shape,Ui+"\n  return cos(x);\n");return this.compileAndRun(t,[a])},e.prototype.tan=function(a){var t=new Wi(a.shape,"return tan(x);");return this.compileAndRun(t,[a])},e.prototype.asin=function(a){var t=new Wi(a.shape,"return asin(x);");return this.compileAndRun(t,[a])},e.prototype.acos=function(a){var t=new Wi(a.shape,"return acos(x);");return this.compileAndRun(t,[a])},e.prototype.atan=function(a){var t=new Wi(a.shape,Ui+"\n  return atan(x);\n");return this.compileAndRun(t,[a])},e.prototype.atan2=function(a,t){var e=_f.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ra("\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",a.shape,t.shape):new na("\n  if (isnan(a)) return a;\n  if (isnan(b)) return b;\n\n  return atan(a, b);\n",a.shape,t.shape);return this.compileAndRun(e,[a,t])},e.prototype.sinh=function(a){var t=new Wi(a.shape,"\n  float e2x = exp(x);\n  return (e2x - 1.0 / e2x) / 2.0;\n");return this.compileAndRun(t,[a])},e.prototype.cosh=function(a){var t=new Wi(a.shape,"\n  float e2x = exp(-x);\n  return (e2x + 1.0 / e2x) / 2.0;\n");return this.compileAndRun(t,[a])},e.prototype.tanh=function(a){var t=new Wi(a.shape,"\n  float e2x = exp(-2.0 * abs(x));\n  return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n");return this.compileAndRun(t,[a])},e.prototype.asinh=function(a){var t=new Wi(a.shape,"return log(x + sqrt(x * x + 1.0));");return this.compileAndRun(t,[a])},e.prototype.acosh=function(a){var t=new Wi(a.shape,Ui+"\n  if (x < 1.0) return NAN;\n  return log(x + sqrt(x * x - 1.0));");return this.compileAndRun(t,[a])},e.prototype.atanh=function(a){var t=new Wi(a.shape,Ui+"\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(t,[a])},e.prototype.erf=function(a){var t=new Wi(a.shape,"\n  // Error function is calculated approximately with elementary function.\n  // See \"Handbook of Mathematical Functions with Formulas,\n  // Graphs, and Mathematical Tables\", Abramowitz and Stegun.\n  float p = 0.3275911;\n  float a1 = 0.254829592;\n  float a2 = -0.284496736;\n  float a3 = 1.421413741;\n  float a4 = -1.453152027;\n  float a5 = 1.061405429;\n\n  float t = 1.0 / (1.0 + p * x);\n  return 1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x);\n");return this.compileAndRun(t,[a])},e.prototype.step=function(a,t){var e=new Wi(a.shape,function(e){return void 0===e&&(e=0),Ui+"\n    return x > 0.0 ? 1.0 : float("+e+");\n  "}(t));return this.compileAndRun(e,[a])},e.prototype.conv2dByMatMul=function(i,t,e,n,r){var o=i.shape,a=this.texData.get(i.dataId),s=e.inChannels,p=o[0]*o[1]*o[2],l=e.outChannels,u=0!=o[2]%2&&!!a.isPacked;if((1==p||1===l)&&1e3<s||!_f.getBool("WEBGL_LAZILY_UNPACK")||!_f.getBool("WEBGL_PACK_BINARY_OPERATIONS")||!u){var c=this.reshape(i,[1,o[0]*o[1]*o[2],e.inChannels]),d=this.reshape(t,[1,e.inChannels,e.outChannels]);return this.reshape(this.fusedBatchMatMul(c,d,!1,!1,n,r),e.outShape)}var h=Lf.make([1,o[0]*o[1]*(o[2]+1),e.inChannels],{dataId:i.dataId},i.dtype,this),m=a.shape;a.shape=a.shape.slice(),a.shape[a.shape.length-2]++,Ue(Ce(a.shape,h.shape),function(){return"packed reshape "+a.shape+" to "+h.shape+" isn't free"});var g=this.reshape(t,[1,e.inChannels,e.outChannels]),f=this.fusedBatchMatMul(h,g,!1,!1,n,r),y=this.texData.get(f.dataId);return Ue(y.isPacked,function(){return"batchMatMul result is expected to be packed"}),a.shape=m,y.shape=e.outShape,Lf.make(e.outShape,{dataId:f.dataId},f.dtype,this)},e.prototype.conv2dWithIm2Row=function(g,t,e,n,r){var o=e.filterWidth,a=e.filterHeight,i=e.inChannels,s=e.outWidth,u=e.outHeight,l=o*a*i,c=u*s,h=[l,c],f=g.squeeze([0]),p=t.reshape([1,l,-1]),d=new ni(h,f.shape,e),v=this.compileAndRun(d,[f]).reshape([1,h[0],h[1]]),m=r?fo(r,!0):null,y=new ui(v.shape,[1,c,e.outChannels],!0,!1,null!=n,m),x=[v,p];return n&&x.push(n),this.compileAndRun(y,x).reshape([1,u,s,e.outChannels])},e.prototype.fusedConv2d=function(a,t,e,n,r){if(1===e.filterHeight&&1===e.filterWidth&&1===e.dilationHeight&&1===e.dilationWidth&&1===e.strideHeight&&1===e.strideWidth&&("SAME"===e.padInfo.type||"VALID"===e.padInfo.type))return this.conv2dByMatMul(a,t,e,n,r);if(_f.getBool("WEBGL_CONV_IM2COL")&&1===a.shape[0])return this.conv2dWithIm2Row(a,t,e,n,r);var o=r?fo(r,!1):null,s=new va(e,null!=n,o),i=[a,t];return n&&i.push(n),this.compileAndRun(s,i)},e.prototype.conv2d=function(a,t,e){if(1===e.filterHeight&&1===e.filterWidth&&1===e.dilationHeight&&1===e.dilationWidth&&1===e.strideHeight&&1===e.strideWidth&&("SAME"===e.padInfo.type||"VALID"===e.padInfo.type))return this.conv2dByMatMul(a,t,e);if(_f.getBool("WEBGL_CONV_IM2COL")&&1===a.shape[0])return this.conv2dWithIm2Row(a,t,e);var n=new va(e);return this.compileAndRun(n,[a,t])},e.prototype.conv2dDerInput=function(a,t,e){var n=new ca(e);return this.compileAndRun(n,[a,t])},e.prototype.conv2dDerFilter=function(a,t,e){var n=new la(e);return this.compileAndRun(n,[a,t])},e.prototype.depthwiseConv2D=function(a,t,e){var n;return _f.getBool("WEBGL_PACK_DEPTHWISECONV")&&2>=e.strideWidth&&1==e.outChannels/e.inChannels?(n=new ya(e),this.compileAndRun(n,[a,t],this.makePackedTensor(e.outShape,a.dtype))):(n=new ga(e),this.compileAndRun(n,[a,t]))},e.prototype.depthwiseConv2DDerInput=function(a,t,e){var n=new da(e);return this.compileAndRun(n,[a,t])},e.prototype.depthwiseConv2DDerFilter=function(a,t,e){var n=new pa(e);return this.compileAndRun(n,[a,t])},e.prototype.conv3d=function(a,t,e){var n=new ma(e);return this.compileAndRun(n,[a,t])},e.prototype.conv3dDerInput=function(a,t,e){var n=new fa(e);return this.compileAndRun(n,[a,t])},e.prototype.conv3dDerFilter=function(a,t,e){var n=new ha(e);return this.compileAndRun(n,[a,t])},e.prototype.maxPool=function(a,t){var e=new di(t,"max",!1),n=this.makeOutputArray(e.outputShape,a.dtype);return this.compileAndRun(e,[a],n)},e.prototype.avgPool=function(a,t){var e=new di(t,"avg",!1),n=this.makeOutputArray(e.outputShape,"float32");return this.compileAndRun(e,[a],n)},e.prototype.maxPoolBackprop=function(p,t,e,n){var r=new di(n,"max",!0),o=this.compileAndRun(r,[t]),a=new si(n),i=this.makeOutputArray(a.outputShape,t.dtype),s=this.compileAndRun(a,[p,o],i);return o.dispose(),s},e.prototype.avgPoolBackprop=function(a,t,e){var n=new jo(e),r=this.makeOutputArray(n.outputShape,t.dtype);return this.compileAndRun(n,[a],r)},e.prototype.cast=function(a,t){return Fr(a,t,this)},e.prototype.unstack=function(p,t){for(var e=p.shape[t],n=Array(p.rank-1),r=0,d=0;d<p.rank;d++)d!==t&&(n[r++]=p.shape[d]);var l=Array(p.rank).fill(0),i=p.shape.slice();i[t]=1;var s=Array(e);for(d=0;d<s.length;d++)l[t]=d,s[d]=this.slice(p,l,i).reshape(n);return s},e.prototype.reshape=function(a,t){var e=this.texData.get(a.dataId);return!e.isPacked||Ce(a.shape,t)||null!==e.texture&&Ce(e.shape,t)?Br(a,t):this.packedReshape(a,t)},e.prototype.resizeBilinear=function(a,t,e,n){var r=_f.getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new xi(a.shape,t,e,n):new yi(a.shape,t,e,n);return this.compileAndRun(r,[a])},e.prototype.resizeBilinearBackprop=function(a,t,e){var n=new gi(a,t,e);return this.compileAndRun(n,[a])},e.prototype.resizeNearestNeighbor=function(a,t,e,n){var r=new wi(a.shape,t,e,n);return this.compileAndRun(r,[a])},e.prototype.resizeNearestNeighborBackprop=function(a,t,e){var n=new bi(a,t,e);return this.compileAndRun(n,[a])},e.prototype.multinomial=function(p,t,e,n){var r=t?p:Ir(p),o=r.shape[0],a=r.shape[1],i=new li(o,a,e),s=this.makeOutputArray(i.outputShape,"int32"),d=i.getCustomSetupFunc(n);return this.compileAndRun(i,[r],s,d)},e.prototype.oneHot=function(a,t,e,n){var r=new ci(a.size,t,e,n);return this.compileAndRun(r,[a])},e.prototype.nonMaxSuppression=function(a,t,e,n,r){return Je("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead"),Gr(a.dataSync(),t.dataSync(),e,n,r)},e.prototype.cropAndResize=function(s,t,e,n,r,o){var a=new xa(s.shape,t.shape,n,r,o);return this.compileAndRun(a,[s,t,e])},e.prototype.depthToSpace=function(p,t,e){Ue(1<t,function(){return"blockSize should be > 1 for depthToSpace, but was: "+t});var n=p.shape[0],r="NHWC"===e?p.shape[1]:p.shape[2],o="NHWC"===e?p.shape[2]:p.shape[3],a="NHWC"===e?p.shape[3]:p.shape[1],i=r*t,s=o*t,d=a/(t*t),l=new Ra("NHWC"===e?[n,i,s,d]:[n,d,i,s],t,e);return this.compileAndRun(l,[p])},e.prototype.split=function(a,t,e){return Hr(a,t,e)},e.prototype.scatterND=function(d,t,e){var n=Tn(0,d,e),r=n.sliceRank,o=n.numUpdates,a=n.sliceSize,i=n.strides,s=n.outputSize,l=d.reshape([o,r]),u=t.reshape([o,a]);if(0===s)return Br(Zt([]),e);var c=Da(0),h=new Ri(o,r,l.rank,u.rank,i,[s/a,a]);return this.compileAndRun(h,[u,l,c]).reshape(e)},e.prototype.sparseToDense=function(p,t,e,n){var r=Tn(0,p,e),o=r.sliceRank,a=r.numUpdates,i=r.strides,s=r.outputSize,d=new Ri(a,o,p.rank,t.rank,i,[s,1],!1);return this.compileAndRun(d,[t,p,n]).reshape(e)},e.prototype.fft=function(e){return this.fftImpl(e,!1)},e.prototype.ifft=function(e){return this.fftImpl(e,!0)},e.prototype.fftImpl=function(p,t){var e=this.texData.get(p.dataId),n=new Aa("return real * expR - imag * expI;",p.shape,t),r=new Aa("return real * expI + imag * expR;",p.shape,t),o=[this.makeComplexComponentTensorHandle(p,e.complexTensors.real),this.makeComplexComponentTensorHandle(p,e.complexTensors.imag)],a=this.compileAndRun(n,o),i=this.compileAndRun(r,o),s=this.complex(a,i).as2D(p.shape[0],p.shape[1]);return a.dispose(),i.dispose(),s},e.prototype.gatherND=function(p,t){var e=t.shape,n=e[e.length-1],r=Nn(p,t),o=r[0],a=r[1],i=r[2],s=r[3],d=t.reshape([a,n]),l=p.reshape([p.size/i,i]),u=new Ba(n,s,[a,i]);return this.compileAndRun(u,[l,d]).reshape(o)},e.prototype.fill=function(s,t,e){if("string"===(e=e||L(t))){var p=N(e,qe(s));return p.fill(t),Lf.make(s,{values:p},e)}var r=new _a(s,t),o=r.getCustomSetupFunc(t),a=this.makeOutputArray(s,e);return this.compileAndRun(r,[],a,o)},e.prototype.onesLike=function(e){if("string"===e.dtype)throw new Error("onesLike is not supported under string dtype");return this.fill(e.shape,1,e.dtype)},e.prototype.zerosLike=function(e){return this.fill(e.shape,"string"===e.dtype?"":0,e.dtype)},e.prototype.linspace=function(a,t,e){return Pr(a,t,e)},e.prototype.makeOutputArray=function(a,t){return Lf.make(a,{},t,this)},e.prototype.makePackedTensor=function(a,t){var e=Lf.make(a,{},t,this);return this.texData.get(e.dataId).isPacked=!0,e},e.prototype.unpackTensor=function(a){var t=new Zi(a.shape);return this.compileAndRun(t,[a],Lf.make(t.outputShape,{},a.dtype,this))},e.prototype.packTensor=function(a){var t=new hi(a.shape);return this.compileAndRun(t,[a],this.makePackedTensor(a.shape,a.dtype),null,!0)},e.prototype.packedReshape=function(a,t){var e=a.reshape([ge(a.shape)].concat(ye(a.shape))),n=[ge(t)].concat(ye(t)),r=new mi(n,e.shape);return this.compileAndRun(r,[e]).reshape(t)},e.prototype.decode=function(p){var t=this.texData.get(p),n=t.isPacked,r=t.shape,o=t.dtype,a=xe(r),i=tt(r),s=this.makeTensorHandle(r,"float32"),d;return this.texData.get(s.dataId).isPacked=!0,this.texData.get(s.dataId).dtype=o,this.texData.get(s.dataId).texShape=i.map(function(e){return 2*e}),d=n?new Ea(a,i):new wa(a,i),this.compileAndRun(d,[{shape:a,dtype:o,dataId:p}],s,null,!0),s},e.prototype.compileAndRun=function(i,t,e,p,r){var d=this;if(void 0===r&&(r=!1),null==e&&(e=i.usesPackedTextures?this.makePackedTensor(i.outputShape,t[0].dtype):this.makeOutputArray(i.outputShape,t[0].dtype)),0===e.size)return this.texData.get(e.dataId).values=S(e.dtype,0),e;var a=t.map(function(t){if("complex64"===t.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");var a=d.texData.get(t.dataId);if(null==a.texture){if(!i.usesPackedTextures&&qe(t.shape)<=_f.getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:t.shape,texData:null,isUniform:!0,uniformValues:a.values};i.usesPackedTextures&&(a.isPacked=!0,a.shape=t.shape)}else if(!!a.isPacked!=!!i.usesPackedTextures)t=a.isPacked?d.unpackTensor(t):d.packTensor(t),a=d.texData.get(t.dataId);else if(a.isPacked&&!Ce(a.shape,t.shape)){var s=t,r=t.shape;t.shape=a.shape,t=d.packedReshape(t,r),a=d.texData.get(t.dataId),s.shape=r}return d.uploadToGPU(t.dataId),{shape:t.shape,texData:a,isUniform:!1}});this.uploadToGPU(e.dataId);var s={shape:e.shape,texData:this.texData.get(e.dataId),isUniform:!1},l=function(s,t,e){var i="";t.concat(e).forEach(function(a){var t=null!=a.texData&&null!=a.texData.slice&&0<a.texData.slice.flatOffset,e=a.isUniform?"uniform":a.texData.texShape;i+=a.shape+"_"+e+"_"+t});var n=s.userCode,o=s.constructor.name;return o+="_"+i+"_"+n}(i,a,s),c=this.getAndSaveBinary(l,function(){return function(i,m,e,t){var n=m.userCode,r=e.map(function(e,t){var a={logicalShape:e.shape,texShape:e.isUniform?null:e.texData.texShape,isUniform:e.isUniform,isPacked:!e.isUniform&&e.texData.isPacked,flatOffset:null};return null!=e.texData&&null!=e.texData.slice&&0<e.texData.slice.flatOffset&&(a.flatOffset=e.texData.slice.flatOffset),{name:m.variableNames[t],shapeInfo:a}}),a=r.map(function(e){return e.shapeInfo}),o={logicalShape:t.shape,texShape:t.texData.texShape,isUniform:!1,isPacked:t.texData.isPacked,flatOffset:null},s=no(r,o,n,m.usesPackedTextures),l=i.createProgram(s),u=null,c=i.getUniformLocation(l,"NAN",!1);1===_f.getNumber("WEBGL_VERSION")&&(u=i.getUniformLocation(l,"INFINITY",!1));for(var g={},p=0,f;p<m.variableNames.length;p++)f=m.variableNames[p],g[f]=i.getUniformLocation(l,f,!1),g["offset"+f]=i.getUniformLocation(l,"offset"+f,!1);return{program:m,source:s,webGLProgram:l,uniformLocations:g,inShapeInfos:a,outShapeInfo:o,infLoc:u,nanLoc:c}}(d.gpgpu,i,a,s)}),h=null!=this.activeTimers,m;return h&&(m=this.startTimer()),function(p,t,e,n,r){ho(t.inShapeInfos,e),ho([t.outShapeInfo],[n]);var o=n.texData.texture,a=n.texData.texShape;n.texData.isPacked?p.setOutputPackedMatrixTexture(o,a[0],a[1]):p.setOutputMatrixTexture(o,a[0],a[1]),p.setProgram(t.webGLProgram),1===_f.getNumber("WEBGL_VERSION")&&null!==t.infLoc&&p.gl.uniform1f(t.infLoc,1/0),null!==t.nanLoc&&p.gl.uniform1f(t.nanLoc,NaN),e.forEach(function(e,n){var r=t.program.variableNames[n],o=t.uniformLocations[r],a=t.uniformLocations["offset"+r];if(null!=o)if(!e.isUniform)null!=e.texData.slice&&null!=a&&p.gl.uniform1i(a,e.texData.slice.flatOffset),p.setInputMatrixTexture(e.texData.texture,o,n);else if(2>qe(e.shape))p.gl.uniform1f(o,e.uniformValues[0]);else{var i=e.uniformValues;i instanceof Float32Array||(i=new Float32Array(i)),p.gl.uniform1fv(o,i)}}),null!=r&&r(p,t.webGLProgram),p.executeProgram()}(this.gpgpu,c,a,s,p),h&&(m=this.endTimer(m),this.activeTimers.push({name:i.constructor.name,query:this.getQueryTime(m)})),!_f.getBool("WEBGL_LAZILY_UNPACK")&&this.texData.get(e.dataId).isPacked&&!1===r?this.unpackTensor(e):e},e.prototype.getAndSaveBinary=function(a,t){return a in this.binaryCache||(this.binaryCache[a]=t()),this.binaryCache[a]},e.prototype.getTextureManager=function(){return this.textureManager},e.prototype.dispose=function(){this.disposed||(this.textureManager.dispose(),null!=this.canvas&&null!=this.canvas.remove?this.canvas.remove():this.canvas=null,null!=this.fromPixels2DContext&&this.fromPixels2DContext.canvas.remove&&this.fromPixels2DContext.canvas.remove(),this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)},e.prototype.floatPrecision=function(){var a=this;return null==this.floatPrecisionValue&&(this.floatPrecisionValue=We(function(){var t=_f.getBool("DEBUG");_f.set("DEBUG",!1);var e=a.abs(Da(1e-8)).dataSync()[0];return _f.set("DEBUG",t),0<e?32:16})),this.floatPrecisionValue},e.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4},e.prototype.uploadToGPU=function(g){var t=this.texData.get(g),n=t.shape,r=t.dtype,o=t.values,a=t.texture,i=t.usage,s=t.isPacked,u;if(null==a){var C=null!=this.activeTimers,c;C&&(c=U());var S=t.texShape;if(null==S&&(S=be(n,s),t.texShape=S),null!=o){var N=xe(n),f=S[1],I=S[0],k=o instanceof Uint8Array,m;s?(f=(u=at(S[0],S[1]))[0],I=u[1],m=new ka(N,[I,f],k)):m=new Na(N,[I,f],k);var T=this.makeTensorHandle([I,f],r);this.texData.get(T.dataId).usage=k?Ft.PIXELS:Ft.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(T.dataId),f,I,o);var y=this.makeTensorHandle(m.outputShape,T.dtype);y.size=qe(m.outputShape),this.texData.get(y.dataId).isPacked=s,this.compileAndRun(m,[T],y);var x=this.texData.get(y.dataId);t.texture=x.texture,t.texShape=x.texShape,t.isPacked=x.isPacked,t.usage=x.usage,this.disposeData(T.dataId),this.texData.delete(y.dataId),t.values=null,C&&(this.uploadWaitMs+=U()-c)}else{var b=this.acquireTexture(S,i,r,s);t.texture=b}}},e.prototype.convertAndCacheOnCPU=function(a,t){var e=this.texData.get(a),n=e.dtype;return this.releaseGPUData(a),null!=t&&(e.values=function(a,t){if("float32"===t||"complex64"===t)return a;if("int32"===t||"bool"===t){for(var e="int32"===t?new Int32Array(a.length):new Uint8Array(a.length),n=0;n<e.length;++n)e[n]=If(a[n]);return e}throw new Error("Unknown dtype "+t)}(t,n)),e.values},e.prototype.acquireTexture=function(a,t,e,n){if(this.numBytesInGPU+=this.computeBytes(a,e),!this.warnedAboutMemory&&this.numBytesInGPU>1024*(1024*this.numMBBeforeWarning)){var r=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn("High memory usage in GPU: "+r+" MB, most likely due to a memory leak")}return this.textureManager.acquireTexture(a,t,n)},e.prototype.computeBytes=function(a,t){return a[0]*a[1]*A(t)},e}();Xe()&&kt.registerBackend("webgl",function(){return new es},2);var os=Xt({abs_:function(a){var o=Lt(a,"x","abs");return"complex64"===o.dtype?kt.runKernel(function(e){return e.complexAbs(o)},{$x:o}):kt.runKernel(function(e,t){var a=e.abs(o);return t([o]),a},{$x:o},function(a,t){var e=t[0];return{$x:function(){return a.mul(e.toFloat().step(-1))}}})}}),as=Xt({acos_:function(a){var o=Lt(a,"x","acos");return kt.runKernel(function(e,t){var a=e.acos(o);return t([o]),a},{$x:o},function(a,t){var e=t[0];return{$x:function(){return a.divStrict(Da(1).sub(e.toFloat().square()).sqrt()).neg()}}})}}),is=Xt({acosh_:function(a){var o=Lt(a,"x","acosh");return kt.runKernel(function(e,t){var a=e.acosh(o);return t([o]),a},{$x:o},function(a,t){var e=t[0];return{$x:function(){return a.divStrict(e.toFloat().square().sub(1).sqrt())}}})}}),ss=Xt({asin_:function(a){var o=Lt(a,"x","asin");return kt.runKernel(function(e,t){var a=e.asin(o);return t([o]),a},{$x:o},function(a,t){var e=t[0];return{$x:function(){return a.divStrict(Da(1).sub(e.toFloat().square()).sqrt())}}})}}),us=Xt({asinh_:function(a){var o=Lt(a,"x","asinh");return kt.runKernel(function(e,t){var a=e.asinh(o);return t([o]),a},{$x:o},function(a,t){var e=t[0];return{$x:function(){return a.divStrict(Da(1).add(e.toFloat().square()).sqrt())}}})}}),ls=Xt({atan_:function(a){var o=Lt(a,"x","atan");return kt.runKernel(function(e,t){var a=e.atan(o);return t([o]),a},{$x:o},function(a,t){var e=t[0];return{$x:function(){return a.div(e.toFloat().square().add(1))}}})}}),cs=Xt({atanh_:function(a){var o=Lt(a,"x","atanh");return kt.runKernel(function(e,t){var a=e.atanh(o);return t([o]),a},{$x:o},function(a,t){var e=t[0];return{$x:function(){return a.div(Da(1).sub(e.toFloat().square()))}}})}}),hs=Xt({ceil_:function(a){var n=Lt(a,"x","ceil");return kt.runKernel(function(e){return e.ceil(n)},{$x:n},function(e){return{$x:function(){return Fn(e)}}})}}),fs=Xt({clipByValue_:function(a,s,e){var n=Lt(a,"x","clipByValue");return Ue(s<=e,function(){return"Error in clip: min ("+s+") must be less than or equal to max ("+e+")."}),kt.runKernel(function(r,t){var o=r.clip(n,s,e);return t([n]),o},{$x:n},function(a,t){var n=t[0];return{$x:function(){return a.where(n.greaterEqual(s).logicalAnd(n.lessEqual(e)),Fn(a))}}})}}),ps=Xt({cos_:function(a){var o=Lt(a,"x","cos");return kt.runKernel(function(e,t){var a=e.cos(o);return t([o]),a},{$x:o},function(a,t){var e=t[0];return{$x:function(){return e.toFloat().sin().neg().mul(a)}}})}}),ds=Xt({cosh_:function(a){var o=Lt(a,"x","cosh");return kt.runKernel(function(e,t){var a=e.cosh(o);return t([o]),a},{$x:o},function(a,t){var e=t[0];return{$x:function(){return e.toFloat().sinh().mulStrict(a)}}})}}),vs=Xt({erf_:function(a){var o=Lt(a,"x","erf");return Ue("int32"===o.dtype||"float32"===o.dtype,function(){return"Input dtype must be `int32` or `float32`."}),"int32"===o.dtype&&(o=o.toFloat()),kt.runKernel(function(e,t){var a=e.erf(o);return t([o]),a},{$x:o},function(a,t){var e=t[0];return{$x:function(){return a.mul(e.square().neg().exp().mul(2/Tf(Math.PI)))}}})}}),ms=Xt({exp_:function(a){var o=Lt(a,"x","exp");return kt.runKernel(function(e,t){var a=e.exp(o);return t([a]),a},{$x:o},function(a,t){return{$x:function(){return a.mulStrict(t[0])}}})}}),gs=Xt({expm1_:function(a){var o=Lt(a,"x","expm1");return kt.runKernel(function(e,t){var a=e.expm1(o);return t([o]),a},{$x:o},function(a,t){var e=t[0];return{$x:function(){return a.mul(e.exp())}}})}}),ys=Xt({floor_:function(a){var n=Lt(a,"x","floor");return kt.runKernel(function(e){return e.floor(n)},{$x:n},function(e){return{$x:function(){return Fn(e)}}})}}),xs=Xt({log_:function(a){var o=Lt(a,"x","log");return kt.runKernel(function(e,t){var a=e.log(o);return t([o]),a},{$x:o},function(a,t){var e=t[0];return{$x:function(){return a.div(e.toFloat())}}})}}),bs=Xt({log1p_:function(a){var o=Lt(a,"x","log1p");return kt.runKernel(function(e,t){var a=e.log1p(o);return t([o]),a},{$x:o},function(a,t){var e=t[0];return{$x:function(){return a.div(e.add(1))}}})}}),ws=Xt({logSigmoid_:function(a){var o=Lt(a,"x","logSigmoid");return kt.runKernel(function(e,t){var a=e.softplus(o.neg()).neg();return t([o]),a},{$x:o},function(a,t){var e=t[0];return{$x:function(){return a.mul(e.neg().sigmoid())}}})}}),Cs=Xt({neg_:function(a){var n=Lt(a,"x","neg");return kt.runKernel(function(e){return e.neg(n)},{$x:n},function(e){return{$x:function(){return e.neg()}}})}}),Es=Xt({reciprocal_:function(a){var o=Lt(a,"x","reciprocal");return kt.runKernel(function(e,t){var a=e.reciprocal(o);return t([o]),a},{$x:o},function(a,t){var e=t[0];return{$x:function(){return a.div(e.square().neg())}}})}}),Rs=Xt({round_:function(a){var n=Lt(a,"x","round");return kt.runKernel(function(e){return e.round(n)},{$x:n},function(e){return{$x:function(){return Fn(e)}}})}}),Is=Xt({rsqrt_:function(a){var o=Lt(a,"x","rsqrt");return kt.runKernel(function(e,t){var a=e.rsqrt(o);return t([o]),a},{$x:o},function(a,t){var e=t[0];return{$x:function(){return a.div(e.pow(1.5).mul(2)).neg()}}})}}),Ss=Xt({sigmoid_:function(a){var o=Lt(a,"x","sigmoid");return kt.runKernel(function(e,t){var a=e.sigmoid(o);return t([a]),a},{$x:o},function(a,t){var e=t[0];return{$x:function(){return a.mul(e.mul(Da(1).sub(e)))}}})}}),Ns=Xt({sign_:function(a){var n=Lt(a,"x","sign");return kt.runKernel(function(e){return e.sign(n)},{$x:n},function(e){return{$x:function(){return Fn(e)}}})}}),ks=Xt({isNaN_:function(a){var n=Lt(a,"x","isNaN");return kt.runKernel(function(e){return e.isNaN(n)},{$x:n},function(e){return{$x:function(){return Fn(e)}}})}}),As=Xt({isInf_:function(a){var n=Lt(a,"x","isInf");return kt.runKernel(function(e){return e.isInf(n)},{$x:n},function(e){return{$x:function(){return Fn(e)}}})}}),Ts=Xt({isFinite_:function(a){var n=Lt(a,"x","isFinite");return kt.runKernel(function(e){return e.isFinite(n)},{$x:n},function(e){return{$x:function(){return Fn(e)}}})}}),Ds=Xt({sin_:function(a){var o=Lt(a,"x","sin");return kt.runKernel(function(e,t){var a=e.sin(o);return t([o]),a},{$x:o},function(a,t){var e=t[0];return{$x:function(){return e.toFloat().cos().mul(a)}}})}}),_s=Xt({sinh_:function(a){var o=Lt(a,"x","sinh");return kt.runKernel(function(e,t){var a=e.sinh(o);return t([o]),a},{$x:o},function(a,t){var e=t[0];return{$x:function(){return e.toFloat().cosh().mulStrict(a)}}})}}),Os=Xt({softplus_:function(a){var o=Lt(a,"x","softplus");return kt.runKernel(function(e,t){var a=e.softplus(o);return t([o]),a},{$x:o},function(a,t){var e=t[0];return{$x:function(){return a.mul(e.sigmoid())}}})}}),Fs=Xt({sqrt_:function(a){var o=Lt(a,"x","sqrt");return kt.runKernel(function(e,t){var a=e.sqrt(o);return t([o]),a},{$x:o},function(a,t){var e=t[0];return{$x:function(){return a.div(e.toFloat().sqrt().mul(2))}}})}}),Ms=Xt({square_:function(a){var r=Lt(a,"x","square");return kt.runKernel(function(e,t){return t([r]),e.square(r)},{$x:r},function(a,t){var e=t[0];return{$x:function(){return a.mul(e.toFloat().mul(2))}}})}}),Bs=Xt({step_:function(a,r){void 0===r&&(r=0);var o=Lt(a,"x","step");return kt.runKernel(function(e){return e.step(o,r)},{$x:o},function(e){return{$x:function(){return Fn(e)}}})}}),Ps=Xt({tan_:function(a){var o=Lt(a,"x","tan");return kt.runKernel(function(e,t){var a=e.tan(o);return t([o]),a},{$x:o},function(a,t){var e=t[0];return{$x:function(){return a.div(e.cos().square())}}})}}),Ls=Xt({tanh_:function(a){var o=Lt(a,"x","tanh");return kt.runKernel(function(e,t){var a=e.tanh(o);return t([a]),a},{$x:o},function(a,t){var e=t[0];return{$x:function(){return Da(1).sub(e.square()).mulStrict(a)}}})}}),Ws=Xt({batchNormalization2d_:function(s,t,e,n,i,o){return void 0===n&&(n=.001),To(),yo(s,t,e,o,i,n)}}),$s=Xt({batchNormalization3d_:function(s,t,e,n,i,o){return void 0===n&&(n=.001),To(),bo(s,t,e,o,i,n)}}),js=Xt({batchNormalization4d_:function(s,t,e,n,i,o){return void 0===n&&(n=.001),To(),xo(s,t,e,o,i,n)}}),Ks=Xt({batchNormalization_:function(s,t,e,n,i,o){return void 0===n&&(n=.001),To(),Co(s,t,e,o,i,n)}}),Xs=Xt({batchNorm_:Co}),Ys=Xt({batchNorm2d_:yo}),Qs=Xt({batchNorm3d_:bo}),Js=Xt({batchNorm4d_:xo}),Zs=Xt({conv1d_:function(p,t,e,n,r,m,g){void 0===r&&(r="NWC"),void 0===m&&(m=1);var i=Lt(p,"x","conv1d"),s=Lt(t,"filter","conv1d"),u=i,b=!1;2===i.rank&&(b=!0,u=i.as3D(1,i.shape[0],i.shape[1])),Ue(3===u.rank,function(){return"Error in conv1d: input must be rank 3, but got rank "+u.rank+"."}),Ue(3===s.rank,function(){return"Error in conv1d: filter must be rank 3, but got rank "+s.rank+"."}),null!=g&&Ue(y(n),function(){return"Error in conv1d: pad must be an integer when using, dimRoundingMode "+g+" but got pad "+n+"."}),Ue(u.shape[2]===s.shape[1],function(){return"Error in conv1d: depth of input ("+u.shape[2]+") must match input depth for filter "+s.shape[1]+"."}),Ue(Lr(e,m),function(){return"Error in conv1D: Either stride or dilation must be 1. Got stride "+e+" and dilation '"+m+"'"}),Ue("NWC"===r,function(){return"Error in conv1d: got dataFormat of "+r+" but only NWC is currently supported."});var x=s.as4D(1,s.shape[0],s.shape[1],s.shape[2]),h=u.as4D(u.shape[0],1,u.shape[1],u.shape[2]),f=ru(h,x,[1,e],n,"NHWC",[1,m],g);return b?f.as2D(f.shape[2],f.shape[3]):f.as3D(f.shape[0],f.shape[2],f.shape[3])}}),ru=Xt({conv2d_:function(p,t,e,n,r,d,m){void 0===r&&(r="NHWC"),void 0===d&&(d=[1,1]);var i=Lt(p,"x","conv2d"),s=Lt(t,"filter","conv2d"),u=i,g=!1;3===i.rank&&(g=!0,u=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),Ue(4===u.rank,function(){return"Error in conv2d: input must be rank 4, but got rank "+u.rank+"."}),Ue(4===s.rank,function(){return"Error in conv2d: filter must be rank 4, but got rank "+s.rank+"."}),null!=m&&Ue(y(n),function(){return"Error in conv2d: pad must be an integer when using, dimRoundingMode "+m+" but got pad "+n+"."}),Ue(u.shape[3]===s.shape[2],function(){return"Error in conv2d: depth of input ("+u.shape[3]+") must match input depth for filter "+s.shape[2]+"."}),Ue(Lr(e,d),function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+d+"'"}),Ue("NHWC"===r,function(){return"Error in conv2d: got dataFormat of "+r+" but only NHWC is currently supported."});var b=Nr(u.shape,s.shape,e,d,n,m),h=kt.runKernel(function(a,t){var e=a.conv2d(u,s,b);return t([s,u]),e},{x:u,$filter:s},function(a,t){var r=t,o=r[0],i=r[1];return Ue(zr(d),function(){return"Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+d+"'"}),{x:function(){return Ro(i.shape,a,o,e,n)},$filter:function(){return Eo(i,a,o.shape,e,n)}}});return g?h.as3D(h.shape[1],h.shape[2],h.shape[3]):h}}),ou=Xt({conv3d_:function(p,t,e,n,r,d){void 0===r&&(r="NDHWC"),void 0===d&&(d=[1,1,1]);var m=Lt(p,"x","conv3d"),i=Lt(t,"filter","conv3d"),s=m,g=!1;4===m.rank&&(g=!0,s=m.as5D(1,m.shape[0],m.shape[1],m.shape[2],m.shape[3])),Ue(5===s.rank,function(){return"Error in conv3d: input must be rank 5, but got rank "+s.rank+"."}),Ue(5===i.rank,function(){return"Error in conv3d: filter must be rank 5, but got rank "+i.rank+"."}),Ue(s.shape[4]===i.shape[3],function(){return"Error in conv3d: depth of input ("+s.shape[4]+") must match input depth for filter "+i.shape[3]+"."}),Ue(function(a,t){return wo(a)||wo(t)}(e,d),function(){return"Error in conv3D: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+d+"'"}),Ue("NDHWC"===r,function(){return"Error in conv3d: got dataFormat of "+r+" but only NDHWC is currently supported."});var f=kr(s.shape,i.shape,e,d,n),c=kt.runKernel(function(a,t){var e=a.conv3d(s,i,f);return t([s,i]),e},{x:s,$filter:i},function(a,t){Ue(wo(d),function(){return"Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+d+"'"});var r=t[0],o=t[1];return{x:function(){return function(p,t,e,n,r){Ue(p.length===t.rank,function(){return"Length of inShape ("+p.length+") and rank of dy ("+t.rank+") must match"});var o=p,d=t,m=!1;4===t.rank&&(m=!0,d=t.as5D(1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]),o=[1,p[0],p[1],p[2],p[3]]);var g=o[4],u=d.shape[4];Ue(5===o.length,function(){return"Error in conv3dDerInput: inShape must be length 5, but got length "+o.length+"."}),Ue(5===d.rank,function(){return"Error in conv3dDerInput: dy must be rank 5, but got rank "+d.rank}),Ue(5===e.rank,function(){return"Error in conv3dDerInput: filter must be rank 5, but got rank "+e.rank}),Ue(g===e.shape[3],function(){return"Error in conv3dDerInput: depth of input ("+g+") must match input depth for filter "+e.shape[3]+"."}),Ue(u===e.shape[4],function(){return"Error in conv3dDerInput: depth of output ("+u+") must match output depth for filter "+e.shape[4]+"."});var l=kr(o,e.shape,n,1,r),c=kt.runKernel(function(a){return a.conv3dDerInput(d,e,l)},{dy5D:d});return m?c.as4D(c.shape[1],c.shape[2],c.shape[3],c.shape[4]):c}(r.shape,a,o,e,n)},$filter:function(){return function(p,t,e,n,r){var o=p;4===p.rank&&(o=p.as5D(1,p.shape[0],p.shape[1],p.shape[2],p.shape[3]));var d=t;4===d.rank&&(d=t.as5D(1,t.shape[0],t.shape[1],t.shape[2],t.shape[3])),Ue(5===o.rank,function(){return"Error in conv3dDerFilter: input must be rank 5, but got shape "+o.shape+"."}),Ue(5===d.rank,function(){return"Error in conv3dDerFilter: dy must be rank 5, but got shape "+d.shape+"."}),Ue(5===e.length,function(){return"Error in conv3dDerFilter: filterShape must be length 5, but got "+e+"."}),Ue(o.shape[4]===e[3],function(){return"Error in conv3dDerFilter: depth of input "+o.shape[4]+") must match input depth in filter ("+e[3]+"."}),Ue(d.shape[4]===e[4],function(){return"Error in conv3dDerFilter: depth of dy ("+d.shape[4]+") must match output depth for filter ("+e[4]+")."});var l=kr(o.shape,e,n,1,r);return kt.runKernel(function(e){return e.conv3dDerFilter(o,d,l)},{x5D:o,dy5D:d})}(r,a,o.shape,e,n)}}});return g?c.as4D(c.shape[1],c.shape[2],c.shape[3],c.shape[4]):c}}),au=Xt({conv2dDerFilter_:Eo}),iu=Xt({conv2dDerInput_:Ro}),su=Xt({depthwiseConv2d_:function(p,t,e,n,r,o,d){void 0===o&&(o=[1,1]);var i=Lt(p,"x","depthwiseConv2d"),s=Lt(t,"filter","depthwiseConv2d"),u=i,m=!1;3===i.rank&&(m=!0,u=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),Ue(4===u.rank,function(){return"Error in depthwiseConv2d: input must be rank 4, but got rank "+u.rank+"."}),Ue(4===s.rank,function(){return"Error in depthwiseConv2d: filter must be rank 4, but got rank "+s.rank+"."}),Ue(u.shape[3]===s.shape[2],function(){return"Error in depthwiseConv2d: number of input channels ("+u.shape[3]+") must match the inChannels dimension in filter "+s.shape[2]+"."}),null==o&&(o=[1,1]),Ue(Lr(e,o),function(){return"Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+o+"'"}),null!=d&&Ue(y(n),function(){return"Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode "+d+" but got pad "+n+"."});var g=Nr(u.shape,s.shape,e,o,n,d,!0),h=kt.runKernel(function(a,t){var e=a.depthwiseConv2D(u,s,g);return t([u,s]),e},{x:u,$filter:s},function(a,t){Ue(zr(o),function(){return"Error in gradient of depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+o+"'"});var e=t[0],n=t[1];return{x:function(){return function(s,t,e,n){var r=t,p=!1;3===t.rank&&(p=!0,r=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var d=kt.runKernel(function(a){return a.depthwiseConv2DDerInput(r,e,n)},{dy4D:r});return p?d.as3D(d.shape[1],d.shape[2],d.shape[3]):d}(e.shape,a,n,g)},$filter:function(){return function(s,t,e,n){var r=s;3===s.rank&&(r=s.as4D(1,s.shape[0],s.shape[1],s.shape[2]));var i=t;return 3===i.rank&&(i=t.as4D(1,t.shape[0],t.shape[1],t.shape[2])),kt.runKernel(function(e){return e.depthwiseConv2DDerFilter(r,i,n)},{x4D:r,dy4D:i})}(e,a,n.shape,g)}}});return m?h.as3D(h.shape[1],h.shape[2],h.shape[3]):h}}),uu=Xt({separableConv2d_:function(p,t,e,n,r,o,g){void 0===o&&(o=[1,1]),void 0===g&&(g="NHWC");var y=Lt(p,"x","separableConv2d"),s=Lt(t,"depthwiseFilter","separableConv2d"),u=Lt(e,"pointwiseFilter","separableConv2d"),l=y,b=!1;if(3===y.rank&&(b=!0,l=y.as4D(1,y.shape[0],y.shape[1],y.shape[2])),"NCHW"===g)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");Ue(4===l.rank,function(){return"Error in separableConv2d: input must be rank 4, but got rank "+l.rank+"."}),Ue(4===s.rank,function(){return"Error in separableConv2d: depthwise filter must be rank 4, but got rank "+s.rank+"."}),Ue(4===u.rank,function(){return"Error in separableConv2d: pointwise filter must be rank 4, but got rank "+s.rank+"."}),Ue(1===u.shape[0],function(){return"Error in separableConv2d: the first dimension of pointwise filter  must be 1, but got "+u.shape[0]+"."}),Ue(1===u.shape[1],function(){return"Error in separableConv2d: the second dimension of pointwise filter must be 1, but got "+u.shape[1]+"."});var x=s.shape[2],f=s.shape[3];Ue(u.shape[2]===x*f,function(){return"Error in separableConv2d: the third dimension of pointwise filter must be "+x*f+", but got "+u.shape[2]+"."});var d=su(l,s,n,r,g,o),v=ru(d,u,1,"valid",g);return b?v.as3D(v.shape[1],v.shape[2],v.shape[3]):v}}),lu=Xt({conv2dTranspose_:function(s,t,e,n,r,o){return Ro(e,Lt(s,"x","conv2dTranspose"),Lt(t,"filter","conv2dTranspose"),n,r,o)}}),cu=Xt({matMul_:function(p,t,y,C){var e;void 0===y&&(y=!1),void 0===C&&(C=!1);var S=Lt(p,"a","matMul"),N=Lt(t,"b","matMul");e=Ke(S,N),S=e[0],N=e[1];var I=y?S.shape[S.rank-2]:S.shape[S.rank-1],s=C?N.shape[N.rank-1]:N.shape[N.rank-2],u=y?S.shape[S.rank-1]:S.shape[S.rank-2],l=C?N.shape[N.rank-2]:N.shape[N.rank-1],c=S.shape.slice(0,-2),h=N.shape.slice(0,-2),f=qe(c),d=qe(h);Ue(2<=S.rank&&2<=N.rank&&S.rank===N.rank,function(){return"Error in matMul: inputs must have the same rank of at least 2, got ranks "+S.rank+" and "+N.rank+"."}),Ue(g(c,h),function(){return"Error in matMul: outer dimensions ("+c+") and ("+h+") of Tensors with shapes "+S.shape+" and "+N.shape+" must match."}),Ue(I===s,function(){return"Error in matMul: inner shapes ("+I+") and ("+s+") of Tensors with shapes "+S.shape+" and "+N.shape+" and transposeA="+y+" and transposeB="+C+" must match."});var v=S.shape.slice(0,-2).concat([u,l]),m=y?S.as3D(f,I,u):S.as3D(f,u,I),x=C?N.as3D(d,l,s):N.as3D(d,s,l);return kt.runKernel(function(a,t){var e=a.batchMatMul(m,x,y,C);return t([m,x]),e},{$a:m,$b:x},function(n,t){var e=t,r=e[0],a=e[1];return y||C?!y&&C?{$a:function(){return n.matMul(a,!1,!1)},$b:function(){return n.matMul(r,!0,!1)}}:y&&!C?{$a:function(){return a.matMul(n,!1,!0)},$b:function(){return r.matMul(n,!1,!1)}}:{$a:function(){return a.matMul(n,!0,!0)},$b:function(){return n.matMul(r,!0,!0)}}:{$a:function(){return n.matMul(a,!1,!0)},$b:function(){return r.matMul(n,!0,!1)}}}).reshape(v)}}),hu=Xt({dot_:function(s,t){var e=Lt(s,"t1","dot"),n=Lt(t,"t2","dot");Ue((1===e.rank||2===e.rank)&&(1===n.rank||2===n.rank),function(){return"Error in dot: inputs must all be rank 1 or 2, but got ranks "+e.rank+" and "+n.rank+"."});var r=1===e.rank?e.size:e.shape[1],o=1===n.rank?n.size:n.shape[0];return Ue(r===o,function(){return"Error in dot: inner dimensions of inputs must match, but got "+r+" and "+o+"."}),1===e.rank&&1===n.rank?e.as2D(1,-1).matMul(n.as2D(-1,1)).asScalar():1===e.rank&&2===n.rank?e.as2D(1,-1).matMul(n.as2D(n.shape[0],n.shape[1])).as1D():2===e.rank&&1===n.rank?e.matMul(n.as2D(-1,1)).as1D():e.matMul(n.as2D(n.shape[0],n.shape[1]))}}),fu=Xt({outerProduct_:function(a,t){var e=Lt(a,"v1","outerProduct"),n=Lt(t,"v2","outerProduct");return Ue(1===e.rank&&1===n.rank,function(){return"Error in outerProduct: inputs must be rank 1, but got ranks "+e.rank+" and "+n.rank+"."}),e.as2D(-1,1).matMul(n.as2D(1,-1))}}),pu=Xt({reverse_:function(a,t){var e=Lt(a,"x","reverse");if(0===e.rank)return e.clone();var n=C(t,e.shape);return kt.runKernel(function(a){return a.reverse(e,n)},{$x:e},function(e){return{$x:function(){return e.reverse(n)}}}).reshapeAs(e)}}),du=Xt({reverse1d_:function(a){var t=Lt(a,"x","reverse");return Ue(1===t.rank,function(){return"Error in reverse1D: x must be rank 1 but got rank "+t.rank+"."}),pu(t,0)}}),vu=Xt({reverse2d_:function(a,t){var e=Lt(a,"x","reverse");return Ue(2===e.rank,function(){return"Error in reverse2D: x must be rank 2 but got rank "+e.rank+"."}),pu(e,t)}}),mu=Xt({reverse3d_:function(a,t){var e=Lt(a,"x","reverse");return Ue(3===e.rank,function(){return"Error in reverse3D: x must be rank 3 but got rank "+e.rank+"."}),pu(e,t)}}),gu=Xt({reverse4d_:function(a,t){var e=Lt(a,"x","reverse");return Ue(4===e.rank,function(){return"Error in reverse4D: x must be rank 4 but got rank "+e.rank+"."}),pu(e,t)}}),yu=Xt({maxPool_:function(a,t,e,n,r){return Ao(a,t,e,1,n,r)}}),wu=Xt({avgPool_:function(a,t,e,n,r){return Do(a,t,e,1,n,r)}}),Cu=Xt({pool_:function(p,t,e,n,C,S){null==C&&(C=[1,1]),null==S&&(S=1),0===n&&(n="valid");var N=Lt(p,"x","maxPool"),i=N,I=!1;3===N.rank&&(I=!0,i=N.as4D(1,N.shape[0],N.shape[1],N.shape[2])),Ue(Lr(S,C),function(){return"Error in pool: Either strides or dilations must be 1. Got strides "+S+" and dilations '"+C+"'"});var k=Sr(i.shape,t,S,C,n),c=[k.dilationHeight,k.dilationWidth],h;h="same"===n?function(a,s){var e=a.map(function(e,t){return e+(e-1)*(s[t]-1)}).map(function(e){return e-1}),n=e.map(function(e){return Cf(e/2)}),r=e.map(function(a,t){return a-n[t]});return e.map(function(a,t){return[n[t],r[t]]})}([k.filterHeight,k.filterWidth],c):[[0,0],[0,0]];var T=1===c[0]&&1===c[1],f=function(p,t,e){var n=e.map(function(e){return e[0]}),r=e.map(function(e){return e[1]}),o=p.concat(n,r),a=t.map(function(a,t){return(a-o[t]%a)%a}),i=r.map(function(n,t){return n+a[t]}),s=t.map(function(a,t){return[n[t],i[t]]}),d=t.map(function(n,t){return[0,a[t]]});return[s,d]}([k.inHeight,k.inWidth],c,h),d=f[0],v=f[1],m=T?n:"valid",g=T?i:yr(i,c,d),y=("avg"===e?function(){return Do(g,t,S,1,m)}:function(){return Ao(g,t,S,1,m)})(),x=T?y:Jn(y,c,v);return I?x.as3D(x.shape[1],x.shape[2],x.shape[3]):x}}),Eu=Xt({slice_:function(s,t,e){var n=Lt(s,"x","slice"),a,p;if(0===n.rank)throw new Error("Slicing scalar is not possible");a="number"==typeof t?[t].concat(Array(n.rank-1).fill(0)):t.length<n.rank?t.concat(Array(n.rank-t.length).fill(0)):t.slice(),p=(p=null==e?Array(n.rank).fill(-1):"number"==typeof e?[e].concat(Array(n.rank-1).fill(-1)):e.length<n.rank?e.concat(Array(n.rank-e.length).fill(-1)):e).map(function(r,t){return 0<=r?r:(Ue(-1==r,function(){return"Bad value in size"}),n.shape[t]-a[t])}),function(a,t,e){Ue(a.rank===t.length,function(){return"Error in slice"+a.rank+"D: Length of begin "+t+" must match the rank of the array ("+a.rank+")."}),Ue(a.rank===e.length,function(){return"Error in slice"+a.rank+"D: Length of size "+e+" must match the rank of the array ("+a.rank+")."});for(var n=function(n){Ue(t[n]+e[n]<=a.shape[n],function(){return"Error in slice"+a.rank+"D: begin["+n+"] + size["+n+"] ("+(t[n]+e[n])+") would overflow input.shape["+n+"] ("+a.shape[n]+")"})},r=0;r<a.rank;++r)n(r)}(n,a,p);var d=n.shape;return kt.runKernel(function(e){return e.slice(n,a,p)},{$x:n},function(r){for(var t=[],e=0;e<r.rank;e++)t.push([a[e],d[e]-a[e]-p[e]]);return{$x:function(){return r.pad(t)}}})}}),Ru=Xt({slice1d_:function(a,t,e){var n=Lt(a,"x","slice1d");return Ue(1===n.rank,function(){return"slice1d expects a rank-1 tensor, but got a rank-"+n.rank+" tensor"}),Eu(n,[t],[e])}}),Iu=Xt({slice2d_:function(a,t,e){var n=Lt(a,"x","slice2d");return Ue(2===n.rank,function(){return"slice2d expects a rank-2 tensor, but got a rank-"+n.rank+" tensor"}),Eu(n,t,e)}}),Su=Xt({slice3d_:function(a,t,e){var n=Lt(a,"x","slice3d");return Ue(3===n.rank,function(){return"slice3d expects a rank-3 tensor, but got a rank-"+n.rank+" tensor"}),Eu(n,t,e)}}),Nu=Xt({slice4d_:function(a,t,e){var n=Lt(a,"x","slice4d");return Ue(4===n.rank,function(){return"slice4d expects a rank-4 tensor, but got a rank-"+n.rank+" tensor"}),Eu(n,t,e)}}),ku=Xt({all_:function(p,t,d){void 0===t&&(t=null),void 0===d&&(d=!1);var l=Lt(p,"x","all","bool"),c=C(t,l.shape),o=c,h=qt(o,l.rank);null!=h&&(l=l.transpose(h),o=Kt(o.length,l.rank));var i=kt.runKernel(function(e){return e.all(l,o)},{$x:l});if(d){var s=Vt(i.shape,c);return i.reshape(s)}return i}}),Tu=Xt({any_:function(p,t,d){void 0===t&&(t=null),void 0===d&&(d=!1);var l=Lt(p,"x","any","bool"),c=C(t,l.shape),o=c,h=qt(o,l.rank);null!=h&&(l=l.transpose(h),o=Kt(o.length,l.rank));var i=kt.runKernel(function(e){return e.any(l,o)},{$x:l});if(d){var s=Vt(i.shape,c);return i.reshape(s)}return i}}),Du=Xt({argMax_:function(a,t){void 0===t&&(t=0);var s=Lt(a,"x","argMax");null==t&&(t=0);var i=C(t,s.shape),p=qt(i,s.rank);return null!=p&&(s=s.transpose(p),i=Kt(i.length,s.rank)),kt.runKernel(function(a,t){var e=a.argMax(s,i[0]);return t([s]),e},{$x:s},function(a,t){var e=t[0];return{$x:function(){return Fn(e)}}})}}),_u=Xt({argMin_:function(a,t){void 0===t&&(t=0);var s=Lt(a,"x","argMin");null==t&&(t=0);var i=C(t,s.shape),p=qt(i,s.rank);return null!=p&&(s=s.transpose(p),i=Kt(i.length,s.rank)),kt.runKernel(function(a,t){var e=a.argMin(s,i[0]);return t([s]),e},{$x:s},function(a,t){var e=t[0];return{$x:function(){return Fn(e)}}})}}),Ou=Xt({logSumExp_:function(p,t,d){void 0===t&&(t=null),void 0===d&&(d=!1);var l=Lt(p,"x","logSumExp"),r=C(t,l.shape),o=l.max(r,!0),a=l.sub(o).exp().sum(r).log(),i=o.reshape(a.shape).add(a);if(d){var s=Vt(i.shape,r);return i.reshape(s)}return i}}),Fu=Xt({max_:function(p,t,d){void 0===t&&(t=null),void 0===d&&(d=!1);var c=Lt(p,"x","max"),h=c,o=C(t,c.shape),a=o,m=qt(a,c.rank);null!=m&&(c=c.transpose(m),a=Kt(a.length,c.rank));var s=kt.runKernel(function(r,t){var e=r.max(c,a);return t([h,e]),e},{$x:c},function(a,t){return _o(a,t[1],t[0],o,m)});if(d){var g=Vt(s.shape,o);s=s.reshape(g)}return s}}),Mu=Xt({mean_:function(s,i,p){void 0===i&&(i=null),void 0===p&&(p=!1);var t=Lt(s,"x","mean"),r=C(i,t.shape),o=qe(Wt(t.shape,r)[1]);return On(function(a){var e=Da(o);return{value:(e.dtype===a.dtype?a:a.cast(e.dtype)).div(e).sum(i,p),gradFunc:function(t){var e=a.shape.slice();return r.forEach(function(a){e[a]=1}),t.reshape(e).mul(sn(a.shape,"float32")).div(o)}}})(t)}}),Bu=Xt({min_:function(p,t,d){void 0===t&&(t=null),void 0===d&&(d=!1);var c=Lt(p,"x","min"),h=c,o=C(t,c.shape),a=o,m=qt(a,c.rank);null!=m&&(c=c.transpose(m),a=Kt(a.length,c.rank));var s=kt.runKernel(function(r,t){var e=r.min(c,a);return t([h,e]),e},{$x:c},function(a,t){return _o(a,t[1],t[0],o,m)});if(d){var g=Vt(s.shape,o);s=s.reshape(g)}return s}}),Pu=Xt({moments_:function(s,p,d){void 0===p&&(p=null),void 0===d&&(d=!1);var l=C(p,(s=Lt(s,"x","moments")).shape),r=s.mean(l,d),o=r.shape;d||(o=Vt(r.shape,l));var u=s.toFloat().sub(r.reshape(o)).square();return{mean:r,variance:u.mean(l,d)}}}),Lu=Xt({sum_:function(a,t,p){void 0===t&&(t=null),void 0===p&&(p=!1);var s=Lt(a,"x","sum");"bool"===s.dtype&&(s=s.toInt());var d=C(t,s.shape);return On(function(o){var t=qt(d,o.rank),e=d,n=o;null!=t&&(n=o.transpose(t),e=Kt(e.length,o.rank));var l=kt.runKernel(function(a){return a.sum(n,e)},{permutedX:n});if(p){var u=Vt(l.shape,d);l=l.reshape(u)}return{value:l,gradFunc:function(t){var e=o.shape.slice();return d.forEach(function(a){e[a]=1}),t.reshape(e).mul(sn(o.shape,"float32"))}}})(s)}}),Wu=Xt({prod_:function(p,t,d){void 0===t&&(t=null),void 0===d&&(d=!1);var c=Lt(p,"x","prod");"bool"===c.dtype&&(c=c.toInt());var h=C(t,c.shape),o=qt(h,c.rank),a=h,m=c;null!=o&&(m=c.transpose(o),a=Kt(a.length,c.rank));var g=kt.runKernel(function(e){return e.prod(m,a)},{permutedX:m});if(d){var f=Vt(g.shape,h);g=g.reshape(f)}return g}}),Uu=Xt({equal_:function(a,t){var e=Lt(a,"a","equal"),s=Lt(t,"b","equal"),i;return i=Ke(e,s),e=i[0],s=i[1],tr(e.shape,s.shape),kt.runKernel(function(a){return a.equal(e,s)},{$a:e,$b:s})}}),zu=Xt({equalStrict_:function(a,t){var e=Lt(a,"a","equalStrict"),n=Lt(t,"b","equalStrict");return p(e.shape,n.shape,"Error in equalStrict: "),e.equal(n)}}),Vu=Xt({greater_:function(a,t){var e=Lt(a,"a","greater"),s=Lt(t,"b","greater"),i;return i=Ke(e,s),e=i[0],s=i[1],tr(e.shape,s.shape),kt.runKernel(function(a){return a.greater(e,s)},{$a:e,$b:s})}}),Gu=Xt({greaterEqual_:function(a,t){var s=Lt(a,"a","greaterEqual"),i=Lt(t,"b","greaterEqual"),e;return e=Ke(s,i),s=e[0],i=e[1],tr(s.shape,i.shape),kt.runKernel(function(a,t){var e=a.greaterEqual(s,i);return t([s,i]),e},{$a:s,$b:i},function(a,t){var e=t[0],n=t[1];return{$a:function(){return Fn(e)},$b:function(){return Fn(n)}}})}}),Hu=Xt({greaterEqualStrict_:function(a,t){var e=Lt(a,"a","greaterEqualStrict"),n=Lt(t,"b","greaterEqualStrict");return p(e.shape,n.shape,"Error in greaterEqualStrict: "),e.greaterEqual(n)}}),qu=Xt({greaterStrict_:function(a,t){var e=Lt(a,"a","greaterStrict"),n=Lt(t,"b","greaterStrict");return p(e.shape,n.shape,"Error in greaterStrict: "),e.greater(n)}}),$u=Xt({less_:function(a,t){var e=Lt(a,"a","less"),s=Lt(t,"b","less"),i;return i=Ke(e,s),e=i[0],s=i[1],tr(e.shape,s.shape),kt.runKernel(function(a){return a.less(e,s)},{$a:e,$b:s})}}),ju=Xt({lessEqual_:function(a,t){var e=Lt(a,"a","lessEqual"),s=Lt(t,"b","lessEqual"),i;return i=Ke(e,s),e=i[0],s=i[1],tr(e.shape,s.shape),kt.runKernel(function(a){return a.lessEqual(e,s)},{$a:e,$b:s})}}),Ku=Xt({lessEqualStrict_:function(a,t){var e=Lt(a,"a","lessEqualStrict"),n=Lt(t,"b","lessEqualStrict");return p(e.shape,n.shape,"Error in lessEqualStrict: "),e.lessEqual(n)}}),Xu=Xt({lessStrict_:function(a,t){var e=Lt(a,"a","lessStrict"),n=Lt(t,"b","lessStrict");return p(e.shape,n.shape,"Error in lessStrict: "),e.less(n)}}),Yu=Xt({notEqual_:function(a,t){var e=Lt(a,"a","notEqual"),s=Lt(t,"b","notEqual"),i;return i=Ke(e,s),e=i[0],s=i[1],tr(e.shape,s.shape),kt.runKernel(function(a){return a.notEqual(e,s)},{$a:e,$b:s})}}),Qu=Xt({notEqualStrict_:function(a,t){var e=Lt(a,"a","notEqualStrict"),n=Lt(t,"b","notEqualStrict");return p(e.shape,n.shape,"Error in notEqualStrict: "),e.notEqual(n)}}),Ju=Xt({add_:function(s,t){var i=Lt(s,"a","add"),p=Lt(t,"b","add"),e;e=Ke(i,p),i=e[0],p=e[1];var d=tr(i.shape,p.shape);return kt.runKernel(function(e){return e.add(i,p)},{$a:i,$b:p},function(a){return{$a:function(){var t=a,r=Zn(i.shape,d);return 0<r.length&&(t=t.sum(r)),t.reshape(i.shape)},$b:function(){var t=a,r=Zn(p.shape,d);return 0<r.length&&(t=t.sum(r)),t.reshape(p.shape)}}})}}),Zu=Xt({addN_:function(a){Ue(Array.isArray(a),function(){return"The argument passed to tf.addN() must be a list of tensors"}),Ue(1<=a.length,function(){return"Must pass at least one tensor to tf.addN(), but got "+a.length});var r=a.map(function(a,t){return Lt(a,"tensors"+t,"addN")}),e=r[0];r.forEach(function(a){if(a.dtype!==e.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),r.forEach(function(a){if(!g(a.shape,e.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});return kt.runKernel(function(e){return e.addN(r)},r,function(e){var t={};return r.forEach(function(a,n){t[n]=function(){return e.clone()}}),t})}}),tl=Xt({addStrict_:function(a,t){var e=Lt(a,"a","addStrict"),n=Lt(t,"b","addStrict");return p(e.shape,n.shape,"Error in addStrict: "),e.add(n)}}),el=Xt({atan2_:function(s,t){var i=Lt(s,"a","atan2"),p=Lt(t,"b","atan2"),e;e=Ke(i,p),i=e[0],p=e[1];var d=tr(i.shape,p.shape);return kt.runKernel(function(a,t){var e=a.atan2(i,p);return t([i,p]),e},{$a:i,$b:p},function(a,t){var s=t[0],n=t[1];return{$a:function(){var t=Ju(s.square(),n.square()),e=a.mul(n.div(t)),r=Zn(s.shape,d);return 0<r.length&&(e=e.sum(r)),e.reshape(s.shape)},$b:function(){var t=Ju(s.square(),n.square()),e=Cs(a.mul(s.div(t))),r=Zn(n.shape,d);return 0<r.length&&(e=e.sum(r)),e.reshape(n.shape)}}})}}),nl=Xt({div_:function(s,t){var i=Lt(s,"a","div"),p=Lt(t,"b","div"),e;if(e=Ke(i,p),i=e[0],p=e[1],"int32"===i.dtype&&"int32"===p.dtype)return ol(i,p);var d=tr(i.shape,p.shape);return kt.runKernel(function(a,t){var e=a.realDivide(i,p);return t([i,p]),e},{$a:i,$b:p},function(a,t){var s=t[0],n=t[1];return{$a:function(){var t=a.div(n.toFloat()),e=Zn(s.shape,d);return 0<e.length?t.sum(e).reshape(s.shape):t},$b:function(){var t=a.mul(s.toFloat()),r=Zn(n.shape,d);0<r.length&&(t=t.sum(r).reshape(n.shape));var o=n.square();return t.div(o.toFloat()).neg()}}})}}),rl=Xt({divStrict_:function(a,t){var e=Lt(a,"a","div"),n=Lt(t,"b","div");return p(e.shape,n.shape,"Error in divideStrict: "),e.div(n)}}),ol=Xt({floorDiv_:function(s,t){var i=Lt(s,"a","floorDiv"),p=Lt(t,"b","floorDiv"),e;e=Ke(i,p),i=e[0],p=e[1];var d=tr(i.shape,p.shape);return kt.runKernel(function(a,t){var e=a.floorDiv(i,p);return t([i,p]),e},{$a:i,$b:p},function(a,t){var s=t[0],n=t[1];return{$a:function(){var t=a.div(n.toFloat()),e=Zn(s.shape,d);return 0<e.length?t.sum(e).reshape(s.shape):t},$b:function(){var t=a.mul(s.toFloat()),r=Zn(n.shape,d);0<r.length&&(t=t.sum(r).reshape(n.shape));var o=n.square();return t.div(o.toFloat()).neg()}}})}}),al=Xt({maximum_:function(a,t){var s=Lt(a,"a","maximum"),i=Lt(t,"b","maximum"),e;return e=Ke(s,i),s=e[0],i=e[1],"bool"===s.dtype&&(s=s.toInt(),i=i.toInt()),tr(s.shape,i.shape),kt.runKernel(function(a,t){var e=a.maximum(s,i);return t([s,i]),e},{$a:s,$b:i},function(a,t){var e=t[0],n=t[1];return{$a:function(){return a.mul(e.greaterEqual(n).toFloat())},$b:function(){return a.mul(e.less(n).toFloat())}}})}}),il=Xt({maximumStrict_:function(a,t){var e=Lt(a,"a","maximumStrict"),n=Lt(t,"b","maximumStrict");return p(e.shape,n.shape,"Error in maximumStrict: "),e.maximum(n)}}),sl=Xt({minimum_:function(a,t){var s=Lt(a,"a","minimum"),i=Lt(t,"b","minimum"),e;return e=Ke(s,i),s=e[0],i=e[1],"bool"===s.dtype&&(s=s.toInt(),i=i.toInt()),tr(s.shape,i.shape),kt.runKernel(function(a,t){var e=a.minimum(s,i);return t([s,i]),e},{$a:s,$b:i},function(a,t){var e=t[0],n=t[1];return{$a:function(){return a.mul(e.lessEqual(n).toFloat())},$b:function(){return a.mul(e.greater(n).toFloat())}}})}}),ul=Xt({minimumStrict_:function(a,t){var e=Lt(a,"a","minimumStrict"),n=Lt(t,"b","minimumStrict");return p(e.shape,n.shape,"Error in minimumStrict: "),e.minimum(n)}}),ll=Xt({mod_:function(s,t){var i=Lt(s,"a","mod"),p=Lt(t,"b","mod"),e;e=Ke(i,p),i=e[0],p=e[1];var d=tr(i.shape,p.shape);return kt.runKernel(function(a,t){var e=a.mod(i,p);return t([i,p]),e},{$a:i,$b:p},function(a,t){var s=t[0],n=t[1];return{$a:function(){var t=Zn(s.shape,d);return 0<t.length?a.sum(t).reshape(s.shape):a},$b:function(){var t=a.mul(s.div(n).floor().neg()),e=Zn(n.shape,d);return 0<e.length?t.sum(e).reshape(n.shape):t}}})}}),cl=Xt({modStrict_:function(a,t){var e=Lt(a,"a","modStrict"),n=Lt(t,"b","modStrict");return p(e.shape,n.shape,"Error in modStrict: "),e.mod(n)}}),hl=Xt({mul_:function(s,t){var i=Lt(s,"a","mul"),p=Lt(t,"b","mul"),e;e=Ke(i,p),i=e[0],p=e[1];var d=tr(i.shape,p.shape);return kt.runKernel(function(a,t){var e=a.multiply(i,p);return t([i,p]),e},{$a:i,$b:p},function(a,t){var s=t[0],n=t[1];return{$a:function(){var t=a.mul(n.toFloat()),e=Zn(s.shape,d);return 0<e.length?t.sum(e).reshape(s.shape):t},$b:function(){var t=a.mul(s.toFloat()),e=Zn(n.shape,d);return 0<e.length?t.sum(e).reshape(n.shape):t}}})}}),fl=Xt({mulStrict_:function(a,t){var e=Lt(a,"a","mul"),n=Lt(t,"b","mul");return p(e.shape,n.shape,"Error in multiplyStrict: "),e.mul(n)}}),pl=Xt({pow_:function(a,s){var i=Lt(a,"base","pow"),n=Lt(s,"exp","pow"),p=tr(i.shape,n.shape);return a=i.cast(Y(i.dtype,n.dtype)),s=n.cast(Y(i.dtype,n.dtype)),kt.runKernel(function(a,t){var e=a.pow(i,n);return t([i,n,e]),e},{$base:i,$exp:n},function(o,t){var d=t[0],n=t[1],r=t[2];return{$base:function(){var t=n.toFloat(),e=o.mul(t.mul(d.pow(t.sub(Da(1))))),r=Zn(d.shape,p);return 0<r.length&&(e=e.sum(r)),e.reshape(d.shape)},$exp:function(){var t=d.greater(0),e=d.log().where(t,Fn(d)),a=o.mul(r.mul(e)),i=Zn(n.shape,p);return 0<i.length&&(a=a.sum(i)),a.reshape(n.shape)}}})}}),dl=Xt({powStrict_:function(a,t){return p(a.shape,t.shape,"Error in powStrict: "),a.pow(t)}}),vl=Xt({squaredDifference_:function(a,t){var s=Lt(a,"a","squaredDifference"),i=Lt(t,"b","squaredDifference"),e;return e=Ke(s,i),s=e[0],i=e[1],tr(s.shape,i.shape),kt.runKernel(function(a,t){var e=a.squaredDifference(s,i);return t([s,i]),e},{$a:s,$b:i},function(a,t){var e=t[0],n=t[1],r=Da(2);return{$a:function(){return a.mul(e.sub(n).mul(r))},$b:function(){return a.mul(n.sub(e).mul(r))}}})}}),ml=Xt({squaredDifferenceStrict_:function(a,t){var e=Lt(a,"a","squaredDifferenceStrict"),n=Lt(t,"b","squaredDifferenceStrict");return p(e.shape,n.shape,"Error in squaredDifferenceStrict: "),e.squaredDifference(n)}}),gl=Xt({sub_:function(s,t){var i=Lt(s,"a","sub"),p=Lt(t,"b","sub"),e;e=Ke(i,p),i=e[0],p=e[1];var d=tr(i.shape,p.shape);return kt.runKernel(function(e){return e.subtract(i,p)},{$a:i,$b:p},function(a){return{$a:function(){var t=a,r=Zn(i.shape,d);return 0<r.length&&(t=t.sum(r)),t.reshape(i.shape)},$b:function(){var t=a,r=Zn(p.shape,d);return 0<r.length&&(t=t.sum(r)),t.neg().reshape(p.shape)}}})}}),yl=Xt({subStrict_:function(a,t){var e=Lt(a,"a","subStrict"),n=Lt(t,"b","subStrict");return p(e.shape,n.shape,"Error in subStrict: "),e.sub(n)}}),xl=Xt({logicalAnd_:function(a,t){var e=Lt(a,"a","logicalAnd","bool"),n=Lt(t,"b","logicalAnd","bool");return tr(e.shape,n.shape),kt.runKernel(function(a){return a.logicalAnd(e,n)},{$a:e,$b:n})}}),bl=Xt({logicalNot_:function(a){var n=Lt(a,"x","logicalNot","bool");return kt.runKernel(function(e){return e.logicalNot(n)},{$x:n})}}),wl=Xt({logicalOr_:function(a,t){var e=Lt(a,"a","logicalOr","bool"),n=Lt(t,"b","logicalOr","bool");return tr(e.shape,n.shape),kt.runKernel(function(a){return a.logicalOr(e,n)},{$a:e,$b:n})}}),Cl=Xt({logicalXor_:function(a,t){var e=Lt(a,"a","logicalXor","bool"),n=Lt(t,"b","logicalXor","bool");return tr(e.shape,n.shape),wl(a,t).logicalAnd(xl(a,t).logicalNot())}}),El=Xt({where_:function(s,t,e){var i=Lt(t,"a","where"),r=Lt(e,"b","where"),o=Lt(s,"condition","where","bool");return p(i.shape,r.shape,"Error in where: "),1===o.rank?Ue(o.shape[0]===i.shape[0],function(){return"The first dimension of `a` must match the size of `condition`."}):p(o.shape,r.shape,"Error in where: "),kt.runKernel(function(a,t){var e=a.select(o,i,r);return t([o]),e},{$condition:o,$a:i,$b:r},function(a,t){var e=t[0];return{$condition:function(){return Fn(e).toFloat()},$a:function(){return a.mul(e.cast(a.dtype))},$b:function(){return a.mul(e.logicalNot().cast(a.dtype))}}})}}),Rl=function(a){return Be(this,void 0,void 0,function(){var t,s,i;return Me(this,function(e){switch(e.label){case 0:return[4,(t=Lt(a,"condition","whereAsync","bool")).data()];case 1:return s=e.sent(),i=Zr(t.shape,s),a!==t&&t.dispose(),[2,i];}})})},Il=Xt({elu_:function(a){var o=Lt(a,"x","elu");return kt.runKernel(function(e,t){var a=e.elu(o);return t([a]),a},{$x:o},function(a,t){var r=t[0];return{$x:function(){return kt.runKernel(function(t){return t.eluDer(a,r)},{dy:a,y:r})}}})}}),Sl=Xt({leakyRelu_:function(a,t){void 0===t&&(t=.2);var r=Lt(a,"x","leakyRelu");return al(Da(t).mul(r),r)}}),Nl=Xt({prelu_:function(a,t){var s=Lt(a,"x","prelu"),n=Lt(t,"alpha","prelu");return kt.runKernel(function(a,t){var e=a.prelu(s,n);return t([s,n]),e},{$x:s,$alpha:n},function(s,t){var i=t[0],n=t[1],r=i.greater(0);return{$x:function(){return El(r,s,s.mul(n))},$alpha:function(){var t=El(r,Fn(s),s.mul(i)),o=Zn(n.shape,s.shape);return 0<o.length&&(t=t.sum(o)),t.reshape(n.shape)}}})}}),kl=Xt({relu_:function(a){var o=Lt(a,"x","relu");return"bool"===o.dtype?o.toInt():kt.runKernel(function(e,t){var a=e.relu(o);return t([o]),a},{$x:o},function(a,t){var e=t[0];return{$x:function(){return a.mulStrict(e.step().toFloat())}}})}}),Al=Xt({selu_:function(a){var o=Lt(a,"x","selu");return kt.runKernel(function(e,t){var a=e.selu(o);return t([o]),a},{$x:o},function(s,t){var p=t[0];return{$x:function(){var t=p.greater(Da(0)),e=Da(Pi),n=Da(Li),r=s.mul(n),a=s.mul(e).mul(p.toFloat().exp());return El(t,r,a)}}})}}),Tl=Xt({transpose_:function(a,r){var o=Lt(a,"x","transpose");return null==r&&(r=o.shape.map(function(a,t){return t}).reverse()),Ue(o.rank===r.length,function(){return"Error in transpose: rank of input "+o.rank+" must match length of perm "+r+"."}),r.forEach(function(e){Ue(0<=e&&e<o.rank,function(){return"All entries in 'perm' must be between 0 and "+(o.rank-1)+" but got "+r})}),1>=o.rank?o.clone():kt.runKernel(function(e){return e.transpose(o,r)},{$x:o},function(e){var t=Ht(r);return{$x:function(){return e.transpose(t)}}})}}),Dl=Xt({localResponseNormalization_:function(p,d,l,c,h){void 0===d&&(d=5),void 0===l&&(l=1),void 0===c&&(c=1),void 0===h&&(h=.5);var t=Lt(p,"x","localResponseNormalization");Ue(4===t.rank||3===t.rank,function(){return"Error in localResponseNormalization: x must be rank 3 or 4 but got\n               rank "+t.rank+"."}),Ue(y(d),function(){return"Error in localResponseNormalization: depthRadius must be an integer but got depthRadius "+d+"."});var m=t,a=!1;3===t.rank&&(a=!0,m=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var g=kt.runKernel(function(e,t){var a=e.localResponseNormalization4D(m,d,l,c,h);return t([m,a]),a},{x4D:m},function(e,t){var n=t[0],r=t[1];return{x4D:function(){return kt.runKernel(function(t){return t.LRNGrad(e,n,r,d,l,c,h)},{})}}});return a?g.as3D(g.shape[1],g.shape[2],g.shape[3]):g}}),_l=Xt({norm_:function(s,p,d,l){void 0===p&&(p="euclidean"),void 0===d&&(d=null),void 0===l&&(l=!1);var u=function a(t,e,n){if(void 0===n&&(n=null),0===t.rank)return t.abs();if(1!==t.rank&&null===n)return a(t.reshape([-1]),e,n);if(1===t.rank||"number"==typeof n||Array.isArray(n)&&1===n.length){if(1===e)return t.abs().sum(n);if(e===1/0)return t.abs().max(n);if(e===-1/0)return t.abs().min(n);if("euclidean"===e||2===e)return t.abs().pow(Da(2,"int32")).sum(n).sqrt();throw new Error("Error in norm: invalid ord value: "+e)}if(Array.isArray(n)&&2===n.length){if(1===e)return t.abs().sum(n[0]).max(n[1]-1);if(e===1/0)return t.abs().sum(n[1]).max(n[0]);if(e===-1/0)return t.abs().sum(n[1]).min(n[0]);if("fro"===e||"euclidean"===e)return t.square().sum(n).sqrt();throw new Error("Error in norm: invalid ord value: "+e)}throw new Error("Error in norm: invalid axis: "+n)}(s=Lt(s,"x","norm"),p,d),o=u.shape;if(l){var c=C(d,s.shape);o=Vt(u.shape,c)}return u.reshape(o)}}),Ol=Xt({gather_:function(s,t,b){void 0===b&&(b=0);var x=Lt(s,"x","gather"),r=Lt(t,"indices","gather","int32");b=C(b,x.shape)[0];var e=function(p,t,e){for(var n=p.shape[e],r=[],o=1,d=1,l=0;l<e;l++)r.push(p.shape[l]),o*=p.shape[l];for(l=0;l<t.rank;l++)r.push(t.shape[l]);for(l=e+1;l<p.rank;l++)r.push(p.shape[l]),d*=p.shape[l];return{batchSize:o,sliceSize:d,dimSize:n,outputShape:r}}(x,r,b);return kt.runKernel(function(n,t){var e=n.gather(x,r.flatten(),b);return t([r]),e},{$x:x},function(n,t){var r=t[0];return{$x:function(){var t=x.shape,e=r.size,a=t.slice(0,b),o=a.length,s=t.slice(b,t.length).slice(1),i=s.length,l=Oo(0,o),u=Oo(o+1,o+1+i),c=Bo([a,[e],s]),h=n.reshape(c),p=r.reshape([e]),d=Bo([[o],l,u]),f=h.transpose(d),m=Bl(f,p,x.shape[b]),v=Ht(d);return m=m.transpose(v)}}}).reshape(e.outputShape)}}),Bl=Xt({unsortedSegmentSum_:function(a,t,s){var n=Lt(a,"x","unsortedSegmentSum"),r=Lt(t,"segmentIds","unsortedSegmentSum","int32");return Ue(y(s),function(){return"numSegments must be of dtype int"}),kt.runKernel(function(o,t){var e=o.unsortedSegmentSum(n,r,s);return t([r]),e},{$x:n},function(a,t){var e=t[0];return{$x:function(){return function(p,t){for(var e=al(t,Fn(t)),n=Ol(p,e),r=Gu(t,Da(0,"int32")),d=n.rank-r.rank,a=0;a<d;++a)r=ar(r,a+1);r=xl(r,sn(n.shape,"bool"));var l=Fn(n);return El(r,n,l)}(a,e)}}})}}),Pl=Xt({basicLSTMCell_:function(C,t,e,n,r,o){var a=Lt(C,"forgetBias","basicLSTMCell"),i=Lt(t,"lstmKernel","basicLSTMCell"),s=Lt(e,"lstmBias","basicLSTMCell"),u=Lt(n,"data","basicLSTMCell"),l=Lt(r,"c","basicLSTMCell"),c=Lt(o,"h","basicLSTMCell"),h=u.concat(c,1).matMul(i).add(s),f=h.shape[0],p=h.shape[1]/4,d=[f,p],v=h.slice([0,0],d),m=h.slice([0,p],d),g=h.slice([0,2*p],d),y=h.slice([0,3*p],d),x=v.sigmoid().mulStrict(m.tanh()).addStrict(l.mulStrict(a.add(g).sigmoid())),b=x.tanh().mulStrict(y.sigmoid());return[x,b]}}),Ll=Xt({multiRNNCell_:function(p,t,e,n){for(var r=Lt(t,"data","multiRNNCell"),o=Bt(e,"c","multiRNNCell"),a=Bt(n,"h","multiRNNCell"),i=r,d=[],u=0,m;u<p.length;u++)m=p[u](i,o[u],a[u]),d.push(m[0]),d.push(m[1]),i=m[1];var g=[],h=[];for(u=0;u<d.length;u+=2)g.push(d[u]),h.push(d[u+1]);return[g,h]}}),Wl=Xt({movingAverage_:function(p,t,e,n,r){void 0===r&&(r=!0);var d=Lt(p,"v","movingAverage"),a=Lt(t,"x","movingAverage"),i=Lt(e,"decay","movingAverage");je(d,a),Ue(g(d.shape,a.shape),function(){return"Shape mismatch in v and x"});var s=Da(1),u=s.sub(i),l=a.sub(d).mul(u);if(r){Ue(null!=n,function(){return"When using zeroDebias: true, step is required."});var m=Lt(n,"step","movingAverage");l=l.div(s.sub(pl(i,m)))}return d.add(l)}}),Ul=Xt({stridedSlice_:function(m,g,e,n,r,y,b,x,v){if(void 0===r&&(r=0),void 0===y&&(y=0),void 0===b&&(b=0),void 0===x&&(x=0),void 0===v&&(v=0),0!==b)throw new Error("ellipsis mask is not yet supported");if(0!==x)throw new Error("new axis mask is not yet supported");var C=Lt(m,"x","stridedSlice");if(n.every(function(e){return 1===e})){var t=Rn(C.shape,g,e,n,r,y,b,x,v),l=t[0],c=t[1],h=t[2],p=c.filter(function(a,t){return-1===h.indexOf(t)});return Eu(C,l,c).reshape(p)}return kt.runKernel(function(a){return a.stridedSlice(C,g,e,n,r,y,b,x,v)},{$x:C})}}),zl=Xt({topk_:function(s,i,p){void 0===i&&(i=1),void 0===p&&(p=!0);var d=Lt(s,"x","topk");if(0===d.rank)throw new Error("topk() expects the input to be of rank 1 or higher");var t=d.shape[d.shape.length-1];if(i>t)throw new Error("'k' passed to topk() must be <= the last dimension ("+t+") but got "+i);var r=kt.runKernel(function(e){return e.topk(d,i,p)},{$x:d});return{values:r[0],indices:r[1]}}}),Vl=Xt({scatterND_:function(a,t,e){var n=Lt(a,"indices","scatterND","int32"),r=Lt(t,"updates","scatterND");return kn(r,n,e),kt.runKernel(function(a){return a.scatterND(n,r,e)},{$indices:n,$updates:r})}}),Gl=Xt({fft_:function(a){Ue("complex64"===a.dtype,function(){return"The dtype for tf.spectral.fft() must be complex64 but got "+a.dtype+"."});var t=a.shape[a.shape.length-1],e=a.size/t,n=a.as2D(e,t);return kt.runKernel(function(e){return e.fft(n)},{input:a}).reshape(a.shape)}}),Hl=Xt({ifft_:function(a){Ue("complex64"===a.dtype,function(){return"The dtype for tf.spectral.ifft() must be complex64 but got "+a.dtype+"."});var t=a.shape[a.shape.length-1],e=a.size/t,n=a.as2D(e,t);return kt.runKernel(function(e){return e.ifft(n)},{input:a}).reshape(a.shape)}}),ql=Xt({rfft_:function(p,t){Ue("float32"===p.dtype,function(){return"The dtype for rfft() must be real value but got "+p.dtype});var e=p.shape[p.shape.length-1],y=p.size/e,o;if(null!=t&&t<e){var b=p.shape.map(function(){return 0}),a=p.shape.map(function(e){return e});a[p.shape.length-1]=t,o=p.slice(b,a),e=t}else if(null!=t&&t>e){var i=p.shape.map(function(e){return e});i[p.shape.length-1]=t-e,o=p.concat(pn(i),p.shape.length-1),e=t}else o=p;var s=o.zerosLike(),u=Hf(o,s).as2D(y,e),l=Gl(u),c=Cf(e/2)+1,h=gn(l),f=yn(l),d=h.split([c,e-c],h.shape.length-1),x=f.split([c,e-c],f.shape.length-1),m=o.shape.slice();return m[o.shape.length-1]=c,Hf(d[0],x[0]).reshape(m)}}),$l=Xt({irfft_:function(p){var t=p.shape[p.shape.length-1],e=p.size/t;if(2>=t){var n=p.as2D(e,t),d=Hl(n);return gn(d)}var m=[e,2*(t-1)],a=gn(p).as2D(e,t),i=yn(p).as2D(e,t),s=a.slice([0,1],[e,t-2]).reverse(1),u=i.slice([0,1],[e,t-2]).reverse(1).mul(Da(-1)),l=a.concat(s,1),c=i.concat(u,1);return n=Hf(l,c).as2D(m[0],m[1]),d=Hl(n),gn(d)}}),jl=Object.freeze({fft:Gl,ifft:Hl,rfft:ql,irfft:$l}),Kl=Xt({sparseToDense_:function(s,t,e,n){void 0===n&&(n=0);var p=Lt(s,"sparseIndices","sparseToDense","int32"),o=Lt(t,"sparseValues","sparseToDense"),a=Lt(n,"defaultValue","sparseToDense",o.dtype);return function(s,t,e,n){if("int32"!==s.dtype)throw new Error("tf.sparseToDense() expects the indices to be int32 type, but the dtype was "+s.dtype+".");if(2<s.rank)throw new Error("sparseIndices should be a scalar, vector, or matrix, but got shape "+s.shape+".");var r=0<s.rank?s.shape[0]:1,o=1<s.rank?s.shape[1]:1;if(e.length!==o)throw new Error("outputShape has incorrect number of elements:, "+e.length+", should be: "+o+".");var a=t.size;if(0!==t.rank&&(1!==t.rank||a!==r))throw new Error("sparseValues has incorrect shape "+t.shape+", should be [] or ["+r+"]");if(t.dtype!==n.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(p,o,e,a),kt.runKernel(function(n){return n.sparseToDense(p,o,e,a)},{$sparseIndices:p,$sparseValues:o,$defaultValue:a})}}),Xl=Xt({gatherND_:function(a,t){var e=Lt(t,"indices","gatherND","int32"),n=Lt(a,"x","gatherND");return kt.runKernel(function(a){return a.gatherND(n,e)},{$x:n,$indices:e})}}),Yl=Xt({dropout_:function(a,t,e,n){if(null!=e&&!g(a.shape,e))throw new Error("Non-default noise shape is not implemented yet: "+JSON.stringify(e));var r=mr(a.shape,0,1,"float32",n).greater(t);return r=r.div(gl(1,t)),a.mul(r)}}),Ql=Xt({hannWindow_:function(e){return Po(e,.5,.5)}}),tc=Xt({hammingWindow_:function(e){return Po(e,.54,.46)}}),ec=Xt({frame_:function(p,t,e,n,d){void 0===n&&(n=!1),void 0===d&&(d=0);for(var l=0,c=[];l+t<=p.size;)c.push(Eu(p,l,t)),l+=e;if(n){var i=l+t-p.size,s=Mn([Eu(p,l,t-i),dn([i],d)]);c.push(s)}return 0===c.length?tn([],[0,t]):Mn(c).as2D(c.length,t)}}),nc=Object.freeze({hannWindow:Ql,hammingWindow:tc,frame:ec}),rc;!function(e){e[e.NONE=0]="NONE",e[e.MEAN=1]="MEAN",e[e.SUM=2]="SUM",e[e.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"}(rc||(rc={}));var Kf=Xt({absoluteDifference_:function(d,t,e,n){void 0===n&&(n=rc.SUM_BY_NONZERO_WEIGHTS);var l=Lt(d,"labels","absoluteDifference"),o=Lt(t,"predictions","absoluteDifference"),a=null;null!=e&&(a=Lt(e,"weights","absoluteDifference")),p(l.shape,o.shape,"Error in absoluteDifference: ");var u=l.sub(o).abs();return oc(u,a,n)}}),oc=Xt({computeWeightedLoss_:function(p,t,e){void 0===e&&(e=rc.SUM_BY_NONZERO_WEIGHTS);var d=Lt(p,"losses","computeWeightedLoss"),r=null;null!=t&&(r=Lt(t,"weights","computeWeightedLoss"));var l=null==r?d:d.mul(r);if(e===rc.NONE)return l;if(e===rc.SUM)return l.sum();if(e===rc.MEAN){if(null==r)return l.mean();var a=d.size/r.size,i=l.sum().div(r.sum());return 1<a?i.div(Da(a)):i}if(e===rc.SUM_BY_NONZERO_WEIGHTS){if(null==r)return l.sum().div(Da(d.size));var s=r.mul(sn(d.shape)).notEqual(Da(0)).sum().toFloat();return l.sum().div(s)}throw Error("Unknown reduction: "+e)}}),ac=Xt({cosineDistance_:function(d,t,e,n,r){void 0===r&&(r=rc.SUM_BY_NONZERO_WEIGHTS);var l=Lt(d,"labels","cosineDistance"),a=Lt(t,"predictions","cosineDistance"),i=null;null!=n&&(i=Lt(n,"weights","cosineDistance")),p(l.shape,a.shape,"Error in cosineDistance: ");var c=Da(1).sub(l.mul(a).sum(e,!0));return oc(c,i,r)}}),ic=Xt({hingeLoss_:function(d,t,e,n){void 0===n&&(n=rc.SUM_BY_NONZERO_WEIGHTS);var l=Lt(d,"labels","hingeLoss"),c=Lt(t,"predictions","hingeLoss"),a=null;null!=e&&(a=Lt(e,"weights","hingeLoss")),p(l.shape,c.shape,"Error in hingeLoss: ");var h=Da(1);l=Da(2).mul(l).sub(h);var s=h.sub(l.mul(c)).relu();return oc(s,a,n)}}),sc=Xt({huberLoss_:function(d,t,e,n,m){void 0===n&&(n=1),void 0===m&&(m=rc.SUM_BY_NONZERO_WEIGHTS);var g=Lt(d,"labels","huberLoss"),a=Lt(t,"predictions","huberLoss"),i=null;null!=e&&(i=Lt(e,"weights","huberLoss")),p(g.shape,a.shape,"Error in huberLoss: ");var y=Da(n),u=a.sub(g).abs(),l=sl(u,y),c=u.sub(l),h=Da(.5).mul(l.square()).add(y.mul(c));return oc(h,i,m)}}),uc=Xt({logLoss_:function(d,t,e,n,h){void 0===n&&(n=1e-7),void 0===h&&(h=rc.SUM_BY_NONZERO_WEIGHTS);var m=Lt(d,"labels","logLoss"),a=Lt(t,"predictions","logLoss"),i=null;null!=e&&(i=Lt(e,"weights","logLoss")),p(m.shape,a.shape,"Error in logLoss: ");var g=Da(1),u=Da(n),l=m.mul(a.add(u).log()).neg().sub(g.sub(m).mul(g.sub(a).add(u).log()));return oc(l,i,h)}}),lc=Xt({meanSquaredError_:function(d,t,e,n){void 0===n&&(n=rc.SUM_BY_NONZERO_WEIGHTS);var l=Lt(d,"labels","meanSquaredError"),o=Lt(t,"predictions","meanSquaredError"),a=null;null!=e&&(a=Lt(e,"weights","meanSquaredError")),p(l.shape,o.shape,"Error in meanSquaredError: ");var u=l.squaredDifference(o);return oc(u,a,n)}}),cc=Xt({sigmoidCrossEntropy_:function(d,t,e,n,m){void 0===n&&(n=0),void 0===m&&(m=rc.SUM_BY_NONZERO_WEIGHTS);var g=Lt(d,"multiClassLabels","sigmoidCrossEntropy"),f=Lt(t,"logits","sigmoidCrossEntropy"),i=null;if(null!=e&&(i=Lt(e,"weights","sigmoidCrossEntropy")),p(g.shape,f.shape,"Error in sigmoidCrossEntropy: "),0<n){var y=Da(n),u=Da(1),l=Da(.5);g=g.mul(u.sub(y)).add(l.mul(y))}var c=function(s,t){var e=Lt(s,"labels","sigmoidCrossEntropyWithLogits"),n=Lt(t,"logits","sigmoidCrossEntropyWithLogits");p(e.shape,n.shape,"Error in sigmoidCrossEntropyWithLogits: ");var r=n.relu(),o=n.mul(e),a=n.abs().neg().exp().log1p();return r.sub(o).add(a)}(g,f);return oc(c,i,m)}}),hc=Xt({softmaxCrossEntropy_:function(d,t,e,n,m){void 0===n&&(n=0),void 0===m&&(m=rc.SUM_BY_NONZERO_WEIGHTS);var g=Lt(d,"onehotLabels","softmaxCrossEntropy"),f=Lt(t,"logits","softmaxCrossEntropy"),i=null;if(null!=e&&(i=Lt(e,"weights","softmaxCrossEntropy")),p(g.shape,f.shape,"Error in softmaxCrossEntropy: "),0<n){var y=Da(n),u=Da(1),l=Da(g.shape[1]);g=g.mul(u.sub(y)).add(y.div(l))}var c=function(a,t,s){if(void 0===s&&(s=-1),-1===s&&(s=t.rank-1),s!==t.rank-1)throw Error("Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank "+t.rank+" and dim was "+s);return On(function(n,t,e){var r=t.logSumExp([s],!0),o=t.toFloat().sub(r);return e([n,o]),{value:o.mul(n).neg().sum([s]),gradFunc:function(n,t){var e=t[0],r=t[1],o=Vt(n.shape,[s]);return[n.reshape(o).mul(e.toFloat().sub(r.exp())),n.reshape(o).mul(r.exp().sub(e.toFloat()))]}}})(a,t)}(g,f);return oc(c,i,m)}}),fc=Object.freeze({get Reduction(){return rc},absoluteDifference:Kf,computeWeightedLoss:oc,cosineDistance:ac,hingeLoss:ic,huberLoss:sc,logLoss:uc,meanSquaredError:lc,sigmoidCrossEntropy:cc,softmaxCrossEntropy:hc}),pc=Xt({gramSchmidt_:function(p){var d;if(Array.isArray(p)){d=!1,Ue(null!=p&&0<p.length,function(){return"Gram-Schmidt process: input must not be null, undefined, or empty"});for(var l=p[0].shape[0],n=function(t){Ue(p[t].shape[0]===l,function(){return"Gram-Schmidt: Non-unique lengths found in the input vectors: ("+p[t].shape[0]+" vs. "+l+")"})},r=1;r<p.length;++r)n(r)}else d=!0,p=Un(p,p.shape[0],0).map(function(e){return xr(e,[0])});Ue(p.length<=p[0].shape[0],function(){return"Gram-Schmidt: Number of vectors ("+p.length+") exceeds number of dimensions ("+p[0].shape[0]+")."});var u=[],a=p,i=function(o){u.push(kt.tidy(function(){var t=a[o];if(0<o)for(var s=0,i;s<o;++s)i=Lu(u[s].mulStrict(t)).mul(u[s]),t=t.sub(i);return t.div(_l(t,"euclidean"))}))};for(r=0;r<p.length;++r)i(r);return d?br(u,0):u}}),vc=Xt({qr_:function(s,p){if(void 0===p&&(p=!1),2>s.rank)throw new Error("qr() requires input tensor to have a rank >= 2, but got rank "+s.rank);if(2===s.rank)return Mo(s,p);var t=s.shape.slice(0,s.shape.length-2).reduce(function(a,t){return a*t}),n=Er(s.reshape([t,s.shape[s.shape.length-2],s.shape[s.shape.length-1]]),0),d=[],o=[];return n.forEach(function(e){var t=Mo(e,p),a=t[0],n=t[1];d.push(a),o.push(n)}),[br(d,0).reshape(s.shape),br(o,0).reshape(s.shape)]}}),mc=Object.freeze({gramSchmidt:pc,qr:vc}),gc=Xt({resizeBilinear_:function(p,t,d){void 0===d&&(d=!1);var e=Lt(p,"images","resizeBilinear");Ue(3===e.rank||4===e.rank,function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+e.rank+"."}),Ue(2===t.length,function(){return"Error in resizeBilinear: new shape must 2D, but got shape "+t+"."});var r=e,l=!1;3===e.rank&&(l=!0,r=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var c=t[0],i=t[1],s=kt.runKernel(function(a,t){return t([r]),a.resizeBilinear(r,c,i,d)},{batchImages:r},function(a,t){return{batchImages:function(){return kt.runKernel(function(e){return e.resizeBilinearBackprop(a,t[0],d)},{})}}});return l?s.as3D(s.shape[1],s.shape[2],s.shape[3]):s}}),xc=Xt({resizeNearestNeighbor_:function(p,t,d){void 0===d&&(d=!1);var e=Lt(p,"images","resizeNearestNeighbor");Ue(3===e.rank||4===e.rank,function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+e.rank+"."}),Ue(2===t.length,function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+t+"."}),Ue("float32"===e.dtype||"int32"===e.dtype,function(){return"`images` must have `int32` or `float32` as dtype"});var r=e,l=!1;3===e.rank&&(l=!0,r=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var c=t[0],i=t[1],s=kt.runKernel(function(a,t){return t([r]),a.resizeNearestNeighbor(r,c,i,d)},{batchImages:r},function(a,t){return{batchImages:function(){return kt.runKernel(function(e){return e.resizeNearestNeighborBackprop(a,t[0],d)},{})}}});return l?s.as3D(s.shape[1],s.shape[2],s.shape[3]):s}}),bc=Xt({nonMaxSuppression_:function(p,t,e,d,l){void 0===d&&(d=.5),void 0===l&&(l=gf);var u=Lt(p,"boxes","nonMaxSuppression"),a=Lt(t,"scores","nonMaxSuppression"),i=Vo(u,a,e,d,l);return e=i.maxOutputSize,d=i.iouThreshold,l=i.scoreThreshold,kt.runKernel(function(n){return n.nonMaxSuppression(u,a,e,d,l)},{$boxes:u})}}),wc=function(p,t,e,d,m){return void 0===d&&(d=.5),void 0===m&&(m=gf),Be(this,void 0,void 0,function(){var a,o,i,g,f,y;return Me(this,function(n){switch(n.label){case 0:return a=Lt(p,"boxes","nonMaxSuppressionAsync"),o=Lt(t,"scores","nonMaxSuppressionAsync"),i=Vo(a,o,e,d,m),e=i.maxOutputSize,d=i.iouThreshold,m=i.scoreThreshold,[4,a.data()];case 1:return g=n.sent(),[4,o.data()];case 2:return f=n.sent(),y=Gr(g,f,e,d,m),a!==p&&a.dispose(),o!==t&&o.dispose(),[2,y];}})})},Cc=Xt({cropAndResize_:function(p,t,e,n,r,d){var c=Lt(p,"image","cropAndResize","float32"),i=Lt(t,"boxes","cropAndResize","float32"),s=Lt(e,"boxInd","cropAndResize","int32");r=r||"bilinear",d=d||0;var u=i.shape[0];return Ue(4===c.rank,function(){return"Error in cropAndResize: image must be rank 4,but got rank "+c.rank+"."}),Ue(2===i.rank&&4===i.shape[1],function(){return"Error in cropAndResize: boxes must be have size ["+u+",4] but had shape "+i.shape+"."}),Ue(1===s.rank&&s.shape[0]===u,function(){return"Error in cropAndResize: boxInd must be have size ["+u+"] but had shape "+i.shape+"."}),Ue(2===n.length,function(){return"Error in cropAndResize: cropSize must be of length 2, but got length "+n.length+"."}),Ue(1<=n[0]&&1<=n[1],function(){return"cropSize must be atleast [1,1], but was "+n}),Ue("bilinear"===r||"nearest"===r,function(){return"method must be bilinear or nearest, but was "+r}),kt.runKernel(function(e){return e.cropAndResize(c,i,s,n,r,d)},{$image:c,$boxes:i})}}),Ec=Object.freeze({resizeBilinear:gc,resizeNearestNeighbor:xc,nonMaxSuppression:bc,nonMaxSuppressionAsync:wc,cropAndResize:Cc}),Rc=Xt({matMul_:function(p,t,y,S,N,I){var e;void 0===y&&(y=!1),void 0===S&&(S=!1),void 0===I&&(I="linear");var o=Lt(p,"a","fused matMul"),k=Lt(t,"b","fused matMul");e=Ke(o,k),o=e[0],k=e[1];var T=y?o.shape[o.rank-2]:o.shape[o.rank-1],l=S?k.shape[k.rank-1]:k.shape[k.rank-2],c=y?o.shape[o.rank-1]:o.shape[o.rank-2],h=S?k.shape[k.rank-2]:k.shape[k.rank-1],f=o.shape.slice(0,-2),d=k.shape.slice(0,-2),v=qe(f),m=qe(d);Ue(2<=o.rank&&2<=k.rank&&o.rank===k.rank,function(){return"Error in fused matMul: inputs must have the same rank of at least 2, got ranks "+o.rank+" and "+k.rank+"."}),Ue(g(f,d),function(){return"Error in fused matMul: outer dimensions ("+f+") and ("+d+") of Tensors with shapes "+o.shape+" and "+k.shape+" must match."}),Ue(T===l,function(){return"Error in fused matMul: inner shapes ("+T+") and ("+l+") of Tensors with shapes "+o.shape+" and "+k.shape+" and transposeA="+y+" and transposeB="+S+" must match."});var x=o.shape.slice(0,-2).concat([c,h]),w=y?o.as3D(v,T,c):o.as3D(v,c,T),C=S?k.as3D(m,h,l):k.as3D(m,l,h),E;null!=N&&tr(x,(E=Ke(E=Lt(N,"bias","fused matMul"),o)[0]).shape);var A={$a:w,$b:C};return null!=N&&(A.$bias=E),kt.runKernel(function(a,t){var e=a.fusedBatchMatMul(w,C,y,S,E,I);return t([w,C,e]),e},A,function(a,t){var e=t[0],n=t[1],r=t[2],o;if(null==I||"linear"===I)o=a;else{if("relu"!==I)throw new Error("Gradient for activation "+I+" has not been implemented yet.");o=a.mul(r.step())}var s={};return null!=N&&(s={$bias:function(){var a=o,n=Zn(E.shape,o.shape);return 0<n.length&&(a=a.sum(n)),a.reshape(E.shape)}}),y||S?!y&&S?Object.assign({$a:function(){return o.matMul(n,!1,!1)},$b:function(){return o.matMul(e,!0,!1)}},s):y&&!S?Object.assign({$a:function(){return n.matMul(o,!1,!0)},$b:function(){return e.matMul(o,!1,!1)}},s):Object.assign({$a:function(){return n.matMul(o,!0,!0)},$b:function(){return o.matMul(e,!0,!0)}},s):Object.assign({$a:function(){return o.matMul(n,!1,!0)},$b:function(){return e.matMul(o,!0,!1)}},s)}).reshape(x)}}),Ic=Xt({conv2d_:function(p,t,e,n,r,b,x,C,s){void 0===r&&(r="NHWC"),void 0===b&&(b=[1,1]),void 0===s&&(s="linear");var i=Lt(p,"x","conv2d"),l=Lt(t,"filter","conv2d"),c=i,S=!1;3===i.rank&&(S=!0,c=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),Ue(4===c.rank,function(){return"Error in fused conv2d: input must be rank 4, but got rank "+c.rank+"."}),Ue(4===l.rank,function(){return"Error in fused conv2d: filter must be rank 4, but got rank "+l.rank+"."}),null!=x&&Ue(y(n),function(){return"Error in fused conv2d: pad must be an integer when using, dimRoundingMode "+x+" but got pad "+n+"."}),Ue(c.shape[3]===l.shape[2],function(){return"Error in conv2d: depth of input ("+c.shape[3]+") must match input depth for filter "+l.shape[2]+"."}),Ue(Lr(e,b),function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+e+" and dilations '"+b+"'"}),Ue("NHWC"===r,function(){return"Error in conv2d: got dataFormat of "+r+" but only NHWC is currently supported."});var N=Nr(c.shape,l.shape,e,b,n,x),v;null!=C&&(v=Ke(v=Lt(C,"bias","fused conv2d"),i)[0],tr(N.outShape,v.shape));var I={x:c,$filter:l};null!=C&&(I.$bias=v);var m=kt.runKernel(function(a,t){var e=a.fusedConv2d(c,l,N,v,s);return t([l,c,e]),e},I,function(a,t){var r=t,i=r[0],p=r[1],d=r[2],l;if(null==s||"linear"===s)l=a;else{if("relu"!==s)throw new Error("Gradient for activation "+s+" has not been implemented yet.");l=a.mul(d.step())}Ue(zr(b),function(){return"Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+b+"'"});var u={};return null!=C&&(u={$bias:function(){var a=l,n=Zn(v.shape,l.shape);return 0<n.length&&(a=a.sum(n)),a.reshape(v.shape)}}),Object.assign({x:function(){return iu(p.shape,l,i,e,n)},$filter:function(){return au(p,l,i.shape,e,n)}},u)});return S?m.as3D(m.shape[1],m.shape[2],m.shape[3]):m}}),Sc=Object.freeze({matMul:Rc,conv2d:Ic}),Nc=Object.freeze({image:Ec,linalg:mc,losses:fc,spectral:jl,fused:Sc,signal:nc,op:Xt,batchNormalization2d:Ws,batchNormalization3d:$s,batchNormalization4d:js,batchNormalization:Ks,batchNorm:Xs,batchNorm2d:Ys,batchNorm3d:Qs,batchNorm4d:Js,complex:Hf,real:gn,imag:yn,concat:Mn,concat1d:Bn,concat2d:Pn,concat3d:Ln,concat4d:Wn,split:Un,conv1d:Zs,conv2d:ru,conv3d:ou,conv2dDerFilter:au,conv2dDerInput:iu,depthwiseConv2d:su,separableConv2d:uu,conv2dTranspose:lu,matMul:cu,dot:hu,outerProduct:fu,reverse:pu,reverse1d:du,reverse2d:vu,reverse3d:mu,reverse4d:gu,maxPool:yu,avgPool:wu,pool:Cu,slice:Eu,slice1d:Ru,slice2d:Iu,slice3d:Su,slice4d:Nu,abs:os,acos:as,acosh:is,asin:ss,asinh:us,atan:ls,atanh:cs,ceil:hs,clipByValue:fs,cos:ps,cosh:ds,erf:vs,exp:ms,expm1:gs,floor:ys,log:xs,log1p:bs,logSigmoid:ws,neg:Cs,reciprocal:Es,round:Rs,rsqrt:Is,sigmoid:Ss,sign:Ns,isNaN:ks,isInf:As,isFinite:Ts,sin:Ds,sinh:_s,softplus:Os,sqrt:Fs,square:Ms,step:Bs,tan:Ps,tanh:Ls,all:ku,any:Tu,argMax:Du,argMin:_u,logSumExp:Ou,max:Fu,mean:Mu,min:Bu,moments:Pu,sum:Lu,prod:Wu,equal:Uu,equalStrict:zu,greater:Vu,greaterEqual:Gu,greaterEqualStrict:Hu,greaterStrict:qu,less:$u,lessEqual:ju,lessEqualStrict:Ku,lessStrict:Xu,notEqual:Yu,notEqualStrict:Qu,add:Ju,addN:Zu,addStrict:tl,atan2:el,div:nl,divStrict:rl,floorDiv:ol,maximum:al,maximumStrict:il,minimum:sl,minimumStrict:ul,mod:ll,modStrict:cl,mul:hl,mulStrict:fl,pow:pl,powStrict:dl,squaredDifference:vl,squaredDifferenceStrict:ml,sub:gl,subStrict:yl,elu:Il,leakyRelu:Sl,prelu:Nl,relu:kl,selu:Al,logicalAnd:xl,logicalNot:bl,logicalOr:wl,logicalXor:Cl,where:El,whereAsync:Rl,buffer:hn,print:mn,batchToSpaceND:Jn,cast:er,clone:nr,cumsum:rr,depthToSpace:or,expandDims:ar,eye:ir,multinomial:sr,oneHot:ur,pad:lr,pad1d:cr,pad2d:hr,pad3d:fr,pad4d:pr,rand:dr,randomNormal:vr,randomUniform:mr,reshape:gr,spaceToBatchND:yr,squeeze:xr,stack:br,tile:wr,truncatedNormal:Cr,unstack:Er,setdiff1dAsync:Rr,fill:dn,linspace:ln,ones:sn,range:un,scalar:Da,tensor:Zt,tensor1d:en,tensor2d:tn,tensor3d:an,tensor4d:nn,tensor5d:rn,tensor6d:on,zeros:pn,onesLike:xn,zerosLike:Fn,transpose:Tl,softmax:Ir,logSoftmax:Kr,localResponseNormalization:Dl,norm:_l,gather:Ol,unsortedSegmentSum:Bl,basicLSTMCell:Pl,multiRNNCell:Ll,movingAverage:Wl,stridedSlice:Ul,topk:zl,scatterND:Vl,fft:Gl,ifft:Hl,rfft:ql,irfft:$l,sparseToDense:Kl,gatherND:Xl,dropout:Yl,hannWindow:Ql,hammingWindow:tc,frame:ec}),kc=function(){function e(){if(this.blockSize=48,this.firstUse=!0,_f.get("IS_BROWSER")){var e="undefined"==typeof OffscreenCanvas?"undefined"==typeof document?null:document.createElement("canvas"):new OffscreenCanvas(300,150);null!==e&&(this.fromPixels2DContext=e.getContext("2d"))}this.data=new Xr(this,kt)}return e.prototype.register=function(a,t,e){if(this.firstUse&&(this.firstUse=!1,_f.get("IS_NODE")&&Je("\n============================\nHi there \uD83D\uDC4B. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.\n============================\n")),this.data.has(a))throw new Error("Data buffer is already registered");this.data.set(a,{dtype:e})},e.prototype.write=function(a,t){if(null==t)throw new Error("MathBackendCPU.write(): values can not be null");this.data.get(a).values=t},e.prototype.fromPixels=function(i,t){if(null==i)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var e=i.data instanceof Uint8Array,o="undefined"!=typeof ImageData&&i instanceof ImageData,a="undefined"!=typeof HTMLVideoElement&&i instanceof HTMLVideoElement,s="undefined"!=typeof HTMLImageElement&&i instanceof HTMLImageElement,p,d;if(_f.get("IS_NODE")&&null==i.getContext)throw new Error("When running in node, pixels must be an HTMLCanvasElement like the one returned by the `canvas` npm package");if(null!=i.getContext)p=i.getContext("2d").getImageData(0,0,i.width,i.height).data;else if(o||e)p=i.data;else{if(!s&&!a)throw new Error("pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData or {data: Uint32Array, width: number, height: number}, but was "+i.constructor.name);if(null==this.fromPixels2DContext)throw new Error("Can't read pixels from HTMLImageElement outside the browser.");this.fromPixels2DContext.canvas.width=i.width,this.fromPixels2DContext.canvas.height=i.height,this.fromPixels2DContext.drawImage(i,0,0,i.width,i.height),p=this.fromPixels2DContext.getImageData(0,0,i.width,i.height).data}if(4===t)d=new Int32Array(p);else{var u=i.width*i.height;d=new Int32Array(u*t);for(var l=0;l<u;l++)for(var m=0;m<t;++m)d[l*t+m]=p[4*l+m]}return an(d,[i.height,i.width,t],"int32")},e.prototype.read=function(e){return Be(this,void 0,void 0,function(){return Me(this,function(){return[2,this.readSync(e)]})})},e.prototype.readSync=function(a){var t=this.data.get(a),e=t.dtype,n=t.complexTensors;return"complex64"===e?Mr(this.readSync(n.real.dataId),this.readSync(n.imag.dataId)):this.data.get(a).values},e.prototype.bufferSync=function(a){var t=this.readSync(a.dataId),e=t;if("string"===a.dtype)try{e=t.map(function(e){return H(e)})}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return hn(a.shape,a.dtype,e)},e.prototype.disposeData=function(a){if(this.data.has(a)){var t=this.data.get(a).complexTensors;null!=t&&(t.real.dispose(),t.imag.dispose()),this.data.delete(a)}},e.prototype.time=function(a){return Be(this,void 0,void 0,function(){var t;return Me(this,function(){return t=U(),a(),[2,{kernelMs:U()-t}]})})},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(a,t){var e=Lf.make(a.shape,{},"complex64");return this.data.get(e.dataId).complexTensors={real:kt.keep(a.clone()),imag:kt.keep(t.clone())},e},e.prototype.real=function(e){return this.data.get(e.dataId).complexTensors.real.clone()},e.prototype.imag=function(e){return this.data.get(e.dataId).complexTensors.imag.clone()},e.prototype.assertNotComplex=function(a,n){Array.isArray(a)||(a=[a]),a.forEach(function(e){null!=e&&Ue("complex64"!==e.dtype,function(){return n+" does not support complex64 tensors."})})},e.prototype.slice=function(p,d,e){if(this.assertNotComplex(p,"slice"),An(p.shape,d,e)){var t=Dn(d,p.strides),n=qe(e);return Zt(this.readSync(p.dataId).subarray(t,t+n),e,p.dtype)}for(var r=hn(e,p.dtype),a=this.bufferSync(p),o=0,i;o<r.size;++o)i=r.indexToLoc(o).map(function(e,t){return e+d[t]}),r.values[o]=a.get.apply(a,i);return r.toTensor()},e.prototype.stridedSlice=function(b,t,e,n,r,o,a,i,s){this.assertNotComplex(b,"stridedSlice");var u=Rn(b.shape,t,e,n,r,o,a,i,s),l=u[0],c=u[1],h=u[2],f=c.filter(function(a,t){return-1===h.indexOf(t)});if(f.some(function(e){return 0===e}))return Zt([],f);for(var p=hn(c,b.dtype),d=this.bufferSync(b),v=0;v<p.size;v++){for(var C=p.indexToLoc(v),g=Array(C.length),y=0;y<g.length;y++)g[y]=C[y]*n[y]+l[y];p.set.apply(p,[d.get.apply(d,g)].concat(C))}return p.toTensor().reshape(f)},e.prototype.unstack=function(p,t){for(var e=p.shape[t],n=Array(p.rank-1),r=0,d=0;d<p.rank;d++)d!==t&&(n[r++]=p.shape[d]);var l=Array(p.rank).fill(0),i=p.shape.slice();i[t]=1;var s=Array(e);for(d=0;d<s.length;d++)l[t]=d,s[d]=this.slice(p,l,i).reshape(n);return s},e.prototype.reverse=function(s,t){this.assertNotComplex(s,"reverse");for(var e=hn(s.shape,s.dtype),n=this.bufferSync(s),r=function(r){var o=e.indexToLoc(r),a=o.slice();t.forEach(function(t){return a[t]=s.shape[t]-1-a[t]}),e.set.apply(e,[n.get.apply(n,a)].concat(o))},o=0;o<e.size;o++)r(o);return e.toTensor()},e.prototype.concat=function(p,d){var c=this;this.assertNotComplex(p,"concat");var e=p.map(function(e){var t=qe(e.shape.slice(d));return e.as2D(-1,t)}),n=$t(e.map(function(e){return e.shape}),1),o=hn(n,p[0].dtype).values;if(1===e[0].shape[0]){var a=0;e.forEach(function(e){o.set(c.readSync(e.dataId),a),a+=e.size})}else{var h=0;e.forEach(function(a){for(var t=c.readSync(a.dataId),e=0,s=0;s<a.shape[0];++s)for(var p=s*n[1]+h,d=0;d<a.shape[1];++d)o[p+d]=t[e++];h+=a.shape[1]})}var t=$t(p.map(function(e){return e.shape}),d);return Zt(o,t,p[0].dtype)},e.prototype.neg=function(e){return this.assertNotComplex(e,"neg"),this.multiply(Da(-1),e)},e.prototype.add=function(a,t){return"complex64"===a.dtype||"complex64"===t.dtype?this.broadcastedBinaryComplexOp(a.cast("complex64"),t.cast("complex64"),function(a,t,e,n){return{real:a+e,imag:t+n}}):this.broadcastedBinaryOp(a,t,Y(a.dtype,t.dtype),function(a,t){return a+t})},e.prototype.addN=function(p){var d=this;this.assertNotComplex(p,"addN");for(var e=p.map(function(e){return d.readSync(e.dataId)}),t=hn(p[0].shape,p[0].dtype),n=t.values,r=0;r<p.length;r++)for(var o=e[r],i=0;i<n.length;i++)n[i]+=o[i];return t.toTensor()},e.prototype.subtract=function(a,t){return"complex64"===a.dtype||"complex64"===t.dtype?this.broadcastedBinaryComplexOp(a.cast("complex64"),t.cast("complex64"),function(a,t,e,n){return{real:a-e,imag:t-n}}):this.broadcastedBinaryOp(a,t,Y(a.dtype,t.dtype),function(a,t){return a-t})},e.prototype.pow=function(a,t){return this.assertNotComplex([a,t],"pow"),this.broadcastedBinaryOp(a,t,a.dtype,function(a,t){return uf(a,t)})},e.prototype.batchMatMul=function(y,t,e,n){this.assertNotComplex([y,t],"matMul");for(var r=e?y.shape[1]:y.shape[2],o=e?y.shape[2]:y.shape[1],a=n?t.shape[1]:t.shape[2],i=y.shape[0],s=this.readSync(y.dataId),u=this.readSync(t.dataId),l=e?[y.strides[0],1,y.strides[1]]:[y.strides[0],y.strides[1],1],c=l[0],h=l[1],f=l[2],p=n?[1,t.strides[1],t.strides[0]]:[t.strides[1],1,t.strides[0]],d=p[0],v=p[1],m=p[2],g=hn([i,o,a],y.dtype),x=g.values,b=this.blockSize,w=0;w<i;w++)for(var O=0;O<o;O+=b)for(var z=0;z<a;z+=b)for(var L=0;L<r;L+=b)for(var F=wf(O+b,o),S=wf(z+b,a),N=wf(L+b,r),k=O;k<F;k++)for(var B=z;B<S;B++){for(var P=0,M=L;M<N;M++)P+=s[w*c+k*h+M*f]*u[M*d+B*v+w*m];x[w*(o*a)+(k*a+B)]+=P}return g.toTensor()},e.prototype.fusedBatchMatMul=function(s,t,e,n,r,o){var a=this.batchMatMul(s,t,e,n);return r&&(a=this.add(a,r)),o&&(a=Go(this,o,a)),a},e.prototype.multiply=function(a,t){return"complex64"===a.dtype||"complex64"===t.dtype?this.broadcastedBinaryComplexOp(a.cast("complex64"),t.cast("complex64"),function(a,t,e,n){return{real:a*e-t*n,imag:a*n+t*e}}):this.broadcastedBinaryOp(a,t,Y(a.dtype,t.dtype),function(a,t){return a*t})},e.prototype.realDivide=function(a,t){return this.assertNotComplex([a,t],"realDivide"),this.broadcastedBinaryOp(a,t,"float32",function(a,t){return a/t})},e.prototype.floorDiv=function(a,t){return this.assertNotComplex([a,t],"floorDiv"),this.broadcastedBinaryOp(a,t,"int32",function(a,t){return Cf(a/t)})},e.prototype.sum=function(p,t){this.assertNotComplex(p,"sum"),Ut("sum",t,p.rank);for(var e=Wt(p.shape,t),n=e[0],r=e[1],o=pn(n,Y(p.dtype,"int32")),a=qe(r),i=this.readSync(o.dataId),s=this.readSync(p.dataId),d=0;d<i.length;++d){for(var u=d*a,c=0,m=0;m<a;++m)c+=s[u+m];i[d]=c}return o},e.prototype.prod=function(p,t){this.assertNotComplex(p,"sum");for(var e=Wt(p.shape,t),n=e[0],r=e[1],o=pn(n,Y(p.dtype,"int32")),a=qe(r),i=this.readSync(o.dataId),s=this.readSync(p.dataId),d=0;d<i.length;++d){for(var u=d*a,c=1,m=0;m<a;++m)c*=s[u+m];i[d]=c}return o},e.prototype.unsortedSegmentSum=function(p,t,d){this.assertNotComplex(p,"unsortedSegmentSum");for(var n=[],r=p.rank-t.rank,o=0;o<r;++o)t=t.expandDims(o+1);for(o=0;o<d;++o){var l=Da(o,"int32"),i=Uu(l,t).asType("float32").mul(p).sum(0);n.push(i)}return br(n)},e.prototype.argMin=function(m,t){this.assertNotComplex(m,"argMin");var e=[t];Ut("argMin",e,m.rank);for(var n=Wt(m.shape,e),r=n[0],o=n[1],a=pn(r,"int32"),i=qe(o),s=this.readSync(a.dataId),u=this.readSync(m.dataId),l=0;l<s.length;++l){for(var g=l*i,h=u[g],y=0,b=0,x;b<i;++b)x=u[g+b],x<h&&(h=x,y=b);s[l]=y}return a},e.prototype.argMax=function(m,t){this.assertNotComplex(m,"argMax");var e=[t];Ut("argMax",e,m.rank);for(var n=Wt(m.shape,e),r=n[0],o=n[1],a=pn(r,"int32"),i=qe(o),s=this.readSync(a.dataId),u=this.readSync(m.dataId),l=0;l<s.length;++l){for(var g=l*i,h=u[g],y=0,b=0,x;b<i;++b)x=u[g+b],x>h&&(h=x,y=b);s[l]=y}return a},e.prototype.cumsum=function(d,t,e,n){if(this.assertNotComplex(d,"cumsum"),t!==d.rank-1)throw new Error("backend.cumsum in CPU expects an inner-most axis="+(d.rank-1)+" but got axis="+t);for(var r=Y(d.dtype,"int32"),o=pn(d.shape,r),a=this.readSync(o.dataId),i=this.readSync(d.dataId),s=d.shape[d.rank-1],u=n?function(a,t){return a+s-t-1}:function(a,t){return a+t},l=0;l<i.length;l+=s)for(var m=0,g;m<s;m++)if(g=u(l,m),0==m)a[g]=e?0:i[g];else{var y=u(l,m-1);a[g]=e?i[y]+a[y]:i[g]+a[y]}return o},e.prototype.equal=function(a,t){return this.assertNotComplex([a,t],"equal"),this.broadcastedBinaryOp(a,t,"bool",function(a,t){return a===t?1:0})},e.prototype.notEqual=function(a,t){return this.assertNotComplex([a,t],"notEqual"),this.broadcastedBinaryOp(a,t,"bool",function(a,t){return a===t?0:1})},e.prototype.less=function(a,t){return this.assertNotComplex([a,t],"less"),this.broadcastedBinaryOp(a,t,"bool",function(a,t){return a<t?1:0})},e.prototype.lessEqual=function(a,t){return this.assertNotComplex([a,t],"lessEqual"),this.broadcastedBinaryOp(a,t,"bool",function(a,t){return a<=t?1:0})},e.prototype.greater=function(a,t){return this.assertNotComplex([a,t],"greater"),this.broadcastedBinaryOp(a,t,"bool",function(a,t){return a>t?1:0})},e.prototype.greaterEqual=function(a,t){return this.assertNotComplex([a,t],"greaterEqual"),this.broadcastedBinaryOp(a,t,"bool",function(a,t){return a>=t?1:0})},e.prototype.logicalNot=function(a){this.assertNotComplex(a,"logicalNot");for(var t=this.readSync(a.dataId),e=new Uint8Array(t.length),n=0;n<t.length;++n)e[n]=t[n]?0:1;return Lf.make(a.shape,{values:e},"bool")},e.prototype.logicalAnd=function(a,t){return this.assertNotComplex([a,t],"logicalAnd"),this.broadcastedBinaryOp(a,t,"bool",function(a,t){return a&&t})},e.prototype.logicalOr=function(a,t){return this.assertNotComplex([a,t],"logicalOr"),this.broadcastedBinaryOp(a,t,"bool",function(a,t){return a||t})},e.prototype.select=function(p,t,e){this.assertNotComplex([p,t,e],"select");for(var n=this.readSync(p.dataId),r=this.readSync(t.dataId),o=this.readSync(e.dataId),a=pn(t.shape,Y(t.dtype,e.dtype)),i=this.readSync(a.dataId),s=0,d=0===p.rank||1<p.rank||1===t.rank?1:t.shape[1],l=0;l<n.length;l++)for(var m=0;m<d;m++)i[s++]=1===n[l]?r[l]:o[l];return a},e.prototype.where=function(a){this.assertNotComplex([a],"where");var t=this.readSync(a.dataId);return Zr(a.shape,t)},e.prototype.topk=function(a,t){return this.assertNotComplex(a,"topk"),$r(this.readSync(a.dataId),a.shape,a.dtype,t)},e.prototype.min=function(d,t){this.assertNotComplex(d,"min"),Ut("min",t,d.rank);for(var e=Wt(d.shape,t),n=e[0],r=e[1],o=pn(n,d.dtype),a=qe(r),i=this.readSync(o.dataId),s=this.readSync(d.dataId),u=0;u<i.length;++u){for(var m=u*a,c=s[m],g=0,y;g<a;++g)y=s[m+g],y<c&&(c=y);i[u]=c}return o},e.prototype.minimum=function(a,t){return this.assertNotComplex([a,t],"minimum"),this.broadcastedBinaryOp(a,t,a.dtype,function(a,t){return wf(a,t)})},e.prototype.mod=function(a,t){return this.assertNotComplex([a,t],"mod"),this.broadcastedBinaryOp(a,t,a.dtype,function(a,t){var e=a%t;return 0>a&&0>t||0<=a&&0<=t?e:(e+t)%t})},e.prototype.max=function(d,t){this.assertNotComplex(d,"max"),Ut("max",t,d.rank);for(var e=Wt(d.shape,t),n=e[0],r=e[1],o=pn(n,d.dtype),a=qe(r),i=this.readSync(o.dataId),s=this.readSync(d.dataId),u=0;u<i.length;++u){for(var m=u*a,c=s[m],g=0,y;g<a;++g)y=s[m+g],y>c&&(c=y);i[u]=c}return o},e.prototype.maximum=function(a,t){return this.assertNotComplex([a,t],"maximum"),this.broadcastedBinaryOp(a,t,a.dtype,function(a,t){return Ef(a,t)})},e.prototype.all=function(d,t){this.assertNotComplex(d,"all"),Ut("all",t,d.rank);for(var e=Wt(d.shape,t),n=e[0],r=e[1],o=pn(n,d.dtype),a=qe(r),i=this.readSync(o.dataId),s=this.readSync(d.dataId),u=0;u<i.length;++u){for(var m=u*a,c=s[m],g=0,y;g<a;++g)y=s[m+g],c=c&&y;i[u]=c}return o},e.prototype.any=function(d,t){this.assertNotComplex(d,"any"),Ut("any",t,d.rank);for(var e=Wt(d.shape,t),n=e[0],r=e[1],o=pn(n,d.dtype),a=qe(r),i=this.readSync(o.dataId),s=this.readSync(d.dataId),u=0;u<i.length;++u){for(var m=u*a,c=s[m],g=0,y;g<a;++g)y=s[m+g],c=c||y;i[u]=c}return o},e.prototype.squaredDifference=function(a,t){return this.assertNotComplex([a,t],"squaredDifference"),this.broadcastedBinaryOp(a,t,a.dtype,function(a,t){var e=a-t;return e*e})},e.prototype.ceil=function(a){this.assertNotComplex(a,"ceil");for(var t=this.readSync(a.dataId),e=new Float32Array(t.length),n=0;n<t.length;++n)e[n]=kf(t[n]);return Lf.make(a.shape,{values:e})},e.prototype.floor=function(a){this.assertNotComplex(a,"floor");for(var t=this.readSync(a.dataId),e=new Float32Array(t.length),n=0;n<t.length;++n)e[n]=Cf(t[n]);return Lf.make(a.shape,{values:e})},e.prototype.sign=function(a){this.assertNotComplex(a,"x");for(var t=this.readSync(a.dataId),e=new Float32Array(t.length),n=0;n<t.length;++n)e[n]=0>t[n]?-1:0<t[n]?1:0;return Lf.make(a.shape,{values:e})},e.prototype.isNaN=function(a){var t=Number.isNaN;this.assertNotComplex(a,"x");for(var o=this.readSync(a.dataId),e=new Uint8Array(o.length),n=0;n<o.length;++n)t(o[n])&&(e[n]=1);return Lf.make(a.shape,{values:e},"bool")},e.prototype.isInf=function(a){this.assertNotComplex(a,"x");for(var t=this.readSync(a.dataId),e=new Uint8Array(t.length),n=0;n<t.length;++n)Sf(t[n])===1/0&&(e[n]=1);return Lf.make(a.shape,{values:e},"bool")},e.prototype.isFinite=function(a){this.assertNotComplex(a,"x");for(var t=this.readSync(a.dataId),e=new Uint8Array(t.length),n=0;n<t.length;++n)hf(t[n])&&(e[n]=1);return Lf.make(a.shape,{values:e},"bool")},e.prototype.round=function(a){this.assertNotComplex(a,"round");for(var t=this.readSync(a.dataId),e=new Float32Array(t.length),n=0,s;n<t.length;++n)s=Cf(t[n]),e[n]=.5>t[n]-s?Cf(t[n]):.5<t[n]-s?kf(t[n]):0==s%2?s:s+1;return Lf.make(a.shape,{values:e})},e.prototype.exp=function(a){this.assertNotComplex(a,"exp");for(var t=this.readSync(a.dataId),e=new Float32Array(t.length),n=0;n<t.length;++n)e[n]=Rf(t[n]);return Lf.make(a.shape,{values:e})},e.prototype.expm1=function(a){var t=Math.expm1;this.assertNotComplex(a,"expm1");for(var o=this.readSync(a.dataId),e=new Float32Array(o.length),n=0;n<o.length;++n)e[n]=t(o[n]);return Lf.make(a.shape,{values:e})},e.prototype.log=function(a){this.assertNotComplex(a,"log");for(var t=this.readSync(a.dataId),e=new Float32Array(t.length),n=0,s;n<t.length;++n)s=t[n],e[n]=mf(s);return Lf.make(a.shape,{values:e})},e.prototype.log1p=function(a){var t=Math.log1p;this.assertNotComplex(a,"log1p");for(var s=this.readSync(a.dataId),e=new Float32Array(s.length),n=0,i;n<s.length;++n)i=s[n],e[n]=t(i);return Lf.make(a.shape,{values:e})},e.prototype.sqrt=function(a){this.assertNotComplex(a,"sqrt");for(var t=this.readSync(a.dataId),e=new Float32Array(t.length),n=0,s;n<t.length;++n)s=t[n],e[n]=Tf(s);return Lf.make(a.shape,{values:e})},e.prototype.rsqrt=function(a){this.assertNotComplex(a,"rsqrt");for(var t=this.readSync(a.dataId),e=new Float32Array(t.length),n=0,s;n<t.length;++n)s=t[n],e[n]=1/Tf(s);return Lf.make(a.shape,{values:e})},e.prototype.square=function(a){this.assertNotComplex(a,"square");for(var t=this.readSync(a.dataId),e=new Float32Array(t.length),n=0,s;n<t.length;++n)s=t[n],e[n]=s*s;return Lf.make(a.shape,{values:e})},e.prototype.reciprocal=function(a){this.assertNotComplex(a,"reciprocal");for(var t=this.readSync(a.dataId),e=new Float32Array(t.length),n=0;n<t.length;++n)e[n]=1/t[n];return Lf.make(a.shape,{values:e})},e.prototype.linear=function(e){return e},e.prototype.relu=function(a){this.assertNotComplex(a,"relu");for(var t=pn(a.shape,a.dtype),e=this.readSync(t.dataId),n=this.readSync(a.dataId),r=0;r<n.length;++r)e[r]=Ef(0,n[r]);return t},e.prototype.prelu=function(a,t){return this.assertNotComplex([a,t],"prelu"),this.broadcastedBinaryOp(a,t,a.dtype,function(a,t){return 0>a?t*a:a})},e.prototype.elu=function(a){this.assertNotComplex(a,"elu");for(var t=new Float32Array(a.size),e=this.readSync(a.dataId),n=0,s;n<e.length;++n)s=e[n],t[n]=0<=s?s:Rf(s)-1;return Lf.make(a.shape,{values:t})},e.prototype.eluDer=function(s,t){this.assertNotComplex([s,t],"eluDer");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=this.readSync(s.dataId),o=0,p;o<n.length;++o)p=n[o],e[o]=1<=p?r[o]:r[o]*(p+1);return Lf.make(t.shape,{values:e})},e.prototype.selu=function(e){this.assertNotComplex(e,"selu");for(var t=new Float32Array(e.size),n=this.readSync(e.dataId),r=0,o;r<n.length;++r)o=n[r],t[r]=0<=o?Li*o:Pi*(Rf(o)-1);return Lf.make(e.shape,{values:t})},e.prototype.clip=function(s,t,e){this.assertNotComplex(s,"clip");for(var n=new Float32Array(s.size),r=this.readSync(s.dataId),o=0,p;o<r.length;++o)p=r[o],n[o]=p>e?e:p<t?t:p;return Lf.make(s.shape,{values:n})},e.prototype.abs=function(a){for(var t=new Float32Array(a.size),e=this.readSync(a.dataId),n=0;n<e.length;++n)t[n]=Sf(e[n]);return Lf.make(a.shape,{values:t})},e.prototype.complexAbs=function(s){for(var t=Math.hypot,i=new Float32Array(s.size),e=this.readSync(s.dataId),n=0;n<s.size;++n){var p=e[2*n],o=e[2*n+1];i[n]=t(p,o)}return Lf.make(s.shape,{values:i})},e.prototype.int=function(a){this.assertNotComplex(a,"int");for(var t=new Int32Array(a.size),e=this.readSync(a.dataId),n=0;n<e.length;++n)t[n]=e[n];return Lf.make(a.shape,{values:t},"int32")},e.prototype.sigmoid=function(a){this.assertNotComplex(a,"sigmoid");for(var t=new Float32Array(a.size),e=this.readSync(a.dataId),n=0;n<e.length;++n)t[n]=1/(1+Rf(-e[n]));return Lf.make(a.shape,{values:t})},e.prototype.softplus=function(p){this.assertNotComplex(p,"softplus");for(var t=mf(1.1920928955078125e-7)+2,e=new Float32Array(p.size),n=this.readSync(p.dataId),r=0;r<n.length;++r){var d=n[r]>-t,a=n[r]<t,i=Rf(n[r]),s=void 0;s=a?i:d?n[r]:mf(1+i),e[r]=s}return Lf.make(p.shape,{values:e})},e.prototype.sin=function(a){this.assertNotComplex(a,"sin");for(var t=new Float32Array(a.size),e=this.readSync(a.dataId),n=0;n<e.length;++n)t[n]=ff(e[n]);return Lf.make(a.shape,{values:t})},e.prototype.cos=function(a){this.assertNotComplex(a,"cos");for(var t=new Float32Array(a.size),e=this.readSync(a.dataId),n=0;n<e.length;++n)t[n]=yf(e[n]);return Lf.make(a.shape,{values:t})},e.prototype.tan=function(a){var t=Math.tan;this.assertNotComplex(a,"tan");for(var o=new Float32Array(a.size),e=this.readSync(a.dataId),n=0;n<e.length;++n)o[n]=t(e[n]);return Lf.make(a.shape,{values:o})},e.prototype.asin=function(a){var t=Math.asin;this.assertNotComplex(a,"asin");for(var o=new Float32Array(a.size),e=this.readSync(a.dataId),n=0;n<e.length;++n)o[n]=t(e[n]);return Lf.make(a.shape,{values:o})},e.prototype.acos=function(a){var t=Math.acos;this.assertNotComplex(a,"acos");for(var o=new Float32Array(a.size),e=this.readSync(a.dataId),n=0;n<e.length;++n)o[n]=t(e[n]);return Lf.make(a.shape,{values:o})},e.prototype.atan=function(a){var t=Math.atan;this.assertNotComplex(a,"atan");for(var o=new Float32Array(a.size),e=this.readSync(a.dataId),n=0;n<e.length;++n)o[n]=t(e[n]);return Lf.make(a.shape,{values:o})},e.prototype.atan2=function(a,t){return this.assertNotComplex([a,t],"atan2"),this.broadcastedBinaryOp(a,t,a.dtype,function(a,t){var e=Math.atan2;return e(a,t)})},e.prototype.sinh=function(a){var t=Math.sinh;this.assertNotComplex(a,"sinh");for(var o=new Float32Array(a.size),e=this.readSync(a.dataId),n=0;n<e.length;++n)o[n]=t(e[n]);return Lf.make(a.shape,{values:o})},e.prototype.cosh=function(a){var t=Math.cosh;this.assertNotComplex(a,"cosh");for(var o=new Float32Array(a.size),e=this.readSync(a.dataId),n=0;n<e.length;++n)o[n]=t(e[n]);return Lf.make(a.shape,{values:o})},e.prototype.tanh=function(a){this.assertNotComplex(a,"tanh");for(var t=new Float32Array(a.size),e=this.readSync(a.dataId),n=0;n<e.length;++n)t[n]=h(e[n]);return Lf.make(a.shape,{values:t})},e.prototype.asinh=function(a){var t=Math.asinh;this.assertNotComplex(a,"asinh");for(var o=new Float32Array(a.size),e=this.readSync(a.dataId),n=0;n<e.length;++n)o[n]=t(e[n]);return Lf.make(a.shape,{values:o})},e.prototype.acosh=function(a){var t=Math.acosh;this.assertNotComplex(a,"acosh");for(var o=new Float32Array(a.size),e=this.readSync(a.dataId),n=0;n<e.length;++n)o[n]=t(e[n]);return Lf.make(a.shape,{values:o})},e.prototype.atanh=function(a){var t=Math.atanh;this.assertNotComplex(a,"atanh");for(var o=new Float32Array(a.size),e=this.readSync(a.dataId),n=0;n<e.length;++n)o[n]=t(e[n]);return Lf.make(a.shape,{values:o})},e.prototype.erf=function(s){this.assertNotComplex(s,"erf");for(var t=new Float32Array(s.size),e=this.readSync(s.dataId),n=0;n<e.length;++n){var i=e[n],o=1/(1+.3275911*i);t[n]=1-((((1.061405429*o-1.453152027)*o+1.421413741)*o-.284496736)*o+.254829592)*o*Rf(-i*i)}return Lf.make(s.shape,{values:t})},e.prototype.step=function(s,t){void 0===t&&(t=0),this.assertNotComplex(s,"step");for(var i=new Float32Array(s.size),n=this.readSync(s.dataId),r=0,p;r<n.length;++r)p=n[r],i[r]=isNaN(p)?NaN:0<p?1:t;return Lf.make(s.shape,{values:i})},e.prototype.fusedConv2d=function(s,t,e,n,r){var o=this.conv2d(s,t,e);return n&&(o=this.add(o,n)),r&&(o=Go(this,r,o)),o},e.prototype.conv2d=function(z,t,e){this.assertNotComplex([z,t],"conv2d");for(var n=e.filterHeight,r=e.filterWidth,o=e.dilationHeight,a=e.dilationWidth,i=e.padInfo.left,s=e.padInfo.top,u=hn(e.outShape,z.dtype),l=this.readSync(z.dataId),c=this.readSync(t.dataId),h=u.values,f=0;f<e.batchSize;++f)for(var L=f*z.strides[0],d=f*u.strides[0],v=0;v<e.outHeight;++v)for(var F=d+v*u.strides[1],g=v*e.strideHeight-s,y=0,B;y<n;y++)if(B=g+y*o,!(0>B||B>=e.inHeight))for(var P=y*t.strides[0],w=L+B*z.strides[1],C=0;C<e.outWidth;++C)for(var M=F+C*e.outChannels,R=C*e.strideWidth-i,I=0,W;I<r;I++)if(W=R+I*a,!(0>W||W>=e.inWidth))for(var V=P+I*t.strides[1],k=w+W*e.inChannels,A=V,U=0;U<e.inChannels;++U){for(var G=l[k+U],_=0;_<e.outChannels;++_)h[M+_]+=G*c[A+_];A+=e.outChannels}return u.toTensor()},e.prototype.conv3d=function(q,t,e){for(var n=e.filterDepth,r=e.filterHeight,o=e.filterWidth,a=e.dilationDepth,i=e.dilationHeight,s=e.dilationWidth,u=e.padInfo.front,l=e.padInfo.left,c=e.padInfo.top,h=hn(e.outShape,q.dtype),f=this.readSync(q.dataId),p=this.readSync(t.dataId),d=h.values,v=0;v<e.batchSize;++v)for(var H=v*q.strides[0],g=v*h.strides[0],y=0;y<e.outDepth;++y)for(var K=g+y*h.strides[1],b=y*e.strideDepth-u,w=0,j;w<n;w++)if(j=b+w*a,!(0>j||j>=e.inDepth))for(var $=w*t.strides[0],R=H+j*q.strides[1],I=0;I<e.outHeight;++I)for(var X=K+I*h.strides[2],N=I*e.strideHeight-c,k=0,Y;k<r;k++)if(Y=N+k*i,!(0>Y||Y>=e.inHeight))for(var Z=$+k*t.strides[1],D=R+Y*q.strides[2],_=0;_<e.outWidth;++_)for(var Q=X+_*e.outChannels,F=_*e.strideWidth-l,M=0,J;M<o;M++)if(J=F+M*s,!(0>J||J>=e.inWidth))for(var ee=Z+M*t.strides[2],L=D+J*e.inChannels,W=ee,te=0;te<e.inChannels;++te){for(var ae=f[L+te],V=0;V<e.outChannels;++V)d[Q+V]+=ae*p[W+V];W+=e.outChannels}return h.toTensor()},e.prototype.conv2dDerInput=function(X,t,e){this.assertNotComplex([X,t],"conv2dDerInput");for(var n=hn(e.inShape,"float32"),r=n.values,o=n.strides,a=o[0],i=o[1],s=o[2],u=this.readSync(X.dataId),l=X.strides,c=l[0],h=l[1],f=l[2],p=this.readSync(t.dataId),d=t.strides,v=d[0],m=d[1],g=d[2],y=e.batchSize,x=e.filterHeight,b=e.filterWidth,w=e.inChannels,C=e.inHeight,E=e.inWidth,R=e.outChannels,I=e.outHeight,S=e.outWidth,N=e.strideHeight,k=e.strideWidth,A=x-1-e.padInfo.top,T=b-1-e.padInfo.left,D=0;D<y;++D)for(var Y=0;Y<w;++Y)for(var Z=0;Z<C;++Z)for(var Q=Z-A,M=Ef(0,kf(Q/N)),B=wf(I,(x+Q)/N),P=0;P<E;++P){for(var J=P-T,W=Ef(0,kf(J/k)),U=wf(S,(b+J)/k),z=0,ee=M;ee<B;++ee)for(var te=ee*N-Q,H=W;H<U;++H)for(var ae=c*D+h*ee+f*H,$=v*(x-1-te)+m*(b-1-(H*k-J))+g*Y,j=0;j<R;++j)z+=u[ae+j]*p[$+j];r[a*D+i*Z+s*P+Y]=z}return n.toTensor()},e.prototype.conv3dDerInput=function(ee,t,e){for(var n=hn(e.inShape,"float32"),r=n.values,o=n.strides,a=o[0],i=o[1],s=o[2],u=o[3],l=this.readSync(ee.dataId),c=ee.strides,h=c[0],f=c[1],p=c[2],d=c[3],v=this.readSync(t.dataId),m=t.strides,g=m[0],y=m[1],x=m[2],b=m[3],w=e.batchSize,C=e.filterDepth,E=e.filterHeight,R=e.filterWidth,I=e.inChannels,S=e.inDepth,N=e.inHeight,k=e.inWidth,A=e.outChannels,T=e.outDepth,D=e.outHeight,_=e.outWidth,O=e.strideDepth,F=e.strideHeight,M=e.strideWidth,B=C-1-e.padInfo.front,P=E-1-e.padInfo.top,L=R-1-e.padInfo.left,W=0;W<w;++W)for(var te=0;te<I;++te)for(var ae=0;ae<S;++ae)for(var ne=ae-B,G=Ef(0,kf(ne/O)),H=wf(T,(C+ne)/O),q=0;q<N;++q)for(var re=q-P,j=Ef(0,kf(re/F)),K=wf(D,(E+re)/F),X=0;X<k;++X){for(var oe=X-L,Q=Ef(0,kf(oe/M)),J=wf(_,(R+oe)/M),Z=0,se=G;se<H;++se)for(var ie=se*O-ne,pe=j;pe<K;++pe)for(var de=pe*F-re,le=Q;le<J;++le)for(var ue=h*W+f*se+p*pe+d*le,ce=g*(C-1-ie)+y*(E-1-de)+x*(R-1-(le*M-oe))+b*te,he=0;he<A;++he)Z+=l[ue+he]*v[ce+he];r[a*W+i*ae+s*q+u*X+te]=Z}return n.toTensor()},e.prototype.conv2dDerFilter=function(S,t,e){this.assertNotComplex([S,t],"conv2dDerFilter");for(var n=e.strideHeight,r=e.strideWidth,o=e.filterHeight,a=e.filterWidth,i=hn(e.filterShape,"float32"),s=e.padInfo.left,u=e.padInfo.top,l=this.bufferSync(S),c=this.bufferSync(t),h=0;h<o;++h)for(var N=Ef(0,kf((u-h)/n)),p=wf(e.outHeight,(e.inHeight+u-h)/n),d=0;d<a;++d)for(var k=Ef(0,kf((s-d)/r)),m=wf(e.outWidth,(e.inWidth+s-d)/r),g=0;g<e.inChannels;++g)for(var T=0;T<e.outChannels;++T){for(var A=0,D=0;D<e.batchSize;++D)for(var _=N;_<p;++_)for(var O=h+_*n-u,E=k,z;E<m;++E)z=d+E*r-s,A+=l.get(D,O,z,g)*c.get(D,_,E,T);i.set(A,h,d,g,T)}return i.toTensor()},e.prototype.conv3dDerFilter=function(ee,t,e){for(var n=e.strideDepth,r=e.strideHeight,o=e.strideWidth,a=e.filterDepth,i=e.filterHeight,s=e.filterWidth,u=hn(e.filterShape,"float32"),l=u.values,c=u.strides,h=c[0],f=c[1],p=c[2],d=c[3],v=this.readSync(t.dataId),m=t.strides,g=m[0],y=m[1],x=m[2],b=m[3],w=this.readSync(ee.dataId),C=ee.strides,E=C[0],R=C[1],I=C[2],S=C[3],N=e.padInfo.front,k=e.padInfo.left,A=e.padInfo.top,T=0;T<a;++T)for(var te=Ef(0,kf((N-T)/n)),_=wf(e.outDepth,(e.inDepth+N-T)/n),O=T*h,F=0;F<i;++F)for(var ae=Ef(0,kf((A-F)/r)),B=wf(e.outHeight,(e.inHeight+A-F)/r),P=F*f+O,L=0;L<s;++L)for(var ne=Ef(0,kf((k-L)/o)),U=wf(e.outWidth,(e.inWidth+k-L)/o),z=L*p+P,V=0;V<e.inChannels;++V)for(var re=V*d+z,H=0;H<e.outChannels;++H){for(var oe=0,se=0;se<e.batchSize;++se)for(var ie=se*E,K=se*g,X=te;X<_;++X)for(var pe=(T+X*n-N)*R+ie,Q=X*y+K,J=ae;J<B;++J)for(var de=(F+J*r-A)*I+pe,le=J*x+Q,ue=ne,ce;ue<U;++ue)ce=ue*b+le,oe+=w[(L+ue*o-k)*S+de+V]*v[ce+H];l[re+H]=oe}return u.toTensor()},e.prototype.depthwiseConv2D=function(z,t,e){this.assertNotComplex([z,t],"depthwiseConv2D");for(var n=e.filterHeight,r=e.filterWidth,o=e.dilationHeight,a=e.dilationWidth,i=e.padInfo.left,s=e.padInfo.top,u=e.outChannels/e.inChannels,l=hn(e.outShape,z.dtype),c=this.readSync(z.dataId),h=this.readSync(t.dataId),f=l.values,p=0;p<e.batchSize;++p)for(var L=p*z.strides[0],v=p*l.strides[0],m=0;m<e.outHeight;++m)for(var B=v+m*l.strides[1],y=m*e.strideHeight-i,x=0,P;x<n;++x)if(P=y+x*o,!(0>P||P>=e.inHeight))for(var W=x*t.strides[0],C=L+P*z.strides[1],E=0;E<e.outWidth;++E)for(var V=B+E*l.strides[2],I=E*e.strideWidth-s,S=0,U;S<r;++S)if(U=I+S*a,!(0>U||U>=e.inWidth))for(var G=W+S*t.strides[1],A=C+U*e.inChannels,T=V,q=G,H=0;H<e.inChannels;++H){for(var K=c[A+H],F=0;F<u;++F)f[T+F]+=K*h[q+F];T+=u,q+=u}return l.toTensor()},e.prototype.depthwiseConv2DDerInput=function(Y,t,e){this.assertNotComplex([Y,t],"depthwiseConv2DDerInput");for(var n=hn(e.inShape,"float32"),r=n.values,o=n.strides,a=o[0],i=o[1],s=o[2],u=this.readSync(Y.dataId),l=Y.strides,c=l[0],h=l[1],f=l[2],p=this.readSync(t.dataId),d=t.strides,v=d[0],m=d[1],g=d[2],y=e.batchSize,x=e.filterHeight,b=e.filterWidth,w=e.inChannels,C=e.inHeight,E=e.inWidth,R=e.outChannels,I=e.outHeight,S=e.outWidth,N=e.strideHeight,k=e.strideWidth,A=x-1-e.padInfo.top,T=b-1-e.padInfo.left,D=R/w,_=0;_<y;++_)for(var Z=0;Z<w;++Z)for(var Q=0;Q<C;++Q)for(var J=Q-A,B=Ef(0,kf(J/N)),P=wf(I,(x+J)/N),L=0;L<E;++L){for(var ee=L-T,U=Ef(0,kf(ee/k)),z=wf(S,(b+ee)/k),V=0,te=B;te<P;++te)for(var ae=te*N-J,q=U;q<z;++q)for(var ne=c*_+h*te+f*q,j=v*(x-1-ae)+m*(b-1-(q*k-ee))+g*Z,K=0;K<D;++K)V+=u[ne+(Z*D+K)]*p[j+K];r[a*_+i*Q+s*L+Z]=V}return n.toTensor()},e.prototype.depthwiseConv2DDerFilter=function(k,t,e){var n=Math.trunc;this.assertNotComplex([k,t],"depthwiseConv2DDerFilter");for(var T=e.strideHeight,r=e.strideWidth,o=e.filterHeight,a=e.filterWidth,i=hn(e.filterShape,"float32"),s=e.padInfo.left,u=e.padInfo.top,l=e.outChannels/e.inChannels,c=this.bufferSync(k),h=this.bufferSync(t),f=0;f<o;++f)for(var A=Ef(0,kf((u-f)/T)),d=wf(e.outHeight,(e.inHeight+u-f)/T),v=0;v<a;++v)for(var D=Ef(0,kf((s-v)/r)),g=wf(e.outWidth,(e.inWidth+s-v)/r),y=0;y<e.outChannels;++y){for(var _=n(y/l),b=y%l,w=0,O=0;O<e.batchSize;++O)for(var z=A;z<d;++z)for(var L=f+z*T-u,I=D,F;I<g;++I)F=v+I*r-s,w+=c.get(O,L,F,_)*h.get(O,z,I,y);i.set(w,f,v,_,b)}return i.toTensor()},e.prototype.tile=function(a,t){return this.assertNotComplex(a,"tile"),jr(this.bufferSync(a),t)},e.prototype.pad=function(p,t,e){this.assertNotComplex(p,"pad");var n=t.map(function(t,e){return t[0]+p.shape[e]+t[1]}),r=t.map(function(e){return e[0]}),o=this.bufferSync(p),a=hn(n,p.dtype);0!==e&&a.values.fill(e);for(var i=0;i<p.size;i++){var d=o.indexToLoc(i),u=d.map(function(a,t){return a+r[t]});a.set.apply(a,[o.get.apply(o,d)].concat(u))}return a.toTensor()},e.prototype.transpose=function(p,t){this.assertNotComplex(p,"transpose");for(var e=Array(p.rank),n=0;n<e.length;n++)e[n]=p.shape[t[n]];var d=this.readSync(p.dataId),o=hn(e,p.dtype),a=this.bufferSync(p);for(n=0;n<p.size;++n){for(var i=a.indexToLoc(n),s=Array(i.length),u=0;u<s.length;u++)s[u]=i[t[u]];var h=o.locToIndex(s);o.values[h]=d[n]}return o.toTensor()},e.prototype.gather=function(p,t,e){this.assertNotComplex([p,t],"gather");var n=p.shape.slice(),r=this.readSync(t.dataId);n[e]=r.length;for(var o=hn(n,p.dtype),a=this.bufferSync(p),i=0;i<o.size;++i){var d=o.indexToLoc(i),u=d.slice();u[e]=r[d[e]];var l=a.locToIndex(u);o.values[i]=a.values[l]}return o.toTensor()},e.prototype.batchToSpaceND=function(p,t,e){this.assertNotComplex([p],"batchToSpaceND");var n=t.reduce(function(a,t){return a*t}),r=fn(p.shape,t,n),o=bn(r.length,t.length),a=vn(p.shape,t,n),i=Cn(e,t.length),s=Sn(a,e,t.length);return p.reshape(r).transpose(o).reshape(a).slice(i,s)},e.prototype.spaceToBatchND=function(p,t,e){this.assertNotComplex([p],"spaceToBatchND");var n=t.reduce(function(a,t){return a*t}),r=[[0,0]];r.push.apply(r,e);for(var o=1+t.length;o<p.shape.length;++o)r.push([0,0]);var d=p.pad(r),i=fn(d.shape,t,n,!1),s=bn(i.length,t.length,!1),u=vn(d.shape,t,n,!1);return d.reshape(i).transpose(s).reshape(u)},e.prototype.pool=function(z,t,e){var n=Number.POSITIVE_INFINITY;this.assertNotComplex(z,"pool");for(var L=t.strideHeight,r=t.strideWidth,o=t.dilationHeight,a=t.dilationWidth,i=t.effectiveFilterHeight,s=t.effectiveFilterWidth,u=t.padInfo.top,l=t.padInfo.left,c="max"===e?gf:n,h=this.readSync(z.dataId),f=hn(t.outShape,z.dtype),p=f.values,d=t.outShape[1]*t.outShape[2]*t.outShape[3],v=t.outShape[2]*t.outShape[3],m=t.outShape[3],g=0;g<t.batchSize;++g)for(var W=g*d,x=g*z.strides[0],b=0;b<t.inChannels;++b)for(var V=0;V<t.outHeight;++V)for(var U=V*L-u,E=Ef(0,U),R=wf(t.inHeight,i+U),I=W+V*v,S=0;S<t.outWidth;++S){for(var G=S*r-l,k=Ef(0,G),A=wf(t.inWidth,s+G),T=c,q=0,H=0,K=E;K<R;K+=o){for(var j=x+K*z.strides[1],M=k,$;M<A;M+=a)$=h[j+M*z.strides[2]+b],"max"===e&&$>T?T=$:"avg"==e&&(q+=$,H++);if(isNaN(T))break}p[I+S*m+b]="avg"===e?q/H:T}return f.toTensor()},e.prototype.maxPool=function(a,t){return this.pool(a,t,"max")},e.prototype.maxPoolPositions=function(T,t){for(var e=hn(t.outShape,"int32"),n=t.strideHeight,r=t.strideWidth,o=t.dilationHeight,a=t.dilationWidth,i=t.effectiveFilterHeight,s=t.effectiveFilterWidth,u=t.padInfo.top,l=t.padInfo.left,c=this.bufferSync(T),h=0;h<t.batchSize;++h)for(var A=0;A<t.inChannels;++A)for(var D=0;D<t.outHeight;++D){for(var _=D*n-u,v=_;0>v;)v+=o;for(var O=wf(t.inHeight,i+_),g=0;g<t.outWidth;++g){for(var z=g*r-l,x=z;0>x;)x+=a;for(var L=wf(t.inWidth,s+z),w=gf,F=-1,B=v;B<O;B+=o)for(var P=B-_,I=x;I<L;I+=a){var M=I-z,N=c.get(h,B,I,A);N>w&&(w=N,F=P*s+M)}e.set(F,h,D,g,A)}}return e.toTensor()},e.prototype.maxPoolBackprop=function(k,t,e,n){this.assertNotComplex([t,e],"maxPoolBackprop");for(var r=this.maxPoolPositions(t,n),o=n.strideHeight,a=n.strideWidth,i=n.dilationHeight,s=n.dilationWidth,u=n.effectiveFilterHeight,l=n.effectiveFilterWidth,c=l-1-n.padInfo.left,h=u-1-n.padInfo.top,f=hn(t.shape,"float32"),p=this.bufferSync(r),d=this.bufferSync(k),v=0;v<n.batchSize;++v)for(var T=0;T<n.inChannels;++T)for(var A=0;A<n.inHeight;++A)for(var D=0;D<n.inWidth;++D){for(var _=A-h,b=D-c,w=0,O=0,z;O<u;O+=i)if(z=(_+O)/o,!(0>z||z>=n.outHeight||Cf(z)!==z))for(var L=0,F;L<l;L+=s)if(F=(b+L)/a,!(0>F||F>=n.outWidth||Cf(F)!==F)){var B=u*l-1-p.get(v,z,F,T)===O*l+L?1:0;0!=B&&(w+=d.get(v,z,F,T)*B)}f.set(w,v,A,D,T)}return f.toTensor()},e.prototype.avgPoolBackprop=function(d,t,e){this.assertNotComplex([d,t],"avgPoolBackprop");for(var n=e.strideHeight,r=e.strideWidth,o=e.filterHeight,a=e.filterWidth,i=e.dilationHeight,s=e.dilationWidth,u=e.effectiveFilterHeight,l=e.effectiveFilterWidth,c=l-1-e.padInfo.left,h=u-1-e.padInfo.top,f=hn(t.shape,"float32"),p=this.bufferSync(d),v=0;v<e.batchSize;++v)for(var N=0;N<e.inChannels;++N)for(var k=0;k<e.inHeight;++k)for(var T=0;T<e.inWidth;++T){for(var A=k-h,b=T-c,w=0,D=0,_;D<u;D+=i)if(_=(A+D)/n,!(0>_||_>=e.outHeight||Cf(_)!==_))for(var O=0,z;O<l;O+=s)z=(b+O)/r,0>z||z>=e.outWidth||Cf(z)!==z||(w+=p.get(v,_,z,N));f.set(w*(1/(o*a)),v,k,T,N)}return f.toTensor()},e.prototype.cast=function(a,t){return Fr(a,t,this)},e.prototype.reshape=function(a,t){return Br(a,t)},e.prototype.avgPool=function(a,t){return this.assertNotComplex(a,"avgPool"),this.pool(a,t,"avg").toFloat()},e.prototype.resizeBilinear=function(g,t,e,n){this.assertNotComplex(g,"resizeBilinear");for(var r=g.shape,o=r[0],a=r[1],i=r[2],s=r[3],u=this.readSync(g.dataId),l=new Float32Array(qe([o,t,e,s])),c=[n&&1<t?a-1:a,n&&1<e?i-1:i],h=[n&&1<t?t-1:t,n&&1<e?e-1:e],f=0,w=c[0]/h[0],d=c[1]/h[1],v=0;v<o;v++)for(var z=0;z<t;z++)for(var W=w*z,x=Cf(W),b=wf(a-1,kf(W)),C=v*g.strides[0]+x*g.strides[1],E=v*g.strides[0]+b*g.strides[1],R=0;R<e;R++)for(var V=d*R,S=Cf(V),N=V-S,k=wf(i-1,kf(V)),A=C+S*g.strides[2],T=E+S*g.strides[2],D=C+ +k*g.strides[2],_=E+k*g.strides[2],O=0;O<s;O++){var U=u[A+O],M=u[T+O],B=U+(u[D+O]-U)*N,P=B+(M+(u[_+O]-M)*N-B)*(W-x);l[f++]=P}return Zt(l,[o,t,e,s])},e.prototype.resizeBilinearBackprop=function(z,t,e){this.assertNotComplex([z,t],"resizeBilinearBackprop");for(var n=t.shape,r=n[0],o=n[1],a=n[2],i=n[3],s=z.shape,u=s[1],l=s[2],c=new Float32Array(r*o*a*i),h=[e&&1<u?o-1:o,e&&1<l?a-1:a],f=[e&&1<u?u-1:u,e&&1<l?l-1:l],p=h[0]/f[0],d=h[1]/f[1],v=this.readSync(z.dataId),m=0,L=0;L<r;L++)for(var W=L*t.strides[0],x=0;x<u;x++)for(var U=x*p,w=Cf(U),C=wf(kf(U),o-1),E=W+w*t.strides[1],R=W+C*t.strides[1],I=U-w,S=1-I,N=0;N<l;N++)for(var q=N*d,A=Cf(q),T=wf(kf(q),a-1),D=q-A,_=1-D,O=E+A*t.strides[2],F=E+T*t.strides[2],M=R+A*t.strides[2],B=R+T*t.strides[2],P=0,H;P<i;P++)H=v[m++],c[O+P]+=H*(S*_),c[F+P]+=H*(S*D),c[M+P]+=H*(I*_),c[B+P]+=H*(I*D);return nn(c,[r,a,o,i],t.dtype)},e.prototype.resizeNearestNeighbor=function(S,t,e,n){this.assertNotComplex(S,"resizeNearestNeighbor");for(var r=S.shape,o=r[0],a=r[1],i=r[2],s=r[3],u=this.readSync(S.dataId),l=new Float32Array(o*t*e*s),c=[n&&1<t?a-1:a,n&&1<e?i-1:i],h=[n&&1<t?t-1:t,n&&1<e?e-1:e],f=c[0]/h[0],p=c[1]/h[1],d=0,N=0;N<o;N++)for(var k=N*S.strides[0],g=0;g<t;g++)for(var T=f*g,x=k+wf(a-1,n?If(T):Cf(T))*S.strides[1],b=0;b<e;b++)for(var A=p*b,C=x+wf(i-1,n?If(A):Cf(A))*S.strides[2],E=0,D;E<s;E++)D=u[C+E],l[d++]=D;return Zt(l,[o,t,e,s],S.dtype)},e.prototype.resizeNearestNeighborBackprop=function(z,t,e){this.assertNotComplex([z,t],"resizeNearestNeighborBackprop");for(var n=t.shape,r=n[0],o=n[1],a=n[2],i=n[3],s=z.shape,u=s[1],l=s[2],c=new Float32Array(r*o*a*i),h=this.readSync(z.dataId),f=[e&&1<u?o-1:o,e&&1<l?a-1:a],p=[e&&1<u?u-1:u,e&&1<l?l-1:l],d=f[0]/p[0],v=f[1]/p[1],m=1/d,g=1/v,y=2*kf(m)+2,x=2*kf(g)+2,b=0;b<r;b++)for(var V=b*t.strides[0],C=0;C<o;C++)for(var G=V+C*t.strides[1],R=Cf(C*m),I=Cf(R-y/2),S=0;S<a;S++)for(var q=G+S*t.strides[2],k=Cf(S*g),A=Cf(k-x/2),T=0;T<i;T++){for(var H=0,K=0,j;K<y;K++)if(j=K+I,!(0>j||j>=u)){var $=V+j*z.strides[1],M=j*d;if(C===wf(o-1,e?If(M):Cf(M)))for(var B=0,X;B<x;B++)if(X=B+A,!(0>X||X>=l)){var Y=$+X*z.strides[2],W=X*v;S===wf(a-1,e?If(W):Cf(W))&&(H+=h[Y+T])}}c[q+T]=H}return nn(c,t.shape,t.dtype)},e.prototype.batchNormalization=function(C,t,e,n,r,o){this.assertNotComplex([C,t,e,r,o],"batchNorm");for(var a=this.readSync(C.dataId),i=this.readSync(t.dataId),s=this.readSync(e.dataId),u=r?this.readSync(r.dataId):new Float32Array([1]),l=o?this.readSync(o.dataId):new Float32Array([0]),c=new Float32Array(a.length),h=l.length,f=u.length,p=s.length,d=i.length,v=0,S=0,N=0,I=0,k=0;k<a.length;++k)c[k]=l[v++]+(a[k]-i[S++])*u[N++]/Tf(s[I++]+n),v>=h&&(v=0),S>=d&&(S=0),N>=f&&(N=0),I>=p&&(I=0);return nn(c,C.shape)},e.prototype.localResponseNormalization4D=function(d,m,e,t,n){function r(e){for(var t=e%c,n=e-t+Ef(0,t-m),s=e-t+wf(t+m,a),o=0,p;n<=s;n++)p=i[n],o+=p*p;return o}this.assertNotComplex(d,"localResponseNormalization4D");for(var c=d.shape[3],a=c-1,i=this.readSync(d.dataId),o=d.size,s=new Float32Array(o),l=0;l<o;l++){var u=r(l),g=i[l]*uf(e+t*u,-n);s[l]=g}return nn(s,d.shape)},e.prototype.LRNGrad=function(b,t,e,n,r,o,a){this.assertNotComplex(b,"LRNGrad");for(var i=b.shape[3],s=this.readSync(b.dataId),u=this.readSync(t.dataId),l=this.readSync(e.dataId),c=new Float32Array(b.size),h=b.size,f=0;f<h;f++){for(var C=f%i,d=f-C+Ef(0,C-n),v=f-C+wf(i,C+n+1),m=0,S=d;S<v;S++)m+=uf(u[S],2);for(m=o*m+r,S=d;S<v;S++){var N=-2*o*a*u[S]*l[f]/m;f===S&&(N+=uf(m,-a)),N*=s[f],c[S]+=N}}return nn(c,b.shape)},e.prototype.multinomial=function(b,t,e,n){this.assertNotComplex(b,"multinomial");for(var r=t?b:Ir(b),o=r.shape[0],a=r.shape[1],i=pn([o,e],"int32"),s=this.readSync(i.dataId),u=this.readSync(r.dataId),l=0;l<o;++l){var x=l*a,h=new Float32Array(a-1);h[0]=u[x];for(var f=1;f<h.length;++f)h[f]=h[f-1]+u[x+f];for(var C=Xn(n.toString()),d=l*e,v=0,S;v<e;++v){S=C(),s[d+v]=h.length;for(var N=0;N<h.length;N++)if(S<h[N]){s[d+v]=N;break}}}return i},e.prototype.oneHot=function(s,t,e,n){this.assertNotComplex(s,"oneHot");var r=new Float32Array(s.size*t);r.fill(n);for(var o=this.readSync(s.dataId),a=0;a<s.size;++a)0<=o[a]&&o[a]<t&&(r[a*t+o[a]]=e);return tn(r,[s.size,t],"int32")},e.prototype.nonMaxSuppression=function(a,t,e,n,r){return this.assertNotComplex(a,"nonMaxSuppression"),Gr(this.readSync(a.dataId),this.readSync(t.dataId),e,n,r)},e.prototype.fft=function(e){return this.fftBatch(e,!1)},e.prototype.ifft=function(e){return this.fftBatch(e,!0)},e.prototype.fftBatch=function(m,t){for(var e=m.shape[0],n=m.shape[1],r=hn(m.shape,"float32"),o=hn(m.shape,"float32"),a=gn(m).as2D(e,n),i=yn(m).as2D(e,n),s=0;s<e;s++)for(var g=a.slice([s,0],[1,n]),l=i.slice([s,0],[1,n]),c=Hf(g,l),h=this.readSync(this.fftImpl(c,t).dataId),f=0,y;f<n;f++)y=Wr(h,f),r.values[s*n+f]=y.real,o.values[s*n+f]=y.imag;return Hf(r.toTensor(),o.toTensor()).as2D(e,n)},e.prototype.fftImpl=function(s,t){var e=s.as1D(),n=e.size;if(this.isExponentOf2(n)){var r=this.fftRadix2(e,n,t).as2D(s.shape[0],s.shape[1]);return t&&(r=Hf(gn(r).div(Da(n)),yn(r).div(Da(n)))),r}var p=this.readSync(s.dataId),a=function(a){for(var t=new Float32Array(a.length/2),e=new Float32Array(a.length/2),n=0;n<a.length;n+=2)t[n/2]=a[n],e[n/2]=a[n+1];return{real:t,imag:e}}(this.fourierTransformByMatmul(p,n,t));return Hf(a.real,a.imag).as2D(s.shape[0],s.shape[1])},e.prototype.isExponentOf2=function(e){return 0==(e&e-1)},e.prototype.fftRadix2=function(m,t,e){if(1===t)return m;var n=this.readSync(m.dataId),r=t/2,o=function(a){for(var t=kf(a.length/4),e=new Float32Array(t),n=new Float32Array(t),r=0;r<a.length;r+=4)e[Cf(r/4)]=a[r],n[Cf(r/4)]=a[r+1];return{real:e,imag:n}}(n),a=Hf(o.real,o.imag).as1D(),g=function(a){for(var t=Cf(a.length/4),e=new Float32Array(t),n=new Float32Array(t),r=2;r<a.length;r+=4)e[Cf(r/4)]=a[r],n[Cf(r/4)]=a[r+1];return{real:e,imag:n}}(n),s=Hf(g.real,g.imag).as1D();a=this.fftRadix2(a,r,e),s=this.fftRadix2(s,r,e);var y=function(s,t){for(var e=new Float32Array(s/2),n=new Float32Array(s/2),r=0,i;r<kf(s/2);r++)i=(t?2:-2)*bf*(r/s),e[r]=yf(i),n[r]=ff(i);return{real:e,imag:n}}(t,e),l=Hf(y.real,y.imag).mul(s),c=a.add(l),h=a.sub(l),f=gn(c).concat(gn(h)),p=yn(c).concat(yn(h));return Hf(f,p).as1D()},e.prototype.fourierTransformByMatmul=function(p,t,e){for(var n=new Float32Array(2*t),r=0;r<t;r++){for(var d=0,c=0,h=0;h<t;h++){var m=Ur(r*h,t,e),u=Wr(p,h);d+=u.real*m.real-u.imag*m.imag,c+=u.real*m.imag+u.imag*m.real}e&&(d/=t,c/=t),Vr(n,d,c,r)}return n},e.prototype.depthToSpace=function(p,t,e){Ue("NHWC"===e,function(){return"Only NHWC dataFormat supported on CPU for depthToSpace. Got "+e}),Ue(1<t,function(){return"blockSize should be > 1 for depthToSpace, but was: "+t});for(var n=p.shape[0],r=p.shape[1],o=p.shape[2],a=p.shape[3],i=r*t,s=o*t,u=a/(t*t),l=this.readSync(p.dataId),c=new Float32Array(n*i*s*u),h=0,S=0;S<n;++S)for(var N=0;N<i;++N)for(var I=Cf(N/t),m=N%t,g=0;g<s;++g)for(var k=Cf(g/t),x=(m*t+g%t)*u,b=0,T;b<u;++b)T=b+x+a*(k+o*(I+r*S)),c[h++]=l[T];return nn(c,[n,i,s,u])},e.prototype.broadcastedBinaryOp=function(g,t,e,y){var n=tr(g.shape,t.shape),r=hn(n,e),a=this.readSync(g.dataId),i=this.readSync(t.dataId),s=Vn(g.shape,n),u=Vn(t.shape,n),l=r.values;if(0===s.length+u.length)for(var o=0;o<l.length;++o)l[o]=y(a[o%a.length],i[o%i.length]);else{var c=this.bufferSync(g),f=this.bufferSync(t),p=function(e){var n=r.indexToLoc(e),o=n.slice(-g.rank);s.forEach(function(e){return o[e]=0});var p=c.locToIndex(o),d=n.slice(-t.rank);u.forEach(function(e){return d[e]=0});var h=f.locToIndex(d);l[e]=y(a[p],i[h])};for(o=0;o<l.length;++o)p(o)}return r.toTensor()},e.prototype.broadcastedBinaryComplexOp=function(b,t,e){var n=tr(b.shape,t.shape),x=hn(n,"float32"),r=hn(n,"float32"),o=this.readSync(b.dataId),i=this.readSync(t.dataId),s=Vn(b.shape,n),u=Vn(t.shape,n),l=x.values,c=r.values;if(0===s.length+u.length)for(var a=0;a<l.length;a++){var h=a%o.length,p=a%i.length,d=e(o[2*h],o[2*h+1],i[2*p],i[2*p+1]);l[a]=d.real,c[a]=d.imag}else{var C=this.bufferSync(this.data.get(b.dataId).complexTensors.real),m=this.bufferSync(this.data.get(t.dataId).complexTensors.real),g=function(n){var r=x.indexToLoc(n),a=r.slice(-b.rank);s.forEach(function(e){return a[e]=0});var h=C.locToIndex(a),p=r.slice(-t.rank);u.forEach(function(e){return p[e]=0});var d=m.locToIndex(p),g=e(o[2*h],o[2*h+1],i[2*d],i[2*d+1]);l[n]=g.real,c[n]=g.imag};for(a=0;a<l.length;a++)g(a)}return this.complex(x.toTensor(),r.toTensor())},e.prototype.split=function(a,t,e){return Hr(a,t,e)},e.prototype.dispose=function(){},e.prototype.floatPrecision=function(){return 32},e.prototype.epsilon=function(){return 1e-7},e.prototype.cropAndResize=function(Y,t,e,n,r,o){for(var a=Y.shape,i=a[0],s=a[1],u=a[2],l=a[3],c=t.shape[0],h=n[0],f=n[1],p=hn([c,h,f,l],Y.dtype),d=this.readSync(t.dataId),v=this.readSync(e.dataId),m=this.readSync(Y.dataId),g=Y.strides,y=p.strides,x=0;x<c;x++){var Z=4*x,w=d[Z],C=d[Z+1],E=d[Z+2],R=d[Z+3],I=v[x];if(!(I>=i))for(var S=1<h?(E-w)*(s-1)/(h-1):0,N=1<f?(R-C)*(u-1)/(f-1):0,k=0,Q;k<h;k++)if(Q=1<h?w*(s-1)+k*S:.5*(w+E)*(s-1),0>Q||Q>s-1)for(var J=0;J<f;J++)for(var ee=0,te;ee<l;ee++)te=ee+J*y[2]+k*y[1]+x*y[0],p.values[te]=o;else if("bilinear"===r){var ae=Cf(Q),F=kf(Q),M=Q-ae;for(J=0;J<f;J++)if(0>(H=1<f?C*(u-1)+J*N:.5*(C+R)*(u-1))||H>u-1)for(ee=0;ee<l;ee++)te=ee+J*y[2]+k*y[1]+x*y[0],p.values[te]=o;else{var B=Cf(H),P=kf(H),L=H-B;for(ee=0;ee<l;ee++){var W=m[te=ee+B*g[2]+ae*g[1]+I*g[0]],U=m[te=ee+P*g[2]+ae*g[1]+I*g[0]],z=m[te=ee+B*g[2]+F*g[1]+I*g[0]],V=W+(U-W)*L,G=z+(m[te=ee+P*g[2]+F*g[1]+I*g[0]]-z)*L;te=ee+J*y[2]+k*y[1]+x*y[0],p.values[te]=V+(G-V)*M}}}else for(J=0;J<f;++J){var H;if(0>(H=1<f?C*(u-1)+J*N:.5*(C+R)*(u-1))||H>u-1)for(ee=0;ee<l;ee++)te=ee+J*y[2]+k*y[1]+x*y[0],p.values[te]=o;else{var ne=If(H),$=If(Q);for(ee=0;ee<l;ee++){var j=ee+ne*g[2]+$*g[1]+I*g[0],K=ee+J*y[2]+k*y[1]+x*y[0];p.values[K]=m[j]}}}}return p.toTensor()},e.prototype.sparseToDense=function(p,t,e,n){var r=Tn(0,p,e),o=r.sliceRank,a=r.numUpdates,i=r.sliceSize,s=r.strides,d=r.outputSize;return this.scatter(p,t,e,d,i,a,o,s,n,!1)},e.prototype.gatherND=function(y,t){var e=t.shape,n=e[e.length-1],r=Nn(y,t),o=r[0],a=r[1],i=r[2],s=r[3];if(0===a)return Zt([],o,y.dtype);for(var u=new Z([a,i],y.dtype),l=this.readSync(t.dataId),c=this.readSync(y.dataId),h=0;h<a;h++){for(var b=[],p=0,x=0,C;x<n;x++)C=l[h*n+x],p+=C*s[x],b.push(C);if(0>p||p>=y.size/i)throw new Error("Invalid indices:  does not index into "+y.shape);for(var S=0;S<i;S++)u.values[h*i+S]=c[p*i+S]}return u.toTensor().reshape(o)},e.prototype.scatterND=function(p,t,e){var n=Tn(0,p,e),r=n.sliceRank,o=n.numUpdates,a=n.sliceSize,i=n.strides,s=n.outputSize,d=Da(0);return this.scatter(p,t,e,s,a,o,r,i,d,!0)},e.prototype.fill=function(a,t,e){var o=N(e=e||L(t),qe(a));return o.fill(t),Lf.make(a,{values:o},e)},e.prototype.onesLike=function(e){if("string"===e.dtype)throw new Error("onesLike is not supported for string tensors");return this.fill(e.shape,1,e.dtype)},e.prototype.zerosLike=function(a){var t=N(a.dtype,qe(a.shape));return Lf.make(a.shape,{values:t},a.dtype)},e.prototype.linspace=function(a,t,e){return Pr(a,t,e)},e.prototype.scatter=function(c,t,e,n,r,o,a,i,s,u){var l=this.readSync(c.dataId),h=this.readSync(t.dataId);if(0===n)return Zt([],e,t.dtype);var f=new Z([n/r,r],t.dtype);f.values.fill(this.readSync(s.dataId)[0]);for(var p=0;p<o;p++){for(var b=[],v=0,C=0,S;C<a;C++)S=l[p*a+C],b.push(S),v+=S*i[C];if(0>v||v>=n/r)throw new Error("Invalid indices:  does not index into "+e);for(var N=0;N<r;N++)u?f.values[v*r+N]+=h[p*r+N]:f.values[v*r+N]=0===t.rank?h[0]:h[p*r+N]}return f.toTensor().reshape(e)},e}();kt.registerBackend("cpu",function(){return new kc},1);var Tc=function(){function e(){this.textEncoder=new TextEncoder}return e.prototype.fetch=function(a,t){return fetch(a,t)},e.prototype.now=function(){return performance.now()},e.prototype.encode=function(a,t){if("utf-8"!==t&&"utf8"!==t)throw new Error("Browser's encoder only supports utf-8, but got "+t);return this.textEncoder.encode(a)},e.prototype.decode=function(a,t){return new TextDecoder(t).decode(a)},e}();_f.get("IS_BROWSER")&&_f.setPlatform("browser",new Tc);var Dc=function(){return require("node-fetch")},Oc=function(){function e(){this.util=require("util"),this.textEncoder=new this.util.TextEncoder}return e.prototype.fetch=function(a,t){return null==_f.global.fetch?(null==Fc&&(Fc=Dc()),Fc(a,t)):_f.global.fetch(a,t)},e.prototype.now=function(){var e=process.hrtime();return 1e3*e[0]+e[1]/1e6},e.prototype.encode=function(a,t){if("utf-8"!==t&&"utf8"!==t)throw new Error("Node built-in encoder only supports utf-8, but got "+t);return this.textEncoder.encode(a)},e.prototype.decode=function(a,t){return 0===a.length?"":new this.util.TextDecoder(t).decode(a)},e}(),Fc;_f.get("IS_NODE")&&_f.setPlatform("node",new Oc);var jf={float32:4,int32:4,uint16:2,uint8:1,bool:1},Mc="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa),Wc=function(){function a(){this.saveRouters=[],this.loadRouters=[]}return a.getInstance=function(){return null==a.instance&&(a.instance=new a),a.instance},a.registerSaveRouter=function(t){a.getInstance().saveRouters.push(t)},a.registerLoadRouter=function(t){a.getInstance().loadRouters.push(t)},a.getSaveHandlers=function(t){return a.getHandlers(t,"save")},a.getLoadHandlers=function(t,e){return a.getHandlers(t,"load",e)},a.getHandlers=function(s,e,i){var r=[];return("load"===e?a.getInstance().loadRouters:a.getInstance().saveRouters).forEach(function(e){var t=e(s,i);null!==t&&r.push(t)}),r},a}(),Hc="://",qc=function(){function a(){this.managers={}}return a.getInstance=function(){return null==a.instance&&(a.instance=new a),a.instance},a.registerManager=function(t,o){Ue(null!=t,function(){return"scheme must not be undefined or null."}),t.endsWith(Hc)&&(t=t.slice(0,t.indexOf(Hc))),Ue(0<t.length,function(){return"scheme must not be an empty string."});var n=a.getInstance();Ue(null==n.managers[t],function(){return"A model store manager is already registered for scheme '"+t+"'."}),n.managers[t]=o},a.getManager=function(a){var t=this.getInstance().managers[a];if(null==t)throw new Error("Cannot find model manager for scheme '"+a+"'");return t},a.getSchemes=function(){return Object.keys(this.getInstance().managers)},a}(),$c="models_store",Xc="model_info_store",Yc=function(){function e(e){if(this.indexedDB=Vs(),null==e||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}return e.prototype.save=function(e){return Be(this,void 0,void 0,function(){return Me(this,function(){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return[2,this.databaseAction(this.modelPath,e)]})})},e.prototype.load=function(){return Be(this,void 0,void 0,function(){return Me(this,function(){return[2,this.databaseAction(this.modelPath)]})})},e.prototype.databaseAction=function(a,p){var d=this;return new Promise(function(e,t){var n=d.indexedDB.open("tensorflowjs",1);n.onupgradeneeded=function(){return Us(n)},n.onsuccess=function(){var r=n.result;if(null==p){var a=r.transaction($c,"readonly"),o=a.objectStore($c).get(d.modelPath);o.onsuccess=function(){return null==o.result?(r.close(),t(new Error("Cannot find model with path '"+d.modelPath+"' in IndexedDB."))):void e(o.result.modelArtifacts)},o.onerror=function(){return r.close(),t(o.error)},a.oncomplete=function(){return r.close()}}else{var s=ns(p),i=r.transaction(Xc,"readwrite"),l=i.objectStore(Xc),c=l.put({modelPath:d.modelPath,modelArtifactsInfo:s}),m;c.onsuccess=function(){var a=(m=r.transaction($c,"readwrite")).objectStore($c).put({modelPath:d.modelPath,modelArtifacts:p,modelArtifactsInfo:s});a.onsuccess=function(){return e({modelArtifactsInfo:s})},a.onerror=function(){var n=(l=i.objectStore(Xc)).delete(d.modelPath);n.onsuccess=function(){return r.close(),t(a.error)},n.onerror=function(){return r.close(),t(a.error)}}},c.onerror=function(){return r.close(),t(c.error)},i.oncomplete=function(){null==m?r.close():m.oncomplete=function(){return r.close()}}}},n.onerror=function(){return t(n.error)}})},e.URL_SCHEME="indexeddb://",e}(),Zc=function(a){return _f.getBool("IS_BROWSER")&&!Array.isArray(a)&&a.startsWith(Yc.URL_SCHEME)?(t=a.slice(Yc.URL_SCHEME.length),new Yc(t)):null;var t};Wc.registerSaveRouter(Zc),Wc.registerLoadRouter(Zc);var th=function(){function e(){this.indexedDB=Vs()}return e.prototype.listModels=function(){return Be(this,void 0,void 0,function(){var a=this;return Me(this,function(){return[2,new Promise(function(s,e){var n=a.indexedDB.open("tensorflowjs",1);n.onupgradeneeded=function(){return Us(n)},n.onsuccess=function(){var r=n.result,t=r.transaction(Xc,"readonly"),i=t.objectStore(Xc).getAll();i.onsuccess=function(){for(var e={},t=0,a=i.result,r;t<a.length;t++)r=a[t],e[r.modelPath]=r.modelArtifactsInfo;s(e)},i.onerror=function(){return r.close(),e(i.error)},t.oncomplete=function(){return r.close()}},n.onerror=function(){return e(n.error)}})]})})},e.prototype.removeModel=function(p){return Be(this,void 0,void 0,function(){var t=this;return Me(this,function(){var e;return p=(e=p).startsWith(Yc.URL_SCHEME)?e.slice(Yc.URL_SCHEME.length):e,[2,new Promise(function(e,n){var r=t.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=function(){return Us(r)},r.onsuccess=function(){var t=r.result,a=t.transaction(Xc,"readwrite"),d=a.objectStore(Xc),s=d.get(p),i;s.onsuccess=function(){if(null==s.result)return t.close(),n(new Error("Cannot find model with path '"+p+"' in IndexedDB."));var e=d.delete(p),a=function(){var e=(i=t.transaction($c,"readwrite")).objectStore($c).delete(p);e.onsuccess=function(){return e(s.result.modelArtifactsInfo)},e.onerror=function(){return n(s.error)}};e.onsuccess=a,e.onerror=function(){return a(),t.close(),n(s.error)}},s.onerror=function(){return t.close(),n(s.error)},a.oncomplete=function(){null==i?t.close():i.oncomplete=function(){return t.close()}}},r.onerror=function(){return n(r.error)}})]})})},e}();if(_f.getBool("IS_BROWSER"))try{qc.registerManager(Yc.URL_SCHEME,new th)}catch(e){}var eh=function(){function e(e){if(!_f.getBool("IS_BROWSER")||void 0===window.localStorage)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,null==e||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=Gs(this.modelPath)}return e.prototype.save=function(r){return Be(this,void 0,void 0,function(){var t,s,i;return Me(this,function(){if(r.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");t=JSON.stringify(r.modelTopology),s=JSON.stringify(r.weightSpecs),i=ns(r);try{return this.LS.setItem(this.keys.info,JSON.stringify(i)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,s),this.LS.setItem(this.keys.weightData,(e=r.weightData,Mc?Buffer.from(e).toString("base64"):btoa(cf.apply(null,new Uint8Array(e))))),this.LS.setItem(this.keys.modelMetadata,JSON.stringify({format:r.format,generatedBy:r.generatedBy,convertedBy:r.convertedBy})),[2,{modelArtifactsInfo:i}]}catch(e){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="+i.modelTopologyBytes+", weightSpecsBytes="+i.weightSpecsBytes+", weightDataBytes="+i.weightDataBytes+".")}var e;return[2]})})},e.prototype.load=function(){return Be(this,void 0,void 0,function(){var r,p,d,l,u,c,h;return Me(this,function(){if(null==(r=JSON.parse(this.LS.getItem(this.keys.info))))throw new Error("In local storage, there is no model with name '"+this.modelPath+"'");if("JSON"!==r.modelTopologyType)throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");if(p={},null==(d=JSON.parse(this.LS.getItem(this.keys.topology))))throw new Error("In local storage, the topology of model '"+this.modelPath+"' is missing.");if(p.modelTopology=d,null==(l=JSON.parse(this.LS.getItem(this.keys.weightSpecs))))throw new Error("In local storage, the weight specs of model '"+this.modelPath+"' are missing.");if(p.weightSpecs=l,null!=(u=this.LS.getItem(this.keys.modelMetadata))&&(c=JSON.parse(u),p.format=c.format,p.generatedBy=c.generatedBy,p.convertedBy=c.convertedBy),null==(h=this.LS.getItem(this.keys.weightData)))throw new Error("In local storage, the binary weight values of model '"+this.modelPath+"' are missing.");return p.weightData=function(a){if(Mc){var t=Buffer.from(a,"base64");return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}for(var e=atob(a),n=new Uint8Array(e.length),r=0;r<e.length;++r)n.set([e.charCodeAt(r)],r);return n.buffer}(h),[2,p]})})},e.URL_SCHEME="localstorage://",e}(),hh=function(a){return _f.getBool("IS_BROWSER")&&!Array.isArray(a)&&a.startsWith(eh.URL_SCHEME)?(t=a.slice(eh.URL_SCHEME.length),new eh(t)):null;var t};Wc.registerSaveRouter(hh),Wc.registerLoadRouter(hh);var fh=function(){function e(){Ue(_f.getBool("IS_BROWSER"),function(){return"Current environment is not a web browser"}),Ue(void 0!==window.localStorage,function(){return"Current browser does not appear to support localStorage"}),this.LS=window.localStorage}return e.prototype.listModels=function(){return Be(this,void 0,void 0,function(){var r,s,p,d,l,u;return Me(this,function(){for(r={},s="tensorflowjs_models/",p="/info",d=0;d<this.LS.length;++d)(l=this.LS.key(d)).startsWith(s)&&l.endsWith(p)&&(u=qs(l),r[u]=JSON.parse(this.LS.getItem(l)));return[2,r]})})},e.prototype.removeModel=function(a){return Be(this,void 0,void 0,function(){var t,r;return Me(this,function(){var e;if(a=(e=a).startsWith(eh.URL_SCHEME)?e.slice(eh.URL_SCHEME.length):e,t=Gs(a),null==this.LS.getItem(t.info))throw new Error("Cannot find model at path '"+a+"'");return r=JSON.parse(this.LS.getItem(t.info)),this.LS.removeItem(t.info),this.LS.removeItem(t.topology),this.LS.removeItem(t.weightSpecs),this.LS.removeItem(t.weightData),[2,r]})})},e}();if(_f.getBool("IS_BROWSER"))try{qc.registerManager(eh.URL_SCHEME,new fh)}catch(e){}var ph=function(){function a(t){if(!_f.getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");t.startsWith(a.URL_SCHEME)&&(t=t.slice(a.URL_SCHEME.length)),null!=t&&0!==t.length||(t="model"),this.modelTopologyFileName=t+".json",this.weightDataFileName=t+".weights.bin"}return a.prototype.save=function(p){return Be(this,void 0,void 0,function(){var t,d,l,u,c,h;return Me(this,function(e){switch(e.label){case 0:if("undefined"==typeof document)throw new Error("Browser downloads are not supported in this environment since `document` is not present");if(t=window.URL.createObjectURL(new Blob([p.weightData],{type:"application/octet-stream"})),!(p.modelTopology instanceof ArrayBuffer))return[3,1];throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");case 1:return d=[{paths:["./"+this.weightDataFileName],weights:p.weightSpecs}],l={modelTopology:p.modelTopology,format:p.format,generatedBy:p.generatedBy,convertedBy:p.convertedBy,weightsManifest:d},u=window.URL.createObjectURL(new Blob([JSON.stringify(l)],{type:"application/json"})),(c=null==this.jsonAnchor?document.createElement("a"):this.jsonAnchor).download=this.modelTopologyFileName,c.href=u,[4,Hs(function(){return c.dispatchEvent(new MouseEvent("click"))})];case 2:return e.sent(),null==p.weightData?[3,4]:((h=null==this.weightDataAnchor?document.createElement("a"):this.weightDataAnchor).download=this.weightDataFileName,h.href=t,[4,Hs(function(){return h.dispatchEvent(new MouseEvent("click"))})]);case 3:e.sent(),e.label=4;case 4:return[2,{modelArtifactsInfo:ns(p)}];}})})},a.URL_SCHEME="downloads://",a}(),yh=function(){function e(e){if(null==e||1>e.length)throw new Error("When calling browserFiles, at least 1 file is required, but received "+e);this.files=e}return e.prototype.load=function(){return Be(this,void 0,void 0,function(){var a=this,n,p;return Me(this,function(){return n=this.files[0],p=this.files.slice(1),[2,new Promise(function(d,e){var t=new FileReader;t.onload=function(t){var r=JSON.parse(t.target.result),i=r.modelTopology;if(null!=i){0===p.length&&d({modelTopology:i});var o=r.weightsManifest;if(null!=o){var s;try{s=a.checkManifestAndWeightFiles(o,p)}catch(a){return void e(a)}var u=[],c=[],h=[];o.forEach(function(e){e.paths.forEach(function(e){c.push(e),h.push(null)}),u.push.apply(u,e.weights)}),o.forEach(function(a){a.paths.forEach(function(a){var t=new FileReader;t.onload=function(t){var e=t.target.result,n=c.indexOf(a);h[n]=e,-1===h.indexOf(null)&&d({modelTopology:i,weightSpecs:u,weightData:Qo(h)})},t.onerror=function(){return e("Failed to weights data from file of path '"+a+"'.")},t.readAsArrayBuffer(s[a])})})}else e(new Error("weightManifest field is missing from file "+n.name))}else e(new Error("modelTopology field is missing from file "+n.name))},t.onerror=function(){return e("Failed to read model topology and weights manifest JSON from file '"+n.name+"'. BrowserFiles supports loading Keras-style tf.Model artifacts only.")},t.readAsText(n)})]})})},e.prototype.checkManifestAndWeightFiles=function(s,p){for(var e=[],n=p.map(function(e){return Jo(e.name)}),r={},t=0,o=s;t<o.length;t++)o[t].paths.forEach(function(o){var t=Jo(o);if(-1!==e.indexOf(t))throw new Error("Duplicate file basename found in weights manifest: '"+t+"'");if(e.push(t),-1===n.indexOf(t))throw new Error("Weight file with basename '"+t+"' is not provided.");r[o]=p[n.indexOf(t)]});if(e.length!==p.length)throw new Error("Mismatch in the number of files in weights manifest ("+e.length+") and the number of weight files provided ("+p.length+").");return r},e}();Wc.registerSaveRouter(function(a){return _f.getBool("IS_BROWSER")&&!Array.isArray(a)&&a.startsWith(ph.URL_SCHEME)?(t=a.slice(ph.URL_SCHEME.length),void 0===t&&(t="model"),new ph(t)):null;var t});var xh=function(){function e(a,t){if(this.DEFAULT_METHOD="POST",null==t&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,null==t.fetchFunc?this.fetch=_f.platform.fetch:(Ue("function"==typeof t.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=t.fetchFunc),Ue(null!=a&&0<a.length,function(){return"URL path for http must not be null, undefined or empty."}),Array.isArray(a)&&Ue(2===a.length,function(){return"URL paths for http must have a length of 2, (actual length is "+a.length+")."}),this.path=a,null!=t.requestInit&&null!=t.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}return e.prototype.save=function(s){return Be(this,void 0,void 0,function(){var t,i,p,d;return Me(this,function(e){switch(e.label){case 0:if(s.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return(t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit)).body=new FormData,i=[{paths:["./model.weights.bin"],weights:s.weightSpecs}],p={modelTopology:s.modelTopology,format:s.format,generatedBy:s.generatedBy,convertedBy:s.convertedBy,weightsManifest:i},t.body.append("model.json",new Blob([JSON.stringify(p)],{type:"application/json"}),"model.json"),null!=s.weightData&&t.body.append("model.weights.bin",new Blob([s.weightData],{type:"application/octet-stream"}),"model.weights.bin"),[4,this.fetch(this.path,t)];case 1:if((d=e.sent()).ok)return[2,{modelArtifactsInfo:ns(s),responses:[d]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+d.status+".");}})})},e.prototype.load=function(){return Be(this,void 0,void 0,function(){var p,d,l,c,h,m,g,f;return Me(this,function(e){switch(e.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(!(p=e.sent()).ok)throw new Error("Request to "+this.path+" failed with status code "+p.status+". Please verify this URL points to the model JSON of the model to load.");e.label=2;case 2:return e.trys.push([2,4,,5]),[4,p.json()];case 3:return d=e.sent(),[3,5];case 4:throw e.sent(),l="Failed to parse model JSON of response from "+this.path+".",l+=this.path.endsWith(".pb")?" 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.":" Please make sure the server is serving valid JSON for this request.",new Error(l);case 5:if(c=d.modelTopology,h=d.weightsManifest,null==c&&null==h)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return null==h?[3,7]:[4,this.loadWeights(h)];case 6:f=e.sent(),m=f[0],g=f[1],e.label=7;case 7:return[2,{modelTopology:c,weightSpecs:m,weightData:g}];}})})},e.prototype.loadWeights=function(p){return Be(this,void 0,void 0,function(){var t,r,d,m,g,y,b,x,v,C,S;return Me(this,function(e){switch(e.label){case 0:for(t=Array.isArray(this.path)?this.path[1]:this.path,r=function(a){var t=a.lastIndexOf("/"),e=a.lastIndexOf("?"),n=a.substring(0,t),r=e>t?a.substring(e):"";return[n+"/",r]}(t),d=r[0],m=r[1],g=this.weightPathPrefix||d,y=[],b=0,x=p;b<x.length;b++)v=x[b],y.push.apply(y,v.weights);return C=[],p.forEach(function(e){e.paths.forEach(function(e){C.push(g+e+m)})}),[4,ri(C,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress})];case 1:return S=e.sent(),[2,[y,Qo(S)]];}})})},e.URL_SCHEME_REGEX=/^https?:\/\//,e}(),Eh=function(a,t){return"undefined"==typeof fetch?null:(Array.isArray(a)?a.every(function(e){return Fi(e)}):Fi(a))?Vi(a,{onProgress:t}):null};Wc.registerSaveRouter(Eh),Wc.registerLoadRouter(Eh);var Ih=function(){function e(e){this.modelArtifacts=e}return e.prototype.load=function(){return Be(this,void 0,void 0,function(){return Me(this,function(){return[2,this.modelArtifacts]})})},e}(),Nh=function(){function e(e){this.saveHandler=e}return e.prototype.save=function(e){return Be(this,void 0,void 0,function(){return Me(this,function(){return[2,this.saveHandler(e)]})})},e}(),kh=Object.freeze({browserFiles:function(e){return new yh(e)},browserHTTPRequest:function(a,t){return Vi(a,t)},concatenateArrayBuffers:Qo,decodeWeights:qo,encodeWeights:function(n,t){return Be(this,void 0,void 0,function(){var e=this,r,p,d,l,c;return Me(this,function(a){switch(a.label){case 0:for(r=[],p=[],d=Array.isArray(n)?n.map(function(e){return e.name}):Object.keys(n),l=function(a){var o=d[a],l=Array.isArray(n)?n[a].tensor:n[o];if("float32"!==l.dtype&&"int32"!==l.dtype&&"bool"!==l.dtype&&"string"!==l.dtype)throw new Error("Unsupported dtype in weight '"+o+"': "+l.dtype);var s={name:o,shape:l.shape,dtype:l.dtype};if("string"===l.dtype){var i=new Promise(function(p){return Be(e,void 0,void 0,function(){var t,d,c,h,m,g,f;return Me(this,function(e){switch(e.label){case 0:return[4,l.bytes()];case 1:for(t=e.sent(),d=t.reduce(function(a,t){return a+t.length},0)+4*t.length,c=new Uint8Array(d),h=0,m=0;m<t.length;m++)g=t[m],f=new Uint8Array(new Uint32Array([g.length]).buffer),c.set(f,h),h+=4,c.set(g,h),h+=g.length;return p(c),[2];}})})});p.push(i)}else p.push(l.data());null!=t&&(s.group=t),r.push(s)},c=0;c<d.length;++c)l(c);return[4,Promise.all(p)];case 1:return[2,{data:Ho(a.sent()),specs:r}];}})})},fromMemory:function(a,t,e,n){return 1===arguments.length?null!=a.modelTopology||null!=a.weightSpecs?new Ih(a):(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 Ih({modelTopology:a})):(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 Ih({modelTopology:a,weightSpecs:t,weightData:e,trainingConfig:n}))},getLoadHandlers:function(a,t){return Wc.getLoadHandlers(a,t)},getModelArtifactsInfoForJSON:ns,getSaveHandlers:function(e){return Wc.getSaveHandlers(e)},http:Vi,isHTTPScheme:Fi,loadWeights:function(n,t,r,o){return void 0===t&&(t=""),Be(this,void 0,void 0,function(){return Me(this,function(){return[2,Oi(function(e){return ri(e,{requestInit:o})})(n,t,r)]})})},registerLoadRouter:function(e){return Wc.registerLoadRouter(e)},registerSaveRouter:function(e){return Wc.registerSaveRouter(e)},weightsLoaderFactory:Oi,withSaveHandler:function(e){return new Nh(e)},copyModel:function(a,t){return Be(this,void 0,void 0,function(){return Me(this,function(){return[2,zs(a,t,!1)]})})},listModels:function(){return Be(this,void 0,void 0,function(){var p,d,l,u,c,h,m;return Me(this,function(e){switch(e.label){case 0:p=qc.getSchemes(),d={},l=0,u=p,e.label=1;case 1:return l<u.length?(c=u[l],[4,qc.getManager(c).listModels()]):[3,4];case 2:for(m in h=e.sent())d[c+Hc+m]=h[m];e.label=3;case 3:return l++,[3,1];case 4:return[2,d];}})})},moveModel:function(a,t){return Be(this,void 0,void 0,function(){return Me(this,function(){return[2,zs(a,t,!0)]})})},removeModel:function(a){return Be(this,void 0,void 0,function(){var t;return Me(this,function(){return t=rs(a),[2,qc.getManager(t.scheme).removeModel(t.path)]})})}}),Ah=Xt({confusionMatrix_:function(s,t,e){var n=Lt(s,"labels","confusionMatrix"),r=Lt(t,"predictions","confusionMatrix");Ue(null==e||0<e&&Nf(e),function(){return"If provided, numClasses must be a positive integer, but got "+e}),Ue(1===n.rank,function(){return"Expected the rank of labels to be 1, but got "+n.rank}),Ue(1===r.rank,function(){return"Expected the rank of predictions to be 1, but got "+r.rank}),Ue(n.shape[0]===r.shape[0],function(){return"Mismatch in the number of examples: "+n.shape[0]+" vs. "+r.shape[0]+". Labels and predictions should have the same number of elements."}),Ue(0<e&&Nf(e),function(){return"numClasses is required to be a positive integer, but got "+e});var o=ur(n.asType("int32"),e),a=ur(r.asType("int32"),e);return o.transpose().matMul(a).asType("int32")}}),Th=Object.freeze({confusionMatrix:Ah}),Dh=Xt({fromPixels_:function(a,t){if(void 0===t&&(t=3),4<t)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");return kt.fromPixels(a,t)}}),_h=Object.freeze({toPixels:function(S,t){return Be(this,void 0,void 0,function(){var e,N,k,T,A,D,_,O,z,L,F,B,P,r,M,W,V,U,G,q,H,K,j;return Me(this,function(a){switch(a.label){case 0:if(e=Lt(S,"img","toPixels"),S instanceof Lf||(e=e.toInt()),2!==e.rank&&3!==e.rank)throw new Error("toPixels only supports rank 2 or 3 tensors, got rank "+e.rank+".");if(N=e.shape.slice(0,2),k=N[0],T=N[1],4<(A=2===e.rank?1:e.shape[2])||2===A)throw new Error("toPixels only supports depth of size 1, 3 or 4 but got "+A);return[4,e.data()];case 1:return D=a.sent(),_=e.min(),O=e.max(),[4,Promise.all([_.data(),O.data()])];case 2:if(z=a.sent(),L=z[0],F=z[1],B=L[0],P=F[0],_.dispose(),O.dispose(),"float32"!==e.dtype){if("int32"!==e.dtype)throw new Error("Unsupported type for toPixels: "+e.dtype+". Please use float32 or int32 tensors.");if(0>B||255<P)throw new Error("Tensor values for a int32 Tensor must be in the range [0 - 255] but got range ["+B+" - "+P+"].")}else if(0>B||1<P)throw new Error("Tensor values for a float32 Tensor must be in the range [0 - 1] but got range ["+B+" - "+P+"].");for(r="float32"===e.dtype?255:1,M=new Uint8ClampedArray(4*(T*k)),W=0;W<k*T;++W)V=void 0,U=void 0,G=void 0,q=void 0,1===A?(V=D[W]*r,U=D[W]*r,G=D[W]*r,q=255):3===A?(V=D[3*W]*r,U=D[3*W+1]*r,G=D[3*W+2]*r,q=255):4===A&&(V=D[4*W]*r,U=D[4*W+1]*r,G=D[4*W+2]*r,q=D[4*W+3]*r),M[0+(H=4*W)]=If(V),M[H+1]=If(U),M[H+2]=If(G),M[H+3]=If(q);return null!=t&&(t.width=T,t.height=k,K=t.getContext("2d"),j=new ImageData(M,T,k),K.putImageData(j,0,0)),e!==S&&e.dispose(),[2,M];}})})},fromPixels:Dh}),Oh=function(){function e(){}return e.prototype.getClassName=function(){return this.constructor.className},e.fromConfig=function(a,t){return new a(t)},e}(),Fh=function(){function a(){this.classNameMap={}}return a.getMap=function(){return null==a.instance&&(a.instance=new a),a.instance},a.register=function(t){a.getMap().classNameMap[t.className]=[t,t.fromConfig]},a}(),Mh=Object.freeze({Serializable:Oh,SerializationMap:Fh,registerClass:Gi}),Ph=.001,Lh=.1,Wh=Object.freeze({TEST_EPSILON_FLOAT16:Lh,expectArraysClose:function(a,t,r){return null==r&&(r=Hi()),Ki(a,t,function(a,t){return ji(a,t,r)})},testEpsilon:Hi,expectPromiseToFail:function(a,t){a().then(function(){return t.fail()},function(){return t()})},expectArraysEqual:function(a,t){var e="string"==typeof t||"number"==typeof t||"boolean"==typeof t?[t]:t;return D(a)||D(a[0])||D(t)||D(t[0])?Ki(a,e,function(a,t){return a==t}):Ki(a,t,function(a,t){return ji(a,t,0)})},expectNumbersClose:function(a,t,e){if(null==e&&(e=Hi()),!ji(a,t,e))throw new Error("Numbers differ: actual === "+a+", expected === "+t)},expectValuesInRange:function(a,t,e){for(var n=0;n<a.length;n++)if(a[n]<t||a[n]>e)throw new Error("Value out of range:"+a[n]+" low: "+t+", high: "+e)},expectArrayBuffersEqual:function(a,t){expect(new Float32Array(a)).toEqual(new Float32Array(t))}}),Gh=Object.freeze({gpgpu_util:Pa,webgl_util:Jt,MathBackendWebGL:es,setWebGLContext:Ye,GPGPUContext:ei}),qh=function(e){function t(){return null!==e&&e.apply(this,arguments)||this}return Fe(t,e),t.prototype.minimize=function(s,t,p){void 0===t&&(t=!1);var n=this.computeGradients(s,p),r=n.value,o=n.grads;if(null!=p){var a=p.map(function(e){return{name:e.name,tensor:o[e.name]}});this.applyGradients(a)}else this.applyGradients(o);return ze(o),t?r:(r.dispose(),null)},Object.defineProperty(t.prototype,"iterations",{get:function(){return null==this.iterations_&&(this.iterations_=0),this.iterations_},enumerable:!0,configurable:!0}),t.prototype.incrementIterations=function(){this.iterations_=this.iterations+1},t.prototype.computeGradients=function(a,t){return _n(a,t)},t.prototype.dispose=function(){null!=this.iterations_&&ze(this.iterations_)},t.prototype.saveIterations=function(){return Be(this,void 0,void 0,function(){return Me(this,function(){return null==this.iterations_&&(this.iterations_=0),[2,{name:"iter",tensor:Da(this.iterations_,"int32")}]})})},t.prototype.getWeights=function(){return Be(this,void 0,void 0,function(){return Me(this,function(){throw new Error("getWeights() is not implemented for this optimizer yet.")})})},t.prototype.setWeights=function(){return Be(this,void 0,void 0,function(){return Me(this,function(){throw new Error("setWeights() is not implemented for this optimizer class "+this.getClassName())})})},t.prototype.extractIterations=function(a){return Be(this,void 0,void 0,function(){var t;return Me(this,function(e){switch(e.label){case 0:return t=this,[4,a[0].tensor.data()];case 1:return t.iterations_=e.sent()[0],[2,a.slice(1)];}})})},t}(Oh);Object.defineProperty(qh,Symbol.hasInstance,{value:function(e){return null!=e.minimize&&null!=e.computeGradients&&null!=e.applyGradients}});var $h=function(a){function e(t,e,n){void 0===n&&(n=null);var s=a.call(this)||this;return s.learningRate=t,s.rho=e,s.epsilon=n,s.accumulatedGrads=[],s.accumulatedUpdates=[],null==n&&(s.epsilon=kt.backend.epsilon()),s}return Fe(e,a),e.prototype.applyGradients=function(p){var d=this;(Array.isArray(p)?p.map(function(e){return e.name}):Object.keys(p)).forEach(function(e,t){var l=kt.registeredVariables[e];null==d.accumulatedGrads[t]&&(d.accumulatedGrads[t]={originalName:e+"/accum_grad",variable:We(function(){return Fn(l).variable(!1)})}),null==d.accumulatedUpdates[t]&&(d.accumulatedUpdates[t]={originalName:e+"/accum_var",variable:We(function(){return Fn(l).variable(!1)})});var o=Array.isArray(p)?p[t].tensor:p[e];if(null!=o){var a=d.accumulatedGrads[t].variable,i=d.accumulatedUpdates[t].variable;We(function(){var e=a.mul(d.rho).add(o.square().mul(1-d.rho)),t=i.add(d.epsilon).sqrt().div(a.add(d.epsilon).sqrt()).mul(o),n=i.mul(d.rho).add(t.square().mul(1-d.rho));a.assign(e),i.assign(n);var r=t.mul(-d.learningRate).add(l);l.assign(r)})}}),this.incrementIterations()},e.prototype.dispose=function(){null!=this.accumulatedUpdates&&(ze(this.accumulatedGrads.map(function(e){return e.variable})),ze(this.accumulatedUpdates.map(function(e){return e.variable})))},e.prototype.getWeights=function(){return Be(this,void 0,void 0,function(){var a;return Me(this,function(t){switch(t.label){case 0:return a=this.accumulatedGrads.concat(this.accumulatedUpdates),[4,this.saveIterations()];case 1:return[2,[t.sent()].concat(a.map(function(e){return{name:e.originalName,tensor:e.variable}}))];}})})},e.prototype.setWeights=function(a){return Be(this,void 0,void 0,function(){var t;return Me(this,function(e){switch(e.label){case 0:return[4,this.extractIterations(a)];case 1:return a=e.sent(),t=a.length/2,this.accumulatedGrads=a.slice(0,t).map(function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}}),this.accumulatedUpdates=a.slice(t,2*t).map(function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}}),[2];}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}},e.fromConfig=function(a,t){return new a(t.learningRate,t.rho,t.epsilon)},e.className="Adadelta",e}(qh);Gi($h);var jh=function(a){function e(t,e){void 0===e&&(e=.1);var o=a.call(this)||this;return o.learningRate=t,o.initialAccumulatorValue=e,o.accumulatedGrads=[],o}return Fe(e,a),e.prototype.applyGradients=function(s){var p=this;(Array.isArray(s)?s.map(function(e){return e.name}):Object.keys(s)).forEach(function(e,t){var r=kt.registeredVariables[e];null==p.accumulatedGrads[t]&&(p.accumulatedGrads[t]={originalName:e+"/accumulator",variable:We(function(){return dn(r.shape,p.initialAccumulatorValue).variable(!1)})});var o=Array.isArray(s)?s[t].tensor:s[e];if(null!=o){var a=p.accumulatedGrads[t].variable;We(function(){var e=a.add(o.square());a.assign(e);var t=o.div(e.add(kt.backend.epsilon()).sqrt()).mul(-p.learningRate).add(r);r.assign(t)})}}),this.incrementIterations()},e.prototype.dispose=function(){null!=this.accumulatedGrads&&ze(this.accumulatedGrads.map(function(e){return e.variable}))},e.prototype.getWeights=function(){return Be(this,void 0,void 0,function(){return Me(this,function(e){switch(e.label){case 0:return[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(this.accumulatedGrads.map(function(e){return{name:e.originalName,tensor:e.variable}}))];}})})},e.prototype.setWeights=function(a){return Be(this,void 0,void 0,function(){return Me(this,function(t){switch(t.label){case 0:return[4,this.extractIterations(a)];case 1:return a=t.sent(),this.accumulatedGrads=a.map(function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}}),[2];}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}},e.fromConfig=function(a,t){return new a(t.learningRate,t.initialAccumulatorValue)},e.className="Adagrad",e}(qh);Gi(jh);var Kh=function(s){function e(t,e,n,r){void 0===r&&(r=null);var i=s.call(this)||this;return i.learningRate=t,i.beta1=e,i.beta2=n,i.epsilon=r,i.accumulatedFirstMoment=[],i.accumulatedSecondMoment=[],We(function(){i.accBeta1=Da(e).variable(),i.accBeta2=Da(n).variable()}),null==r&&(i.epsilon=kt.backend.epsilon()),i}return Fe(e,s),e.prototype.applyGradients=function(m){var t=this,e=Array.isArray(m)?m.map(function(e){return e.name}):Object.keys(m);We(function(){var n=gl(1,t.accBeta1),r=gl(1,t.accBeta2);e.forEach(function(e,o){var a=kt.registeredVariables[e];null==t.accumulatedFirstMoment[o]&&(t.accumulatedFirstMoment[o]={originalName:e+"/m",variable:We(function(){return Fn(a).variable(!1)})}),null==t.accumulatedSecondMoment[o]&&(t.accumulatedSecondMoment[o]={originalName:e+"/v",variable:We(function(){return Fn(a).variable(!1)})});var i=Array.isArray(m)?m[o].tensor:m[e];if(null!=i){var s=t.accumulatedFirstMoment[o].variable,u=t.accumulatedSecondMoment[o].variable,l=s.mul(t.beta1).add(i.mul(1-t.beta1)),c=u.mul(t.beta2).add(i.square().mul(1-t.beta2)),h=l.div(n),g=c.div(r);s.assign(l),u.assign(c);var p=h.div(g.sqrt().add(t.epsilon)).mul(-t.learningRate).add(a);a.assign(p)}}),t.accBeta1.assign(t.accBeta1.mul(t.beta1)),t.accBeta2.assign(t.accBeta2.mul(t.beta2))}),this.incrementIterations()},e.prototype.dispose=function(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&ze(this.accumulatedFirstMoment.map(function(e){return e.variable})),null!=this.accumulatedSecondMoment&&ze(this.accumulatedSecondMoment.map(function(e){return e.variable}))},e.prototype.getWeights=function(){return Be(this,void 0,void 0,function(){var a;return Me(this,function(t){switch(t.label){case 0:return a=this.accumulatedFirstMoment.concat(this.accumulatedSecondMoment),[4,this.saveIterations()];case 1:return[2,[t.sent()].concat(a.map(function(e){return{name:e.originalName,tensor:e.variable}}))];}})})},e.prototype.setWeights=function(a){return Be(this,void 0,void 0,function(){var t=this,n;return Me(this,function(e){switch(e.label){case 0:return[4,this.extractIterations(a)];case 1:return a=e.sent(),We(function(){t.accBeta1.assign(pl(t.beta1,t.iterations_+1)),t.accBeta2.assign(pl(t.beta2,t.iterations_+1))}),n=a.length/2,this.accumulatedFirstMoment=a.slice(0,n).map(function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}}),this.accumulatedSecondMoment=a.slice(n,2*n).map(function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}}),[2];}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}},e.fromConfig=function(a,t){return new a(t.learningRate,t.beta1,t.beta2,t.epsilon)},e.className="Adam",e}(qh);Gi(Kh);var Xh=function(s){function e(t,e,n,r,p){void 0===r&&(r=null),void 0===p&&(p=0);var d=s.call(this)||this;return d.learningRate=t,d.beta1=e,d.beta2=n,d.epsilon=r,d.decay=p,d.accumulatedFirstMoment=[],d.accumulatedWeightedInfNorm=[],We(function(){d.iteration=Da(0).variable(),d.accBeta1=Da(e).variable()}),null==r&&(d.epsilon=kt.backend.epsilon()),d}return Fe(e,s),e.prototype.applyGradients=function(m){var t=this,e=Array.isArray(m)?m.map(function(e){return e.name}):Object.keys(m);We(function(){var n=gl(1,t.accBeta1),r=nl(-t.learningRate,t.iteration.mul(t.decay).add(1));e.forEach(function(e,o){var a=kt.registeredVariables[e];null==t.accumulatedFirstMoment[o]&&(t.accumulatedFirstMoment[o]={originalName:e+"/m",variable:Fn(a).variable(!1)}),null==t.accumulatedWeightedInfNorm[o]&&(t.accumulatedWeightedInfNorm[o]={originalName:e+"/v",variable:Fn(a).variable(!1)});var i=Array.isArray(m)?m[o].tensor:m[e];if(null!=i){var s=t.accumulatedFirstMoment[o].variable,u=t.accumulatedWeightedInfNorm[o].variable,l=s.mul(t.beta1).add(i.mul(1-t.beta1)),c=u.mul(t.beta2),h=i.abs(),g=c.maximum(h);s.assign(l),u.assign(g);var p=r.div(n).mul(l.div(g.add(t.epsilon))).add(a);a.assign(p)}}),t.iteration.assign(t.iteration.add(1)),t.accBeta1.assign(t.accBeta1.mul(t.beta1))}),this.incrementIterations()},e.prototype.dispose=function(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&ze(this.accumulatedFirstMoment.map(function(e){return e.variable})),null!=this.accumulatedWeightedInfNorm&&ze(this.accumulatedWeightedInfNorm.map(function(e){return e.variable}))},e.prototype.getWeights=function(){return Be(this,void 0,void 0,function(){return Me(this,function(){throw new Error("getWeights() is not implemented for Adamax yet.")})})},e.prototype.setWeights=function(){return Be(this,void 0,void 0,function(){return Me(this,function(){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(a,t){return new a(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)},e.className="Adamax",e}(qh);Gi(Xh);var Yh=function(a){function e(t){var e=a.call(this)||this;return e.learningRate=t,e.setLearningRate(t),e}return Fe(e,a),e.prototype.applyGradients=function(s){var n=this;(Array.isArray(s)?s.map(function(e){return e.name}):Object.keys(s)).forEach(function(e,t){var r=Array.isArray(s)?s[t].tensor:s[e];if(null!=r){var o=kt.registeredVariables[e];We(function(){var e=n.c.mul(r).add(o);o.assign(e)})}}),this.incrementIterations()},e.prototype.setLearningRate=function(e){this.learningRate=e,null!=this.c&&this.c.dispose(),this.c=Ve(Da(-e))},e.prototype.dispose=function(){this.c.dispose()},e.prototype.getWeights=function(){return Be(this,void 0,void 0,function(){return Me(this,function(e){switch(e.label){case 0:return[4,this.saveIterations()];case 1:return[2,[e.sent()]];}})})},e.prototype.setWeights=function(a){return Be(this,void 0,void 0,function(){return Me(this,function(t){switch(t.label){case 0:return[4,this.extractIterations(a)];case 1:if(0!==(a=t.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(a,t){return new a(t.learningRate)},e.className="SGD",e}(qh);Gi(Yh);var Qh=function(a){function e(t,e,n){void 0===n&&(n=!1);var s=a.call(this,t)||this;return s.learningRate=t,s.momentum=e,s.useNesterov=n,s.accumulations=[],s.m=Da(s.momentum),s}return Fe(e,a),e.prototype.applyGradients=function(s){var p=this;(Array.isArray(s)?s.map(function(e){return e.name}):Object.keys(s)).forEach(function(e,t){var r=kt.registeredVariables[e];null==p.accumulations[t]&&(p.accumulations[t]={originalName:e+"/momentum",variable:We(function(){return Fn(r).variable(!1)})});var o=p.accumulations[t].variable,a=Array.isArray(s)?s[t].tensor:s[e];null!=a&&We(function(){var e=p.m.mul(o).add(a),n;n=p.useNesterov?p.c.mul(a.add(e.mul(p.m))).add(r):p.c.mul(e).add(r),o.assign(e),r.assign(n)})}),this.incrementIterations()},e.prototype.dispose=function(){this.m.dispose(),null!=this.accumulations&&ze(this.accumulations.map(function(e){return e.variable}))},e.prototype.setMomentum=function(e){this.momentum=e},e.prototype.getWeights=function(){return Be(this,void 0,void 0,function(){return Me(this,function(e){switch(e.label){case 0:return[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(this.accumulations.map(function(e){return{name:e.originalName,tensor:e.variable}}))];}})})},e.prototype.setWeights=function(a){return Be(this,void 0,void 0,function(){return Me(this,function(t){switch(t.label){case 0:return[4,this.extractIterations(a)];case 1:return a=t.sent(),this.accumulations=a.map(function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}}),[2];}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}},e.fromConfig=function(a,t){return new a(t.learningRate,t.momentum,t.useNesterov)},e.className="Momentum",e}(Yh);Gi(Qh);var Jh=function(s){function e(t,e,p,d,l){void 0===e&&(e=.9),void 0===p&&(p=0),void 0===d&&(d=null),void 0===l&&(l=!1);var u=s.call(this)||this;return u.learningRate=t,u.decay=e,u.momentum=p,u.epsilon=d,u.accumulatedMeanSquares=[],u.accumulatedMoments=[],u.accumulatedMeanGrads=[],u.centered=l,null==d&&(u.epsilon=kt.backend.epsilon()),u}return Fe(e,s),e.prototype.applyGradients=function(p){var d=this;(Array.isArray(p)?p.map(function(e){return e.name}):Object.keys(p)).forEach(function(e,h){var r=kt.registeredVariables[e];null==d.accumulatedMeanSquares[h]&&(d.accumulatedMeanSquares[h]={originalName:e+"/rms",variable:We(function(){return Fn(r).variable(!1)})}),null==d.accumulatedMoments[h]&&(d.accumulatedMoments[h]={originalName:e+"/momentum",variable:We(function(){return Fn(r).variable(!1)})}),null==d.accumulatedMeanGrads[h]&&d.centered&&(d.accumulatedMeanGrads[h]={originalName:e+"/mg",variable:We(function(){return Fn(r).variable(!1)})});var o=Array.isArray(p)?p[h].tensor:p[e];if(null!=o){var a=d.accumulatedMeanSquares[h].variable,i=d.accumulatedMoments[h].variable;We(function(){var e=a.mul(d.decay).add(o.square().mul(1-d.decay));if(d.centered){var t=d.accumulatedMeanGrads[h].variable,n=t.mul(d.decay).add(o.mul(1-d.decay)),s=i.mul(d.momentum).add(o.mul(d.learningRate).div(e.sub(n.square().add(d.epsilon)).sqrt()));a.assign(e),t.assign(n),i.assign(s);var p=r.sub(s);r.assign(p)}else{var u=a.mul(d.decay).add(o.square().mul(1-d.decay));s=i.mul(d.momentum).add(o.mul(d.learningRate).div(u.add(d.epsilon).sqrt())),a.assign(u),i.assign(s),p=r.sub(s),r.assign(p)}})}}),this.incrementIterations()},e.prototype.dispose=function(){null!=this.accumulatedMeanSquares&&ze(this.accumulatedMeanSquares.map(function(e){return e.variable})),null!=this.accumulatedMeanGrads&&this.centered&&ze(this.accumulatedMeanGrads.map(function(e){return e.variable})),null!=this.accumulatedMoments&&ze(this.accumulatedMoments.map(function(e){return e.variable}))},e.prototype.getWeights=function(){return Be(this,void 0,void 0,function(){var a;return Me(this,function(t){switch(t.label){case 0:return a=this.accumulatedMeanSquares.concat(this.accumulatedMoments),this.centered&&a.push.apply(a,this.accumulatedMeanGrads),[4,this.saveIterations()];case 1:return[2,[t.sent()].concat(a.map(function(e){return{name:e.originalName,tensor:e.variable}}))];}})})},e.prototype.setWeights=function(a){return Be(this,void 0,void 0,function(){var t;return Me(this,function(e){switch(e.label){case 0:return[4,this.extractIterations(a)];case 1:return a=e.sent(),t=this.centered?a.length/3:a.length/2,this.accumulatedMeanSquares=a.slice(0,t).map(function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}}),this.accumulatedMoments=a.slice(t,2*t).map(function(e){return{originalName:e.name,variable:e.tensor.variable(!1)}}),this.centered&&(this.accumulatedMeanGrads=a.slice(2*t,3*t).map(function(e){return{originalName:e.name,variable:e.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(a,t){return new a(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)},e.className="RMSProp",e}(qh);Gi(Jh);var Zh=function(){function e(){}return e.sgd=function(e){return new Yh(e)},e.momentum=function(a,t,e){return void 0===e&&(e=!1),new Qh(a,t,e)},e.rmsprop=function(a,t,s,i,p){return void 0===t&&(t=.9),void 0===s&&(s=0),void 0===i&&(i=null),void 0===p&&(p=!1),new Jh(a,t,s,i,p)},e.adam=function(a,o,s,i){return void 0===a&&(a=.001),void 0===o&&(o=.9),void 0===s&&(s=.999),void 0===i&&(i=null),new Kh(a,o,s,i)},e.adadelta=function(a,r,o){return void 0===a&&(a=.001),void 0===r&&(r=.95),void 0===o&&(o=null),new $h(a,r,o)},e.adamax=function(a,s,i,p,d){return void 0===a&&(a=.002),void 0===s&&(s=.9),void 0===i&&(i=.999),void 0===p&&(p=null),void 0===d&&(d=0),new Xh(a,s,i,p,d)},e.adagrad=function(a,t){return void 0===t&&(t=.1),new jh(a,t)},e}(),tf={sgd:Zh.sgd,momentum:Zh.momentum,adadelta:Zh.adadelta,adagrad:Zh.adagrad,rmsprop:Zh.rmsprop,adamax:Zh.adamax,adam:Zh.adam},ef="undefined"==typeof requestAnimationFrame?"undefined"==typeof setImmediate?function(e){return e()}:setImmediate:requestAnimationFrame;st=Nc;/**
       * @license
       * Copyright 2019 Google LLC. All Rights Reserved.
       * Licensed under the Apache License, Version 2.0 (the "License");
       * you may not use this file except in compliance with the License.
       * You may obtain a copy of the License at
       *
       * http://www.apache.org/licenses/LICENSE-2.0
       *
       * Unless required by applicable law or agreed to in writing, software
       * distributed under the License is distributed on an "AS IS" BASIS,
       * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       * See the License for the specific language governing permissions and
       * limitations under the License.
       * =============================================================================
       */var nf=function(a,e){return(nf=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,e){a.__proto__=e}||function(a,e){for(var t in e)e.hasOwnProperty(t)&&(a[t]=e[t])})(a,e)},$f=function(){return($f=Object.assign||function(a){for(var e=1,o=arguments.length,r;e<o;e++)for(var s in r=arguments[e])Object.prototype.hasOwnProperty.call(r,s)&&(a[s]=r[s]);return a}).apply(this,arguments)},Xf=function(a){function e(t){var n=a.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return Xi(e,a),e}(Error),Yf=function(a){function e(t){var n=a.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return Xi(e,a),e}(Error),Zf=function(a){function e(t){var n=a.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return Xi(e,a),e}(Error),Qf=function(a){function e(t){var n=a.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return Xi(e,a),e}(Error),Jf=function(a){function e(t){var n=a.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return Xi(e,a),e}(Error),ey=function(a){function e(t){var n=a.call(this,t)||this;return Object.setPrototypeOf(n,e.prototype),n}return Xi(e,a),e}(Error),ty={},ay=function(a){function e(){return null!==a&&a.apply(this,arguments)||this}return Xi(e,a),e.prototype.getConfig=function(){return{}},e}(Mh.Serializable),ny=function(a){function e(e){var t=a.call(this)||this;return t.defaultMaxValue=2,t.defaultAxis=0,t.maxValue=null==e.maxValue?t.defaultMaxValue:e.maxValue,t.axis=null==e.axis?t.defaultAxis:e.axis,t}return Xi(e,a),e.prototype.apply=function(a){var e=this;return We(function(){var t=vp(a,e.axis),n=fs(t,0,e.maxValue);return hl(a,nl(n,Ju(Ji(),t)))})},e.prototype.getConfig=function(){return{maxValue:this.maxValue,axis:this.axis}},e.className="MaxNorm",e}(ay),ry;Mh.registerClass(ny);var oy=function(a){function e(e){var t=a.call(this)||this;return t.defaultAxis=0,t.axis=null==e.axis?t.defaultAxis:e.axis,t}return Xi(e,a),e.prototype.apply=function(a){var e=this;return We(function(){return nl(a,Ju(Ji(),vp(a,e.axis)))})},e.prototype.getConfig=function(){return{axis:this.axis}},e.className="UnitNorm",e}(ay);Mh.registerClass(oy);var sy=function(a){function e(){return null!==a&&a.apply(this,arguments)||this}return Xi(e,a),e.prototype.apply=function(t){return kl(t)},e.className="NonNeg",e}(ay);Mh.registerClass(sy);var iy=function(a){function e(e){var t=a.call(this)||this;return t.defaultMinValue=0,t.defaultMaxValue=1,t.defaultRate=1,t.defaultAxis=0,t.minValue=null==e.minValue?t.defaultMinValue:e.minValue,t.maxValue=null==e.maxValue?t.defaultMaxValue:e.maxValue,t.rate=null==e.rate?t.defaultRate:e.rate,t.axis=null==e.axis?t.defaultAxis:e.axis,t}return Xi(e,a),e.prototype.apply=function(a){var e=this;return We(function(){var t=vp(a,e.axis),n=Ju(hl(e.rate,fs(t,e.minValue,e.maxValue)),hl(1-e.rate,t));return hl(a,nl(n,Ju(Ji(),t)))})},e.prototype.getConfig=function(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}},e.className="MinMaxNorm",e}(ay);Mh.registerClass(iy);var py={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"},dy=Object.freeze({maxNorm:function(t){return new ny(t)},unitNorm:function(t){return new oy(t)},nonNeg:function(){return new sy},minMaxNorm:function(t){return new iy(t)}}),ly=["channelsFirst","channelsLast"],uy=["valid","same","causal"],cy=["max","avg"],hy=["sum","mul","concat","ave"],my=new Map,gy=[],fy=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/),yy=["fanIn","fanOut","fanAvg"],by=["normal","uniform","truncatedNormal"],xy=function(a){function e(){return null!==a&&a.apply(this,arguments)||this}return Xi(e,a),e.prototype.fromConfigUsesCustomObjects=function(){return!1},e.prototype.getConfig=function(){return{}},e}(Mh.Serializable),vy=function(a){function e(){return null!==a&&a.apply(this,arguments)||this}return Xi(e,a),e.prototype.apply=function(a,e){return pn(a,e)},e.className="Zeros",e}(xy);Mh.registerClass(vy);var Cy=function(a){function e(){return null!==a&&a.apply(this,arguments)||this}return Xi(e,a),e.prototype.apply=function(a,e){return sn(a,e)},e.className="Ones",e}(xy);Mh.registerClass(Cy);var Sy=function(a){function e(e){var t=a.call(this)||this;if("object"!=typeof e)throw new Zf("Expected argument of type ConstantConfig but got "+e);if(void 0===e.value)throw new Zf("config must have value set but got "+e);return t.value=e.value,t}return Xi(e,a),e.prototype.apply=function(a,e){var t=this;return We(function(){return hl(Da(t.value),sn(a,e))})},e.prototype.getConfig=function(){return{value:this.value}},e.className="Constant",e}(xy);Mh.registerClass(Sy);var Ny=function(a){function e(e){var t=a.call(this)||this;return t.DEFAULT_MINVAL=-.05,t.DEFAULT_MAXVAL=.05,t.minval=e.minval||t.DEFAULT_MINVAL,t.maxval=e.maxval||t.DEFAULT_MAXVAL,t.seed=e.seed,t}return Xi(e,a),e.prototype.apply=function(a,e){return mr(a,this.minval,this.maxval,e)},e.prototype.getConfig=function(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}},e.className="RandomUniform",e}(xy);Mh.registerClass(Ny);var Iy=function(a){function e(e){var t=a.call(this)||this;return t.DEFAULT_MEAN=0,t.DEFAULT_STDDEV=.05,t.mean=e.mean||t.DEFAULT_MEAN,t.stddev=e.stddev||t.DEFAULT_STDDEV,t.seed=e.seed,t}return Xi(e,a),e.prototype.apply=function(a,e){if("float32"!==(e=e||"float32")&&"int32"!==e)throw new Qf("randomNormal does not support dType "+e+".");return Xp(a,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}(xy);Mh.registerClass(Iy);var ky=function(a){function e(e){var t=a.call(this)||this;return t.DEFAULT_MEAN=0,t.DEFAULT_STDDEV=.05,t.mean=e.mean||t.DEFAULT_MEAN,t.stddev=e.stddev||t.DEFAULT_STDDEV,t.seed=e.seed,t}return Xi(e,a),e.prototype.apply=function(a,e){if("float32"!==(e=e||"float32")&&"int32"!==e)throw new Qf("truncatedNormal does not support dType "+e+".");return Cr(a,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}(xy);Mh.registerClass(ky);var Ty=function(a){function e(e){var t=a.call(this)||this;return t.gain=null==e.gain?1:e.gain,t}return Xi(e,a),e.prototype.apply=function(t){var e=this;return We(function(){if(2!==t.length||t[0]!==t[1])throw new Zf("Identity matrix initializer can only be used for 2D square matrices.");return hl(e.gain,ir(t[0]))})},e.prototype.getConfig=function(){return{gain:this.gain}},e.className="Identity",e}(xy);Mh.registerClass(Ty);var Ry=function(a){function e(e){var t=a.call(this)||this;if(0>e.scale)throw new Zf("scale must be a positive float. Got: "+e.scale);return t.scale=null==e.scale?1:e.scale,t.mode=null==e.mode?"fanIn":e.mode,sd(t.mode),t.distribution=null==e.distribution?"normal":e.distribution,id(t.distribution),t.seed=e.seed,t}return Xi(e,a),e.prototype.apply=function(p,e){var d=pd(p),n=d[0],r=d[1],i=this.scale;if(i/="fanIn"===this.mode?Ef(1,n):"fanOut"===this.mode?Ef(1,r):Ef(1,(n+r)/2),"normal"===this.distribution){var l=Tf(i);if("float32"!==(e=e||"float32")&&"int32"!==e)throw new Qf(this.getClassName()+" does not support dType "+e+".");return Cr(p,0,l,e,this.seed)}var o=Tf(3*i);return mr(p,-o,o,e)},e.prototype.getConfig=function(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}},e.className="VarianceScaling",e}(xy);Mh.registerClass(Ry);var Ey=function(a){function e(e){return a.call(this,{scale:1,mode:"fanAvg",distribution:"uniform",seed:null==e?null:e.seed})||this}return Xi(e,a),e.prototype.getClassName=function(){return Ry.className},e.className="GlorotUniform",e}(Ry);Mh.registerClass(Ey);var wy=function(a){function e(e){return a.call(this,{scale:1,mode:"fanAvg",distribution:"normal",seed:null==e?null:e.seed})||this}return Xi(e,a),e.prototype.getClassName=function(){return Ry.className},e.className="GlorotNormal",e}(Ry);Mh.registerClass(wy);var Ay=function(a){function e(e){return a.call(this,{scale:2,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})||this}return Xi(e,a),e.prototype.getClassName=function(){return Ry.className},e.className="HeNormal",e}(Ry);Mh.registerClass(Ay);var Dy=function(a){function e(e){return a.call(this,{scale:2,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})||this}return Xi(e,a),e.prototype.getClassName=function(){return Ry.className},e.className="HeUniform",e}(Ry);Mh.registerClass(Dy);var _y=function(a){function e(e){return a.call(this,{scale:1,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})||this}return Xi(e,a),e.prototype.getClassName=function(){return Ry.className},e.className="LeCunNormal",e}(Ry);Mh.registerClass(_y);var Oy=function(a){function e(e){return a.call(this,{scale:1,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})||this}return Xi(e,a),e.prototype.getClassName=function(){return Ry.className},e.className="LeCunNormal",e}(Ry);Mh.registerClass(Oy);var zy=function(a){function e(e){var t=a.call(this)||this;if(t.DEFAULT_GAIN=1,t.gain=null==e.gain?t.DEFAULT_GAIN:e.gain,t.seed=e.seed,null!=t.seed)throw new Qf("Random seed is not implemented for Orthogonal Initializer yet.");return t}return Xi(e,a),e.prototype.apply=function(a){var e=this;return We(function(){if(2!==a.length)throw new Qf("The Orthogonal Initializer does not support non-2D shapes yet.");2e3<a[0]*a[1]&&console.warn("Orthogonal initializer is being called on a matrix with more than 2000 ("+a[0]*a[1]+") elements: Slowness may result.");var n=Xp(a[0]>a[1]?[a[1],a[0]]:a,0,1,"float32"),t=mc.gramSchmidt(n);return a[0]>a[1]&&(t=t.transpose()),hl(e.gain,t)})},e.prototype.getConfig=function(){return{gain:this.gain,seed:this.seed}},e.className="Orthogonal",e}(xy);Mh.registerClass(zy);var Ly={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"},Fy=Object.freeze({zeros:function(){return new vy},ones:function(){return new Cy},constant:function(t){return new Sy(t)},randomUniform:function(t){return new Ny(t)},randomNormal:function(t){return new Iy(t)},truncatedNormal:function(t){return new ky(t)},identity:function(t){return new Ty(t)},varianceScaling:function(t){return new Ry(t)},glorotUniform:function(t){return new Ey(t)},glorotNormal:function(t){return new wy(t)},heNormal:function(t){return new Ay(t)},heUniform:function(t){return new Dy(t)},leCunNormal:function(t){return new _y(t)},leCunUniform:function(t){return new Oy(t)},orthogonal:function(t){return new zy(t)}}),By=0,Py={},My="Variable",Wy=function(){function t(a,e,o,s,p){void 0===e&&(e="float32"),void 0===o&&(o=My),void 0===s&&(s=!0),void 0===p&&(p=null),this.dtype=null==e?"float32":e,this.shape=a.shape,this.id=cd(),o=null==o?My:o,this.originalName=wp(o),this.name=Ap(this.originalName),this.trainable_=s,this.constraint=p,this.val=ft(a,this.trainable_,this.name,this.dtype)}return t.prototype.read=function(){return this.assertNotDisposed(),this.val},t.prototype.write=function(t){return this.assertNotDisposed(),xd(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}(),Vy=function(){return function(t){this.dtype=t.dtype,this.shape=t.shape,this.ndim=null==t.shape?t.ndim:t.shape.length,this.maxNDim=t.maxNDim,this.minNDim=t.minNDim,this.axes=t.axes||{}}}(),Uy=function(){return function(s,e,t,n,r,i,a){this.dtype=s,this.shape=e,this.sourceLayer=t,this.inputs=n,this.callArgs=r,this.outputTensorIndex=a,this.id=cd(),null!=i&&(this.originalName=wp(i),this.name=Ap(this.originalName)),this.rank=e.length}}(),Gy=0,qy=function(){function t(a,e){this.callArgs=e,this.id=Gy++,this.outboundLayer=a.outboundLayer,this.inboundLayers=a.inboundLayers,this.nodeIndices=a.nodeIndices,this.tensorIndices=a.tensorIndices,this.inputTensors=a.inputTensors,this.outputTensors=a.outputTensors,this.inputMasks=a.inputMasks,this.outputMasks=a.outputMasks,this.inputShapes=a.inputShapes,this.outputShapes=a.outputShapes;for(var t=0,o=a.inboundLayers,r;t<o.length;t++)r=o[t],null!=r&&r.outboundNodes.push(this);a.outboundLayer.inboundNodes.push(this)}return t.prototype.getConfig=function(){for(var a=[],e=0,o=this.inboundLayers,n;e<o.length;e++)n=o[e],null==n?a.push(null):a.push(n.name);return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:a,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}},t}(),Hy=0,Ky=function(p){function e(e){var t=p.call(this)||this;t._callHook=null,t._addedWeightNames=[],t._stateful=!1,t.id=Hy++,t.activityRegularizer=null,t.inputSpec=null,t.supportsMasking=!1,t._trainableWeights=[],t._nonTrainableWeights=[],t._losses=[],t._updates=[],t._built=!1,t.inboundNodes=[],t.outboundNodes=[];var n=e.name;if(!n){var d=t.getClassName();n=sp(d)+"_"+hd(d)}if(t.name=n,t.trainable_=null==e.trainable||e.trainable,null!=e.inputShape||null!=e.batchInputShape){var i;if(null!=e.batchInputShape)i=e.batchInputShape;else if(null!=e.inputShape){var l=null;null!=e.batchSize&&(l=e.batchSize),i=[l].concat(e.inputShape)}t.batchInputShape=i;var u=e.dtype;null==u&&(u=e.inputDType),null==u&&(u="float32"),t.dtype=u}return t.initialWeights=null==e.weights?null:e.weights,t._refCount=null,t.fastWeightInitDuringBuild=!1,t}return Xi(e,p),e.nodeKey=function(a,e){return a.name+"_ib-"+e.toString()},e.prototype.getNodeAtIndex=function(a,e){if(0===this.inboundNodes.length)throw new Yf("The layer has never been called and thus has no defined "+e+".");if(this.inboundNodes.length<=a)throw new Zf("Asked to get "+e+" at node "+a+", but the layer has only "+this.inboundNodes.length+" inbound nodes.");return this.inboundNodes[a]},e.prototype.getInputAt=function(t){return rp(this.getNodeAtIndex(t,"input").inputTensors)},e.prototype.getOutputAt=function(t){return rp(this.getNodeAtIndex(t,"output").outputTensors)},Object.defineProperty(e.prototype,"input",{get:function(){if(1<this.inboundNodes.length)throw new Xf("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 Xf("Layer "+this.name+" is not connected, no input to return.");return rp(this.getNodeAtIndex(0,"input").inputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"output",{get:function(){if(0===this.inboundNodes.length)throw new Xf("Layer "+this.name+" has no inbound nodes.");if(1<this.inboundNodes.length)throw new Xf("Layer "+this.name+" has multiple inbound nodes, hence the notion of \"layer output\" is ill-defined. Use `getOutputAt(nodeIndex)` instead.");return rp(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(a){this._trainableWeights.forEach(function(e){return e.trainable=a}),this.trainable_=a},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(m){if(m=op(m),null!=this.inputSpec&&0!==this.inputSpec.length){var g=op(this.inputSpec);if(m.length!==g.length)throw new Zf("Layer "+this.name+" expects "+g.length+" inputs, but it received "+m.length+" input tensors. Input received: "+m);for(var t=0;t<m.length;t++){var f=m[t],r=g[t];if(null!=r){var i=f.rank;if(null!=r.ndim&&i!==r.ndim)throw new Zf("Input "+t+" is incompatible with layer "+this.name+": expected ndim="+r.ndim+", found ndim="+i);if(null!=r.maxNDim&&i>r.maxNDim)throw new Zf("Input "+t+" is incompatible with layer "+this.name+": expected max_ndim="+r.maxNDim+", found ndim="+i);if(null!=r.minNDim&&i<r.minNDim)throw new Zf("Input "+t+" is incompatible with layer "+this.name+": expected min_ndim="+r.minNDim+", found ndim="+i+".");if(null!=r.dtype&&f.dtype!==r.dtype)throw new Zf("Input "+t+" is incompatible with layer "+this.name+" : expected dtype="+r.dtype+", found dtype="+f.dtype+".");if(r.axes){var a=f.shape;for(var o in r.axes){var s=+o,l=r.axes[o],u=0<=s?a[s]:a[a.length+s];if(null!=l&&-1===[l,null].indexOf(u))throw new Zf("Input "+t+" is incompatible with layer "+this.name+": expected axis "+s+" of input shape to have value "+l+" but got shape "+a+".")}}if(null!=r.shape)for(var c=0;c<r.shape.length;++c){var y=r.shape[c],h=f.shape[c];if(null!=y&&null!=h&&y!==h)throw new Zf("Input "+t+" is incompatible with layer "+this.name+": expected shape="+r.shape+", found shape="+f.shape+".")}}}}},e.prototype.call=function(t){return t},e.prototype.invokeCallHook=function(a,e){null!=this._callHook&&this._callHook(a,e)},e.prototype.setCallHook=function(t){this._callHook=t},e.prototype.clearCallHook=function(){this._callHook=null},e.prototype.apply=function(y,e){var b=this;e=e||{},this.assertNotDisposed();for(var n=op(y),r=!0,p=0,d=n;p<d.length;p++)if(!(d[p]instanceof Uy)){r=!1;break}for(var x=!0,o=0,c=n;o<c.length;o++)if(c[o]instanceof Uy){x=!1;break}if(r==x)throw new Zf("Arguments to apply() must be all SymbolicTensors or all Tensors");return Rp(this.name,function(){if(!b.built){b.assertInputCompatibility(y);for(var t=[],r=0,s=op(y),o;r<s.length;r++)o=s[r],t.push(o.shape);b.build(rp(t)),b.built=!0,b.initialWeights&&b.setWeights(b.initialWeights),null===b._refCount&&x&&(b._refCount=1)}if(b.assertInputCompatibility(y),x){for(var i=[],u=0,v=op(f=b.call(y,e)),p;u<v.length;u++)p=v[u],-1!==n.indexOf(p)&&(p=p.clone()),i.push(p);if(f=rp(i),null!=b.activityRegularizer)throw new Qf("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return f}var C=Sd(y),d=b.computeOutputShape(C),f=void 0,S=Nd(y);if(b.warnOnIncompatibleInputShape(Array.isArray(y)?C[0]:C),f=null!=d&&0<d.length&&Array.isArray(d[0])?d.map(function(t,a){return new Uy(S,t,b,op(y),e,b.name,a)}):new Uy(S,d,b,op(y),e,b.name),b.addInboundNode(y,f,null,null,C,d,e),b._refCount++,null!=b.activityRegularizer)throw new Qf("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return f})},e.prototype.warnOnIncompatibleInputShape=function(a){if(null!=this.batchInputShape)if(a.length!==this.batchInputShape.length)console.warn("The rank of the input tensor provided (shape: "+JSON.stringify(a)+") does not match that of the batchInputShape ("+JSON.stringify(this.batchInputShape)+") of the layer "+this.name);else{var e=!1;this.batchInputShape.forEach(function(t,n){null!=t&&null!=a[n]&&a[n]!==t&&(e=!0)}),e&&console.warn("The shape of the input tensor ("+JSON.stringify(a)+") 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 Xf("The layer "+this.name+" has never been called and thus has no defined output shape.");for(var o=[],e=0,s=this.inboundNodes;e<s.length;e++){var n=s[e],r=JSON.stringify(n.outputShapes);-1===o.indexOf(r)&&o.push(r)}if(1===o.length){var i=this.inboundNodes[0].outputShapes;return Array.isArray(i)&&Array.isArray(i[0])&&1===i.length?i[0]:i}throw new Xf("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 Yf("You tried to call countParams() on "+this.name+", but the layer is not built yet. Build it first by calling build(batchInputShape).");return bd(this.weights)},e.prototype.build=function(){this.built=!0},e.prototype.getWeights=function(t){return void 0===t&&(t=!1),vd(t?this.trainableWeights:this.weights)},e.prototype.setWeights=function(p){var e=this;We(function(){var t=e.weights;if(t.length!==p.length)throw new Zf("You called setWeights(weights) on layer \""+e.name+"\" with a weight list of length "+p.length+", but the layer was expecting "+t.length+" weights. Provided weights: "+p+"...");if(0!==t.length){for(var n=[],r=vd(t),i=0;i<r.length;++i){var d=r[i],o=t[i],s=p[i];if(!Of.arraysEqual(d.shape,s.shape))throw new Zf("Layer weight shape "+d.shape+" not compatible with provided weight shape "+s.shape);n.push([o,s])}Cd(n)}})},e.prototype.addWeight=function(p,e,t,d,u,i,c){if(-1!==this._addedWeightNames.indexOf(p))throw new Zf("Duplicate weight name "+p+" for layer "+this.name);this._addedWeightNames.push(p),null==t&&(t="float32"),this.fastWeightInitDuringBuild&&(d=ud("zeros"));var o=d.apply(e,t),s=new Wy(o,t,p,i,c);return o.dispose(),null!=u&&this.addLoss(function(){return u.apply(s.read())}),null==i&&(i=!0),i?this._trainableWeights.push(s):this._nonTrainableWeights.push(s),s},e.prototype.setFastWeightInitDuringBuild=function(t){this.fastWeightInitDuringBuild=t},e.prototype.addLoss=function(a){var n;null==a||Array.isArray(a)&&0===a.length||(a=op(a),void 0!==this._losses&&null!==this._losses&&(n=this.losses).push.apply(n,a))},e.prototype.computeOutputShape=function(t){return t},e.prototype.computeMask=function(a,e){var t=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(a){if(null!=a)throw new TypeError("Layer "+t.name+" does not support masking, but was passed an inputMask.")})}return null}return e},e.prototype.addInboundNode=function(m,e,g,y,b,x,v){void 0===v&&(v=null);var C=op(m);e=op(e),g=op(g),y=op(y),b=gd(b),x=gd(x);for(var s=[],l=[],u=[],c=0,S=C,h;c<S.length;c++)h=S[c],s.push(h.sourceLayer),l.push(h.nodeIndex),u.push(h.tensorIndex);new qy({outboundLayer:this,inboundLayers:s,nodeIndices:l,tensorIndices:u,inputTensors:C,outputTensors:e,inputMasks:g,outputMasks:y,inputShapes:b,outputShapes:x},v);for(var N=0;N<e.length;N++)e[N].sourceLayer=this,e[N].nodeIndex=this.inboundNodes.length-1,e[N].tensorIndex=N},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}(Mh.Serializable),jy=function(o){function e(e){var t=o.call(this,{dtype:e.dtype,name:null==e.name?hd("input").toString():e.name})||this;if(null==e.batchSize&&(e.batchSize=null),null==e.sparse&&(e.sparse=!1),t.trainable=!1,t.built=!0,t.sparse=e.sparse,null!=e.inputShape&&null!=e.batchInputShape)throw new Zf("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");var n=e.batchInputShape;if(null==n){if(null==e.inputShape)throw new Zf("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");n=[e.batchSize].concat(e.inputShape)}else if(null!=e.batchSize)throw new Zf("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");var s=e.dtype||"float32";t.batchInputShape=n,t.dtype=s,t.inputSpec=[{shape:n}];var i=new Uy(t.dtype,t.batchInputShape,t,[],{},t.name);return i.nodeIndex=0,i.tensorIndex=0,new qy({outboundLayer:t,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[i],outputTensors:[i],inputMasks:[null],outputMasks:[null],inputShapes:[n],outputShapes:[n]}),t}return Xi(e,o),e.prototype.apply=function(){throw new Zf("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}(Ky),$y;Mh.registerClass(jy),function(t){t[t.SILENT=0]="SILENT",t[t.VERBOSE=1]="VERBOSE"}($y||($y={}));var Xy=function(){function t(){this.validationData=null}return t.prototype.setParams=function(t){this.params=t},t.prototype.onEpochBegin=function(){return Yi(this,void 0,void 0,function(){return Qi(this,function(){return[2]})})},t.prototype.onEpochEnd=function(){return Yi(this,void 0,void 0,function(){return Qi(this,function(){return[2]})})},t.prototype.onBatchBegin=function(){return Yi(this,void 0,void 0,function(){return Qi(this,function(){return[2]})})},t.prototype.onBatchEnd=function(){return Yi(this,void 0,void 0,function(){return Qi(this,function(){return[2]})})},t.prototype.onTrainBegin=function(){return Yi(this,void 0,void 0,function(){return Qi(this,function(){return[2]})})},t.prototype.onTrainEnd=function(){return Yi(this,void 0,void 0,function(){return Qi(this,function(){return[2]})})},t.prototype.setModel=function(){},t}(),Yy=function(){function t(a,n){void 0===n&&(n=10),null==a&&(a=[]),this.callbacks=a,this.queueLength=n}return t.prototype.append=function(t){this.callbacks.push(t)},t.prototype.setParams=function(a){for(var e=0,r=this.callbacks;e<r.length;e++)r[e].setParams(a)},t.prototype.setModel=function(a){for(var e=0,r=this.callbacks;e<r.length;e++)r[e].setModel(a)},t.prototype.onEpochBegin=function(a,e){return Yi(this,void 0,void 0,function(){var t,o;return Qi(this,function(n){switch(n.label){case 0:null==e&&(e={}),t=0,o=this.callbacks,n.label=1;case 1:return t<o.length?[4,o[t].onEpochBegin(a,e)]:[3,4];case 2:n.sent(),n.label=3;case 3:return t++,[3,1];case 4:return[2];}})})},t.prototype.onEpochEnd=function(a,e){return Yi(this,void 0,void 0,function(){var t,o;return Qi(this,function(n){switch(n.label){case 0:null==e&&(e={}),t=0,o=this.callbacks,n.label=1;case 1:return t<o.length?[4,o[t].onEpochEnd(a,e)]:[3,4];case 2:n.sent(),n.label=3;case 3:return t++,[3,1];case 4:return[2];}})})},t.prototype.onBatchBegin=function(a,e){return Yi(this,void 0,void 0,function(){var t,o;return Qi(this,function(n){switch(n.label){case 0:null==e&&(e={}),t=0,o=this.callbacks,n.label=1;case 1:return t<o.length?[4,o[t].onBatchBegin(a,e)]:[3,4];case 2:n.sent(),n.label=3;case 3:return t++,[3,1];case 4:return[2];}})})},t.prototype.onBatchEnd=function(a,e){return Yi(this,void 0,void 0,function(){var t,o;return Qi(this,function(n){switch(n.label){case 0:null==e&&(e={}),t=0,o=this.callbacks,n.label=1;case 1:return t<o.length?[4,o[t].onBatchEnd(a,e)]:[3,4];case 2:n.sent(),n.label=3;case 3:return t++,[3,1];case 4:return[2];}})})},t.prototype.onTrainBegin=function(a){return Yi(this,void 0,void 0,function(){var e,o;return Qi(this,function(t){switch(t.label){case 0:null==a&&(a={}),e=0,o=this.callbacks,t.label=1;case 1:return e<o.length?[4,o[e].onTrainBegin(a)]:[3,4];case 2:t.sent(),t.label=3;case 3:return e++,[3,1];case 4:return[2];}})})},t.prototype.onTrainEnd=function(a){return Yi(this,void 0,void 0,function(){var e,o;return Qi(this,function(t){switch(t.label){case 0:null==a&&(a={}),e=0,o=this.callbacks,t.label=1;case 1:return e<o.length?[4,o[e].onTrainEnd(a)]:[3,4];case 2:t.sent(),t.label=3;case 3:return e++,[3,1];case 4:return[2];}})})},t}(),Zy=function(a){function e(){return a.call(this)||this}return Xi(e,a),e.prototype.onEpochBegin=function(){return Yi(this,void 0,void 0,function(){return Qi(this,function(){return this.seen=0,this.totals={},[2]})})},e.prototype.onBatchEnd=function(a,s){return Yi(this,void 0,void 0,function(){var t=this,a,o,p,d;return Qi(this,function(){for(d in null==s&&(s={}),a=null==s.size?0:s.size,this.seen+=a,o=function(e){var n=s[e];if("number"==typeof n)p.totals.hasOwnProperty(e)||(p.totals[e]=0),p.totals[e]+=n*a;else{var r;e in p.totals?r=p.totals[e]:p.totals[e]=0,p.totals[e]=We(function(){return Ju(t.totals[e],hl(n,a))}),null!=r&&r.dispose()}},p=this,s)o(d);return[2]})})},e.prototype.onEpochEnd=function(a,s){return Yi(this,void 0,void 0,function(){var t=this,o,p,d,l,u;return Qi(this,function(){if(null!=s)for(o=function(a){return null==p.totals[a]?"continue":void("number"==typeof p.totals[a]?s[a]=p.totals[a]/p.seen:We(function(){s[a]=hl(nl(1,t.seen),t.totals[a]),t.totals[a].dispose(),Ve(s[a])}))},p=this,d=0,l=this.params.metrics;d<l.length;d++)u=l[d],o(u);return[2]})})},e}(Xy),Qy=function(a){function e(){return null!==a&&a.apply(this,arguments)||this}return Xi(e,a),e.prototype.onTrainBegin=function(){return Yi(this,void 0,void 0,function(){return Qi(this,function(){return this.epoch=[],this.history={},[2]})})},e.prototype.onEpochEnd=function(a,e){return Yi(this,void 0,void 0,function(){var t;return Qi(this,function(){for(t in null==e&&(e={}),this.epoch.push(a),e)null==this.history[t]&&(this.history[t]=[]),this.history[t].push(e[t]);return[2]})})},e.prototype.syncData=function(){return Yi(this,void 0,void 0,function(){var p,d,c,u,h,m,g,f,y;return Qi(this,function(e){switch(e.label){case 0:for(u in p=[],d=[],c=[],this.history)for(h=this.history[u],m=0;m<h.length;++m)"number"!=typeof h[m]&&(g=h[m],p.push(g.data()),d.push(u),c.push(m));return[4,Promise.all(p)];case 1:for(f=e.sent(),y=0;y<f.length;++y)this.history[d[y]][c[y]].dispose(),this.history[d[y]][c[y]]=f[y][0];return[2];}})})},e}(Xy),Jy=function(a){function e(e,t){var n=a.call(this)||this;if(n.currentEpoch=0,n.yieldEvery=t||"auto","auto"===n.yieldEvery&&(n.yieldEvery=125),"never"===n.yieldEvery&&null!=e.onYield)throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");return Of.isNumber(n.yieldEvery)&&(n.maybeWait=xp(n.maybeWait.bind(n),n.yieldEvery)),n.trainBegin=e.onTrainBegin,n.trainEnd=e.onTrainEnd,n.epochBegin=e.onEpochBegin,n.epochEnd=e.onEpochEnd,n.batchBegin=e.onBatchBegin,n.batchEnd=e.onBatchEnd,n.yield=e.onYield,n}return Xi(e,a),e.prototype.maybeWait=function(a,e,t){return Yi(this,void 0,void 0,function(){var n;return Qi(this,function(r){switch(r.label){case 0:return n=[],null==this.yield?[3,2]:[4,Td(t)];case 1:r.sent(),n.push(this.yield(a,e,t)),r.label=2;case 2:return n.push($i()),[4,Promise.all(n)];case 3:return r.sent(),[2];}})})},e.prototype.onEpochBegin=function(a,e){return Yi(this,void 0,void 0,function(){return Qi(this,function(t){switch(t.label){case 0:return this.currentEpoch=a,null==this.epochBegin?[3,3]:[4,Td(e)];case 1:return t.sent(),[4,this.epochBegin(a,e)];case 2:t.sent(),t.label=3;case 3:return[2];}})})},e.prototype.onEpochEnd=function(a,e){return Yi(this,void 0,void 0,function(){var t;return Qi(this,function(n){switch(n.label){case 0:return t=[],null==this.epochEnd?[3,2]:[4,Td(e)];case 1:n.sent(),t.push(this.epochEnd(a,e)),n.label=2;case 2:return"epoch"===this.yieldEvery&&t.push($i()),[4,Promise.all(t)];case 3:return n.sent(),[2];}})})},e.prototype.onBatchBegin=function(a,e){return Yi(this,void 0,void 0,function(){return Qi(this,function(t){switch(t.label){case 0:return null==this.batchBegin?[3,3]:[4,Td(e)];case 1:return t.sent(),[4,this.batchBegin(a,e)];case 2:t.sent(),t.label=3;case 3:return[2];}})})},e.prototype.onBatchEnd=function(a,e){return Yi(this,void 0,void 0,function(){var t;return Qi(this,function(n){switch(n.label){case 0:return t=[],null==this.batchEnd?[3,2]:[4,Td(e)];case 1:n.sent(),t.push(this.batchEnd(a,e)),n.label=2;case 2:return"batch"===this.yieldEvery?t.push($i()):Of.isNumber(this.yieldEvery)&&t.push(this.maybeWait(this.currentEpoch,a,e)),[4,Promise.all(t)];case 3:return n.sent(),[2];}})})},e.prototype.onTrainBegin=function(a){return Yi(this,void 0,void 0,function(){return Qi(this,function(e){switch(e.label){case 0:return null==this.trainBegin?[3,3]:[4,Td(a)];case 1:return e.sent(),[4,this.trainBegin(a)];case 2:e.sent(),e.label=3;case 3:return[2];}})})},e.prototype.onTrainEnd=function(a){return Yi(this,void 0,void 0,function(){return Qi(this,function(e){switch(e.label){case 0:return null==this.trainEnd?[3,3]:[4,Td(a)];case 1:return e.sent(),[4,this.trainEnd(a)];case 2:e.sent(),e.label=3;case 3:return[2];}})})},e}(Xy),eb=function(){function a(){}return a.registerCallbackConstructor=function(e,t){Of.assert(0<=e&&Nf(e),function(){return"Verbosity level is expected to be an integer >= 0, but got "+e}),a.checkForDuplicate(t),null==a.constructors[e]&&(a.constructors[e]=[]),a.constructors[e].push(t)},a.checkForDuplicate=function(r){for(var e in a.constructors)a.constructors[+e].forEach(function(t){if(t===r)throw new Zf("Duplicate callback constructor.")})},a.clear=function(){a.constructors={}},a.createCallbacks=function(e){var t=[];for(var n in a.constructors){var r=+n;e>=r&&t.push.apply(t,a.constructors[r])}return t.map(function(t){return new t})},a.constructors={},a}(),tb={meanSquaredError:_d,meanAbsoluteError:Od,meanAbsolutePercentageError:zd,meanSquaredLogarithmicError:function(o,e){return We(function(){var t=fs(e,Ji(),Number.MAX_VALUE),n=xs(Ju(1,t)),r=fs(o,Ji(),Number.MAX_VALUE),s=xs(Ju(1,r));return Mu(Qp(gl(n,s)),-1)})},squaredHinge:function(a,e){return We(function(){var t=al(0,gl(1,hl(a,e)));return Mu(Qp(t),-1)})},hinge:function(a,e){return We(function(){var t=al(0,gl(1,hl(a,e)));return Mu(t,-1)})},categoricalHinge:function(a,e){return We(function(){var t=Lu(hl(a,e),-1),n=Fu(hl(gl(1,a),e),-1);return al(0,Ju(1,gl(n,t)))})},logcosh:function(a,e){return We(function(){var t=mf(2),n=gl(e,a),r=gl(Ju(n,Os(hl(-2,n))),t);return Mu(r,-1)})},categoricalCrossentropy:Ld,sparseCategoricalCrossentropy:Fd,binaryCrossentropy:Pd,kullbackLeiblerDivergence:function(a,e){return We(function(){var t=fs(a,Ji(),1),n=fs(e,Ji(),1);return Lu(hl(a,xs(nl(t,n))),-1)})},poisson:function(a,e){return We(function(){var t=xs(Ju(Ji(),e));return Mu(gl(e,hl(a,t)),-1)})},cosineProximity:Md},ab=Ld,nb=Fd,rb={binaryAccuracy:Vd,categoricalAccuracy:Ud,precision:Kd,categoricalCrossentropy:ab,sparseCategoricalCrossentropy:nb,mse:_d,MSE:_d,mae:Od,MAE:Od,mape:zd,MAPE:zd,cosine:Md},ob="1.2.7",sb=function(){function o(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof o)for(var t in e.id2Value)this.id2Value[t]=e.id2Value[t],t in e.id2Mask&&(this.id2Mask[t]=e.id2Mask[t]);else{if(null==e)return;for(var n=0,s=e,i;n<s.length;n++)i=s[n],this.add(i.key,i.value)}}return o.prototype.add=function(a,e,t){if(null!=this.id2Value[a.id])throw new Zf("Duplicate key: name="+a.name+", id="+a.id);return this.id2Value[a.id]=Au(a,e),this.name2Id[a.name]=a.id,null!=t&&(this.id2Mask[a.id]=t),this},o.prototype.addFeed=function(t){this.add(t.key,t.value)},o.prototype.hasKey=function(t){return null!=this.id2Value[t.id]},o.prototype.names=function(){return Object.keys(this.name2Id)},o.prototype.getValue=function(a){if(a instanceof Uy){if(null==this.id2Value[a.id])throw new Zf("Nonexistent key: "+a.name);return this.id2Value[a.id]}var e=this.name2Id[a];if(null==e)throw new Zf("Feed dict has no SymbolicTensor name: "+a);return this.id2Value[e]},o.prototype.getMask=function(a){if(a instanceof Uy){if(null==this.id2Value[a.id])throw new Zf("Nonexistent key: "+a.name);return this.id2Mask[a.id]}var e=this.name2Id[a];if(null==e)throw new Zf("Feed dict has no SymbolicTensor name: "+a);return this.id2Mask[e]},o.prototype.disposeMasks=function(){null!=this.id2Mask&&ze(this.id2Mask)},o}(),ib={},pb={},db=function(ae){function x(e){var t=ae.call(this,{})||this;if(t.containerNodes=new Set,t.name=e.name,null==t.name){var n=t.getClassName().toLowerCase();t.name=hd(n)}if(t.supportsMasking=!1,t.trainable_=!0,t.inputs=Array.isArray(e.inputs)?e.inputs.slice():[e.inputs],t.outputs=Array.isArray(e.outputs)?e.outputs.slice():[e.outputs],hp(t.inputs).length!==t.inputs.length)throw new Zf("The list of inputs passed to the model is redundant. All inputs should only appear once. Found: "+t.inputs.map(function(t){return t.name}));hp(t.outputs).length!==t.outputs.length&&console.warn("The list of outputs passed to the model is redundant. All outputs should only appear once. Found: "+t.outputs.map(function(t){return t.name})),t.inputLayers=[],t.inputLayersNodeIndices=[],t.inputLayersTensorIndices=[],t.outputLayers=[],t.outputLayersNodeIndices=[],t.outputLayersTensorIndices=[],t.layers=[];for(var r=0,i=t.outputs;r<i.length;r++){var o=(C=i[r]).sourceLayer,oe=C.nodeIndex,se=C.tensorIndex;t.outputLayers.push(o),t.outputLayersNodeIndices.push(oe),t.outputLayersTensorIndices.push(se)}for(var pe=0,de=t.inputs;pe<de.length;pe++)o=(C=de[pe]).sourceLayer,oe=C.nodeIndex,se=C.tensorIndex,ap(0===oe,"input layer has >1 nodes"),ap(0===se,"input layer has >1 tensors"),t.inputLayers.push(o),t.inputLayersNodeIndices.push(oe),t.inputLayersTensorIndices.push(se);t.inputNames=[],t.outputNames=[],t.feedInputShapes=[],t.feedInputNames=[],t.feedOutputNames=[];for(var p=0;p<t.inputLayers.length;p++){if(!((o=t.inputLayers[p])instanceof jy))throw new TypeError("Input layers to a LayersModel must be InputLayer objects. Received inputs: "+e.inputs+". Input "+p+" (0-based) originates from layer type "+o.getClassName()+".");t.inputNames.push(o.name),t.feedInputShapes.push(o.batchInputShape),t.feedInputNames.push(o.name)}for(var le=0,ue=t.outputLayers;le<ue.length;le++)o=ue[le],t.outputNames.push(o.name);t.internalInputShapes=t.inputs.map(function(t){return t.shape}),t.internalOutputShapes=t.outputs.map(function(t){return t.shape});for(var f={},g={},m={},y={},v={},b=[],w=function(r,e,n,i,m,g){null!=i&&null!=m&&null!=g||(i=r.sourceLayer,m=r.nodeIndex,g=r.tensorIndex);var y=i.inboundNodes[m];if(-1!==n.indexOf(y))throw new Yf("The tensor "+r.name+" at layer \""+i.name+"\" is part of a cycle.");if(-1===e.indexOf(y)){t.containerNodes.add(x.nodeKey(i,m)),(i.id in v)||(v[i.id]=Object.keys(v).length),-1===n.indexOf(y)&&n.push(y);for(var l=y.inboundLayers.length,u=0;u<l;u++){var C=y.inputTensors[u],p=y.inboundLayers[u],h=y.nodeIndices[u],d=y.tensorIndices[u];w(C,e,n,p,h,d)}for(e.push(y);0<=n.indexOf(y);)n.splice(n.indexOf(y),1);b.push(y)}},z=[],S=[],A=0,ce=t.outputs,C;A<ce.length;A++)C=ce[A],w(C,z,S);for(var he=0,me=b.slice().reverse();he<me.length;he++){g[(Z=me[he]).id]=Z,Z.id in f||(f[Z.id]=0);var N=f[Z.id],ge=null==m[Z.outboundLayer.id]?0:m[Z.outboundLayer.id];for(N=Ef(N,ge),m[Z.outboundLayer.id]=N,y[Z.outboundLayer.id]=Z.outboundLayer,f[Z.id]=N,p=0;p<Z.inboundLayers.length;p++){var L=Z.inboundLayers[p],fe=(oe=Z.nodeIndices[p],L.inboundNodes[oe]),T=null==f[fe.id]?0:f[fe.id];f[fe.id]=Ef(N+1,T),g[fe.id]=fe}}var D={};for(var O in f)(N=f[O])in D||(D[N]=[]),D[N].push(g[O]);var R={};for(var M in m)(N=m[M])in R||(R[N]=[]),R[N].push(y[M]);var P=Object.keys(R).map(function(t){return parseInt(t,10)}).sort(cp);t.layers=[];for(var ye=0,be=P,B;ye<be.length;ye++){B=R[N=be[ye]],B.sort(function(a,e){var t=v[a.id],n=v[e.id];return t<n?-1:t>n?1:0});for(var xe=0,ve=B;xe<ve.length;xe++)o=ve[xe],t.layers.push(o)}t.layersByDepth=R,P=Object.keys(D).map(function(t){return parseInt(t,10)}).sort(cp);for(var j=t.inputs.slice(),$=[],q=0,Ce=P;q<Ce.length;q++)for(var H=0,Se=D[N=Ce[q]];H<Se.length;H++){var Z;if(null!=(o=(Z=Se[H]).outboundLayer)){for(var Ne=0,Ie=Z.inputTensors;Ne<Ie.length;Ne++)if(C=Ie[Ne],-1===j.indexOf(C))throw new Yf("Graph disconnected: cannot obtain value for tensor "+C+" at layer \""+o.name+"\". The following previous layers were accessed without issue: "+$);for(var X=0,ke=Z.outputTensors;X<ke.length;X++)C=ke[X],j.push(C);$.push(o.name)}}t.nodesByDepth=D;for(var ee=t.layers.map(function(t){return t.name}),te=function(a){var e=ee.filter(function(e){return e===a}).length;if(1!==e)throw new Yf("The name \""+a+"\" is used "+e+" times in the model. All layer names should be unique. Layer names: "+JSON.stringify(ee))},ne=0,Te=ee;ne<Te.length;ne++)te(Te[ne]);return t.outboundNodes=[],t.inboundNodes=[],new qy({outboundLayer:t,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:t.inputs,outputTensors:t.outputs,inputMasks:t.inputs.map(function(){return null}),outputMasks:t.outputs.map(function(){return null}),inputShapes:t.inputs.map(function(t){return t.shape}),outputShapes:t.outputs.map(function(t){return t.shape})}),t.built=!0,t._refCount=1,t}return Xi(x,ae),x.prototype.assertNotDisposed=function(){if(0===this._refCount)throw new Error("Container '"+this.name+"' is already disposed.")},x.prototype.dispose=function(){this.assertNotDisposed();var a={refCountAfterDispose:null,numDisposedVariables:0};if(0==--this._refCount)for(var e=0,o=this.layers,n;e<o.length;e++)n=o[e],a.numDisposedVariables+=n.dispose().numDisposedVariables;return a.refCountAfterDispose=this._refCount,a},Object.defineProperty(x.prototype,"trainable",{get:function(){return this.trainable_},set:function(a){this.layers.forEach(function(e){e._trainableWeights.forEach(function(e){return e.trainable=a})}),this.trainable_=a},enumerable:!0,configurable:!0}),Object.defineProperty(x.prototype,"trainableWeights",{get:function(){if(0<this._trainableWeights.length)throw new Zf("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 a=[],o=0,s=this.layers,n;o<s.length;o++)n=s[o],a=a.concat(n.trainableWeights);return a},enumerable:!0,configurable:!0}),Object.defineProperty(x.prototype,"nonTrainableWeights",{get:function(){for(var s=[],e=0,p=this.layers,n;e<p.length;e++)n=p[e],s.push.apply(s,n.nonTrainableWeights);if(!this.trainable){for(var d=[],i=0,l=this.layers;i<l.length;i++)n=l[i],d.push.apply(d,n.trainableWeights);return d.concat(s)}return s},enumerable:!0,configurable:!0}),Object.defineProperty(x.prototype,"weights",{get:function(){return this.trainableWeights.concat(this.nonTrainableWeights)},enumerable:!0,configurable:!0}),x.prototype.loadWeights=function(d,e){void 0===e&&(e=!0);for(var m={},n=0,g=0,f=this.layers;g<f.length;g++)for(var a=0,y=f[g].weights,s;a<y.length;a++){if(s=y[a],null!=m[s.originalName])throw new Zf("Duplicate weight name: "+s.originalName);m[s.originalName]=s,n++}var b=[];for(var u in d){if(null!=m[u])b.push([m[u],d[u]]);else if(e)throw new Zf("Provided weight data has no target variable: "+u);delete m[u]}if(e){var c=[];for(var p in m)c.push(p);if(0<c.length)throw new Zf(c.length+" of "+n+" weights are not set: "+c)}Cd(b)},x.prototype.updatedConfig=function(){var a=this.getConfig(),e={};return e.className=this.getClassName(),e.config=a,e.kerasVersion="tfjs-layers "+ob,e.backend="TensorFlow.js",e},x.prototype.toJSON=function(a,e){void 0===e&&(e=!0);var r=xu(this.updatedConfig());return e?JSON.stringify(r):r},x.prototype.call=function(a,o){var t=this;return We(function(){a=op(a);for(var e=new sb,n=0;n<t.inputs.length;++n)e.add(t.inputs[n],a[n]);return dc(t.outputs,e,o)})},x.prototype.computeMask=function(a,o){var t=this;return We(function(){var e;return a=op(a),e=null==o?tp(null,a.length):op(o),t.runInternalGraph(a,e)[1]})},x.prototype.computeOutputShape=function(x){var e=gd(x);if(e.length!==this.inputLayers.length)throw new Zf("Invalid inputShape argument "+x+": model has "+this.inputLayers.length+" tensor inputs.");for(var t={},n=0;n<e.length;n++){var C=this.inputLayers[n],N=e[n];t[S=C.name+"_0_0"]=N}var a=Object.keys(this.nodesByDepth).map(function(t){return parseInt(t,10)}).sort(cp);if(1<a.length)for(var o=0,I=a;o<I.length;o++)for(var l=I[o],u=0,k=this.nodesByDepth[l],p;u<k.length;u++)if(p=k[u],C=p.outboundLayer,-1===this.inputLayers.map(function(t){return t.id}).indexOf(C.id)){for(var T=[],d=0;d<p.inboundLayers.length;d++){var R=p.inboundLayers[d],g=p.nodeIndices[d],m=p.tensorIndices[d],E=t[S=R.name+"_"+g+"_"+m];T.push(E)}var v=gd(C.computeOutputShape(rp(T))),b=C.inboundNodes.indexOf(p);for(d=0;d<v.length;d++)t[S=C.name+"_"+b+"_"+d]=v[d]}var D=[],O=[];for(n=0;n<this.outputLayers.length;n++){C=this.outputLayers[n],b=this.outputLayersNodeIndices[n],m=this.outputLayersTensorIndices[n];var S=C.name+"_"+b+"_"+m;O.push(S)}for(n=0;n<O.length;n++){var z=O[n];ap(z in t),D.push(t[z])}return rp(D)},x.prototype.runInternalGraph=function(R,e){null==e&&(e=tp(null,R.length));for(var O={},n=0;n<this.inputs.length;++n){var F=this.inputs[n],B=R[n],P=e[n];O[F.id]=[B,P]}for(var M=0,W=Object.keys(this.nodesByDepth).map(function(t){return parseInt(t,10)}).sort(cp);M<W.length;M++)for(var l=W[M],u=0,V=this.nodesByDepth[l];u<V.length;u++){for(var p=V[u],h=p.outboundLayer,d=p.inputTensors,f=p.outputTensors,g=[],m=0,U=d;m<U.length;m++)(F=U[m]).id in O&&g.push(O[F.id]);if(g.length===d.length){var v={},G=void 0,q=void 0,H=void 0,K=void 0;if(null!=p.callArgs&&(v=p.callArgs),1===g.length){var j=g[0],_=j[0],C=j[1];null==v.mask&&(v.mask=C),H=op(h.call(_,v)),K=op(h.computeMask(_,C)),G=[_],q=[C]}else G=g.map(function(t){return t[0]}),q=g.map(function(t){return t[1]}),null==v.mask&&(v.mask=q),H=op(h.call(G,v)),K=op(h.computeMask(G,q));if(h.activityRegularizer)throw new Qf("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(n=0;n<f.length;++n)F=f[n],B=H[n],P=K[n],O[F.id]=[B,P]}}for(var I=[],E=[],N=[],k=0,$=this.outputs;k<$.length;k++){ap((F=$[k]).id in O,"Could not compute output "+F.name+" : "+F.id);var x=O[F.id],T=x[0];P=x[1],N.push(T.shape),I.push(T),E.push(P)}return[I,E,N]},x.prototype.buildNodeConversionMap=function(){for(var e={},t=0,r=this.layers,a,p;t<r.length;t++){p=r[t],a=p instanceof x?1:0;for(var d=0,u;d<p.inboundNodes.length;d++)u=x.nodeKey(p,d),this.containerNodes.has(u)&&(e[u]=a,a+=1)}return e},x.prototype.getLayer=function(a,e){if(null!=e){if(this.layers.length<=e)throw new Zf("Was asked to retrieve layer at index "+e+", but model only has "+this.layers.length+" layer(s).");return this.layers[e]}if(null==a)throw new Zf("Provide either a layer name or layer index");for(var t=0,o=this.layers,r;t<o.length;t++)if(r=o[t],r.name===a)return r;throw new Zf("No such layer: "+a)},x.prototype.calculateLosses=function(){var t=this;return We(function(){for(var e=[],n=0,p=t.layers;n<p.length;n++)for(var i=p[n],a=0,d;a<i.inboundNodes.length;++a)d=x.nodeKey(i,a),t.containerNodes.has(d)&&e.push.apply(e,i.calculateLosses());return e})},x.prototype.getConfig=function(){for(var t={name:this.name},e=this.buildNodeConversionMap(this.layers),n=[],r=0,C=this.layers;r<C.length;r++){for(var a=(b=C[r]).getClassName(),o=b.getConfig(),s=[],l=0;l<b.inboundNodes.length;l++){var N=b.inboundNodes[l],c=x.nodeKey(b,l),I={};if(this.containerNodes.has(c)){if(N.callArgs)try{JSON.stringify(N.callArgs),I=N.callArgs}catch(t){console.warn("Layer "+b.name+" was passed non-serializable keyword arguments: "+N.callArgs+". They will not be included in the serialized model (and thus will be missing at deserialization time)."),I={}}if(0<N.inboundLayers.length){for(var k=[],d=0;d<N.inboundLayers.length;d++){var T=N.inboundLayers[d],g=N.nodeIndices[d],R=N.tensorIndices[d];null==(D=e[x.nodeKey(T,g)])&&(D=0),k.push([T.name,D,R,I])}s.push(k)}}}var E={};E.name=b.name,E.className=a,E.config=o,E.inboundNodes=s,n.push(E)}t.layers=n;var v=[];for(d=0;d<this.inputLayers.length;d++){var b=this.inputLayers[d];g=this.inputLayersNodeIndices[d],c=x.nodeKey(b,g),this.containerNodes.has(c)&&(null!==(D=e[c])&&void 0!==D||(D=0),R=this.inputLayersTensorIndices[d],v.push([b.name,D,R]))}t.inputLayers=v;var A=[];for(d=0;d<this.outputLayers.length;d++)if(b=this.outputLayers[d],g=this.outputLayersNodeIndices[d],c=x.nodeKey(b,g),this.containerNodes.has(c)){var D;null!==(D=e[c])&&void 0!==D||(D=0),R=this.outputLayersTensorIndices[d],A.push([b.name,D,R])}return t.outputLayers=A,t},x.fromConfig=function(x,T,e,t){function n(a,e){a.name in i?i[a.name].push(e):i[a.name]=[e]}function o(o,e){for(var t=[],r=0,i=e,s;r<i.length;r++){var m=i[r],l=m[0],u=m[1],c=m[2];if(s=null==m[3]?{}:m[3],!(l in R))return void n(o,e);var p=R[l];if(p.inboundNodes.length<=u)return void n(o,e);var h=p.inboundNodes[u];t.push(h.outputTensors[c])}0<t.length&&o.apply(rp(t),s)}function s(r){var e=r.name,o=Ad(r,null==T.customObjects?{}:T.customObjects);o.setFastWeightInitDuringBuild(t),R[e]=o,r.inboundNodes.forEach(function(t){if(!(t instanceof Array))throw new Zf("Corrupted configuration, expected array for nodeData: "+t);n(o,t)})}void 0===t&&(t=!1);for(var R={},i={},a=T.name,l=T.layers,u=0,c=l;u<c.length;u++)s(f=c[u]);for(;!mp(i);)for(var h=0,D=l,f;h<D.length;h++)if(f=D[h],(N=R[f.name]).name in i){var O=i[N.name];delete i[N.name];for(var m=0,L=O;m<L.length;m++)o(N,L[m])}for(var v=[],b=[],w=0,F=T.inputLayers;w<F.length;w++){var S=(f=F[w])[0],B=f[1],P=f[2];ap(S in R);var M=(N=R[S]).inboundNodes[B].outputTensors;v.push(M[P])}for(var W=0,V=T.outputLayers;W<V.length;W++){S=(f=V[W])[0],B=f[1],P=f[2],ap(S in R);var N;M=(N=R[S]).inboundNodes[B].outputTensors,b.push(M[P])}return new x({inputs:v,outputs:b,name:a})},Object.defineProperty(x.prototype,"stateful",{get:function(){if(this._stateful)throw new Zf("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 a=0,n=this.layers;a<n.length;a++)if(n[a].stateful)return!0;return!1},enumerable:!0,configurable:!0}),x.prototype.resetStates=function(){var t=this;We(function(){t.layers.forEach(function(t){t.stateful&&t.resetStates()})})},x}(Ky),lb=function(a){function e(e){var t=a.call(this,e)||this;return t.isTraining=!1,t}return Xi(e,a),e.prototype.summary=function(a,e,t){if(void 0===t&&(t=console.log),!this.built)throw new Zf("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).");Jd(this,a,e,t)},e.prototype.compile=function(m){var g=this;if(null==m.loss&&(m.loss=[]),this.loss=m.loss,"string"==typeof m.optimizer)this.optimizer_=Qd(m.optimizer),this.isOptimizerOwned=!0;else{if(!(m.optimizer instanceof qh))throw new Zf("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=m.optimizer,this.isOptimizerOwned=!1}var e=[];if(!(Array.isArray(m.loss)||"string"==typeof m.loss||"function"==typeof m.loss)){for(var t in m.loss=m.loss,m.loss)if(-1===this.outputNames.indexOf(t))throw new Zf("Unknown entry in loss dictionary: \""+t+"\". Only expected the following keys: "+this.outputNames);for(var a=0,f=this.outputNames,s;a<f.length;a++)s=f[a],null==m.loss[s]&&console.warn("Output \""+s+"\" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to "+s+" during training"),e.push(Wd(m.loss[s]))}else if(Array.isArray(m.loss)){if(m.loss.length!==this.outputs.length)throw new Zf("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="+m.loss+".");var y=m.loss;e=y.map(function(t){return Wd(t)})}else{var r=Wd(m.loss);this.outputs.forEach(function(){e.push(r)})}this.lossFunctions=e,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(var i=0;i<this.outputs.length;++i){var b=this.internalOutputShapes[i],c=this.outputNames[i];this.feedOutputNames.push(c),this.feedOutputShapes.push(b),this.feedLossFns.push(this.lossFunctions[i])}var p=[];this.metrics=m.metrics,this.metricsNames=["loss"],this.metricsTensors=[],Rp("loss",function(){for(var t=0;t<g.outputs.length;++t)if(-1===p.indexOf(t)){var a=g.lossFunctions[t];1<g.outputs.length&&(g.metricsTensors.push([a,t]),g.metricsNames.push(g.outputNames[t]+"_loss"))}});var h=zh(m.metrics,this.outputNames);Rp("metric",function(){for(var t=function(t){return-1===p.indexOf(t)?void!function(e){for(var n=function(e){if("string"==typeof e&&-1!==["accuracy","acc","crossentropy","ce"].indexOf(e)){var a=g.internalOutputShapes[t];1===a[a.length-1]||g.lossFunctions[t]===Pd?-1===["accuracy","acc"].indexOf(e)?-1!==["crossentropy","ce"].indexOf(e)&&(l=$d):l=Vd:g.lossFunctions[t]===Fd?-1===["accuracy","acc"].indexOf(e)?-1!==["crossentropy","ce"].indexOf(e)&&(l=nb):l=Xd:-1===["accuracy","acc"].indexOf(e)?-1!==["crossentropy","ce"].indexOf(e)&&(l=ab):l=Ud;var n;-1===["accuracy","acc"].indexOf(e)?-1!==["crossentropy","ce"].indexOf(e)&&(n="ce"):n="acc",u=l,d=""+n}else{var r=Yd(e);u=r,d=""+Zd(e)}var o;Rp(d,function(){o=u}),function(t,e,a){1<g.outputNames.length&&(e=g.outputNames[t]+"_"+e),g.metricsNames.push(e),g.metricsTensors.push([a,t])}(t,d,o)},o=0,p=e,d,l,u;o<p.length;o++)n(p[o])}(h[t]):"continue"},e=0;e<g.outputs.length;++e)t(e)}),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(s,e,t){void 0===t&&(t={});var p=null==t.batchSize?32:t.batchSize;oh(p);var r=this.standardizeUserDataXY(s,e,!0,p);try{var i=r[0].concat(r[1]);this.makeTestFunction();var a=this.testFunction;return rp(this.testLoop(a,i,p,t.verbose,t.steps))}finally{mh(r[0],s),mh(r[1],e)}},e.prototype.evaluateDataset=function(a,e){return Yi(this,void 0,void 0,function(){return Qi(this,function(){return this.makeTestFunction(),[2,rh(this,a,e)]})})},e.prototype.checkNumSamples=function(a,e,t,n){var o;if(void 0===n&&(n="steps"),null==t){if(null==a)throw new Zf("Either the input data should have a defined shape, or "+n+" shoud be specified.");o=Array.isArray(a)?a[0].shape[0]:a.shape[0]}else if(o=null,null!=e)throw new Zf("If "+n+" is set, batchSize must be null or undefined.Got batchSize = "+e);return o},e.prototype.execute=function(d,h){if(Array.isArray(h)&&0===h.length)throw new Zf("`outputs` is an empty Array, which is not allowed.");var t=Array.isArray(h),n=t?h:[h],r=this.retrieveSymbolicTensors(n),i=new sb;if(d instanceof Lf&&(d=[d]),Array.isArray(d)){if(d.length!==this.inputs.length)throw new Zf("The number of inputs provided ("+d.length+") does not match the number of inputs of this model ("+this.inputs.length+").");for(var a=0;a<this.inputs.length;++a)i.add(this.inputs[a],d[a])}else for(var m=0,g=this.inputs;m<g.length;m++){var l=g[m],u=d[l.name];if(null==u)throw new Zf("No value is provided for the model's input "+l.name);i.add(l,u)}var c=dc(r,i);return t?c:c[0]},e.prototype.retrieveSymbolicTensors=function(p){for(var e=tp(null,p.length),t=p.length,d=0,h=this.layers;d<h.length;d++){for(var i=h[d],a=Array.isArray(i.output)?i.output:[i.output],o=a.map(function(t){return t.name}),s=0,m;s<p.length&&(m=o.indexOf(p[s]),-1!==m&&(e[s]=a[m],t--),0!==t);++s);if(0===t)break}if(0<t){var g=[];throw e.forEach(function(e,t){null==e&&g.push(p[t])}),new Zf("Cannot find SymbolicTensors for output name(s): "+JSON.stringify(g))}return e},e.prototype.predictLoop=function(p,e,d){var c=this;return void 0===e&&(e=32),void 0===d&&(d=!1),We(function(){var t=c.checkNumSamples(p);if(d)throw new Qf("Verbose predictLoop() is not implemented yet.");for(var r=dh(t,e),a=c.outputs.map(function(){return[]}),n=function(e){We(function(){var t=r[e][0],a=r[e][1],n=sh(p,t,a),o=[];if(Array.isArray(n))for(var s=0;s<n.length;++s)o.push({key:c.inputs[s],value:n[s]});else o.push({key:c.inputs[0],value:n});var i=new sb(o);return dc(c.outputs,i)}).forEach(function(n,e){return a[e].push(n)})},o=0;o<r.length;++o)n(o);return rp(a.map(function(t){return Mn(t,0)}))})},e.prototype.predict=function(a,e){void 0===e&&(e={});var o=ch(a);wh(o,this.inputNames,this.feedInputShapes,!1);try{var n=null==e.batchSize?32:e.batchSize;return oh(n),this.predictLoop(o,n)}finally{mh(o,a)}},e.prototype.predictOnBatch=function(a){wh(a,this.inputNames,this.feedInputShapes,!0);var e=(Array.isArray(a)?a[0]:a).shape[0];return this.predictLoop(a,e)},e.prototype.standardizeUserDataXY=function(s,p,d,n){if(null==this.optimizer_)throw new Yf("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");for(var r=[],i=0,l;i<this.feedOutputShapes.length;++i)l=this.feedOutputShapes[i],this.feedLossFns[i]===Fd?r.push(l.slice(0,l.length-1).concat([1])):r.push(l);if(Sh(s=Ch(s,this.feedInputNames,this.feedInputShapes,!1,"input"),p=Ch(p,this.feedOutputNames,r,!1,"target")),Rh(p,this.feedLossFns,this.feedOutputShapes),this.stateful&&null!=n&&0<n&&0!=s[0].shape[0]%n)throw new Zf("In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size "+n+". Found: "+s[0].shape[0]+" sample(s).");return[s,p]},e.prototype.standardizeUserData=function(m,e,t,n,r,g){return void 0===r&&(r=!0),Yi(this,void 0,void 0,function(){var a,i,y,b,x,v,C,S;return Qi(this,function(o){switch(o.label){case 0:if(a=this.standardizeUserDataXY(m,e,r,g),i=a[0],y=a[1],null!=t)throw new Error("sample weight is not supported yet.");if(b=null,null==n)return[3,4];x=Pc(n,this.outputNames),b=[],v=0,o.label=1;case 1:return v<x.length?(S=(C=b).push,[4,Vc(y[v],null,x[v])]):[3,4];case 2:S.apply(C,[o.sent()]),o.label=3;case 3:return++v,[3,1];case 4:return[2,[i,y,b]];}})})},e.prototype.testLoop=function(o,e,t,n,b){var i=this;return void 0===n&&(n=0),We(function(){var a=i.checkNumSamples(e,t,b,"steps"),r=[];if(0<n)throw new Qf("Verbose mode is not implemented yet.");if(null!=b)throw new Qf("steps mode in testLoop() is not implemented yet");for(var s=dh(a,t),l=en(Bp(0,a)),u=0;u<s.length;++u){var x=s[u][0],p=s[u][1],h=Gp(l,x,p-x),d=ih(e,h),f=o(d);if(0==u)for(var g=0;g<f.length;++g)r.push(Da(0));for(g=0;g<f.length;++g){var v=f[g];r[g]=Ju(r[g],hl(p-x,v))}}for(g=0;g<r.length;++g)r[g]=nl(r[g],a);return r})},e.prototype.getDedupedMetricsNames=function(){for(var a=this.metricsNames,e=[],t=0;t<a.length;++t){var o=a[t],r=o;1<np(a,o)&&(r+="_"+np(a.slice(0,t),o)),e.push(r)}return e},e.prototype.makeTrainFunction=function(){var m=this;return function(e){var t=[],n=e.slice(0,m.inputs.length),r=e.slice(m.inputs.length,m.inputs.length+m.outputs.length),i=e.slice(m.inputs.length+m.outputs.length,m.inputs.length+2*m.outputs.length),a=[],o=m.collectedTrainableWeights.map(function(t){return t.read()});return[m.optimizer_.minimize(function(){for(var e=[],o=0;o<m.inputs.length;++o)e.push({key:m.inputs[o],value:n[o]});var y=new sb(e),u=dc(m.outputs,y,{training:!0}),c;for(o=0;o<m.lossFunctions.length;++o){var b=(0,m.lossFunctions[o])(r[o],u[o]);null!=i[o]&&(b=Uc(b,i[o]));var x=Mu(b);t.push(x),c=0==o?b:Ju(c,b)}for(o=0;o<m.metricsTensors.length;++o){var h=void 0;if(1<m.outputs.length&&o<m.outputs.length)h=t[o];else{var v=m.metricsTensors[o][0],f=m.metricsTensors[o][1];h=Mu(v(r[f],u[f]))}Ve(h),a.push(h)}return c=Mu(c),m.calculateLosses().forEach(function(t){c=Ju(c,t)}),c},!0,o)].concat(a)}},e.prototype.makeTestFunction=function(){var m=this;this.testFunction=function(e){return We(function(){for(var t=[],r=e.slice(0,m.inputs.length),i=e.slice(m.inputs.length,m.inputs.length+m.outputs.length),a=[],o=0,g;o<m.inputs.length;++o)a.push({key:m.inputs[o],value:r[o]});var y=new sb(a),l=dc(m.outputs,y);for(o=0;o<m.lossFunctions.length;++o){var u=m.lossFunctions[o],c=Mu(u(i[o],l[o]));g=0==o?c:Ju(g,c),t.push(g)}for(o=0;o<m.metricsTensors.length;++o){var p=m.metricsTensors[o][0],h=m.metricsTensors[o][1],d=Mu(p(i[h],l[h]));t.push(d)}return t})}},e.prototype.fit=function(a,e,t){return void 0===t&&(t={}),Yi(this,void 0,void 0,function(){return Qi(this,function(){return[2,uh(this,a,e,t)]})})},e.prototype.fitDataset=function(a,e){return Yi(this,void 0,void 0,function(){return Qi(this,function(){return[2,Qc(this,a,e)]})})},e.prototype.trainOnBatch=function(d,e){return Yi(this,void 0,void 0,function(){var t,h,m,g,f,y,b,x,v;return Qi(this,function(a){switch(a.label){case 0:return[4,this.standardizeUserData(d,e)];case 1:t=a.sent(),h=t[0],m=t[1],g=this.makeTrainFunction(),f=g(h.concat(m)),y=[],b=0,x=f,a.label=2;case 2:return b<x.length?[4,x[b].data()]:[3,5];case 3:v=a.sent(),y.push(v[0]),a.label=4;case 4:return b++,[3,2];case 5:return ze(f),[2,rp(y)];}})})},e.prototype.getNamedWeights=function(o){for(var e=[],t=null!=o&&o.trainableOnly,n=t?this.trainableWeights:this.weights,r=this.getWeights(t),s=0;s<n.length;++s)t&&!n[s].trainable||e.push({name:n[s].originalName,tensor:r[s]});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=a.prototype.dispose.call(this);if(0===e.refCountAfterDispose&&null!=this.optimizer&&this.isOptimizerOwned){var t=Pe().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-Pe().numTensors}return e},e.prototype.getLossIdentifiers=function(){var p;if("string"==typeof this.loss)p=sp(this.loss);else if(Array.isArray(this.loss)){for(var d=0,l=this.loss;d<l.length;d++)if("string"!=typeof l[d])throw new Error("Serialization of non-string loss is not supported.");p=this.loss.map(function(t){return sp(t)})}else{var n=Object.keys(this.loss);p={};for(var r=this.loss,i=0,u=n,o;i<u.length;i++){if(o=u[i],"string"!=typeof r[o])throw new Error("Serialization of non-string loss is not supported.");p[o]=sp(r[o])}}return p},e.prototype.getMetricIdentifiers=function(){if("string"==typeof this.metrics||"function"==typeof this.metrics)return[sp(Zd(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(function(t){return sp(Zd(t))});var a={};for(var e in this.metrics)a[e]=sp(Zd(this.metrics[e]));return a},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(a){if(null!=a.weighted_metrics)throw new Error("Loading weight_metrics is not supported yet.");if(null!=a.loss_weights)throw new Error("Loading loss_weights is not supported yet.");if(null!=a.sample_weight_mode)throw new Error("Loading sample_weight_mode is not supported yet.");var e=Ad(bu(a.optimizer_config)),r,o;if("string"==typeof a.loss)r=ip(a.loss);else if(Array.isArray(a.loss))r=a.loss.map(function(t){return ip(t)});else if(null!=a.loss)for(var s in r={},a.loss)r[s]=ip(a.loss[s]);if(Array.isArray(a.metrics))o=a.metrics.map(function(t){return ip(t)});else if(null!=a.metrics)for(var s in o={},a.metrics)o[s]=ip(a.metrics[s]);this.compile({loss:r,metrics:o,optimizer:e})},e.prototype.save=function(m,y){return Yi(this,void 0,void 0,function(){var e,t,b,x,v,C,S,N,I,k,T,R,E;return Qi(this,function(a){switch(a.label){case 0:if("string"==typeof m){if(0===(t=kh.getSaveHandlers(m)).length)throw new Zf("Cannot find any save handlers for URL '"+m+"'");if(1<t.length)throw new Zf("Found more than one ("+t.length+") save handlers for URL '"+m+"'");m=t[0]}if(null==m.save)throw new Zf("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return[4,kh.encodeWeights(this.getNamedWeights(y))];case 1:return b=a.sent(),x=!1,v=null,C=this.toJSON(v,x),S={modelTopology:C,format:"layers-model",generatedBy:"TensorFlow.js tfjs-layers v"+ob,convertedBy:null},null!=y&&y.includeOptimizer&&null!=this.optimizer?(S.trainingConfig=this.getTrainingConfig(),N="optimizer",E=(R=kh).encodeWeights,[4,this.optimizer.getWeights()]):[3,4];case 2:return[4,E.apply(R,[a.sent(),N])];case 3:I=a.sent(),k=I.data,T=I.specs,(e=b.specs).push.apply(e,T),b.data=kh.concatenateArrayBuffers([b.data,k]),a.label=4;case 4:return S.weightData=b.data,S.weightSpecs=b.specs,[2,m.save(S)];}})})},e.className="Model",e}(db);Mh.registerClass(lb);var ub=function(o){function p(e){var s=o.call(this,{inputs:[],outputs:[]})||this;if(e=e||{},s.trainable=!0,s.built=!1,s.name=null==e.name?hd("sequential_"):e.name,null!=e.layers)for(var n=0,p=e.layers,i;n<p.length;n++)i=p[n],s.add(i);return s}return Xi(p,o),p.prototype.checkShape=function(t){if(t.inboundNodes[0].outputTensors[0].shape.some(function(t){return 0>t}))throw new Zf("Negative dimension size caused by adding layer "+t.name+" with input shape ["+t.inboundNodes[0].inputTensors[0].shape+"]")},p.prototype.add=function(t){var e=t instanceof p||t instanceof lb,r;if(e){if(1!==(r=t).outputs.length)throw new Zf("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(1!==r.inputs.length)throw new Zf("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 Zf("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");var o=kd({batchShape:t.batchInputShape,dtype:t.dtype,name:t.name+"_input"});t.apply(o)}if(e)this.outputs=r.outputs,this.inputs=r.inputs;else{if(1!==t.inboundNodes.length)throw new Zf("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 Zf("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=Id(this.outputs[0])}this.inboundNodes=[],new qy({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:tp(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(function(t){return t.shape}),outputShapes:this.outputs[0].shape})}else{var s=t.apply(this.outputs[0]);if(Array.isArray(s))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=[s],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(t),this.built=!1},p.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]}},p.prototype.call=function(a,e){return null==this.model&&this.build(),this.model.call(a,e)},p.prototype.build=function(t){if(yd(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 lb({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},p.prototype.countParams=function(){return this.built||this.build(),o.prototype.countParams.call(this)},p.prototype.summary=function(e,t,a){void 0===a&&(a=console.log),this.built||this.build(),o.prototype.summary.call(this,e,t,a)},p.prototype.setWeights=function(t){null==this.model&&this.build(),this.model.setWeights(t)},p.prototype.evaluate=function(a,e,t){if(void 0===t&&(t={}),!this.built)throw new Yf("The model needs to be compiled before being used.");return this.model.evaluate(a,e,t)},p.prototype.evaluateDataset=function(a,e){return Yi(this,void 0,void 0,function(){return Qi(this,function(){if(!this.built)throw new Yf("The model needs to be compiled before being used.");return[2,this.model.evaluateDataset(a,e)]})})},p.prototype.predict=function(a,e){return void 0===e&&(e={}),null==this.model&&this.build(),this.model.predict(a,e)},p.prototype.predictOnBatch=function(t){return null==this.model&&this.build(),this.model.predictOnBatch(t)},p.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(p.prototype,"optimizer",{get:function(){return null==this.model?void 0:this.model.optimizer},set:function(t){this.model.optimizer=t},enumerable:!0,configurable:!0}),p.prototype.fit=function(a,e,t){return void 0===t&&(t={}),Yi(this,void 0,void 0,function(){return Qi(this,function(){if(!this.built)throw new Yf("The model needs to be compiled before being used.");return[2,this.model.fit(a,e,t)]})})},p.prototype.fitDataset=function(a,e){return Yi(this,void 0,void 0,function(){return Qi(this,function(){if(!this.built)throw new Yf("The model needs to be compiled before being used.");return[2,this.model.fitDataset(a,e)]})})},p.prototype.trainOnBatch=function(a,e){return Yi(this,void 0,void 0,function(){return Qi(this,function(){return[2,this.model.trainOnBatch(a,e)]})})},p.fromConfig=function(t,e,n,r){var d;void 0===r&&(r=!1);var h={};if(e instanceof Array){if(null==e[0].className||"Merge"===e[0].className)throw new Zf("Legacy serialization format not supported yet.");d=e}else Of.assert(null!=e.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."}),d=e.layers,delete e.layers,h=e;var m=new t(h);if(!(m instanceof p))throw new Qf("Sequential.fromConfig called on non-Sequential input: "+m);for(var s=0,g=d,u;s<g.length;s++)u=Ad(g[s],void 0,r),r&&u.setFastWeightInitDuringBuild(!0),m.add(u);return m},Object.defineProperty(p.prototype,"stopTraining",{get:function(){if(null==this.model)throw new Zf("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 Zf("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=t},enumerable:!0,configurable:!0}),p.prototype.getConfig=function(){for(var a=[],e=0,o=this.layers;e<o.length;e++){var n=o[e],r={};r.className=n.getClassName(),r.config=n.getConfig(),a.push(r)}return a},p.className="Sequential",p}(lb);Mh.registerClass(ub);var cb=function(a){function e(){return null!==a&&a.apply(this,arguments)||this}return Xi(e,a),e.prototype.getConfig=function(){return{}},e}(Mh.Serializable),hb=function(a){function e(){return null!==a&&a.apply(this,arguments)||this}return Xi(e,a),e.prototype.apply=function(a,e){return void 0===e&&(e=1),td(a,e)},e.className="elu",e}(cb);Mh.registerClass(hb);var mb=function(a){function e(){return null!==a&&a.apply(this,arguments)||this}return Xi(e,a),e.prototype.apply=function(t){return Al(t)},e.className="selu",e}(cb);Mh.registerClass(mb);var gb=function(a){function e(){return null!==a&&a.apply(this,arguments)||this}return Xi(e,a),e.prototype.apply=function(t){return kl(t)},e.className="relu",e}(cb);Mh.registerClass(gb);var fb=function(a){function e(){return null!==a&&a.apply(this,arguments)||this}return Xi(e,a),e.prototype.apply=function(t){return We(function(){return sl(6,kl(t))})},e.className="relu6",e}(cb);Mh.registerClass(fb);var yb=function(a){function e(){return null!==a&&a.apply(this,arguments)||this}return Xi(e,a),e.prototype.apply=function(t){return t},e.className="linear",e}(cb);Mh.registerClass(yb);var bb=function(a){function e(){return null!==a&&a.apply(this,arguments)||this}return Xi(e,a),e.prototype.apply=function(t){return Ss(t)},e.className="sigmoid",e}(cb);Mh.registerClass(bb);var xb=function(a){function e(){return null!==a&&a.apply(this,arguments)||this}return Xi(e,a),e.prototype.apply=function(t){return rd(t)},e.className="hardSigmoid",e}(cb);Mh.registerClass(xb);var vb=function(a){function e(){return null!==a&&a.apply(this,arguments)||this}return Xi(e,a),e.prototype.apply=function(t){return Os(t)},e.className="softplus",e}(cb);Mh.registerClass(vb);var Cb=function(a){function e(){return null!==a&&a.apply(this,arguments)||this}return Xi(e,a),e.prototype.apply=function(t){return ad(t)},e.className="softsign",e}(cb);Mh.registerClass(Cb);var Sb=function(a){function e(){return null!==a&&a.apply(this,arguments)||this}return Xi(e,a),e.prototype.apply=function(t){return Ls(t)},e.className="tanh",e}(cb);Mh.registerClass(Sb);var Nb=function(a){function e(){return null!==a&&a.apply(this,arguments)||this}return Xi(e,a),e.prototype.apply=function(a,e){return void 0===e&&(e=-1),Ir(a,e)},e.className="softmax",e}(cb);Mh.registerClass(Nb);var Ib=function(a){function e(){return null!==a&&a.apply(this,arguments)||this}return Xi(e,a),e.prototype.apply=function(a,e){return void 0===e&&(e=-1),Kr(a,e)},e.className="logSoftmax",e}(cb);Mh.registerClass(Ib);var kb=function(a){function e(){return null!==a&&a.apply(this,arguments)||this}return Xi(e,a),e}(Mh.Serializable),Tb=function(a){function e(e){var t=a.call(this)||this;return t.l1=null==e||null==e.l1?.01:e.l1,t.l2=null==e||null==e.l2?.01:e.l2,t.hasL1=0!==t.l1,t.hasL2=0!==t.l2,t}return Xi(e,a),e.prototype.apply=function(a){var e=this;return We(function(){var t=pn([1]);return e.hasL1&&(t=Ju(t,Lu(hl(e.l1,os(a))))),e.hasL2&&(t=Ju(t,Lu(hl(e.l2,Qp(a))))),t.asScalar()})},e.prototype.getConfig=function(){return{l1:this.l1,l2:this.l2}},e.fromConfig=function(a,e){return new a({l1:e.l1,l2:e.l2})},e.className="L1L2",e}(kb);Mh.registerClass(Tb);var Rb={l1l2:"L1L2"},Eb=function(a){function e(e){var t=a.call(this,null==e?{}:e)||this;return t.supportsMasking=!0,null!=e&&(t.maxValue=e.maxValue),t}return Xi(e,a),e.prototype.call=function(t){t=fd(t);var a=kl(t);return null!=this.maxValue&&(a=fs(a,0,this.maxValue)),a},e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e={maxValue:this.maxValue},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e.className="ReLU",e}(Ky);Mh.registerClass(Eb);var wb=function(a){function e(e){var r=a.call(this,null==e?{}:e)||this;return r.DEFAULT_ALPHA=.3,null==e&&(e={}),r.alpha=null==e.alpha?r.DEFAULT_ALPHA:e.alpha,r}return Xi(e,a),e.prototype.call=function(t){var e=fd(t);return Sl(e,this.alpha)},e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e={alpha:this.alpha},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e.className="LeakyReLU",e}(Ky);Mh.registerClass(wb);var Ab=function(a){function e(e){var r=a.call(this,null==e?{}:e)||this;if(r.DEFAULT_ALPHA_INITIALIZER="zeros",null==e&&(e={}),r.supportsMasking=!0,r.alphaInitializer=ud(e.alphaInitializer||r.DEFAULT_ALPHA_INITIALIZER),r.alphaRegularizer=im(e.alphaRegularizer),r.alphaConstraint=Np(e.alphaConstraint),null==e.sharedAxes)r.sharedAxes=null;else if(Array.isArray(e.sharedAxes))r.sharedAxes=e.sharedAxes;else{if("number"!=typeof e.sharedAxes)throw new Zf("Expected sharedAxes to be a number or an array of numbers, but got "+e.sharedAxes);r.sharedAxes=[e.sharedAxes]}return r}return Xi(e,a),e.prototype.build=function(o){var s=(o=yd(o)).slice(1);if(null!=this.sharedAxes)for(var t=0,p=this.sharedAxes;t<p.length;t++)s[(i=p[t])-1]=1;this.alpha=this.addWeight("alpha",s,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);var r={};if(null!=this.sharedAxes)for(var i=1;i<o.length;++i)r[i]=o[i];this.inputSpec=[new Vy({ndim:o.length,axes:r})],this.built=!0},e.prototype.call=function(t){return t=fd(t),Nl(t,this.alpha.read())},e.prototype.getConfig=function(){var e={alphaInitializer:ld(this.alphaInitializer),alphaRegularizer:om(this.alphaRegularizer),alphaConstraint:Cp(this.alphaConstraint),sharedAxes:this.sharedAxes},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e.className="PReLU",e}(Ky);Mh.registerClass(Ab);var Db=function(a){function e(e){var r=a.call(this,null==e?{}:e)||this;if(r.DEFAULT_ALPHA=1,null==e&&(e={}),null!=e.alpha&&e.alpha!==r.DEFAULT_ALPHA)throw new Qf("Non-default alpha value ("+e.alpha+") is not supported by the ELU layer yet.");return r.alpha=null==e.alpha?r.DEFAULT_ALPHA:e.alpha,r}return Xi(e,a),e.prototype.call=function(t){var e=fd(t);return Il(e)},e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e={alpha:this.alpha},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e.className="ELU",e}(Ky);Mh.registerClass(Db);var _b=function(a){function e(e){var r=a.call(this,null==e?{}:e)||this;return r.DEFAULT_THETA=1,null==e&&(e={}),r.theta=null==e.theta?r.DEFAULT_THETA:e.theta,r}return Xi(e,a),e.prototype.call=function(t){var e=fd(t);return e.mul(Pp(e.greater(this.theta),"float32"))},e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e={theta:this.theta},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e.className="ThresholdedReLU",e}(Ky);Mh.registerClass(_b);var Ob=function(a){function e(e){var r=a.call(this,null==e?{}:e)||this;return r.DEFAULT_AXIS=1,null==e&&(e={}),r.softmax=new Nb().apply,r.axis=null==e.axis?r.DEFAULT_AXIS:e.axis,r}return Xi(e,a),e.prototype.call=function(t){var e=fd(t);return this.softmax(e,this.axis)},e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e={axis:this.axis},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e.className="Softmax",e}(Ky);Mh.registerClass(Ob);var zb=function(a){function e(t,n){var r=a.call(this,n)||this;if(r.bias=null,r.DEFAULT_KERNEL_INITIALIZER="glorotNormal",r.DEFAULT_BIAS_INITIALIZER="zeros",e.verifyArgs(n),r.rank=t,yp(r.rank,"rank"),1!==r.rank&&2!==r.rank&&3!==r.rank)throw new Qf("Convolution layer for rank other than 1, 2, or 3 ("+r.rank+") is not implemented yet.");if(r.kernelSize=pm(n.kernelSize,t,"kernelSize"),r.strides=pm(null==n.strides?1:n.strides,t,"strides"),r.padding=null==n.padding?"valid":n.padding,kp(r.padding),r.dataFormat=null==n.dataFormat?"channelsLast":n.dataFormat,Ip(r.dataFormat),r.activation=am(n.activation),r.useBias=null==n.useBias||n.useBias,r.biasInitializer=ud(n.biasInitializer||r.DEFAULT_BIAS_INITIALIZER),r.biasConstraint=Np(n.biasConstraint),r.biasRegularizer=im(n.biasRegularizer),r.activityRegularizer=im(n.activityRegularizer),r.dilationRate=pm(null==n.dilationRate?1:n.dilationRate,t,"dilationRate"),1===r.rank&&Array.isArray(r.dilationRate)&&1!==r.dilationRate.length)throw new Zf("dilationRate must be a number or an array of a single number for 1D convolution, but received "+JSON.stringify(r.dilationRate));if(2===r.rank){if("number"==typeof r.dilationRate)r.dilationRate=[r.dilationRate,r.dilationRate];else if(2!==r.dilationRate.length)throw new Zf("dilationRate must be a number or array of two numbers for 2D convolution, but received "+JSON.stringify(r.dilationRate));}else if(3===r.rank)if("number"==typeof r.dilationRate)r.dilationRate=[r.dilationRate,r.dilationRate,r.dilationRate];else if(3!==r.dilationRate.length)throw new Zf("dilationRate must be a number or array of three numbers for 3D convolution, but received "+JSON.stringify(r.dilationRate));return r}return Xi(e,a),e.verifyArgs=function(t){if(ap("kernelSize"in t,"required key 'kernelSize' not in config"),"number"!=typeof t.kernelSize&&!fp(t.kernelSize,"number",1,3))throw new Zf("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:em(this.activation),useBias:this.useBias,biasInitializer:ld(this.biasInitializer),biasRegularizer:om(this.biasRegularizer),activityRegularizer:om(this.activityRegularizer),biasConstraint:Cp(this.biasConstraint)},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e}(Ky),Lb=function(a){function e(t,n){var r=a.call(this,t,n)||this;return r.kernel=null,e.verifyArgs(n),r.filters=n.filters,yp(r.filters,"filters"),r.kernelInitializer=ud(n.kernelInitializer||r.DEFAULT_KERNEL_INITIALIZER),r.kernelConstraint=Np(n.kernelConstraint),r.kernelRegularizer=im(n.kernelRegularizer),r}return Xi(e,a),e.prototype.build=function(a){var o;a=yd(a);var s="channelsFirst"===this.dataFormat?1:a.length-1;if(null==a[s])throw new Zf("The channel dimension of the input should be defined. Found "+a[s]);var n=a[s],r=this.kernelSize.concat([n,this.filters]);this.kernel=this.addWeight("kernel",r,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:(o={},o[s]=n,o)}],this.built=!0},e.prototype.call=function(a){var o=this;return We(function(){var e;a=fd(a);var n=null==o.bias?null:o.bias.read();if(1===o.rank)e=hm(a,o.kernel.read(),n,o.strides[0],o.padding,o.dataFormat,o.dilationRate[0]);else if(2===o.rank)e=mm(a,o.kernel.read(),n,o.strides,o.padding,o.dataFormat,o.dilationRate);else{if(3!==o.rank)throw new Qf("convolutions greater than 3D are not implemented yet.");e=gm(a,o.kernel.read(),n,o.strides,o.padding,o.dataFormat,o.dilationRate)}return null!=o.activation&&(e=o.activation.apply(e)),e})},e.prototype.computeOutputShape=function(o){o=yd(o);for(var s=[],t="channelsLast"===this.dataFormat?o.slice(1,o.length-1):o.slice(2),n=0,p;n<t.length;++n)p=dm(t[n],this.kernelSize[n],this.padding,this.strides[n],"number"==typeof this.dilationRate?this.dilationRate:this.dilationRate[n]),s.push(p);var d=[o[0]];return"channelsLast"===this.dataFormat?(d=d.concat(s)).push(this.filters):(d.push(this.filters),d=d.concat(s)),d},e.prototype.getConfig=function(){var e={filters:this.filters,kernelInitializer:ld(this.kernelInitializer),kernelRegularizer:om(this.kernelRegularizer),kernelConstraint:Cp(this.kernelConstraint)},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e.verifyArgs=function(t){if(!("filters"in t)||"number"!=typeof t.filters||1>t.filters)throw new Zf("Convolution layer expected config.filters to be a 'number' > 0 but got "+JSON.stringify(t.filters))},e}(zb),Fb=function(a){function e(t){var n=a.call(this,2,t)||this;return e.verifyArgs(t),n}return Xi(e,a),e.prototype.getConfig=function(){var e=a.prototype.getConfig.call(this);return delete e.rank,e},e.verifyArgs=function(t){if("number"!=typeof t.kernelSize&&!fp(t.kernelSize,"number",1,2))throw new Zf("Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received "+JSON.stringify(t.kernelSize)+".")},e.className="Conv2D",e}(Lb);Mh.registerClass(Fb);var Bb=function(a){function e(t){var n=a.call(this,3,t)||this;return e.verifyArgs(t),n}return Xi(e,a),e.prototype.getConfig=function(){var e=a.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 Zf("Conv3D expects config.kernelSize to be number or [number, number, number], but received "+JSON.stringify(t.kernelSize)+".")},e.className="Conv3D",e}(Lb);Mh.registerClass(Bb);var Pb=function(a){function e(e){var t=a.call(this,e)||this;if(t.inputSpec=[new Vy({ndim:4})],"same"!==t.padding&&"valid"!==t.padding)throw new Zf("Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode "+t.padding);return t}return Xi(e,a),e.prototype.build=function(a){var o;if(4!==(a=yd(a)).length)throw new Zf("Input should have rank 4; Received input shape: "+JSON.stringify(a));var s="channelsFirst"===this.dataFormat?1:a.length-1;if(null==a[s])throw new Zf("The channel dimension of the inputs should be defined. Found `None`.");var n=a[s],r=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",r,"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 Vy({ndim:4,axes:(o={},o[s]=n,o)})],this.built=!0},e.prototype.call=function(m){var e=this;return We(function(){var n=fd(m);if(4!==n.shape.length)throw new Zf("Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-"+n.shape.length);var g=n.shape,a=g[0],o,y;"channelsFirst"===e.dataFormat?(o=2,y=3):(o=1,y=2);var b=g[o],s=g[y],l=e.kernelSize[0],u=e.kernelSize[1],c=e.strides[0],p=e.strides[1],h=[a,lm(b,c,l,e.padding),lm(s,p,u,e.padding),e.filters];"channelsLast"!==e.dataFormat&&(n=Tl(n,[0,2,3,1]));var d=lu(n,e.kernel.read(),h,e.strides,e.padding);return"channelsLast"!==e.dataFormat&&(d=Tl(d,[0,3,1,2])),null!=e.bias&&(d=ed(d,e.bias.read(),e.dataFormat)),null!=e.activation&&(d=e.activation.apply(d)),d})},e.prototype.computeOutputShape=function(p){var d=(p=yd(p)).slice(),i,u,c;"channelsFirst"===this.dataFormat?(i=1,u=2,c=3):(i=3,u=1,c=2);var h=this.kernelSize[0],a=this.kernelSize[1],o=this.strides[0],s=this.strides[1];return d[i]=this.filters,d[u]=lm(d[u],o,h,this.padding),d[c]=lm(d[c],s,a,this.padding),d},e.prototype.getConfig=function(){var e=a.prototype.getConfig.call(this);return delete e.dilationRate,e},e.className="Conv2DTranspose",e}(Fb);Mh.registerClass(Pb);var Mb=function(a){function e(e,t){var n=a.call(this,e,t)||this;if(n.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",n.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",n.depthwiseKernel=null,n.pointwiseKernel=null,null==t.filters)throw new Zf("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=t.kernelInitializer||null!=t.kernelRegularizer||null!=t.kernelConstraint)throw new Zf("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(null!=t.padding&&"same"!==t.padding&&"valid"!==t.padding)throw new Zf("SeparableConv"+n.rank+"D supports only padding modes: 'same' and 'valid', but received "+JSON.stringify(t.padding));return n.depthMultiplier=null==t.depthMultiplier?1:t.depthMultiplier,n.depthwiseInitializer=ud(t.depthwiseInitializer||n.DEFAULT_DEPTHWISE_INITIALIZER),n.depthwiseRegularizer=im(t.depthwiseRegularizer),n.depthwiseConstraint=Np(t.depthwiseConstraint),n.pointwiseInitializer=ud(t.depthwiseInitializer||n.DEFAULT_POINTWISE_INITIALIZER),n.pointwiseRegularizer=im(t.pointwiseRegularizer),n.pointwiseConstraint=Np(t.pointwiseConstraint),n}return Xi(e,a),e.prototype.build=function(s){var p;if((s=yd(s)).length<this.rank+2)throw new Zf("Inputs to SeparableConv"+this.rank+"D should have rank "+(this.rank+2)+", but received input shape: "+JSON.stringify(s));var d="channelsFirst"===this.dataFormat?1:s.length-1;if(null==s[d]||0>s[d])throw new Zf("The channel dimension of the inputs should be defined, but found "+JSON.stringify(s[d]));for(var n=s[d],r=this.kernelSize.concat([n,this.depthMultiplier]),i=[],a=0;a<this.rank;++a)i.push(1);i.push(n*this.depthMultiplier,this.filters),this.depthwiseKernel=this.addWeight("depthwise_kernel",r,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",i,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,!0,this.pointwiseConstraint),this.bias=this.useBias?this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):null,this.inputSpec=[new Vy({ndim:this.rank+2,axes:(p={},p[d]=n,p)})],this.built=!0},e.prototype.call=function(a){var r=this;return We(function(){var e;if(a=fd(a),1===r.rank)throw new Qf("1D separable convolution is not implemented yet.");return 2===r.rank&&("channelsFirst"===r.dataFormat&&(a=Tl(a,[0,2,3,1])),e=uu(a,r.depthwiseKernel.read(),r.pointwiseKernel.read(),r.strides,r.padding,r.dilationRate,"NHWC")),r.useBias&&(e=ed(e,r.bias.read(),r.dataFormat)),null!=r.activation&&(e=r.activation.apply(e)),"channelsFirst"===r.dataFormat&&(e=Tl(e,[0,3,1,2])),e})},e.prototype.getConfig=function(){var e=a.prototype.getConfig.call(this);return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=ld(this.depthwiseInitializer),e.pointwiseInitializer=ld(this.pointwiseInitializer),e.depthwiseRegularizer=om(this.depthwiseRegularizer),e.pointwiseRegularizer=om(this.pointwiseRegularizer),e.depthwiseConstraint=Cp(this.depthwiseConstraint),e.pointwiseConstraint=Cp(this.pointwiseConstraint),e},e.className="SeparableConv",e}(Lb),Wb=function(a){function e(e){return a.call(this,2,e)||this}return Xi(e,a),e.className="SeparableConv2D",e}(Mb);Mh.registerClass(Wb);var Vb=function(a){function e(t){var n=a.call(this,1,t)||this;return e.verifyArgs(t),n.inputSpec=[{ndim:3}],n}return Xi(e,a),e.prototype.getConfig=function(){var e=a.prototype.getConfig.call(this);return delete e.rank,delete e.dataFormat,e},e.verifyArgs=function(t){if("number"!=typeof t.kernelSize&&!fp(t.kernelSize,"number",1,1))throw new Zf("Conv1D expects config.kernelSize to be number or number[] with length 1, but received "+JSON.stringify(t.kernelSize)+".")},e.className="Conv1D",e}(Lb);Mh.registerClass(Vb);var Ub=function(a){function e(e){var t=a.call(this,e)||this;return t.cropping="number"==typeof e.cropping?[[e.cropping,e.cropping],[e.cropping,e.cropping]]:"number"==typeof e.cropping[0]?[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:e.cropping,t.dataFormat=void 0===e.dataFormat?"channelsLast":e.dataFormat,t.inputSpec=[{ndim:4}],t}return Xi(e,a),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){var a=this;return We(function(){return t=fd(t),"channelsLast"===a.dataFormat?Hp(Hp(t,a.cropping[0][0],t.shape[1]-a.cropping[0][0]-a.cropping[0][1],2),a.cropping[1][0],t.shape[2]-a.cropping[1][1]-a.cropping[1][0],3):Hp(Hp(t,a.cropping[0][0],t.shape[2]-a.cropping[0][0]-a.cropping[0][1],3),a.cropping[1][0],t.shape[3]-a.cropping[1][1]-a.cropping[1][0],4)})},e.prototype.getConfig=function(){var e={cropping:this.cropping,dataFormat:this.dataFormat},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e.className="Cropping2D",e}(Ky);Mh.registerClass(Ub);var Gb=function(a){function e(e){var t=a.call(this,e)||this;return t.DEFAULT_SIZE=[2,2],t.inputSpec=[{ndim:4}],t.size=null==e.size?t.DEFAULT_SIZE:e.size,t.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,t}return Xi(e,a),e.prototype.computeOutputShape=function(a){if("channelsFirst"===this.dataFormat){var e=null==a[2]?null:this.size[0]*a[2],r=null==a[3]?null:this.size[1]*a[3];return[a[0],a[1],e,r]}return e=null==a[1]?null:this.size[0]*a[1],r=null==a[2]?null:this.size[1]*a[2],[a[0],e,r,a[3]]},e.prototype.call=function(s){var e=this;return We(function(){var n=fd(s),p=n.shape;if("channelsFirst"===e.dataFormat){n=Tl(n,[0,2,3,1]);var r=e.size[0]*p[2],d=e.size[1]*p[3],l=n.resizeNearestNeighbor([r,d]);return Tl(l,[0,3,1,2])}return r=e.size[0]*p[1],d=e.size[1]*p[2],n.resizeNearestNeighbor([r,d])})},e.prototype.getConfig=function(){var e={size:this.size,dataFormat:this.dataFormat},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e.className="UpSampling2D",e}(Ky);Mh.registerClass(Gb);var qb=function(a){function e(e){var t=a.call(this,2,e)||this;return t.depthwiseKernel=null,t.depthMultiplier=null==e.depthMultiplier?1:e.depthMultiplier,t.depthwiseInitializer=ud(e.depthwiseInitializer||t.DEFAULT_KERNEL_INITIALIZER),t.depthwiseConstraint=Np(e.depthwiseConstraint),t.depthwiseRegularizer=im(e.depthwiseRegularizer),t}return Xi(e,a),e.prototype.build=function(a){if(4>(a=yd(a)).length)throw new Zf("Inputs to DepthwiseConv2D should have rank 4. Received input shape: "+JSON.stringify(a)+".");var o="channelsFirst"===this.dataFormat?1:3;if(null==a[o]||0>a[o])throw new Zf("The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not ("+a[o]+").");var t=a[o],n=[this.kernelSize[0],this.kernelSize[1],t,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",n,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.bias=this.useBias?this.addWeight("bias",[t*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):null,this.built=!0},e.prototype.call=function(a){var r=this;return We(function(){var e=fm(a=fd(a),r.depthwiseKernel.read(),r.strides,r.padding,r.dataFormat,null);return r.useBias&&(e=ed(e,r.bias.read(),r.dataFormat)),null!=r.activation&&(e=r.activation.apply(e)),e})},e.prototype.computeOutputShape=function(o){o=yd(o);var s="channelsFirst"===this.dataFormat?o[2]:o[1],t="channelsFirst"===this.dataFormat?o[3]:o[2],n="channelsFirst"===this.dataFormat?o[1]*this.depthMultiplier:o[3]*this.depthMultiplier,r=dm(s,this.kernelSize[0],this.padding,this.strides[0]),i=dm(t,this.kernelSize[1],this.padding,this.strides[1]);return"channelsFirst"===this.dataFormat?[o[0],n,r,i]:[o[0],r,i,n]},e.prototype.getConfig=function(){var e=a.prototype.getConfig.call(this);return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=ld(this.depthwiseInitializer),e.depthwiseRegularizer=om(this.depthwiseRegularizer),e.depthwiseConstraint=Cp(this.depthwiseRegularizer),e},e.className="DepthwiseConv2D",e}(zb);Mh.registerClass(qb);var Hb=function(a){function e(e){var t=a.call(this,e)||this;if(t.rate=Ef(wf(e.rate,1),0),t.noiseShape=e.noiseShape,t.seed=e.seed,null!=t.seed)throw new Qf("Non-default seed is not implemented in Dropout layer yet: "+t.seed);return t.supportsMasking=!0,t}return Xi(e,a),e.prototype.getNoiseShape=function(a){if(null==this.noiseShape)return this.noiseShape;for(var e=a.shape,t=[],n=0;n<this.noiseShape.length;++n)t.push(null==this.noiseShape[n]?e[n]:this.noiseShape[n]);return t},e.prototype.call=function(o,e){var t=this;return We(function(){t.invokeCallHook(o,e);var n=fd(o);if(null!=t.noiseShape&&!Of.arraysEqual(n.shape,t.noiseShape))throw new Qf("Non-default noise shape is not implemented in Dropout layer yet: "+JSON.stringify(t.noiseShape));if(0<t.rate&&1>t.rate){var r=null!=e.training&&e.training,s=t.getNoiseShape(n);return od(function(){return nd(n,t.rate,s,t.seed)},function(){return n},r)}return o})},e.prototype.getConfig=function(){var e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e.prototype.dispose=function(){return a.prototype.dispose.call(this)},e.className="Dropout",e}(Ky);Mh.registerClass(Hb);var Kb=function(a){function e(e){var t=a.call(this,e)||this;if(t.activation=null,t.useBias=!0,t.kernel=null,t.bias=null,t.DEFAULT_KERNEL_INITIALIZER="glorotNormal",t.DEFAULT_BIAS_INITIALIZER="zeros",null==e.batchInputShape&&null==e.inputShape&&null!=e.inputDim){var n=null;null!=e.batchSize&&(n=e.batchSize),t.batchInputShape=[n,e.inputDim]}return t.units=e.units,yp(t.units,"units"),t.activation=am(e.activation),null!=e.useBias&&(t.useBias=e.useBias),t.kernelInitializer=ud(e.kernelInitializer||t.DEFAULT_KERNEL_INITIALIZER),t.biasInitializer=ud(e.biasInitializer||t.DEFAULT_BIAS_INITIALIZER),t.kernelConstraint=Np(e.kernelConstraint),t.biasConstraint=Np(e.biasConstraint),t.kernelRegularizer=im(e.kernelRegularizer),t.biasRegularizer=im(e.biasRegularizer),t.activityRegularizer=im(e.activityRegularizer),t.supportsMasking=!0,t.inputSpec=[{minNDim:2}],t}return Xi(e,a),e.prototype.build=function(a){var r=(a=yd(a))[a.length-1],n;null==this.kernel&&(this.kernel=this.addWeight("kernel",[r,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:(n={},n[-1]=r,n)}],this.built=!0},e.prototype.computeOutputShape=function(a){var n=(a=yd(a)).slice();return n[n.length-1]=this.units,n},e.prototype.call=function(o,e){var t=this;return We(function(){t.invokeCallHook(o,e);var n=fd(o),s=ym(t.activation.getClassName()),a;return null==s?(a=Yp(n,t.kernel.read()),null!=t.bias&&(a=ed(a,t.bias.read())),null!=t.activation&&(a=t.activation.apply(a))):a=Yp(n,t.kernel.read(),s,t.bias?t.bias.read():null),a})},e.prototype.getConfig=function(){var e={units:this.units,activation:em(this.activation),useBias:this.useBias,kernelInitializer:ld(this.kernelInitializer),biasInitializer:ld(this.biasInitializer),kernelRegularizer:om(this.kernelRegularizer),biasRegularizer:om(this.biasRegularizer),activityRegularizer:om(this.activityRegularizer),kernelConstraint:Cp(this.kernelConstraint),biasConstraint:Cp(this.biasConstraint)},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e.className="Dense",e}(Ky);Mh.registerClass(Kb);var jb=function(a){function e(e){var t=a.call(this,e||{})||this;return t.inputSpec=[{minNDim:3}],t}return Xi(e,a),e.prototype.computeOutputShape=function(a){for(var r=0,o=(a=yd(a)).slice(1);r<o.length;r++)if(null==o[r])throw new Zf("The shape of the input to \"Flatten\" is not fully defined (got "+a.slice(1)+"). Make sure to pass a complete \"input_shape\" or \"batch_input_shape\" argument to the first layer in your model.");return[a[0],Op(a,1)]},e.prototype.call=function(a,e){var t=this;return We(function(){return t.invokeCallHook(a,e),Up(fd(a))})},e.className="Flatten",e}(Ky);Mh.registerClass(jb);var $b=function(a){function e(e){var t=a.call(this,e)||this;return t.supportsMasking=!0,t.activation=am(e.activation),t}return Xi(e,a),e.prototype.call=function(a,e){var t=this;return We(function(){t.invokeCallHook(a,e);var n=fd(a);return t.activation.apply(n)})},e.prototype.getConfig=function(){var e={activation:em(this.activation)},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e.className="Activation",e}(Ky);Mh.registerClass($b);var Xb=function(a){function e(e){var t=a.call(this,e)||this;return t.n=e.n,t.inputSpec=[{ndim:2}],t}return Xi(e,a),e.prototype.computeOutputShape=function(t){return[t[0],this.n,t[1]]},e.prototype.call=function(t){var a=this;return We(function(){return Wp(t=fd(t),a.n)})},e.prototype.getConfig=function(){var e={n:this.n},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e.className="RepeatVector",e}(Ky);Mh.registerClass(Xb);var Yb=function(a){function e(e){var t=a.call(this,e)||this;t.targetShape=e.targetShape;for(var n=0;n<t.targetShape.length;++n)t.isUnknown(t.targetShape[n])&&(t.targetShape[n]=null);return t}return Xi(e,a),e.prototype.isUnknown=function(t){return 0>t||null==t},e.prototype.fixUnknownDimension=function(p,e){for(var t="Total size of new array must be unchanged.",n=e.slice(),r=1,d=null,u=0,c;u<n.length;++u)if(c=n[u],this.isUnknown(c)){if(null!=d)throw new Zf("Can only specifiy one unknown dimension.");d=u}else r*=c;var h=Op(p);if(null!==d){if(0===r||0!=h%r)throw new Zf(t);n[d]=h/r}else if(h!==r)throw new Zf(t);return n},e.prototype.computeOutputShape=function(a){for(var e=!1,r=0;r<a.length;++r)if(this.isUnknown(a[r])){e=!0;break}return e?a.slice(0,1).concat(this.targetShape):a.slice(0,1).concat(this.fixUnknownDimension(a.slice(1),this.targetShape))},e.prototype.call=function(o,e){var t=this;return We(function(){t.invokeCallHook(o,e);var n=fd(o),r=n.shape,s=r.slice(0,1).concat(t.fixUnknownDimension(r.slice(1),t.targetShape));return n.reshape(s)})},e.prototype.getConfig=function(){var e={targetShape:this.targetShape},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e.className="Reshape",e}(Ky);Mh.registerClass(Yb);var Zb=function(a){function e(e){var t=a.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 n=Bp(1,e.dims.length+1);if(!Of.arraysEqual(e.dims.slice().sort(),n))throw new Error("Invalid permutation `dims`: "+JSON.stringify(e.dims)+" `dims` must contain consecutive integers starting from 1.");return t.dims=e.dims,t.dimsIncludingBatch=[0].concat(t.dims),t.inputSpec=[new Vy({ndim:t.dims.length+1})],t}return Xi(e,a),e.prototype.computeOutputShape=function(a){var o=(a=yd(a)).slice();return this.dims.forEach(function(e,t){o[t+1]=a[e]}),o},e.prototype.call=function(t){return Tl(fd(t),this.dimsIncludingBatch)},e.prototype.getConfig=function(){var e={dims:this.dims},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e.className="Permute",e}(Ky);Mh.registerClass(Zb);var Qb=function(a){function e(e){var t=a.call(this,null==e?{}:e)||this;return t.supportsMasking=!0,t.maskValue=null==e?0:null==e.maskValue?0:e.maskValue,t}return Xi(e,a),e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e=a.prototype.getConfig.call(this),t={maskValue:this.maskValue};return Object.assign(t,e),t},e.prototype.computeMask=function(t){var e=fd(t);return Tu(Yu(e,this.maskValue),-1)},e.prototype.call=function(a,e){var t=this;return We(function(){t.invokeCallHook(a,e);var n=fd(a),r=Tu(Yu(n,t.maskValue),-1,!0);return n.mul(r.asType(n.dtype))})},e.className="Masking",e}(Ky);Mh.registerClass(Qb);var Jb=function(a){function e(e){var t=a.call(this,e)||this;if(t.embeddings=null,t.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",null==e.batchInputShape&&null==e.inputShape){var n=null;null!=e.batchSize&&(n=e.batchSize),t.batchInputShape=null==e.inputLength?[n,null]:[n].concat(op(e.inputLength))}return t.inputDim=e.inputDim,yp(t.inputDim,"inputDim"),t.outputDim=e.outputDim,yp(t.outputDim,"outputDim"),t.embeddingsInitializer=ud(e.embeddingsInitializer||t.DEFAULT_EMBEDDINGS_INITIALIZER),t.embeddingsRegularizer=im(e.embeddingsRegularizer),t.activityRegularizer=im(e.activityRegularizer),t.embeddingsConstraint=Np(e.embeddingsConstraint),t.maskZero=e.maskZero,t.supportsMasking=e.maskZero,t.inputLength=e.inputLength,t}return Xi(e,a),e.prototype.build=function(){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(){},e.prototype.computeMask=function(t){var a=this;return We(function(){return a.maskZero?(t=fd(t),Yu(t,Fn(t))):null})},e.prototype.computeOutputShape=function(o){if(o=yd(o),null==this.inputLength)return o.concat([this.outputDim]);var s=op(this.inputLength);if(s.length!==o.length-1)throw new Zf("\"inputLength\" is "+this.inputLength+", but received input shape has shape "+o);for(var t=0,p=0;p<s.length;++p){var d=s[p],i=o[p+1];if(null!=d&&null!=i&&d!==i)throw new Zf("\"inputLength\" is "+this.inputLength+", but received input shape has shape "+o);null==d&&(s[t]=i),t++}return[o[0]].concat(s,[this.outputDim])},e.prototype.call=function(a,e){var t=this;return We(function(){t.invokeCallHook(a,e);var n=fd(a);return"int32"!==n.dtype&&(n=Pp(n,"int32")),Zp(t.embeddings.read(),n.as1D()).reshape(yd(t.computeOutputShape(n.shape)))})},e.prototype.getConfig=function(){var e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:ld(this.embeddingsInitializer),embeddingsRegularizer:om(this.embeddingsRegularizer),activityRegularizer:om(this.activityRegularizer),embeddingsConstraint:Cp(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e.className="Embedding",e}(Ky);Mh.registerClass(Jb);var ex=function(a){function e(e){var t=a.call(this,e||{})||this;return t.supportsMasking=!0,t}return Xi(e,a),e.prototype.mergeFunction=function(){throw new Qf},e.prototype.computeElementwiseOpOutputShape=function(o,e){if(null==o||null==e)return null;if(o.length<e.length)return this.computeElementwiseOpOutputShape(e,o);if(0===e.length)return o;for(var t=o.slice(0,o.length-e.length),n=0;n<e.length;++n){var s=o[o.length-e.length+n],i=e[n];if(null==s||null==i||0>s||0>i)t.push(null);else if(1===s)t.push(i);else if(1===i)t.push(s);else{if(s!==i)throw new Zf("Operands could not be broadcast together with shapes "+JSON.stringify(o)+" "+JSON.stringify(e));t.push(s)}}return t},e.prototype.build=function(p){if(Array.isArray(p)&&!Array.isArray(p[0])&&(p=[yd(p)]),2>(p=p).length)throw new Zf("A merge layer should be called on an Array of at least 2 inputs. Got "+p.length+" input(s).");for(var d=[],l=0,u=p;l<u.length;l++)null!=(h=u[l])&&null!==h[0]&&d.push(h[0]);if(1<(d=hp(d)).length)throw new Zf("Can not merge tensors with different batch sizes. Got tensors with shapes: "+JSON.stringify(p)+".");for(var r=null==p[0]?null:p[0].slice(1),c=1,h;c<p.length;++c)h=null==p[c]?null:p[c].slice(1),r=this.computeElementwiseOpOutputShape(r,h);var m=p.map(function(t){return t.length});this.reshapeRequired=-1!==p.indexOf(null)||1!==hp(m).length},e.prototype.call=function(x){var C=this;return We(function(){if(x=x,C.reshapeRequired){var e=[],t=x.map(function(t){return t.rank});if(-1===t.indexOf(null)){for(var n=Fp(t),r=0,i=x;r<i.length;r++){for(var o=(p=i[r]).rank,S=0;S<n-o;++S)p=Mp(p,1);e.push(p)}return C.mergeFunction(e)}for(var N=!1,I=0,k=x;I<k.length;I++){var p;if(null==(o=(p=k[I]).rank)){var T=p.shape,d=T[0],R=T.slice(1).concat([d]),E=p.reshape([d].concat(Op(T.slice(1))));E=(E=Tl(E,[1,0])).reshape(R),e.push(E),N=!0}else if(1<o){var A=Bp(1,o).concat([0]);e.push(Tl(p,A)),N=!0}else e.push(p)}var D=C.mergeFunction(e),_=D.rank;if(N)if(null==_){var b=D.shape;R=[d=b[b.length-1]].concat(b.slice(0,b.length-1)),D=Tl(D.reshape([-1,d]),[1,0]).reshape(R)}else 1<_&&(A=[_-1].concat(Bp(0,_-1)),D=Tl(D,A));return D}return C.mergeFunction(x)})},e.prototype.computeOutputShape=function(s){var p=null==(s=s)[0]?null:s[0].slice(1);for(var d=1,l;d<s.length;++d)l=null==s[d]?null:s[d].slice(1),p=this.computeElementwiseOpOutputShape(p,l);for(var u=[],c=0,h=s;c<h.length;c++)null!=(l=h[c])&&null!==l[0]&&u.push(l[0]);return p=1===(u=hp(u)).length?u.concat(p):[null].concat(p)},e.prototype.computeMask=function(a,e){return We(function(){if(null==e)return null;if(!Array.isArray(e))throw new Zf("`mask` should be an Array");if(!Array.isArray(a))throw new Zf("`inputs` should be an Array");if(e.length!==a.length)throw new Zf("The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths ("+a.length+" vs "+e.length+")");if(e.every(function(t){return null==t}))return null;for(var t=(e=e.map(function(t){return null==t?t:ar(t,0)}))[0],o=1;o<e.length-1;++o)t=xl(t,e[o]);return t})},e}(Ky),tx=function(a){function e(e){return a.call(this,e)||this}return Xi(e,a),e.prototype.mergeFunction=function(a){return We(function(){for(var e=a[0].clone(),r=1;r<a.length;++r)e=Ju(e,a[r]);return e})},e.className="Add",e}(ex);Mh.registerClass(tx);var ax=function(a){function e(e){return a.call(this,e)||this}return Xi(e,a),e.prototype.mergeFunction=function(a){return We(function(){for(var e=a[0].clone(),r=1;r<a.length;++r)e=hl(e,a[r]);return e})},e.className="Multiply",e}(ex);Mh.registerClass(ax);var nx=function(a){function e(e){return a.call(this,e)||this}return Xi(e,a),e.prototype.mergeFunction=function(a){return We(function(){for(var e=a[0].clone(),r=1;r<a.length;++r)e=Ju(e,a[r]);return hl(1/a.length,e)})},e.className="Average",e}(ex);Mh.registerClass(nx);var rx=function(a){function e(e){return a.call(this,e)||this}return Xi(e,a),e.prototype.mergeFunction=function(a){return We(function(){for(var e=a[0],r=1;r<a.length;++r)e=al(e,a[r]);return e})},e.className="Maximum",e}(ex);Mh.registerClass(rx);var ox=function(a){function e(e){return a.call(this,e)||this}return Xi(e,a),e.prototype.mergeFunction=function(a){return We(function(){for(var e=a[0],r=1;r<a.length;++r)e=sl(e,a[r]);return e})},e.className="Minimum",e}(ex);Mh.registerClass(ox);var sx=function(a){function e(e){var r=a.call(this,e)||this;return r.DEFAULT_AXIS=-1,null==e&&(e={}),r.axis=null==e.axis?r.DEFAULT_AXIS:e.axis,r.supportsMasking=!0,r.reshapeRequired=!1,r}return Xi(e,a),e.prototype.build=function(p){if(!Array.isArray(p)||!Array.isArray(p[0])||1===p.length)throw new Zf("A `Concatenate` layer should be called on a list of at least 2 inputs");for(var d=!0,h=0,m=p=p;h<m.length;h++)if(null!=(u=m[h])){d=!1;break}if(!d){for(var r=[],i=0,g;i<p.length;++i){g=p[i].slice(),g.splice(this.axis,1);for(var f=!1,y=0,b=r,u;y<b.length;y++)if(u=b[y],Of.arraysEqual(u,g)){f=!0;break}f||r.push(g)}if(1<r.length)throw new Zf("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(p))}},e.prototype.mergeFunction=function(a){var e=this;return We(function(){return Kp(a,e.axis)})},e.prototype.computeOutputShape=function(s){if(!Array.isArray(s)||!Array.isArray(s[0]))throw new Zf("A `Concatenate` layer should be called on a list of inputs.");for(var e=s,t=e[0].slice(),n=0>this.axis?t.length+this.axis:this.axis,r=0,p=e.slice(1),a;r<p.length;r++){if(a=p[r],null==t[n]||null==a[n]){t[n]=null;break}t[n]+=a[n]}return t},e.prototype.computeMask=function(r,e){var t=this;if(null==e)return null;if(!Array.isArray(e))throw new Zf("`mask` should be an array for Concatenate");if(!Array.isArray(r))throw new Zf("`inputs` should be an array for Concatenate");if(e.length!==r.length)throw new Zf("Mismatch in the length of mask ("+e.length+") and the legnth of inputs ("+r.length+")");return We(function(){var n=!0;if(e.forEach(function(t){null==t||(n=!1)}),n)return null;for(var s=[],i=0;i<r.length;++i)null==e[i]?s.push(xn(r[i]).asType("bool")):e[i].rank<r[i].rank?s.push(ar(e[i],-1)):s.push(e[i]);var p=Mn(s,t.axis);return ku(p,-1,!1)})},e.prototype.getConfig=function(){var e={axis:this.axis},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e.className="Concatenate",e}(ex);Mh.registerClass(sx);var ix=function(a){function e(e){var t=a.call(this,e)||this;return t.axes=e.axes,t.normalize=null!=e.normalize&&e.normalize,t.supportsMasking=!0,t.reshapeRequired=!1,t}return Xi(e,a),e.prototype.build=function(a){Of.assert(Array.isArray(a)&&2===a.length&&Array.isArray(a[0])&&Array.isArray(a[1]),function(){return"A `Dot` layer should be called on a list of exactly 2 inputs."});var e=a[0],t=a[1];if(3<e.length||3<t.length)throw new Qf("Dot layer does not support tensors of 4D or higher rank yet.");var n=this.interpretAxes(e,t);if(e[n[0]]!==t[n[1]])throw new Zf("Dimension incompatibility: "+e[n[0]]+" !== "+t[n[1]])},e.prototype.mergeFunction=function(a){if(2!==a.length)throw new Zf("A `Dot` layer must be called on exactly 2 inputs, but received "+a.length+" input(s).");var e=a[0],o=a[1],s;return s=Array.isArray(this.axes)?this.axes.map(function(e,t){return bm(e,a[t].shape.length)}):[bm(this.axes,e.shape.length),bm(this.axes,o.shape.length)],this.normalize&&(e=Dd(e,s[0]),o=Dd(o,s[1])),xm(e,o,s)},e.prototype.interpretAxes=function(a,e){return Array.isArray(this.axes)?this.axes:[bm(this.axes,a.length),bm(this.axes,e.length)]},e.prototype.computeOutputShape=function(a){Of.assert(Array.isArray(a)&&2===a.length&&Array.isArray(a[0])&&Array.isArray(a[1]),function(){return"A `Dot` layer should be called on a list of exactly 2 inputs."});var e=a[0].slice(),t=a[1].slice();if(3<e.length||3<t.length)throw new Qf("Dot layer does not support tensors of 4D or higher rank yet.");var n=this.interpretAxes(e,t);e.splice(n[0],1),t.splice(n[1],1),t.splice(0,1);var r=e.concat(t);return 1===r.length&&r.push(1),r},e.prototype.computeMask=function(){return null},e.prototype.getConfig=function(){var e={axes:this.axes,normalize:this.normalize},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e.className="Dot",e}(ex);Mh.registerClass(ix);var px=function(a){function e(e){var t=a.call(this,e)||this;return t.supportsMasking=!0,t.stddev=e.stddev,t}return Xi(e,a),e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e=a.prototype.getConfig.call(this),t={stddev:this.stddev};return Object.assign(t,e),t},e.prototype.call=function(a,e){var t=this;return We(function(){t.invokeCallHook(a,e);var n=fd(a);return od(function(){return Xp(n.shape,0,t.stddev).add(n)},function(){return n},e.training||!1)})},e.className="GaussianNoise",e}(Ky);Mh.registerClass(px);var dx=function(a){function e(e){var t=a.call(this,e)||this;return t.supportsMasking=!0,t.rate=e.rate,t}return Xi(e,a),e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e=a.prototype.getConfig.call(this),t={rate:this.rate};return Object.assign(t,e),t},e.prototype.call=function(a,e){var t=this;return We(function(){t.invokeCallHook(a,e);var n=fd(a);return 0<t.rate&&1>t.rate?od(function(){var a=Tf(t.rate/(1-t.rate));return n.mul(Xp(n.shape,1,a))},function(){return n},e.training||!1):n})},e.className="GaussianDropout",e}(Ky);Mh.registerClass(dx);var lx=function(a){function e(e){var t=a.call(this,e)||this;return t.supportsMasking=!0,t.rate=e.rate,t.noiseShape=e.noiseShape,t}return Xi(e,a),e.prototype._getNoiseShape=function(t){return this.noiseShape||fd(t).shape},e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e=a.prototype.getConfig.call(this),t={rate:this.rate};return Object.assign(t,e),t},e.prototype.call=function(p,e){var d=this;return We(function(){if(1>d.rate&&0<d.rate){var n=d._getNoiseShape(p);return od(function(){var e=fd(p),t=-1.7580993408473766,r=Gu(mr(n),d.rate);r=Pp(r,"float32");var i=uf((1-d.rate)*(1+d.rate*uf(t,2)),-.5),o=-i*t*d.rate;return e.mul(r).add(r.add(-1).mul(t)).mul(i).add(o)},function(){return fd(p)},e.training||!1)}return p})},e.className="AlphaDropout",e}(Ky);Mh.registerClass(lx);var ux=function(a){function e(e){var r=this;return null==e&&(e={}),(r=a.call(this,e)||this).supportsMasking=!0,r.axis=null==e.axis?-1:e.axis,r.momentum=null==e.momentum?.99:e.momentum,r.epsilon=null==e.epsilon?.001:e.epsilon,r.center=null==e.center||e.center,r.scale=null==e.scale||e.scale,r.betaInitializer=ud(e.betaInitializer||"zeros"),r.gammaInitializer=ud(e.gammaInitializer||"ones"),r.movingMeanInitializer=ud(e.movingMeanInitializer||"zeros"),r.movingVarianceInitializer=ud(e.movingVarianceInitializer||"ones"),r.betaConstraint=Np(e.betaConstraint),r.gammaConstraint=Np(e.gammaConstraint),r.betaRegularizer=im(e.betaRegularizer),r.gammaRegularizer=im(e.gammaRegularizer),r}return Xi(e,a),e.prototype.build=function(a){var o;a=yd(a);var s=0<=this.axis?this.axis:this.axis+a.length,n=a[s];if(null==n)throw new Zf("Axis "+s+" of input tensor should have a defined dimension but the layer received an input with shape "+JSON.stringify(a)+".");this.inputSpec=[new Vy({ndim:a.length,axes:(o={},o[s]=n,o)})];var r=[n];this.scale&&(this.gamma=this.addWeight("gamma",r,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",r,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",r,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",r,null,this.movingVarianceInitializer,null,!1),this.built=!0},e.prototype.call=function(y,e){var b=this;return We(function(){var t=null!=e.training&&e.training,n=fd(y),r=n.shape,a=r.length,o=Bp(0,a),s=0<=b.axis?b.axis:b.axis+a;o.splice(s,1);var i=tp(1,a);i[s]=r[s];var l=o.slice();l.sort();var u=!Of.arraysEqual(l,Bp(0,a).slice(0,a-1));if(!t)return function(){if(u){var o=b.movingMean.read().reshape(i),e=b.movingVariance.read().reshape(i),t=b.center?b.beta.read().reshape(i):null,r=b.scale?b.gamma.read().reshape(i):null;return vm(n,o,e,t,r,b.epsilon)}return vm(n,b.movingMean.read(),b.movingVariance.read(),null==b.beta?null:b.beta.read(),null==b.gamma?null:b.gamma.read(),b.epsilon)}();var p=Nm(n,b.gamma.read(),b.beta.read(),o,b.epsilon),c=p[0],d=p[1],h=p[2],g=function(r,e,t){We(function(){var n=r.read(),o=n.sub(e).mul(1-t);r.write(n.sub(o))})};return g(b.movingMean,d,b.momentum),g(b.movingVariance,h,b.momentum),c})},e.prototype.getConfig=function(){var e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:ld(this.betaInitializer),gammaInitializer:ld(this.gammaInitializer),movingMeanInitializer:ld(this.movingMeanInitializer),movingVarianceInitializer:ld(this.movingVarianceInitializer),betaRegularizer:om(this.betaRegularizer),gammaRegularizer:om(this.gammaRegularizer),betaConstraint:Cp(this.betaConstraint),gammaConstraint:Cp(this.gammaConstraint)},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e.className="BatchNormalization",e}(Ky);Mh.registerClass(ux);var cx=function(a){function e(e){var o=this;if(null==e&&(e={}),(o=a.call(this,e)||this).dataFormat=null==e.dataFormat?ep():e.dataFormat,null==e.padding)o.padding=[[1,1],[1,1]];else if("number"==typeof e.padding)o.padding=[[e.padding,e.padding],[e.padding,e.padding]];else{if(e.padding=e.padding,2!==e.padding.length)throw new Zf("ZeroPadding2D expects padding to be a length-2 array, but received a length-"+e.padding.length+" array.");var s,p;if("number"==typeof e.padding[0])s=[e.padding[0],e.padding[0]],p=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,2!==e.padding[0].length)throw new Zf("ZeroPadding2D expects height padding to be a length-2 array, but received a length-"+e.padding[0].length+" array.");if(s=e.padding[0],2!==e.padding[1].length)throw new Zf("ZeroPadding2D expects width padding to be a length-2 array, but received a length-"+e.padding[1].length+" array.");p=e.padding[1]}o.padding=[s,p]}return o.inputSpec=[new Vy({ndim:4})],o}return Xi(e,a),e.prototype.computeOutputShape=function(a){var r,o;return a=yd(a),"channelsFirst"===this.dataFormat?(r=null!=a[2]&&0<=a[2]?a[2]+this.padding[0][0]+this.padding[0][1]:null,o=null!=a[3]&&0<=a[3]?a[3]+this.padding[1][0]+this.padding[1][1]:null,[a[0],a[1],r,o]):(r=null!=a[1]&&0<=a[1]?a[1]+this.padding[0][0]+this.padding[0][1]:null,o=null!=a[2]&&0<=a[2]?a[2]+this.padding[1][0]+this.padding[1][1]:null,[a[0],r,o,a[3]])},e.prototype.call=function(t){var e=this;return We(function(){return Im(fd(t),e.padding,e.dataFormat)})},e.prototype.getConfig=function(){var e={padding:this.padding,dataFormat:this.dataFormat},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e.className="ZeroPadding2D",e}(Ky);Mh.registerClass(cx);var hx=function(a){function e(e){var t=this;if(null==e.poolSize&&(e.poolSize=2),t=a.call(this,e)||this,"number"==typeof e.poolSize)t.poolSize=[e.poolSize];else{if(!Array.isArray(e.poolSize)||1!==e.poolSize.length||"number"!=typeof e.poolSize[0])throw new Zf("poolSize for 1D convolutional layer must be a number or an Array of a single number, but received "+JSON.stringify(e.poolSize));t.poolSize=e.poolSize}if(yp(t.poolSize,"poolSize"),null==e.strides)t.strides=t.poolSize;else if("number"==typeof e.strides)t.strides=[e.strides];else{if(!Array.isArray(e.strides)||1!==e.strides.length||"number"!=typeof e.strides[0])throw new Zf("strides for 1D convolutional layer must be a number or an Array of a single number, but received "+JSON.stringify(e.strides));t.strides=e.strides}return yp(t.strides,"strides"),t.padding=null==e.padding?"valid":e.padding,kp(t.padding),t.inputSpec=[new Vy({ndim:3})],t}return Xi(e,a),e.prototype.computeOutputShape=function(a){var n=dm((a=yd(a))[1],this.poolSize[0],this.padding,this.strides[0]);return[a[0],n,a[2]]},e.prototype.call=function(a,o){var t=this;return We(function(){t.invokeCallHook(a,o),a=Mp(fd(a),2);var e=t.poolingFunction(fd(a),[t.poolSize[0],1],[t.strides[0],1],t.padding,"channelsLast");return xr(e,[2])})},e.prototype.getConfig=function(){var e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e}(Ky),mx=function(a){function e(e){return a.call(this,e)||this}return Xi(e,a),e.prototype.poolingFunction=function(a,e,t,n,r){return Ip(r),kp(n),km(a,e,t,n,r,"max")},e.className="MaxPooling1D",e}(hx);Mh.registerClass(mx);var gx=function(a){function e(e){return a.call(this,e)||this}return Xi(e,a),e.prototype.poolingFunction=function(a,e,t,n,r){return Ip(r),kp(n),km(a,e,t,n,r,"avg")},e.className="AveragePooling1D",e}(hx);Mh.registerClass(gx);var fx=function(a){function e(e){var t=this;if(null==e.poolSize&&(e.poolSize=[2,2]),(t=a.call(this,e)||this).poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],null==e.strides)t.strides=t.poolSize;else if(Array.isArray(e.strides)){if(2!==e.strides.length)throw new Zf("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+".");t.strides=e.strides}else t.strides=[e.strides,e.strides];return yp(t.poolSize,"poolSize"),yp(t.strides,"strides"),t.padding=null==e.padding?"valid":e.padding,t.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,Ip(t.dataFormat),kp(t.padding),t.inputSpec=[new Vy({ndim:4})],t}return Xi(e,a),e.prototype.computeOutputShape=function(a){a=yd(a);var r="channelsFirst"===this.dataFormat?a[2]:a[1],o="channelsFirst"===this.dataFormat?a[3]:a[2];return r=dm(r,this.poolSize[0],this.padding,this.strides[0]),o=dm(o,this.poolSize[1],this.padding,this.strides[1]),"channelsFirst"===this.dataFormat?[a[0],a[1],r,o]:[a[0],r,o,a[3]]},e.prototype.call=function(a,e){var t=this;return We(function(){return t.invokeCallHook(a,e),t.poolingFunction(fd(a),t.poolSize,t.strides,t.padding,t.dataFormat)})},e.prototype.getConfig=function(){var e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e}(Ky),yx=function(a){function e(e){return a.call(this,e)||this}return Xi(e,a),e.prototype.poolingFunction=function(a,e,t,n,r){return Ip(r),kp(n),km(a,e,t,n,r,"max")},e.className="MaxPooling2D",e}(fx);Mh.registerClass(yx);var bx=function(a){function e(e){return a.call(this,e)||this}return Xi(e,a),e.prototype.poolingFunction=function(a,e,t,n,r){return Ip(r),kp(n),km(a,e,t,n,r,"avg")},e.className="AveragePooling2D",e}(fx);Mh.registerClass(bx);var xx=function(a){function e(e){var t=a.call(this,e)||this;return t.inputSpec=[new Vy({ndim:3})],t}return Xi(e,a),e.prototype.computeOutputShape=function(t){return[t[0],t[2]]},e.prototype.call=function(){throw new Qf},e}(Ky),vx=function(a){function e(e){return a.call(this,e||{})||this}return Xi(e,a),e.prototype.call=function(a){return We(function(){var e=fd(a);return Mu(e,1)})},e.className="GlobalAveragePooling1D",e}(xx);Mh.registerClass(vx);var Cx=function(a){function e(e){return a.call(this,e||{})||this}return Xi(e,a),e.prototype.call=function(a){return We(function(){var e=fd(a);return Fu(e,1)})},e.className="GlobalMaxPooling1D",e}(xx);Mh.registerClass(Cx);var Sx=function(a){function e(e){var t=a.call(this,e)||this;return t.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,Ip(t.dataFormat),t.inputSpec=[new Vy({ndim:4})],t}return Xi(e,a),e.prototype.computeOutputShape=function(t){return t=t,"channelsLast"===this.dataFormat?[t[0],t[3]]:[t[0],t[1]]},e.prototype.call=function(){throw new Qf},e.prototype.getConfig=function(){var e={dataFormat:this.dataFormat},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e}(Ky),Nx=function(a){function e(){return null!==a&&a.apply(this,arguments)||this}return Xi(e,a),e.prototype.call=function(a){var e=this;return We(function(){var n=fd(a);return"channelsLast"===e.dataFormat?Mu(n,[1,2]):Mu(n,[2,3])})},e.className="GlobalAveragePooling2D",e}(Sx);Mh.registerClass(Nx);var Ix=function(a){function e(){return null!==a&&a.apply(this,arguments)||this}return Xi(e,a),e.prototype.call=function(a){var e=this;return We(function(){var n=fd(a);return"channelsLast"===e.dataFormat?Fu(n,[1,2]):Fu(n,[2,3])})},e.className="GlobalMaxPooling2D",e}(Sx);Mh.registerClass(Ix);var kx=function(m){function e(e){var t=m.call(this,e)||this,a;if(null==e.cell)throw new Zf("cell property is missing for the constructor of RNN.");if(null==(a=Array.isArray(e.cell)?new Ox({cells:e.cell}):e.cell).stateSize)throw new Zf("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");return t.cell=a,t.returnSequences=null!=e.returnSequences&&e.returnSequences,t.returnState=null!=e.returnState&&e.returnState,t.goBackwards=null!=e.goBackwards&&e.goBackwards,t._stateful=null!=e.stateful&&e.stateful,t.unroll=null!=e.unroll&&e.unroll,t.supportsMasking=!0,t.inputSpec=[new Vy({ndim:3})],t.stateSpec=null,t.states_=null,t.numConstants=null,t.keptStates=[],t}return Xi(e,m),e.prototype.getStates=function(){return null==this.states_?Bp(0,Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1).map(function(){return null}):this.states_},e.prototype.setStates=function(t){this.states_=t},e.prototype.computeOutputShape=function(p){md(p)&&(p=p[0]),p=p;var d=this.cell.stateSize;Array.isArray(d)||(d=[d]);var l=d[0],r;if(r=this.returnSequences?[p[0],p[1],l]:[p[0],l],this.returnState){for(var u=[],i=0,c=d,o;i<c.length;i++)o=c[i],u.push([p[0],o]);return[r].concat(u)}return r},e.prototype.computeMask=function(a,o){var s=this;return We(function(){Array.isArray(o)&&(o=o[0]);var t=s.returnSequences?o:null;if(s.returnState){var e=s.states.map(function(){return null});return[t].concat(e)}return t})},Object.defineProperty(e.prototype,"states",{get:function(){if(null==this.states_){for(var a=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,e=[],t=0;t<a;++t)e.push(null);return e}return this.states_},set:function(t){this.states_=t},enumerable:!0,configurable:!0}),e.prototype.build=function(a){if(null!=this.numConstants)throw new Qf("Constants support is not implemented in RNN yet.");md(a)&&(a=a[0]),a=a;var o=this.stateful?a[0]:null,t=a[a.length-1];this.inputSpec[0]=new Vy({shape:[o,null,t]});var n=[a[0]].concat(a.slice(2)),s;if(this.cell.build(n),s=Array.isArray(this.cell.stateSize)?this.cell.stateSize:[this.cell.stateSize],null==this.stateSpec)this.stateSpec=s.map(function(t){return new Vy({shape:[null,t]})});else if(!Of.arraysEqual(this.stateSpec.map(function(t){return t.shape[t.shape.length-1]}),s))throw new Zf("An initialState was passed that is not compatible with cell.stateSize. Received stateSpec="+this.stateSpec+"; However cell.stateSize is "+this.cell.stateSize);this.stateful&&this.resetStates()},e.prototype.resetStates=function(p,d){var l=this;void 0===d&&(d=!1),We(function(){if(!l.stateful)throw new Xf("Cannot call resetStates() on an RNN Layer that is not stateful.");var t=l.inputSpec[0].shape[0];if(null==t)throw new Zf("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==l.states_)l.states_=Array.isArray(l.cell.stateSize)?l.cell.stateSize.map(function(a){return pn([t,a])}):[pn([t,l.cell.stateSize])];else if(null==p)ze(l.states_),null!=l.keptStates&&(ze(l.keptStates),l.keptStates=[]),Array.isArray(l.cell.stateSize)?l.states_=l.cell.stateSize.map(function(a){return pn([t,a])}):l.states_[0]=pn([t,l.cell.stateSize]);else{if(Array.isArray(p)||(p=[p]),p.length!==l.states_.length)throw new Zf("Layer "+l.name+" expects "+l.states_.length+" state(s), but it received "+p.length+" state value(s). Input received: "+p);!0===d?l.keptStates.push(l.states_.slice()):ze(l.states_);for(var e=0;e<l.states_.length;++e){var n=p[e],a=Array.isArray(l.cell.stateSize)?l.cell.stateSize[e]:l.cell.stateSize,r=[t,a];if(!Of.arraysEqual(n.shape,r))throw new Zf("State "+e+" is incompatible with layer "+l.name+": expected shape="+r+", received shape="+n.shape);l.states_[e]=n}}l.states_=l.states_.map(function(t){return Ve(t.clone())})})},e.prototype.apply=function(e,g){var y=null==g?null:g.initialState,b=null==g?null:g.constants;null==g&&(g={});var x=Tm(e,y,b,this.numConstants);e=x.inputs,y=x.initialState,b=x.constants;var a=[],v=[];if(null!=y){g.initialState=y,a=a.concat(y),this.stateSpec=[];for(var C=0,S=y,u;C<S.length;C++)u=S[C],this.stateSpec.push(new Vy({shape:u.shape}));v=v.concat(this.stateSpec)}if(null!=b&&(g.constants=b,a=a.concat(b),this.numConstants=b.length),a[0]instanceof Uy){var N=[e].concat(a),p=this.inputSpec.concat(v),h=this.inputSpec;this.inputSpec=p;var d=m.prototype.apply.call(this,N,g);return this.inputSpec=h,d}return m.prototype.apply.call(this,e,g)},e.prototype.call=function(d,m){var g=this;return We(function(){var e=null==m?null:m.mask,t=null==m?null:m.training,n=null==m?null:m.initialState;d=fd(d),null==n&&(n=g.stateful?g.states_:g.getInitialState(d));var r=Array.isArray(g.cell.stateSize)?g.cell.stateSize.length:1;if(n.length!==r)throw new Zf("RNN Layer has "+r+" state(s) but was passed "+n.length+" initial state(s).");g.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");var o={training:t},s=Rm(function(a,e){var t=g.cell.call([a].concat(e),o);return[t[0],t.slice(1)]},d,n,g.goBackwards,e,null,g.unroll,g.returnSequences),i=s[0],l=s[1],u=s[2];g.stateful&&g.resetStates(u,t);var p=g.returnSequences?l:i;return g.returnState?[p].concat(u):p})},e.prototype.getInitialState=function(a){var e=this;return We(function(){var t=pn(a.shape);return t=Mp(t=Lu(t,[1,2])),Array.isArray(e.cell.stateSize)?e.cell.stateSize.map(function(a){return 1<a?$p(t,[1,a]):t}):1<e.cell.stateSize?[$p(t,[1,e.cell.stateSize])]:[t]})},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){m.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 t=this.cell.getConfig();e.cell={className:this.cell.getClassName(),config:t};var a=m.prototype.getConfig.call(this);return Object.assign(e,a),e},e.fromConfig=function(a,e,t){void 0===t&&(t={});var o=Ad(e.cell,t);return new a(Object.assign(e,{cell:o}))},e.className="RNN",e}(Ky);Mh.registerClass(kx);var Tx=function(a){function e(){return null!==a&&a.apply(this,arguments)||this}return Xi(e,a),e}(Ky),Rx=function(a){function e(e){var t=a.call(this,e)||this;return t.DEFAULT_ACTIVATION="tanh",t.DEFAULT_KERNEL_INITIALIZER="glorotNormal",t.DEFAULT_RECURRENT_INITIALIZER="orthogonal",t.DEFAULT_BIAS_INITIALIZER="zeros",t.units=e.units,yp(t.units,"units"),t.activation=am(null==e.activation?t.DEFAULT_ACTIVATION:e.activation),t.useBias=null==e.useBias||e.useBias,t.kernelInitializer=ud(e.kernelInitializer||t.DEFAULT_KERNEL_INITIALIZER),t.recurrentInitializer=ud(e.recurrentInitializer||t.DEFAULT_RECURRENT_INITIALIZER),t.biasInitializer=ud(e.biasInitializer||t.DEFAULT_BIAS_INITIALIZER),t.kernelRegularizer=im(e.kernelRegularizer),t.recurrentRegularizer=im(e.recurrentRegularizer),t.biasRegularizer=im(e.biasRegularizer),t.kernelConstraint=Np(e.kernelConstraint),t.recurrentConstraint=Np(e.recurrentConstraint),t.biasConstraint=Np(e.biasConstraint),t.dropout=Lp([1,Fp([0,null==e.dropout?0:e.dropout])]),t.recurrentDropout=Lp([1,Fp([0,null==e.recurrentDropout?0:e.recurrentDropout])]),t.stateSize=t.units,t.dropoutMask=null,t.recurrentDropoutMask=null,t}return Xi(e,a),e.prototype.build=function(t){t=yd(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.bias=this.useBias?this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):null,this.built=!0},e.prototype.call=function(p,d){var t=this;return We(function(){if(2!==(p=p).length)throw new Zf("SimpleRNNCell expects 2 input Tensors, got "+p.length+".");var e=p[1];p=p[0];var n=null!=d.training&&d.training,a;0<t.dropout&&1>t.dropout&&null==t.dropoutMask&&(t.dropoutMask=Em(function(){return xn(p)},t.dropout,n)),0<t.recurrentDropout&&1>t.recurrentDropout&&null==t.recurrentDropoutMask&&(t.recurrentDropoutMask=Em(function(){return xn(e)},t.recurrentDropout,n));var u=t.dropoutMask,o=t.recurrentDropoutMask;a=Yp(null==u?p:hl(p,u),t.kernel.read()),null!=t.bias&&(a=ed(a,t.bias.read())),null!=o&&(e=hl(e,o));var s=Ju(a,Yp(e,t.recurrentKernel.read()));return null!=t.activation&&(s=t.activation.apply(s)),[s,s]})},e.prototype.getConfig=function(){var e={units:this.units,activation:em(this.activation),useBias:this.useBias,kernelInitializer:ld(this.kernelInitializer),recurrentInitializer:ld(this.recurrentInitializer),biasInitializer:ld(this.biasInitializer),kernelRegularizer:om(this.kernelRegularizer),recurrentRegularizer:om(this.recurrentRegularizer),biasRegularizer:om(this.biasRegularizer),activityRegularizer:om(this.activityRegularizer),kernelConstraint:Cp(this.kernelConstraint),recurrentConstraint:Cp(this.recurrentConstraint),biasConstraint:Cp(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e.className="SimpleRNNCell",e}(Tx);Mh.registerClass(Rx);var Ex=function(s){function e(e){return e.cell=new Rx(e),s.call(this,e)||this}return Xi(e,s),e.prototype.call=function(e,t){var n=this;return We(function(){null!=n.cell.dropoutMask&&(ze(n.cell.dropoutMask),n.cell.dropoutMask=null),null!=n.cell.recurrentDropoutMask&&(ze(n.cell.recurrentDropoutMask),n.cell.recurrentDropoutMask=null);var r=null==t?null:t.mask,i=null==t?null:t.training,a=null==t?null:t.initialState;return s.prototype.call.call(n,e,{mask:r,training:i,initialState:a})})},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:em(this.activation),useBias:this.useBias,kernelInitializer:ld(this.kernelInitializer),recurrentInitializer:ld(this.recurrentInitializer),biasInitializer:ld(this.biasInitializer),kernelRegularizer:om(this.kernelRegularizer),recurrentRegularizer:om(this.recurrentRegularizer),biasRegularizer:om(this.biasRegularizer),activityRegularizer:om(this.activityRegularizer),kernelConstraint:Cp(this.kernelConstraint),recurrentConstraint:Cp(this.recurrentConstraint),biasConstraint:Cp(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout},t=s.prototype.getConfig.call(this);return delete t.cell,Object.assign(e,t),e},e.fromConfig=function(a,e){return new a(e)},e.className="SimpleRNN",e}(kx);Mh.registerClass(Ex);var wx=function(a){function e(e){var t=a.call(this,e)||this;return t.DEFAULT_ACTIVATION="tanh",t.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",t.DEFAULT_KERNEL_INITIALIZER="glorotNormal",t.DEFAULT_RECURRENT_INITIALIZER="orthogonal",t.DEFAULT_BIAS_INITIALIZER="zeros",t.units=e.units,yp(t.units,"units"),t.activation=am(void 0===e.activation?t.DEFAULT_ACTIVATION:e.activation),t.recurrentActivation=am(void 0===e.recurrentActivation?t.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),t.useBias=null==e.useBias||e.useBias,t.kernelInitializer=ud(e.kernelInitializer||t.DEFAULT_KERNEL_INITIALIZER),t.recurrentInitializer=ud(e.recurrentInitializer||t.DEFAULT_RECURRENT_INITIALIZER),t.biasInitializer=ud(e.biasInitializer||t.DEFAULT_BIAS_INITIALIZER),t.kernelRegularizer=im(e.kernelRegularizer),t.recurrentRegularizer=im(e.recurrentRegularizer),t.biasRegularizer=im(e.biasRegularizer),t.kernelConstraint=Np(e.kernelConstraint),t.recurrentConstraint=Np(e.recurrentConstraint),t.biasConstraint=Np(e.biasConstraint),t.dropout=Lp([1,Fp([0,null==e.dropout?0:e.dropout])]),t.recurrentDropout=Lp([1,Fp([0,null==e.recurrentDropout?0:e.recurrentDropout])]),t.implementation=e.implementation,t.stateSize=t.units,t.dropoutMask=null,t.recurrentDropoutMask=null,t}return Xi(e,a),e.prototype.build=function(a){var n=(a=yd(a))[a.length-1];this.kernel=this.addWeight("kernel",[n,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.bias=this.useBias?this.addWeight("bias",[3*this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):null,this.built=!0},e.prototype.call=function(x,C){var t=this;return We(function(){if(2!==(x=x).length)throw new Zf("GRUCell expects 2 input Tensors (inputs, h, c), got "+x.length+".");var e=null!=C.training&&C.training,n=x[1];x=x[0],0<t.dropout&&1>t.dropout&&null==t.dropoutMask&&(t.dropoutMask=Em(function(){return xn(x)},t.dropout,e,3)),0<t.recurrentDropout&&1>t.recurrentDropout&&null==t.recurrentDropoutMask&&(t.recurrentDropoutMask=Em(function(){return xn(n)},t.recurrentDropout,e,3));var r=t.dropoutMask,l=t.recurrentDropoutMask,u,N,I;0<t.dropout&&1>t.dropout&&(x=hl(x,r[0]));var k=Yp(x,t.kernel.read());t.useBias&&(k=ed(k,t.bias.read())),0<t.recurrentDropout&&1>t.recurrentDropout&&(n=hl(n,l[0]));var T=t.recurrentKernel.read(),p=Un(T,[2*t.units,t.units],T.rank-1),h=p[0],d=p[1],f=Yp(n,h),g=Un(k,3,k.rank-1),m=g[0],y=g[1],v=g[2],b=Un(f,2,f.rank-1),R=b[0],E=b[1];u=t.recurrentActivation.apply(Ju(m,R)),N=t.recurrentActivation.apply(Ju(y,E));var S=Yp(hl(N,n),d);I=t.activation.apply(Ju(v,S));var w=Ju(hl(u,n),hl(Ju(1,Cs(u)),I));return[w,w]})},e.prototype.getConfig=function(){var e={units:this.units,activation:em(this.activation),recurrentActivation:em(this.recurrentActivation),useBias:this.useBias,kernelInitializer:ld(this.kernelInitializer),recurrentInitializer:ld(this.recurrentInitializer),biasInitializer:ld(this.biasInitializer),kernelRegularizer:om(this.kernelRegularizer),recurrentRegularizer:om(this.recurrentRegularizer),biasRegularizer:om(this.biasRegularizer),activityRegularizer:om(this.activityRegularizer),kernelConstraint:Cp(this.kernelConstraint),recurrentConstraint:Cp(this.recurrentConstraint),biasConstraint:Cp(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e.className="GRUCell",e}(Tx);Mh.registerClass(wx);var Ax=function(s){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 wx(e),s.call(this,e)||this}return Xi(e,s),e.prototype.call=function(e,t){var n=this;return We(function(){null!=n.cell.dropoutMask&&(ze(n.cell.dropoutMask),n.cell.dropoutMask=null),null!=n.cell.recurrentDropoutMask&&(ze(n.cell.recurrentDropoutMask),n.cell.recurrentDropoutMask=null);var r=null==t?null:t.mask,i=null==t?null:t.training,a=null==t?null:t.initialState;return s.prototype.call.call(n,e,{mask:r,training:i,initialState:a})})},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:em(this.activation),recurrentActivation:em(this.recurrentActivation),useBias:this.useBias,kernelInitializer:ld(this.kernelInitializer),recurrentInitializer:ld(this.recurrentInitializer),biasInitializer:ld(this.biasInitializer),kernelRegularizer:om(this.kernelRegularizer),recurrentRegularizer:om(this.recurrentRegularizer),biasRegularizer:om(this.biasRegularizer),activityRegularizer:om(this.activityRegularizer),kernelConstraint:Cp(this.kernelConstraint),recurrentConstraint:Cp(this.recurrentConstraint),biasConstraint:Cp(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},t=s.prototype.getConfig.call(this);return delete t.cell,Object.assign(e,t),e},e.fromConfig=function(a,e){return 0===e.implmentation&&(e.implementation=1),new a(e)},e.className="GRU",e}(kx);Mh.registerClass(Ax);var Dx=function(a){function e(e){var t=a.call(this,e)||this;return t.DEFAULT_ACTIVATION="tanh",t.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",t.DEFAULT_KERNEL_INITIALIZER="glorotNormal",t.DEFAULT_RECURRENT_INITIALIZER="orthogonal",t.DEFAULT_BIAS_INITIALIZER="zeros",t.units=e.units,yp(t.units,"units"),t.activation=am(void 0===e.activation?t.DEFAULT_ACTIVATION:e.activation),t.recurrentActivation=am(void 0===e.recurrentActivation?t.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),t.useBias=null==e.useBias||e.useBias,t.kernelInitializer=ud(e.kernelInitializer||t.DEFAULT_KERNEL_INITIALIZER),t.recurrentInitializer=ud(e.recurrentInitializer||t.DEFAULT_RECURRENT_INITIALIZER),t.biasInitializer=ud(e.biasInitializer||t.DEFAULT_BIAS_INITIALIZER),t.unitForgetBias=e.unitForgetBias,t.kernelRegularizer=im(e.kernelRegularizer),t.recurrentRegularizer=im(e.recurrentRegularizer),t.biasRegularizer=im(e.biasRegularizer),t.kernelConstraint=Np(e.kernelConstraint),t.recurrentConstraint=Np(e.recurrentConstraint),t.biasConstraint=Np(e.biasConstraint),t.dropout=Lp([1,Fp([0,null==e.dropout?0:e.dropout])]),t.recurrentDropout=Lp([1,Fp([0,null==e.recurrentDropout?0:e.recurrentDropout])]),t.implementation=e.implementation,t.stateSize=[t.units,t.units],t.dropoutMask=null,t.recurrentDropoutMask=null,t}return Xi(e,a),e.prototype.build=function(o){var s=(o=yd(o))[o.length-1],r,p;if(this.kernel=this.addWeight("kernel",[s,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 d=this.biasInitializer,i=this.units;p=new((r=function(a){function e(){return null!==a&&a.apply(this,arguments)||this}return Xi(e,a),e.prototype.apply=function(){var e=d.apply([i]),t=new Cy().apply([i]),a=d.apply([2*i]);return jp(jp(e,t),a)},e}(xy)).className="CustomInit",r)}else p=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.units],null,p,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0},e.prototype.call=function(b,x){var t=this;return We(function(){var e=null!=x.training&&x.training;if(3!==(b=b).length)throw new Zf("LSTMCell expects 3 input Tensors (inputs, h, c), got "+b.length+".");var n=b[1],r=b[2];b=b[0],0<t.dropout&&1>t.dropout&&null==t.dropoutMask&&(t.dropoutMask=Em(function(){return xn(b)},t.dropout,e,4)),0<t.recurrentDropout&&1>t.recurrentDropout&&null==t.recurrentDropoutMask&&(t.recurrentDropoutMask=Em(function(){return xn(n)},t.recurrentDropout,e,4));var a=t.dropoutMask,c=t.recurrentDropoutMask,p,C,S,N;0<t.dropout&&1>t.dropout&&(b=hl(b,a[0]));var I=Yp(b,t.kernel.read());0<t.recurrentDropout&&1>t.recurrentDropout&&(n=hl(n,c[0])),I=Ju(I,Yp(n,t.recurrentKernel.read())),t.useBias&&(I=ed(I,t.bias.read()));var k=Un(I,4,I.rank-1),d=k[0],f=k[1],g=k[2],m=k[3];p=t.recurrentActivation.apply(d),C=t.recurrentActivation.apply(f),S=Ju(hl(C,r),hl(p,t.activation.apply(g))),N=t.recurrentActivation.apply(m);var y=hl(N,t.activation.apply(S));return[y,y,S]})},e.prototype.getConfig=function(){var e={units:this.units,activation:em(this.activation),recurrentActivation:em(this.recurrentActivation),useBias:this.useBias,kernelInitializer:ld(this.kernelInitializer),recurrentInitializer:ld(this.recurrentInitializer),biasInitializer:ld(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:om(this.kernelRegularizer),recurrentRegularizer:om(this.recurrentRegularizer),biasRegularizer:om(this.biasRegularizer),activityRegularizer:om(this.activityRegularizer),kernelConstraint:Cp(this.kernelConstraint),recurrentConstraint:Cp(this.recurrentConstraint),biasConstraint:Cp(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e.className="LSTMCell",e}(Tx);Mh.registerClass(Dx);var _x=function(s){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 Dx(e),s.call(this,e)||this}return Xi(e,s),e.prototype.call=function(e,t){var n=this;return We(function(){null!=n.cell.dropoutMask&&(ze(n.cell.dropoutMask),n.cell.dropoutMask=null),null!=n.cell.recurrentDropoutMask&&(ze(n.cell.recurrentDropoutMask),n.cell.recurrentDropoutMask=null);var r=null==t?null:t.mask,i=null==t?null:t.training,a=null==t?null:t.initialState;return s.prototype.call.call(n,e,{mask:r,training:i,initialState:a})})},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:em(this.activation),recurrentActivation:em(this.recurrentActivation),useBias:this.useBias,kernelInitializer:ld(this.kernelInitializer),recurrentInitializer:ld(this.recurrentInitializer),biasInitializer:ld(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:om(this.kernelRegularizer),recurrentRegularizer:om(this.recurrentRegularizer),biasRegularizer:om(this.biasRegularizer),activityRegularizer:om(this.activityRegularizer),kernelConstraint:Cp(this.kernelConstraint),recurrentConstraint:Cp(this.recurrentConstraint),biasConstraint:Cp(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},t=s.prototype.getConfig.call(this);return delete t.cell,Object.assign(e,t),e},e.fromConfig=function(a,e){return 0===e.implmentation&&(e.implementation=1),new a(e)},e.className="LSTM",e}(kx);Mh.registerClass(_x);var Ox=function(s){function e(e){var t=s.call(this,e)||this;return t.cells=e.cells,t}return Xi(e,s),Object.defineProperty(e.prototype,"stateSize",{get:function(){for(var a=[],e=0,o=this.cells.slice().reverse(),n;e<o.length;e++)n=o[e],Array.isArray(n.stateSize)?a.push.apply(a,n.stateSize):a.push(n.stateSize);return a},enumerable:!0,configurable:!0}),e.prototype.call=function(p,a){var t=this;return We(function(){for(var e=(p=p).slice(1),n=[],i=0,m=t.cells.slice().reverse(),o;i<m.length;i++)o=m[i],Array.isArray(o.stateSize)?n.push(e.splice(0,o.stateSize.length)):n.push(e.splice(0,1));n.reverse();for(var g=[],u=0,f;u<t.cells.length;++u)o=t.cells[u],e=n[u],f=0==u?[p[0]].concat(e):[f[0]].concat(e),f=o.call(f,a),g.push(f.slice(1));e=[];for(var y=0,b=g.slice().reverse(),h;y<b.length;y++)h=b[y],e.push.apply(e,h);return[f[0]].concat(e)})},e.prototype.build=function(a){var o;md(a)&&(a=a[0]),a=a;for(var s=0,p=this.cells,r;s<p.length;s++)r=p[s],r.build(a),o=Array.isArray(r.stateSize)?r.stateSize[0]:r.stateSize,a=[a[0],o];this.built=!0},e.prototype.getConfig=function(){for(var e=[],t=0,p=this.cells,r;t<p.length;t++)r=p[t],e.push({className:r.getClassName(),config:r.getConfig()});var d={cells:e},a=s.prototype.getConfig.call(this);return Object.assign(d,a),d},e.fromConfig=function(s,e,t){void 0===t&&(t={});for(var p=[],r=0,d=e.cells,a;r<d.length;r++)a=d[r],p.push(Ad(a,t));return new s({cells:p})},Object.defineProperty(e.prototype,"trainableWeights",{get:function(){if(!this.trainable)return[];for(var a=[],e=0,o=this.cells,n;e<o.length;e++)n=o[e],a.push.apply(a,n.trainableWeights);return a},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"nonTrainableWeights",{get:function(){for(var s=[],e=0,p=this.cells,n;e<p.length;e++)n=p[e],s.push.apply(s,n.nonTrainableWeights);if(!this.trainable){for(var d=[],i=0,l=this.cells;i<l.length;i++)n=l[i],d.push.apply(d,n.trainableWeights);return d.concat(s)}return s},enumerable:!0,configurable:!0}),e.prototype.getWeights=function(){for(var a=[],e=0,o=this.cells,n;e<o.length;e++)n=o[e],a.push.apply(a,n.weights);return vd(a)},e.prototype.setWeights=function(p){for(var e=[],t=0,d=this.cells;t<d.length;t++)for(var r=d[t],i=r.weights.length,a=p.splice(i),o=0;o<r.weights.length;++o)e.push([r.weights[o],a[o]]);Cd(e)},e.className="StackedRNNCells",e}(Tx);Mh.registerClass(Ox);var zx=function(a){function e(e){var t=a.call(this,e)||this;return t.layer=e.layer,t}return Xi(e,a),e.prototype.build=function(){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()}},t=a.prototype.getConfig.call(this);return Object.assign(e,t),e},e.prototype.setFastWeightInitDuringBuild=function(e){a.prototype.setFastWeightInitDuringBuild.call(this,e),null!=this.layer&&this.layer.setFastWeightInitDuringBuild(e)},e.fromConfig=function(a,e,t){void 0===t&&(t={});var o=Ad(e.layer,t);delete e.layer;var r={layer:o};return Object.assign(r,e),new a(r)},e}(Ky),Lx=function(a){function e(e){var t=a.call(this,e)||this;return t.supportsMasking=!0,t}return Xi(e,a),e.prototype.build=function(e){if(3>(e=yd(e)).length)throw new Zf("TimeDistributed layer expects an input shape >= 3D, but received input shape "+JSON.stringify(e));this.inputSpec=[{shape:e}];var r=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(r),this.layer.built=!0),a.prototype.build.call(this,e)},e.prototype.computeOutputShape=function(a){var o=[(a=yd(a))[0]].concat(a.slice(2)),t=this.layer.computeOutputShape(o),n=a[1];return[t[0],n].concat(t.slice(1))},e.prototype.call=function(a,r){var t=this;return We(function(){return Rm(function(a){return[fd(t.layer.call(a,r)),[]]},a=fd(a),[],!1,null,null,!1,!0)[1]})},e.className="TimeDistributed",e}(zx);Mh.registerClass(Lx);var Fx=function(y){function e(e){var t=y.call(this,e)||this,n=e.layer.getConfig(),r={};r.className=e.layer.getClassName(),r.config=n,t.forwardLayer=Ad(r),n.goBackwards=!0!==n.goBackwards;var o={};if(o.className=e.layer.getClassName(),o.config=n,t.backwardLayer=Ad(o),t.forwardLayer.name="forward_"+t.forwardLayer.name,t.backwardLayer.name="backward_"+t.backwardLayer.name,t.mergeMode=void 0===e.mergeMode?"concat":e.mergeMode,wm(t.mergeMode),e.weights)throw new Qf("weights support is not implemented for Bidirectional layer yet.");return t._stateful=e.layer.stateful,t.returnSequences=e.layer.returnSequences,t.returnState=e.layer.returnState,t.supportsMasking=!0,t._trainable=!0,t.inputSpec=e.layer.inputSpec,t.numConstants=null,t}return Xi(e,y),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(a){var e=a.length,t=Cf(e/2);this.forwardLayer.setWeights(a.slice(0,t)),this.backwardLayer.setWeights(a.slice(t))},e.prototype.computeOutputShape=function(a){var e=this.forwardLayer.computeOutputShape(a),o,s,p;return Array.isArray(e)&&Array.isArray(e[0])||(e=[e]),e=e,this.returnState?(p=e.slice(1),o=e[0]):o=e[0],o=o,"concat"===this.mergeMode?(o[o.length-1]*=2,s=[o]):s=null==this.mergeMode?[o,o.slice()]:[o],this.returnState?null==this.mergeMode?s.concat(p).concat(p.slice()):[o].concat(p).concat(p.slice()):rp(s)},e.prototype.apply=function(e,b){var x=null==b?null:b.initialState,v=null==b?null:b.constants;null==b&&(b={});var C=Tm(e,x,v,this.numConstants);if(e=C.inputs,x=C.initialState,v=C.constants,Array.isArray(e)&&(x=e.slice(1),e=e[0]),(null==x||0===x.length)&&null==v)return y.prototype.apply.call(this,e,b);var a=[],o=[];if(null!=x){var s=x.length;if(0<s%2)throw new Zf("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");b.initialState=x,a.push.apply(a,x);var l=x.map(function(t){return new Vy({shape:t.shape})});this.forwardLayer.stateSpec=l.slice(0,s/2),this.backwardLayer.stateSpec=l.slice(s/2),o.push.apply(o,l)}if(null!=v)throw new Qf("Support for constants in Bidirectional layers is not implemented yet.");for(var u=a[0]instanceof Uy,c=0,S=a;c<S.length;c++)if(S[c]instanceof Uy!=u)throw new Zf("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(u){var h=[e].concat(a),d=this.inputSpec.concat(o),f=this.inputSpec;this.inputSpec=d;var g=y.prototype.apply.call(this,h,b);return this.inputSpec=f,g}return y.prototype.apply.call(this,e,b)},e.prototype.call=function(p,e){var t=this;return We(function(){if(null!=e.mask)throw new Qf("The support for masking is not implemented for Bidirectional layers yet.");var n=e.initialState,s,d,c,h;if(null==n)s=t.forwardLayer.call(p,e),d=t.backwardLayer.call(p,e);else{var m=n.slice(0,n.length/2),l=n.slice(n.length/2);s=t.forwardLayer.call(p,Object.assign(e,{initialState:m})),d=t.backwardLayer.call(p,Object.assign(e,{initialState:l}))}return t.returnState&&(Array.isArray(s)&&(c=s.slice(1).concat(d.slice(1))),s=s[0],d=d[0]),t.returnSequences&&(d=pu(d,1)),"concat"===t.mergeMode?h=Kp([s,d]):"sum"===t.mergeMode?h=Ju(s,d):"ave"===t.mergeMode?h=hl(.5,Ju(s,d)):"mul"===t.mergeMode?h=hl(s,d):null==t.mergeMode&&(h=[s,d]),t.returnState?null==t.mergeMode?h.concat(c):[h].concat(c):h})},e.prototype.resetStates=function(){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()},e.prototype.build=function(a){var e=this;Rp(this.forwardLayer.name,function(){e.forwardLayer.build(a)}),Rp(this.backwardLayer.name,function(){e.backwardLayer.build(a)}),this.built=!0},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){y.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},t=y.prototype.getConfig.call(this);return Object.assign(e,t),e},e.fromConfig=function(a,e){var t=Ad(e.layer);if(delete e.layer,null!=e.numConstants)throw new Qf("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");var n=e;return n.layer=t,new a(n)},e.className="Bidirectional",e}(zx);Mh.registerClass(Fx);var Bx=Object.freeze({inputLayer:function(t){return new jy(t)},elu:function(t){return new Db(t)},reLU:function(t){return new Eb(t)},leakyReLU:function(t){return new wb(t)},prelu:function(t){return new Ab(t)},softmax:function(t){return new Ob(t)},thresholdedReLU:function(t){return new _b(t)},conv1d:function(t){return new Vb(t)},conv2d:function(t){return new Fb(t)},conv2dTranspose:function(t){return new Pb(t)},conv3d:function(t){return new Bb(t)},separableConv2d:function(t){return new Wb(t)},cropping2D:function(t){return new Ub(t)},upSampling2d:function(t){return new Gb(t)},depthwiseConv2d:function(t){return new qb(t)},activation:function(t){return new $b(t)},dense:function(t){return new Kb(t)},dropout:function(t){return new Hb(t)},flatten:function(t){return new jb(t)},repeatVector:function(t){return new Xb(t)},reshape:function(t){return new Yb(t)},permute:function(t){return new Zb(t)},embedding:function(t){return new Jb(t)},add:function(t){return new tx(t)},average:function(t){return new nx(t)},concatenate:function(t){return new sx(t)},maximum:function(t){return new rx(t)},minimum:function(t){return new ox(t)},multiply:function(t){return new ax(t)},dot:function(t){return new ix(t)},batchNormalization:function(t){return new ux(t)},zeroPadding2d:function(t){return new cx(t)},averagePooling1d:Am,avgPool1d:function(t){return Am(t)},avgPooling1d:function(t){return Am(t)},averagePooling2d:Dm,avgPool2d:function(t){return Dm(t)},avgPooling2d:function(t){return Dm(t)},globalAveragePooling1d:function(t){return new vx(t)},globalAveragePooling2d:function(t){return new Nx(t)},globalMaxPooling1d:_m,globalMaxPooling2d:Om,maxPooling1d:zm,maxPooling2d:Lm,gru:function(t){return new Ax(t)},gruCell:function(t){return new wx(t)},lstm:function(t){return new _x(t)},lstmCell:function(t){return new Dx(t)},simpleRNN:function(t){return new Ex(t)},simpleRNNCell:function(t){return new Rx(t)},rnn:function(t){return new kx(t)},stackedRNNCells:function(t){return new Ox(t)},bidirectional:function(t){return new Fx(t)},timeDistributed:function(t){return new Lx(t)},globalMaxPool1d:_m,globalMaxPool2d:Om,maxPool1d:zm,maxPool2d:Lm,Layer:Ky,RNN:kx,RNNCell:Tx,input:function(t){return kd(t)},gaussianNoise:function(t){return new px(t)},gaussianDropout:function(t){return new dx(t)},alphaDropout:function(t){return new lx(t)},masking:function(t){return new Qb(t)}}),Px=Object.freeze({binaryAccuracy:Fm,binaryCrossentropy:Bm,sparseCategoricalAccuracy:Pm,categoricalAccuracy:Mm,categoricalCrossentropy:Wm,precision:Vm,recall:Um,cosineProximity:Gm,meanAbsoluteError:qm,meanAbsolutePercentageError:Hm,MAPE:Km,mape:jm,meanSquaredError:$m,MSE:Xm,mse:Ym}),Mx=Object.freeze({modelFromJSON:function(p,d){return Yi(this,void 0,void 0,function(){var e,t,h,m,g,f,y,b;return Qi(this,function(a){switch(a.label){case 0:return"modelTopology"in p||(p={modelTopology:p}),null!=(e=(p=p).modelTopology).model_config&&(e=e.model_config),t=bu(e),h=Ad(t,d),null==p.weightsManifest?[3,2]:[4,kh.loadWeights(p.weightsManifest,p.pathPrefix,h.weights.map(function(t){return t.originalName}))];case 1:for(m=a.sent(),g={},f=0,y=h.weights;f<y.length;f++)b=y[f],g[b.originalName]=m[b.originalName];h.loadWeights(g),ze(m),a.label=2;case 2:return[2,h];}})})}}),Wx=Object.freeze({l1l2:function(t){return new Tb(t)},l1:function(t){return nm(t)},l2:function(t){return rm(t)}}),Vx=function(a){function e(){var e=null!==a&&a.apply(this,arguments)||this;return e.model=null,e}return Xi(e,a),e.prototype.setModel=function(t){if(!(t instanceof lb))throw new Error("model must be a LayersModel, not some other Container");this.model=t},e}(Xy),Ux=function(a){function e(e){var r=a.call(this)||this;if(null==e&&(e={}),e.restoreBestWeights)throw new Qf("restoreBestWeights = True is not implemented in EarlyStopping yet.");return r.monitor=e.monitor||"val_loss",r.minDelta=Sf(e.minDelta||0),r.patience=e.patience||0,r.verbose=e.verbose||0,r.mode=e.mode||"auto",r.baseline=e.baseline,-1===["auto","min","max"].indexOf(r.mode)&&(console.warn("EarlyStopping mode '"+r.mode+"' is invalid. Falling back to mode 'auto'."),r.mode="auto"),r.monitorFunc="min"===r.mode?Zm:"max"===r.mode?Qm:-1===r.monitor.indexOf("acc")?Zm:Qm,r.monitorFunc===Zm&&(r.minDelta*=-1),r}return Xi(e,a),e.prototype.onTrainBegin=function(){return Yi(this,void 0,void 0,function(){return Qi(this,function(){return this.wait=0,this.stoppedEpoch=0,this.best=null==this.baseline?this.monitorFunc===Zm?1/0:-1/0:this.baseline,[2]})})},e.prototype.onEpochEnd=function(a,e){return Yi(this,void 0,void 0,function(){var t;return Qi(this,function(n){switch(n.label){case 0:return[4,Td(e)];case 1:return n.sent(),null==(t=this.getMonitorValue(e))?[2]:(this.monitorFunc(t-this.minDelta,this.best)?(this.best=t,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=a,this.model.stopTraining=!0)),[2]);}})})},e.prototype.onTrainEnd=function(){return Yi(this,void 0,void 0,function(){return Qi(this,function(){return 0<this.stoppedEpoch&&this.verbose&&console.log("Epoch "+this.stoppedEpoch+": early stopping."),[2]})})},e.prototype.getMonitorValue=function(a){null==a&&(a={});var n=a[this.monitor];return null==n&&console.warn("Metric for EarlyStopping "+this.monitor+" is not available. Available metrics are: "+Object.keys(a)),n},e}(Vx),Gx=function(){return(Gx=Object.assign||function(o){for(var e=1,s=arguments.length,r;e<s;e++)for(var i in r=arguments[e])Object.prototype.hasOwnProperty.call(r,i)&&(o[i]=r[i]);return o}).apply(this,arguments)},qx={},Hx,Kx;!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"}(Hx||(Hx={})),function(t){!function(t){t[t.LEGACY=0]="LEGACY",t[t.V1=1]="V1",t[t.V2=2]="V2"}(t.CheckpointFormatVersion||(t.CheckpointFormatVersion={}))}(Kx||(Kx={}));var jx=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:"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}]}]}),$x=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:"Neg",category:"basic_math",inputs:[{start:0,name:"x",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}]}]}),Xx=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"}]}]}),Yx=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:"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:"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[]"}]}]}),Zx=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"}]}]}),Qx=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:"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}]}]}),Jx=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"}]}]}),ev=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"}]}]}),tv=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"}]}]}),av=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}]}]}),nv=Object.freeze({json:[{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}]}]}),rv=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}]}]}),ov=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"}]}]}),sv=Object.freeze({json:[{tfOpName:"ConcatV2",category:"slice_join",inputs:[{start:0,end:-1,name:"tensors",type:"tensors"},{start:-1,name:"axis",type:"number"}]},{tfOpName:"Concat",category:"slice_join",inputs:[{start:1,end:0,name:"tensors",type:"tensors"},{start:0,name:"axis",type:"number"}]},{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}]}]}),iv=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}]}]}),pv=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"}]}]}),dv=function(){function t(){var e=[].concat.apply([],[jx,$x,Xx,Yx,Zx,Qx,Jx,av,tv,ev,nv,rv,ov,sv,iv,pv].map(function(t){return t.json}));this.opMappers=e.reduce(function(a,e){return a[e.tfOpName]=e,a},{})}return Object.defineProperty(t,"Instance",{get:function(){return this._instance||(this._instance=new this)},enumerable:!0,configurable:!0}),t.prototype.transformGraph=function(i){var d=this,t=[],a=[],r=i.node.reduce(function(r,e){return r[e.name]=d.mapNode(e),"Placeholder"===e.op&&t.push(r[e.name]),"Const"===e.op&&a.push(r[e.name]),r},{}),n=[],s=[],e=Object.keys(r);return e.forEach(function(a){var o=r[a];o.inputNames.forEach(function(t){var e=sg(t)[0];o.inputs.push(r[e]),r[e].children.push(o)}),0===o.inputs.length&&n.push(o)}),e.forEach(function(a){var e=r[a];0===e.children.length&&s.push(e)}),{nodes:r,inputs:n,outputs:s,weights:a,placeholders:t}},t.prototype.mapNode=function(n){var e=ag(n.op)||this.opMappers[n.op]||{};null==n.attr&&(n.attr={});var t={name:n.name,op:n.op,category:e.category,inputNames:(n.input||[]).map(function(t){return t.startsWith("^")?t.substr(1):t}),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:n.attr};return null!=e.inputs&&(t.inputParams=e.inputs.reduce(function(a,e){return a[e.name]={type:e.type,inputIndexStart:e.start,inputIndexEnd:e.end},a},{})),null!=e.attrs&&(t.attrParams=e.attrs.reduce(function(e,t){var a=t.type,r;switch(t.type){case"string":void 0===(r=cg(n.attr,t.tfName,t.defaultValue))&&t.tfDeprecatedName&&(r=cg(n.attr,t.tfDeprecatedName,t.defaultValue));break;case"string[]":void 0===(r=Cg(n.attr,t.tfName,t.defaultValue))&&t.tfDeprecatedName&&(r=Cg(n.attr,t.tfDeprecatedName,t.defaultValue));break;case"number":void 0===(r=mg(n.attr,t.tfName,t.defaultValue||0))&&t.tfDeprecatedName&&(r=mg(n.attr,t.tfDeprecatedName,t.defaultValue));break;case"number[]":void 0===(r=vg(n.attr,t.tfName,t.defaultValue))&&t.tfDeprecatedName&&(r=vg(n.attr,t.tfDeprecatedName,t.defaultValue));break;case"bool":void 0===(r=hg(n.attr,t.tfName,t.defaultValue))&&t.tfDeprecatedName&&(r=hg(n.attr,t.tfDeprecatedName,t.defaultValue));break;case"bool[]":void 0===(r=Ng(n.attr,t.tfName,t.defaultValue))&&t.tfDeprecatedName&&(r=Ng(n.attr,t.tfDeprecatedName,t.defaultValue));break;case"shape":void 0===(r=xg(n.attr,t.tfName,t.defaultValue))&&t.tfDeprecatedName&&(r=xg(n.attr,t.tfDeprecatedName,t.defaultValue));break;case"shape[]":void 0===(r=Sg(n.attr,t.tfName,t.defaultValue))&&t.tfDeprecatedName&&(r=Sg(n.attr,t.tfDeprecatedName,t.defaultValue));break;case"dtype":void 0===(r=fg(n.attr,t.tfName,t.defaultValue))&&t.tfDeprecatedName&&(r=fg(n.attr,t.tfDeprecatedName,t.defaultValue));break;case"dtype[]":void 0===(r=yg(n.attr,t.tfName,t.defaultValue))&&t.tfDeprecatedName&&(r=yg(n.attr,t.tfDeprecatedName,t.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error("Unsupported param type: "+t.type+" for op: "+n.op);}return e[t.name]={value:r,type:a},e},{})),t},t}(),lv=function(){function t(n,e,t){var a=this;this.node=n,this.tensorMap=e,this.context=t,this.inputs=[],this.attrs={},this.inputs=n.inputNames.map(function(t){return a.getInput(t)}),null!=n.rawAttrs&&(this.attrs=Object.keys(n.rawAttrs).reduce(function(n,e){return n[e]=a.getAttr(e),n},{}))}return t.prototype.getInput=function(t){return rg(t,this.tensorMap,this.context)},t.prototype.getAttr=function(n,e){var t=this.node.rawAttrs[n];if(null!=t.tensor)return rg(n,this.tensorMap,this.context);if(null!=t.i||null!=t.f)return mg(this.node.rawAttrs,n,e);if(null!=t.s)return cg(this.node.rawAttrs,n,e);if(null!=t.b)return hg(this.node.rawAttrs,n,e);if(null!=t.shape)return xg(this.node.rawAttrs,n,e);if(null!=t.type)return fg(this.node.rawAttrs,n,e);if(null!=t.list){if(null!=t.list.i||null!=t.list.f)return vg(this.node.rawAttrs,n,e);if(null!=t.list.s)return Cg(this.node.rawAttrs,n,e);if(null!=t.list.shape)return Sg(this.node.rawAttrs,n,e);if(null!=t.list.b)return Ng(this.node.rawAttrs,n,e);if(null!=t.list.type)return yg(this.node.rawAttrs,n,e)}return e},t}(),uv=function(n,e,t){switch(n.op){case"BiasAdd":case"AddV2":case"Add":return[Ju(ng("a",n,e,t),ng("b",n,e,t))];case"AddN":return[Zu(ng("tensors",n,e,t))];case"FloorMod":case"Mod":return[ll(ng("a",n,e,t),ng("b",n,e,t))];case"Mul":return[hl(ng("a",n,e,t),ng("b",n,e,t))];case"RealDiv":case"Div":return[nl(ng("a",n,e,t),ng("b",n,e,t))];case"FloorDiv":return[ol(ng("a",n,e,t),ng("b",n,e,t))];case"Sub":return[gl(ng("a",n,e,t),ng("b",n,e,t))];case"Minimum":return[sl(ng("a",n,e,t),ng("b",n,e,t))];case"Maximum":return[al(ng("a",n,e,t),ng("b",n,e,t))];case"Pow":return[pl(ng("a",n,e,t),ng("b",n,e,t))];case"SquaredDifference":return[vl(ng("a",n,e,t),ng("b",n,e,t))];default:throw TypeError("Node type "+n.op+" is not implemented");}},cv=function(n,e,t){switch(n.op){case"Abs":case"ComplexAbs":return[os(ng("x",n,e,t))];case"Acos":return[as(ng("x",n,e,t))];case"Acosh":return[is(ng("x",n,e,t))];case"Asin":return[ss(ng("x",n,e,t))];case"Asinh":return[us(ng("x",n,e,t))];case"Atan":return[ls(ng("x",n,e,t))];case"Atan2":return[el(ng("x",n,e,t),ng("y",n,e,t))];case"Atanh":return[cs(ng("x",n,e,t))];case"Ceil":return[hs(ng("x",n,e,t))];case"Complex":return[Hf(ng("real",n,e,t),ng("imag",n,e,t))];case"Cos":return[ps(ng("x",n,e,t))];case"Cosh":return[ds(ng("x",n,e,t))];case"Elu":return[Il(ng("x",n,e,t))];case"Erf":return[vs(ng("x",n,e,t))];case"Exp":return[ms(ng("x",n,e,t))];case"Expm1":return[gs(ng("x",n,e,t))];case"Floor":return[ys(ng("x",n,e,t))];case"Log":return[xs(ng("x",n,e,t))];case"Log1p":return[bs(ng("x",n,e,t))];case"Neg":return[Cs(ng("x",n,e,t))];case"Reciprocal":return[Es(ng("x",n,e,t))];case"Relu":return[kl(ng("x",n,e,t))];case"Round":return[Rs(ng("x",n,e,t))];case"Selu":return[Al(ng("x",n,e,t))];case"Sigmoid":return[Ss(ng("x",n,e,t))];case"Sin":return[Ds(ng("x",n,e,t))];case"Sign":return[Ns(ng("x",n,e,t))];case"Sinh":return[_s(ng("x",n,e,t))];case"Softplus":return[Os(ng("x",n,e,t))];case"Sqrt":return[Fs(ng("x",n,e,t))];case"Square":return[Ms(ng("x",n,e,t))];case"Tanh":return[Ls(ng("x",n,e,t))];case"Tan":return[Ps(ng("x",n,e,t))];case"Relu6":case"ClipByValue":return[fs(ng("x",n,e,t),ng("clipValueMin",n,e,t),ng("clipValueMax",n,e,t))];case"Rsqrt":return[Is(rg(n.inputNames[0],e,t))];case"Prod":return[Wu(ng("x",n,e,t),ng("axes",n,e,t))];case"LeakyRelu":return[Sl(ng("x",n,e,t),ng("alpha",n,e,t))];default:throw TypeError("Node type "+n.op+" is not implemented");}},hv=function(){function i(e,t,a,r,n,s,o){this.name=e,this.dtype=t,this.maxSize=a,this.elementShape=r,this.identicalElementShapes=n,this.dynamicSize=s,this.clearAfterRead=o,this.tensors=[],this.closed_=!1,this.id=i.nextId++}return Object.defineProperty(i.prototype,"closed",{get:function(){return this.closed_},enumerable:!0,configurable:!0}),i.prototype.clearAndClose=function(){this.tensors.forEach(function(t){return t.tensor.dispose()}),this.tensors=[],this.closed_=!0},i.prototype.size=function(){return this.tensors.length},i.prototype.read=function(a){if(this.closed_)throw new Error("TensorArray "+this.name+" has already been closed.");if(0>a||a>=this.tensors.length)throw new Error("Tried to read from index "+a+", but array size is: "+this.tensors.length);var e=this.tensors[a];if(e.cleared)throw new Error("TensorArray "+this.name+": Could not read index "+a+" 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},i.prototype.readMany=function(a){var n=this;return a.map(function(t){return n.read(t)})},i.prototype.write=function(n,e){if(this.closed_)throw new Error("TensorArray "+this.name+" has already been closed.");if(0>n||!this.dynamicSize&&n>=this.maxSize)throw new Error("Tried to write to index "+n+", but array is not resizeable and size is: "+this.maxSize);var t=this.tensors[n]||{};if(e.dtype!==this.dtype)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+n+",\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 "+n+"."),t&&t.read)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+n+", because it has already been read.");if(t&&t.written)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+n+", because it has already been written.");t.tensor=e,t.written=!0,this.tensors[n]=t},i.prototype.writeMany=function(n,o){var t=this;if(n.length!==o.length)throw new Error("TensorArray "+this.name+": could not write multiple tensors,because the index size: "+n.length+" is not the same as tensors size: "+o.length+".");n.forEach(function(a,e){return t.write(a,o[e])})},i.prototype.gather=function(n,o){if(o&&o!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but gather requested dtype "+o);if(!n){n=[];for(var t=0;t<this.size();t++)n.push(t)}if(0===n.length)return Zt([],[0].concat(this.elementShape));var s=this.readMany(n);return this.assertShapesMatchAllowUndefinedSize(this.elementShape,s[0].shape,"TensorArray shape mismatch: "),br(s,0)},i.prototype.concat=function(n){if(n&&n!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but concat requested dtype "+n);if(0===this.size())return Zt([],[0].concat(this.elementShape));for(var e=[],t=0;t<this.size();t++)e.push(t);var o=this.readMany(e);return this.assertShapesMatchAllowUndefinedSize(this.elementShape,o[0].shape,"TensorArray shape mismatch: tensor array shape ("+this.elementShape+") vs first tensor shape ("+o[0].shape+")"),Mn(o,0)},i.prototype.scatter=function(n,e){if(e.dtype!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but tensor has dtype "+e.dtype);if(n.length!==e.shape[0])throw new Error("Expected len(indices) == tensor.shape[0], but saw: "+n.length+" vs. "+e.shape[0]);var t=Ef.apply(Math,n);if(!this.dynamicSize&&t>=this.maxSize)throw new Error("Max index must be < array size ("+t+"  vs. "+this.maxSize+")");this.writeMany(n,Er(e,0))},i.prototype.split=function(d,e){var l=this;if(e.dtype!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but tensor has dtype "+e.dtype);var a=0,c=d.map(function(t){return a+=t});if(a!==e.shape[0])throw new Error("Expected sum of lengths to be equal to\n          tensor.shape[0], but sum of lengths is\n        "+a+", and tensor's shape is: "+e.shape);if(!this.dynamicSize&&d.length!==this.maxSize)throw new Error("TensorArray's size is not equal to the size of lengths ("+this.maxSize+" vs. "+d.length+"), and the TensorArray is not marked as dynamically resizeable");var n=0===a?0:e.size/a,s=[];We(function(){e=e.reshape([1,a,n]);for(var t=0;t<d.length;++t){var r=[0,0==t?0:c[t-1],0],o=[1,d[t],n];s[t]=Eu(e,r,o).reshape(l.elementShape)}return s});for(var o=[],i=0;i<d.length;i++)o[i]=i;this.writeMany(o,s)},i.prototype.assertShapesMatchAllowUndefinedSize=function(n,e,t){void 0===t&&(t=""),Of.assert(this.shapesEqualAllowUndefinedSize(n,e),function(){return t+" Shapes "+n+" and "+e+" must match"})},i.prototype.shapesEqualAllowUndefinedSize=function(n,e){if(n.length!==e.length)return!1;for(var t=0;t<n.length;t++)if(-1!==n[t]&&-1!==e[t]&&n[t]!==e[t])return!1;return!0},i.nextId=0,i}(),mv=function(d,e,t){switch(d.op){case"Conv1D":var a=ng("stride",d,e,t),l=ng("pad",d,e,t),c=ng("dataFormat",d,e,t).toUpperCase(),h=ng("dilation",d,e,t);return[Zs(ng("x",d,e,t),ng("filter",d,e,t),a,l,c,h)];case"Conv2D":a=ng("strides",d,e,t),l=ng("pad",d,e,t),c=ng("dataFormat",d,e,t).toUpperCase();var o=ng("dilations",d,e,t);return[ru(ng("x",d,e,t),ng("filter",d,e,t),[a[1],a[2]],l,c,[o[1],o[2]])];case"Conv2DBackpropInput":case"Conv2dTranspose":var m=ng("outputShape",d,e,t);return a=ng("strides",d,e,t),l=ng("pad",d,e,t),[lu(ng("x",d,e,t),ng("filter",d,e,t),m,[a[1],a[2]],l)];case"DepthwiseConv2dNative":case"DepthwiseConv2d":return a=ng("strides",d,e,t),l=ng("pad",d,e,t),o=ng("dilations",d,e,t),c=ng("dataFormat",d,e,t).toUpperCase(),[su(ng("input",d,e,t),ng("filter",d,e,t),[a[1],a[2]],l,c,[o[1],o[2]])];case"AvgPool":a=ng("strides",d,e,t),l=ng("pad",d,e,t);var u=ng("kernelSize",d,e,t);return[wu(ng("x",d,e,t),[u[1],u[2]],[a[1],a[2]],l)];case"MaxPool":return a=ng("strides",d,e,t),l=ng("pad",d,e,t),u=ng("kernelSize",d,e,t),[yu(ng("x",d,e,t),[u[1],u[2]],[a[1],a[2]],l)];default:throw TypeError("Node type "+d.op+" is not implemented");}},gv=function(b,e,t){switch(b.op){case"Fill":var a=ng("shape",b,e,t),x=ng("dtype",b,e,t),n=ng("value",b,e,t);return[dn(a,n,x)];case"LinSpace":var s=ng("start",b,e,t),v=ng("stop",b,e,t),p=ng("num",b,e,t);return[ln(s,v,p)];case"OneHot":var u=ng("indices",b,e,t),i=ng("depth",b,e,t),m=ng("onValue",b,e,t),c=ng("offValue",b,e,t);return[ur(u,i,m,c)];case"Ones":return[sn(ng("shape",b,e,t),ng("dtype",b,e,t))];case"OnesLike":return[xn(ng("x",b,e,t))];case"RandomUniform":return[mr(ng("shape",b,e,t),ng("minval",b,e,t),ng("maxval",b,e,t),ng("dtype",b,e,t))];case"Range":s=ng("start",b,e,t);var l=ng("stop",b,e,t),d=ng("step",b,e,t);return[un(s,l,d,ng("dtype",b,e,t))];case"TruncatedNormal":a=ng("shape",b,e,t);var y=ng("mean",b,e,t),f=ng("stdDev",b,e,t),h=ng("seed",b,e,t);return[Cr(a,y,f,ng("dtype",b,e,t),h)];case"Zeros":return[pn(ng("shape",b,e,t),ng("dtype",b,e,t))];case"ZerosLike":return[Fn(ng("x",b,e,t))];default:throw TypeError("Node type "+b.op+" is not implemented");}},fv=function(i,e,t){switch(i.op){case"TopKV2":var a=ng("x",i,e,t),r=ng("k",i,e,t),n=ng("sorted",i,e,t),s=zl(a,r,n);return[s.values,s.indices];default:throw TypeError("Node type "+i.op+" is not implemented");}},yv=function(i,e,t){switch(i.op){case"Const":return e[i.name];case"PlaceholderWithDefault":var a=ng("default",i,e,t);return[rg(i.name,e,t)||a];case"Placeholder":return[rg(i.name,e,t)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":return[ng("x",i,e,t).clone()];case"IdentityN":return ng("x",i,e,t).map(function(t){return t.clone()});case"Snapshot":return[ng("x",i,e,t).clone()];case"Shape":return[en(ng("x",i,e,t).shape,"int32")];case"ShapeN":return ng("x",i,e,t).map(function(t){return en(t.shape)});case"Size":return[Da(ng("x",i,e,t).size,"int32")];case"Rank":return[Da(ng("x",i,e,t).rank,"int32")];case"NoOp":return[];case"Print":var r=ng("x",i,e,t),n=ng("data",i,e,t),s=ng("message",i,e,t),o=ng("summarize",i,e,t);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(s);for(var p=0;p<n.length;p++)console.log(Array.prototype.slice.call(n[p].dataSync()).slice(0,o));return[r];default:throw TypeError("Node type "+i.op+" is not implemented");}},bv=function(d,e,t){switch(d.op){case"ResizeBilinear":var a=ng("images",d,e,t),l=ng("size",d,e,t),h=ng("alignCorners",d,e,t);return[Ec.resizeBilinear(a,[l[0],l[1]],h)];case"ResizeNearestNeighbor":return a=ng("images",d,e,t),l=ng("size",d,e,t),h=ng("alignCorners",d,e,t),[Ec.resizeNearestNeighbor(a,[l[0],l[1]],h)];case"CropAndResize":var g=ng("image",d,e,t),o=ng("boxes",d,e,t),p=ng("boxInd",d,e,t),u=ng("cropSize",d,e,t),i=ng("method",d,e,t),m=ng("extrapolationValue",d,e,t);return[Ec.cropAndResize(g,o,p,u,i,m)];default:throw TypeError("Node type "+d.op+" is not implemented");}},xv=function(n,e,t){switch(n.op){case"Equal":return[Uu(ng("a",n,e,t),ng("b",n,e,t))];case"NotEqual":return[Yu(ng("a",n,e,t),ng("b",n,e,t))];case"Greater":return[Vu(ng("a",n,e,t),ng("b",n,e,t))];case"GreaterEqual":return[Gu(ng("a",n,e,t),ng("b",n,e,t))];case"Less":return[$u(ng("a",n,e,t),ng("b",n,e,t))];case"LessEqual":return[ju(ng("a",n,e,t),ng("b",n,e,t))];case"LogicalAnd":return[xl(ng("a",n,e,t),ng("b",n,e,t))];case"LogicalNot":return[bl(ng("a",n,e,t))];case"LogicalOr":return[wl(ng("a",n,e,t),ng("b",n,e,t))];case"Select":return[El(ng("condition",n,e,t),ng("a",n,e,t),ng("b",n,e,t))];default:throw TypeError("Node type "+n.op+" is not implemented");}},vv=function(n,e,t){switch(n.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[cu(ng("a",n,e,t),ng("b",n,e,t),ng("transposeA",n,e,t),ng("transposeB",n,e,t))];case"Transpose":return[Tl(ng("x",n,e,t),ng("perm",n,e,t))];default:throw TypeError("Node type "+n.op+" is not implemented");}},Cv=function(n,e,t){switch(n.op){case"FusedBatchNorm":case"FusedBatchNormV2":case"FusedBatchNormV3":return[Xs(ng("x",n,e,t),ng("mean",n,e,t),ng("variance",n,e,t),ng("offset",n,e,t),ng("scale",n,e,t),ng("epsilon",n,e,t))];case"LRN":return[Dl(ng("x",n,e,t),ng("radius",n,e,t),ng("bias",n,e,t),ng("alpha",n,e,t),ng("beta",n,e,t))];case"Softmax":return[Ir(ng("x",n,e,t))];case"LogSoftmax":return[Kr(ng("x",n,e,t))];case"SparseToDense":return[Kl(ng("sparseIndices",n,e,t),ng("outputShape",n,e,t),ng("sparseValues",n,e,t),ng("defaultValue",n,e,t))];default:throw TypeError("Node type "+n.op+" is not implemented");}},Sv=function(o,e,t){switch(o.op){case"Max":var a=ng("axis",o,e,t),s=ng("keepDims",o,e,t);return[Fu(ng("x",o,e,t),a,s)];case"Mean":return a=ng("axis",o,e,t),s=ng("keepDims",o,e,t),[Mu(ng("x",o,e,t),a,s)];case"Min":return a=ng("axis",o,e,t),s=ng("keepDims",o,e,t),[Bu(ng("x",o,e,t),a,s)];case"Sum":return a=ng("axis",o,e,t),s=ng("keepDims",o,e,t),[Lu(ng("x",o,e,t),a,s)];case"All":return a=ng("axis",o,e,t),s=ng("keepDims",o,e,t),[ku(ng("x",o,e,t),a,s)];case"Any":return a=ng("axis",o,e,t),s=ng("keepDims",o,e,t),[Tu(ng("x",o,e,t),a,s)];case"ArgMax":return a=ng("axis",o,e,t),[Du(ng("x",o,e,t),a)];case"ArgMin":return a=ng("axis",o,e,t),[_u(ng("x",o,e,t),a)];case"Prod":return a=ng("axis",o,e,t),s=ng("keepDims",o,e,t),[Wu(ng("x",o,e,t),a,s)];default:throw TypeError("Node type "+o.op+" is not implemented");}},Nv=function(v,e,t){switch(v.op){case"ConcatV2":case"Concat":var a=ng("axis",v,e,t),C=ng("tensors",v,e,t);return[Mn(C,a)];case"GatherV2":case"Gather":a=ng("axis",v,e,t);var n=ng("x",v,e,t),S=ng("indices",v,e,t);return[Ol(n,S.asType("int32"),a)];case"ReverseV2":case"Reverse":return a=ng("axis",v,e,t),n=ng("x",v,e,t),[pu(n,a)];case"Slice":var I=ng("begin",v,e,t),k=ng("size",v,e,t);return[Eu(ng("x",v,e,t),I,k)];case"StridedSlice":I=ng("begin",v,e,t);var u=ng("end",v,e,t),i=ng("strides",v,e,t),m=ng("beginMask",v,e,t),c=ng("endMask",v,e,t),l=ng("ellipsisMask",v,e,t),d=ng("newAxisMask",v,e,t),y=ng("shrinkAxisMask",v,e,t),f=ng("x",v,e,t);if(1===I.length&&1<f.shape.length)for(var h=1;h<f.shape.length;h++)I.push(0),u.push(f.shape[h]),i.push(i[0]);return[Ul(f,I,u,i,m,c,l,d,y)];case"Pack":return We(function(){var a=ng("axis",v,e,t),r=ng("tensors",v,e,t),n=r[0].shape,s=r[0].squeeze().shape,o=r.map(function(a){var e=Of.arraysEqual(a.shape,n);if(!e&&!Of.arraysEqual(a.squeeze().shape,s))throw new Error("the input tensors shape does not match");return e?a:a.reshape(n)});return[br(o,a)]});case"Unpack":return We(function(){var a=ng("axis",v,e,t),r=ng("tensor",v,e,t);return Er(r,a)});case"Tile":var R=ng("reps",v,e,t);return[wr(ng("x",v,e,t),R)];case"Split":case"SplitV":a=ng("axis",v,e,t);var N=ng("numOrSizeSplits",v,e,t);return Un(ng("x",v,e,t),N,a);case"ScatterNd":S=ng("indices",v,e,t);var x=ng("values",v,e,t),b=ng("shape",v,e,t);return[Vl(S,x,b)];case"GatherNd":var E=ng("x",v,e,t);return S=ng("indices",v,e,t),[Xl(E,S)];case"SparseToDense":S=ng("sparseIndices",v,e,t),b=ng("outputShape",v,e,t);var w=ng("sparseValues",v,e,t),T=ng("defaultValue",v,e,t);return[Kl(S,w,b,w.dtype===T.dtype?T:T.asType(w.dtype))];default:throw TypeError("Node type "+v.op+" is not implemented");}},Iv=function(n,e,t){switch(n.op){case"FFT":return[Gl(ng("x",n,e,t))];case"IFFT":return[Hl(ng("x",n,e,t))];case"RFFT":return[ql(ng("x",n,e,t))];case"IRFFT":return[$l(ng("x",n,e,t))];default:throw TypeError("Node type "+n.op+" is not implemented");}},kv=function(i,e,t){switch(i.op){case"Cast":return[er(ng("x",i,e,t),ng("dtype",i,e,t))];case"ExpandDims":var a=ng("axis",i,e,t);return[ar(ng("x",i,e,t),a)];case"Squeeze":return a=ng("axis",i,e,t),[xr(ng("x",i,e,t),a)];case"Reshape":return[gr(ng("x",i,e,t),ng("shape",i,e,t))];case"PadV2":case"Pad":return[lr(ng("x",i,e,t),dg(ng("padding",i,e,t),2),ng("constantValue",i,e,t))];case"SpaceToBatchND":var d=ng("blockShape",i,e,t),l=dg(ng("paddings",i,e,t),2);return[yr(ng("x",i,e,t),d,l)];case"BatchToSpaceND":d=ng("blockShape",i,e,t);var s=dg(ng("crops",i,e,t),2);return[Jn(ng("x",i,e,t),d,s)];case"DepthToSpace":var o=ng("blockSize",i,e,t),p=ng("dataFormat",i,e,t).toUpperCase();return[or(ng("x",i,e,t),o,p)];default:throw TypeError("Node type "+i.op+" is not implemented");}},Tv=function(){function t(a,e){this.weightMap=a,this.tensorArrayMap=e,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}return t.prototype.newFrame=function(a,e){return{id:a,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 n=[],e=0,r;e<this.contexts.length-1;e++)r=this.contexts.slice(0,this.contexts.length-e),n.push(this.contextIdforContexts(r));n.push(""),this._currentContextIds=n},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&&1<this.contexts.length))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&&0<this.contexts.length))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}(),Rv=["Switch","Merge","Enter","Exit","NextIteration"],Ev=["NonMaxSuppressionV2","NonMaxSuppressionV3","Where"],wv=function(){function t(t){this.graph=t,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this.placeholders=t.placeholders,this._outputs=t.outputs}return Object.defineProperty(t.prototype,"weightMap",{get:function(){return this._weightMap},set:function(a){var e=Object.keys(a).map(function(e){return a[e].map(function(t){return t.id})});this.weightIds=[].concat.apply([],e),this._weightMap=a},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputs",{get:function(){return this.placeholders.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.placeholders.map(function(t){return t.name})},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"outputNodes",{get:function(){return this.outputs.map(function(t){return t.name})},enumerable:!0,configurable:!0}),t.prototype.getCompilationKey=function(n,e){var t=n.map(function(t){return t.name}).sort(),a=e.map(function(t){return t.name}).sort();return t.join(this.SEPERATOR)+"--"+a.join(this.SEPERATOR)},t.prototype.compile=function(i,e){var t=Rg(i,e,this.weightMap),a=t.missingInputs,r=t.dynamicNode,n=t.syncInputs;if(null!=r)throw new Error("This execution contains the node '"+r.name+"', which has the dynamic op '"+r.op+"'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs ["+n+"]");if(0<a.length){var s=e.map(function(t){return t.name}),o=Object.keys(i);throw new Error("Cannot compute the outputs ["+s+"] from the provided inputs ["+o+"]. Missing the following inputs: ["+a+"]")}return Eg(this.graph,this.weightMap,t)},t.prototype.fusePrelu=function(){Dg(this.graph,this.weightMap)},t.prototype.execute=function(d,e){var t=this,a=Object.keys(d).sort();this.checkInputs(d),this.checkInputShapeAndType(d),this.checkOutputs(e);var r=a.map(function(a){return t.graph.nodes[a]}),n=e.map(function(a){return t.graph.nodes[pg(a)[0]]}),s=this.getCompilationKey(r,n),l=this.compiledMap.get(s);null==l&&(l=this.compile(d,n),this.compiledMap.set(s,l));var h={};return We(function(){var a=new Tv(t._weightMap,h),r=Gx({},t.weightMap);Object.keys(d).forEach(function(e){r[e]=[d[e]]});for(var n=t.getFrozenTensorIds(r),s={},o=0,p;o<l.length;o++)if(p=l[o],!r[p.name]){var u=Tg(p,r,a);if(u instanceof Promise)throw new Error("The execution of the op '"+p.op+"' returned a promise. Please use model.executeAsync() instead.");r[p.name]=u,t.checkTensorForDisposal(p.name,p,r,a,n,e,s)}return e.map(function(t){return rg(t,r,a)})})},t.prototype.getFrozenTensorIds=function(a){var e=[].concat.apply([],Object.keys(a).map(function(e){return a[e]}).map(function(t){return t.map(function(t){return t.id})}));return new Set(e)},t.prototype.checkTensorForDisposal=function(i,p,d,a,r,e,n){"control"!==p.category&&-1===e.indexOf(i)&&(d[i].forEach(function(t){null!=t&&(n[t.id]=(n[t.id]||0)+p.children.length)}),p.inputs.forEach(function(o){if("control"!==o.category){var e=og(o.name,d,a);null!=e&&e.forEach(function(a){if(a&&!r.has(a.id)){var e=n[a.id];1===e?(a.dispose(),delete n[a.id]):null!=e&&n[a.id]--}})}}))},t.prototype.executeAsync=function(d,e){return Jm(this,void 0,void 0,function(){var t=this,l,u,c,h,m,g;return eg(this,function(a){switch(a.label){case 0:return this.checkInputs(d),this.checkInputShapeAndType(d),this.checkOutputs(e),l={},u=new Tv(this._weightMap,l),[4,this.executeWithControlFlow(d,u,e)];case 1:return c=a.sent(),h=e.map(function(t){return rg(t,c,u)}),m=new Set(h.map(function(t){return t.id})),g=new Set(Object.keys(d).map(function(e){return d[e].id})),Object.keys(c).forEach(function(a){c[a].forEach(function(a){!a||a.isDisposed||m.has(a.id)||g.has(a.id)||-1!==t.weightIds.indexOf(a.id)||a.dispose()})}),[2,h];}})})},t.prototype.executeWithControlFlow=function(v,C,e){return Jm(this,void 0,void 0,function(){var t=this,a,x,S,I,k,T,R,E,w,A,D,_,O,z,L,F;return eg(this,function(n){switch(n.label){case 0:a=Object.keys(v),x=a.map(function(a){return t.graph.nodes[a]}),S=e.map(function(a){return t.graph.nodes[pg(a)[0]]}),I=Rg(v,S,this.weightMap),k=I.usedNodes,T=I.missingInputs,R=I.dynamicNode,E=I.syncInputs,w=x.concat(this.graph.weights).map(function(t){return{node:t,contexts:C.currentContext}}),A=Gx({},this.weightMap),Object.keys(v).forEach(function(e){A[e]=[v[e]]}),D={},_=this.getFrozenTensorIds(A),O={},n.label=1;case 1:return 0<w.length?(z=this.processStack(x,w,C,A,O,_,e,D,k),[4,Promise.all(z)]):[3,3];case 2:return n.sent(),[3,1];case 3:if(null==R&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead."),0<(L=S.filter(function(t){return!wg(t)&&!rg(t.name,A,C)}).map(function(t){return t.name})).length)throw F="",null!=R&&(F="Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs ["+E+"]"),new Error("Cannot compute the outputs ["+L+"] from the provided inputs ["+a+"]. Consider providing the following inputs: ["+T+"]. "+F);return[2,A];}})})},t.prototype.processStack=function(h,g,t,a,r,n,s,o,p){for(var u=this,e=[],i=function(){var i=g.pop();t.currentContext=i.contexts;var l="";if("Enter"===i.node.op&&ng("isConstant",i.node,a,t)&&(l=sg(i.node.name,t)[0]),-1===h.indexOf(i.node)){var c=Tg(i.node,a,t);l||(l=sg(i.node.name,t)[0]);var y=t.currentContext;c instanceof Promise?e.push(c.then(function(d){return a[l]=d,t.currentContext=y,u.checkTensorForDisposal(l,i.node,a,t,n,s,o),u.processChildNodes(i.node,g,t,a,r,p),d})):(a[l]=c,m.checkTensorForDisposal(l,i.node,a,t,n,s,o),m.processChildNodes(i.node,g,t,a,r,p))}else m.processChildNodes(i.node,g,t,a,r,p)},m=this;0<g.length;)i();return e},t.prototype.processChildNodes=function(o,i,t,a,r,n){o.children.forEach(function(s){var e=sg(s.name,t)[0];!r[e]&&n.has(s.name)&&("Merge"===s.op?s.inputNames.some(function(n){return!!rg(n,a,t)})&&(r[e]=!0,i.push({contexts:t.currentContext,node:s})):s.inputNames.every(function(n){return!!rg(n,a,t)})&&(r[e]=!0,i.push({contexts:t.currentContext,node:s})))})},t.prototype.dispose=function(){var a=this;Object.keys(this.weightMap).forEach(function(e){return a.weightMap[e].forEach(function(t){return t.dispose()})})},t.prototype.checkInputShapeAndType=function(i){var e=this;Object.keys(i).forEach(function(t){var a=i[t],r=e.graph.nodes[t];if(r.attrParams.shape&&r.attrParams.shape.value){var n=r.attrParams.shape.value,s=n.length===a.shape.length&&a.shape.every(function(a,e){return-1===n[e]||n[e]===a});Of.assert(s,function(){return"The shape of dict['"+r.name+"'] provided in model.execute(dict) must be ["+n+"], but was ["+a.shape+"]"})}r.attrParams.dtype&&r.attrParams.dtype.value&&Of.assert(a.dtype===r.attrParams.dtype.value,function(){return"The dtype of dict['"+r.name+"'] provided in model.execute(dict) must be "+r.attrParams.dtype.value+", but was "+a.dtype})})},t.prototype.checkInputs=function(n){var r=this,e=Object.keys(n).filter(function(t){return!r.graph.nodes[t]});if(0<e.length)throw new Error("The dict provided in model.execute(dict) has keys: ["+e+"] that are not part of graph")},t.prototype.checkOutputs=function(a){var n=this;a.forEach(function(t){var e=pg(t)[0];if(!n.graph.nodes[e])throw new Error("The output '"+t+"' is not found in the graph")})},t}(),Av=function(){function t(a,e){void 0===e&&(e={}),this.modelUrl=a,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.fusePrelu=function(){this.executor.fusePrelu(),null==ag("Prelu")&&tg("Prelu",function(n){var e=n.inputs[0],t=n.inputs[1];return Nl(e,t)})},t.prototype.findIOHandler=function(){var a=this.modelUrl;if(null!=a.load)this.handler=a;else if(null!=this.loadOptions.requestInit)this.handler=kh.browserHTTPRequest(a,this.loadOptions);else{var e=kh.getLoadHandlers(a,this.loadOptions.onProgress);if(0===e.length)e.push(kh.browserHTTPRequest(a,this.loadOptions));else if(1<e.length)throw new Error("Found more than one ("+e.length+") load handlers for URL '"+[a]+"'");this.handler=e[0]}},t.prototype.load=function(){return Jm(this,void 0,void 0,function(){var n,o,s;return eg(this,function(e){switch(e.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[4,this.handler.load()];case 1:return n=e.sent(),o=n.modelTopology,this.version=o.versions.producer+"."+o.versions.minConsumer,s=kh.decodeWeights(n.weightData,n.weightSpecs),this.executor=new wv(dv.Instance.transformGraph(o)),this.executor.weightMap=this.convertTensorMapToTensorsMap(s),[2,!0];}})})},t.prototype.predict=function(t){return this.execute(t,this.outputNodes)},t.prototype.normalizeInputs=function(n){if(!(n instanceof Lf||Array.isArray(n)))return n;if((n=Array.isArray(n)?n:[n]).length!==this.inputNodes.length)throw new Error("Input tensor count mismatch,the graph model has "+this.inputNodes.length+" placeholders, while there are "+n.length+" input tensors.");return this.inputNodes.reduce(function(e,t,a){return e[t]=n[a],e},{})},t.prototype.normalizeOutputs=function(t){return t=t||this.outputNodes,Array.isArray(t)?t:[t]},t.prototype.execute=function(n,r){n=this.normalizeInputs(n),r=this.normalizeOutputs(r);var o=this.executor.execute(n,r);return 1<o.length?o:o[0]},t.prototype.executeAsync=function(n,o){return Jm(this,void 0,void 0,function(){var e;return eg(this,function(t){switch(t.label){case 0:return n=this.normalizeInputs(n),o=this.normalizeOutputs(o),[4,this.executor.executeAsync(n,o)];case 1:return[2,1<(e=t.sent()).length?e:e[0]];}})})},t.prototype.convertTensorMapToTensorsMap=function(n){return Object.keys(n).reduce(function(e,t){return e[t]=[n[t]],e},{})},t.prototype.dispose=function(){this.executor.dispose()},t}(),Dv=function(a,t){return(Dv=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(a,t){a.__proto__=t}||function(a,t){for(var e in t)t.hasOwnProperty(e)&&(a[e]=t[e])})(a,t)},_v=Lg(function(e){!function(a,t,e){function s(a,t){return t.c=a.c,t.s0=a.s0,t.s1=a.s1,t.s2=a.s2,t}function n(a,t){var e=new function(a){var o=this,t=(s=4022871197,function(e){e=e.toString();for(var a=0,o;a<e.length;a++)o=.02519603282416938*(s+=e.charCodeAt(a)),o-=s=o>>>0,s=(o*=s)>>>0,s+=4294967296*(o-=s);return 23283064365386963e-26*(s>>>0)}),s;o.next=function(){var e=2091639*o.s0+23283064365386963e-26*o.c;return o.s0=o.s1,o.s1=o.s2,o.s2=e-(o.c=0|e)},o.c=1,o.s0=t(" "),o.s1=t(" "),o.s2=t(" "),o.s0-=t(a),0>o.s0&&(o.s0+=1),o.s1-=t(a),0>o.s1&&(o.s1+=1),o.s2-=t(a),0>o.s2&&(o.s2+=1),t=null}(a),n=t&&t.state,r=e.next;return r.int32=function(){return 0|4294967296*e.next()},r.double=function(){return r()+11102230246251565e-32*(0|2097152*r())},r.quick=r,n&&("object"==typeof n&&s(n,e),r.state=function(){return s(e,{})}),r}t&&t.exports?t.exports=n:e&&e.amd?e(function(){return n}):this.alea=n}(0,e,!1)}),Ov=Lg(function(e){!function(a,t,e){function s(a,t){return t.x=a.x,t.y=a.y,t.z=a.z,t.w=a.w,t}function n(a,t){var e=new function(a){var o=this,e="";o.x=0,o.y=0,o.z=0,o.w=0,o.next=function(){var e=o.x^o.x<<11;return o.x=o.y,o.y=o.z,o.z=o.w,o.w^=o.w>>>19^e^e>>>8},a===(0|a)?o.x=a:e+=a;for(var t=0;t<e.length+64;t++)o.x^=0|e.charCodeAt(t),o.next()}(a),n=t&&t.state,r=function(){return(e.next()>>>0)/4294967296};return r.double=function(){do var a=((e.next()>>>11)+(e.next()>>>0)/4294967296)/2097152;while(0===a);return a},r.int32=e.next,r.quick=r,n&&("object"==typeof n&&s(n,e),r.state=function(){return s(e,{})}),r}t&&t.exports?t.exports=n:e&&e.amd?e(function(){return n}):this.xor128=n}(0,e,!1)}),zv=Lg(function(e){!function(a,t,e){function s(a,t){return t.x=a.x,t.y=a.y,t.z=a.z,t.w=a.w,t.v=a.v,t.d=a.d,t}function n(a,t){var e=new function(a){var o=this,e="";o.next=function(){var e=o.x^o.x>>>2;return o.x=o.y,o.y=o.z,o.z=o.w,o.w=o.v,0|(o.d=0|o.d+362437)+(o.v=o.v^o.v<<4^e^e<<1)},o.x=0,o.y=0,o.z=0,o.w=0,o.v=0,a===(0|a)?o.x=a:e+=a;for(var t=0;t<e.length+64;t++)o.x^=0|e.charCodeAt(t),t==e.length&&(o.d=o.x<<10^o.x>>>4),o.next()}(a),n=t&&t.state,r=function(){return(e.next()>>>0)/4294967296};return r.double=function(){do var a=((e.next()>>>11)+(e.next()>>>0)/4294967296)/2097152;while(0===a);return a},r.int32=e.next,r.quick=r,n&&("object"==typeof n&&s(n,e),r.state=function(){return s(e,{})}),r}t&&t.exports?t.exports=n:e&&e.amd?e(function(){return n}):this.xorwow=n}(0,e,!1)}),Lv=Lg(function(e){!function(a,t,e){function s(a,t){return t.x=a.x.slice(),t.i=a.i,t}function n(a,n){null==a&&(a=+new Date);var e=new function(a){var o=this;o.next=function(){var e=o.x,a=o.i,n,s;return n=e[a],s=(n^=n>>>7)^n<<24,s^=(n=e[7&a+1])^n>>>10,s^=(n=e[7&a+3])^n>>>3,s^=(n=e[7&a+4])^n<<7,n=e[7&a+7],s^=(n^=n<<13)^n<<9,e[a]=s,o.i=7&a+1,s},function(a,t){var o=[],n;if(t===(0|t))o[0]=t;else for(t=""+t,n=0;n<t.length;++n)o[7&n]=o[7&n]<<15^t.charCodeAt(n)+o[7&n+1]<<13;for(;8>o.length;)o.push(0);for(n=0;8>n&&0===o[n];++n);for(8==n?o[7]=-1:o[n],a.x=o,a.i=0,n=256;0<n;--n)a.next()}(o,a)}(a),r=n&&n.state,i=function(){return(e.next()>>>0)/4294967296};return i.double=function(){do var a=((e.next()>>>11)+(e.next()>>>0)/4294967296)/2097152;while(0===a);return a},i.int32=e.next,i.quick=i,r&&(r.x&&s(r,e),i.state=function(){return s(e,{})}),i}t&&t.exports?t.exports=n:e&&e.amd?e(function(){return n}):this.xorshift7=n}(0,e,!1)}),Fv=Lg(function(e){!function(a,t,e){function s(a,t){return t.i=a.i,t.w=a.w,t.X=a.X.slice(),t}function n(a,n){null==a&&(a=+new Date);var e=new function(a){var s=this;s.next=function(){var e=s.w,a=s.X,i=s.i,p,d;return s.w=e=0|e+1640531527,d=a[127&i+34],p=a[i=127&i+1],d^=d<<13,p^=p<<17,d^=d>>>15,p^=p>>>12,d=a[i]=d^p,s.i=i,0|d+(e^e>>>16)},function(p,t){var d=[],s=128,l,c,h,m,g;for(t===(0|t)?(c=t,t=null):(t+="\0",c=0,s=Ef(s,t.length)),h=0,m=-32;m<s;++m)t&&(c^=t.charCodeAt((m+32)%t.length)),0===m&&(g=c),c^=c<<10,c^=c>>>15,c^=c<<4,c^=c>>>13,0<=m&&(g=0|g+1640531527,h=0==(l=d[127&m]^=c+g)?h+1:0);for(128<=h&&(d[127&(t&&t.length||0)]=-1),h=127,m=512;0<m;--m)c=d[127&h+34],l=d[h=127&h+1],c^=c<<13,l^=l<<17,c^=c>>>15,l^=l>>>12,d[h]=c^l;p.w=g,p.X=d,p.i=h}(s,a)}(a),r=n&&n.state,i=function(){return(e.next()>>>0)/4294967296};return i.double=function(){do var a=((e.next()>>>11)+(e.next()>>>0)/4294967296)/2097152;while(0===a);return a},i.int32=e.next,i.quick=i,r&&(r.X&&s(r,e),i.state=function(){return s(e,{})}),i}t&&t.exports?t.exports=n:e&&e.amd?e(function(){return n}):this.xor4096=n}(0,e,!1)}),Bv=Lg(function(e){!function(a,t,e){function s(a,t){return t.a=a.a,t.b=a.b,t.c=a.c,t.d=a.d,t}function n(a,t){var e=new function(a){var o=this,e="";o.next=function(){var e=o.b,a=o.c,s=o.d,p=o.a;return e=e<<25^e>>>7^a,a=0|a-s,s=s<<24^s>>>8^p,p=0|p-e,o.b=e=e<<20^e>>>12^a,o.c=a=0|a-s,o.d=s<<16^a>>>16^p,o.a=0|p-e},o.a=0,o.b=0,o.c=-1640531527,o.d=1367130551,a===Cf(a)?(o.a=0|a/4294967296,o.b=0|a):e+=a;for(var t=0;t<e.length+20;t++)o.b^=0|e.charCodeAt(t),o.next()}(a),n=t&&t.state,r=function(){return(e.next()>>>0)/4294967296};return r.double=function(){do var a=((e.next()>>>11)+(e.next()>>>0)/4294967296)/2097152;while(0===a);return a},r.int32=e.next,r.quick=r,n&&("object"==typeof n&&s(n,e),r.state=function(){return s(e,{})}),r}t&&t.exports?t.exports=n:e&&e.amd?e(function(){return n}):this.tychei=n}(0,e,!1)}),Pv=Lg(function(a){!function(o,s){function e(e,t,a){var n=[],m=d(function a(t,e){var r=[],s=typeof t,o;if(e&&"object"==s)for(o in t)try{r.push(a(t[o],e-1))}catch(e){}return r.length?r:"string"==s?t:t+"\0"}((t=1==t?{entropy:!0}:t||{}).entropy?[e,p(o)]:null==e?function(){try{var e;return l&&(e=l.randomBytes)?e=e(256):(e=new Uint8Array(256),(h.crypto||h.msCrypto).getRandomValues(e)),p(e)}catch(e){var n=h.navigator,r=n&&n.plugins;return[+new Date,h,r,h.screen,p(o)]}}():e,3),n),b=new function(o){var p=o.length,d=this,n=0,l=d.i=d.j=0,u=d.S=[],s;for(p||(o=[p++]);256>n;)u[n]=n++;for(n=0;256>n;n++)u[n]=u[l=255&l+o[n%p]+(s=u[n])],u[l]=s;(d.g=function(n){for(var o=0,p=d.i,l=d.j,u=d.S,s;n--;)s=u[p=255&p+1],o=256*o+u[255&(u[p]=u[l=255&l+s])+(u[l]=s)];return d.i=p,d.j=l,o})(256)}(n),y=function(){for(var a=b.g(6),n=i,o=0;a<u;)a=256*(a+o),n*=256,o=b.g(1);for(;a>=c;)a/=2,n/=2,o>>>=1;return(a+o)/n};return y.int32=function(){return 0|b.g(4)},y.quick=function(){return b.g(4)/4294967296},y.double=y,d(p(b.S),o),(t.pass||a||function(a,t,e,n){return n&&(n.S&&r(n,b),a.state=function(){return r(b,{})}),e?(s.random=a,t):a})(y,m,"global"in t?t.global:this==s,t.state)}function r(a,t){return t.i=a.i,t.j=a.j,t.S=a.S.slice(),t}function d(a,t){for(var e=a+"",n=0,o;n<e.length;)t[255&n]=255&(o^=19*t[255&n])+e.charCodeAt(n++);return p(t)}function p(e){return cf.apply(0,e)}var h=this,i=s.pow(256,6),u=s.pow(2,52),c=2*u,l;if(s.seedrandom=e,d(s.random(),o),a.exports){a.exports=e;try{l=require("crypto")}catch(e){}}}([],Math)});Pv.alea=_v,Pv.xor128=Ov,Pv.xorwow=zv,Pv.xorshift7=Lv,Pv.xor4096=Fv,Pv.tychei=Bv;var Mv=Pv.alea,Wv=function(){function e(e){if(this.capacity=e,this.begin=0,this.end=0,null==e)throw new RangeError("Can't create a ring buffer of unknown capacity.");if(1>e)throw new RangeError("Can't create ring buffer of capacity < 1.");this.data=Array(e),this.doubledCapacity=2*e}return e.prototype.wrap=function(e){for(;0>e;)e+=this.doubledCapacity;return e%this.doubledCapacity},e.prototype.get=function(e){if(0>e)throw new RangeError("Can't get item at a negative index.");return this.data[e%this.capacity]},e.prototype.set=function(a,t){if(0>a)throw new RangeError("Can't set item at a negative index.");this.data[a%this.capacity]=t},e.prototype.length=function(){var e=this.end-this.begin;return 0>e&&(e=this.doubledCapacity+e),e},e.prototype.isFull=function(){return this.length()===this.capacity},e.prototype.isEmpty=function(){return 0===this.length()},e.prototype.push=function(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.set(this.end,e),this.end=this.wrap(this.end+1)},e.prototype.pushAll=function(a){for(var t=0,o=a,r;t<o.length;t++)r=o[t],this.push(r)},e.prototype.pop=function(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");this.end=this.wrap(this.end-1);var e=this.get(this.end);return this.set(this.end,void 0),e},e.prototype.unshift=function(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.begin=this.wrap(this.begin-1),this.set(this.begin,e)},e.prototype.shift=function(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");var e=this.get(this.begin);return this.set(this.begin,void 0),this.begin=this.wrap(this.begin+1),e},e.prototype.shuffleExcise=function(a){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");var t=this.wrap(this.begin+a),e=this.get(t);return this.set(t,this.pop()),e},e}(),Vv=function(a){function t(){return a.call(this,t.INITIAL_CAPACITY)||this}return _g(t,a),t.prototype.isFull=function(){return!1},t.prototype.push=function(t){a.prototype.isFull.call(this)&&this.expand(),a.prototype.push.call(this,t)},t.prototype.unshift=function(t){a.prototype.isFull.call(this)&&this.expand(),a.prototype.unshift.call(this,t)},t.prototype.expand=function(){for(var a=2*this.capacity,t=Array(a),e=this.length(),r=0;r<e;r++)t[r]=this.get(this.wrap(this.begin+r));this.data=t,this.capacity=a,this.doubledCapacity=2*this.capacity,this.begin=0,this.end=e},t.INITIAL_CAPACITY=32,t}(Wv),Uv=function(){function e(){}return e.prototype.toArray=function(){return Og(this,void 0,void 0,function(){var a,n;return zg(this,function(e){switch(e.label){case 0:return a=[],[4,this.next()];case 1:n=e.sent(),e.label=2;case 2:return n.done?[3,4]:(a.push(n.value),[4,this.next()]);case 3:return n=e.sent(),[3,2];case 4:return[2,a];}})})},e.prototype.toArrayForTest=function(){return Og(this,void 0,void 0,function(){var a,o,s;return zg(this,function(e){switch(e.label){case 0:return a=this.prefetch(100),o=[],[4,a.next()];case 1:s=e.sent(),e.label=2;case 2:return s.done?[3,4]:(o.push(s.value),[4,a.next()]);case 3:return s=e.sent(),[3,2];case 4:return[2,o];}})})},e.prototype.resolveFully=function(){return Og(this,void 0,void 0,function(){var a;return zg(this,function(t){switch(t.label){case 0:return[4,this.next()];case 1:a=t.sent(),t.label=2;case 2:return a.done?[3,4]:[4,this.next()];case 3:return a=t.sent(),[3,2];case 4:return[2];}})})},e.prototype.resolveWhile=function(a){return Og(this,void 0,void 0,function(){var t,o;return zg(this,function(e){switch(e.label){case 0:return[4,this.next()];case 1:t=e.sent(),o=a(t.value),e.label=2;case 2:return t.done||!o?[3,4]:[4,this.next()];case 3:return t=e.sent(),o=a(t.value),[3,2];case 4:return[2];}})})},e.prototype.handleErrors=function(e){return new Zv(this,e)},e.prototype.filter=function(e){return new Xv(this,e)},e.prototype.map=function(e){return new Yv(this,e)},e.prototype.mapAsync=function(e){return new Qv(this,e)},e.prototype.serialMapAsync=function(e){return new Qv(this,e).serial()},e.prototype.flatmap=function(e){return new eC(this,e)},e.prototype.forEachAsync=function(e){return Og(this,void 0,void 0,function(){return zg(this,function(){return[2,this.map(e).resolveFully()]})})},e.prototype.serialForEach=function(e){return Og(this,void 0,void 0,function(){return zg(this,function(){return[2,this.serialMapAsync(e).resolveWhile(function(e){return!0===e})]})})},e.prototype.rowMajorBatch=function(a,t){return void 0===t&&(t=!0),new $v(this,a,t)},e.prototype.columnMajorBatch=function(a,t,n){return void 0===t&&(t=!0),void 0===n&&(n=Wg),this.rowMajorBatch(a,t).map(function(e){return Pg(e,n)})},e.prototype.concatenate=function(a,t){return new tC(jg([this,a]),t)},e.prototype.take=function(e){return 0>e||null==e?this:new jv(this,e)},e.prototype.skip=function(e){return 0>e||null==e?this:new Kv(this,e)},e.prototype.prefetch=function(e){return new rC(this,e)},e.prototype.shuffle=function(a,t){return new oC(this,a,t)},e.prototype.serial=function(){return new Hv(this)},e}(),Gv=function(a){function t(t){var e=a.call(this)||this;return e.items=t,e.trav=0,e}return _g(t,a),t.prototype.summary=function(){return"Array of "+this.items.length+" items"},t.prototype.next=function(){return Og(this,void 0,void 0,function(){var e;return zg(this,function(){return this.trav>=this.items.length?[2,{value:null,done:!0}]:(e=this.items[this.trav],this.trav++,[2,{value:Hg(e),done:!1}])})})},t}(Uv),qv=function(a){function t(t){var e=a.call(this)||this;return e.nextFn=t,e}return _g(t,a),t.prototype.summary=function(){return"Function call"},t.prototype.next=function(){return Og(this,void 0,void 0,function(){return zg(this,function(){try{return[2,this.nextFn()]}catch(e){throw e.message="Error thrown while iterating through a dataset: "+e.message,e}return[2]})})},t}(Uv),Hv=function(a){function t(t){var e=a.call(this)||this;return e.upstream=t,e.lastRead=Promise.resolve({value:null,done:!1}),e}return _g(t,a),t.prototype.summary=function(){return this.upstream.summary()+" -> Serial"},t.prototype.next=function(){return Og(this,void 0,void 0,function(){var e=this;return zg(this,function(){return this.lastRead=this.lastRead.then(function(){return e.serialNext()}),[2,this.lastRead]})})},t.prototype.serialNext=function(){return Og(this,void 0,void 0,function(){return zg(this,function(){return[2,this.upstream.next()]})})},t}(Uv),Kv=function(a){function t(t,e){var r=a.call(this)||this;return r.upstream=t,r.maxCount=e,r.count=0,r.lastRead=Promise.resolve({value:null,done:!1}),r}return _g(t,a),t.prototype.summary=function(){return this.upstream.summary()+" -> Skip"},t.prototype.next=function(){return Og(this,void 0,void 0,function(){var e=this;return zg(this,function(){return this.lastRead=this.lastRead.then(function(){return e.serialNext()}),[2,this.lastRead]})})},t.prototype.serialNext=function(){return Og(this,void 0,void 0,function(){var a;return zg(this,function(t){switch(t.label){case 0:return this.count++<this.maxCount?[4,this.upstream.next()]:[3,2];case 1:return(a=t.sent()).done?[2,a]:(ze(a.value),[3,0]);case 2:return[2,this.upstream.next()];}})})},t}(Uv),jv=function(a){function t(t,e){var r=a.call(this)||this;return r.upstream=t,r.maxCount=e,r.count=0,r}return _g(t,a),t.prototype.summary=function(){return this.upstream.summary()+" -> Take"},t.prototype.next=function(){return Og(this,void 0,void 0,function(){return zg(this,function(){return this.count++>=this.maxCount?[2,{value:null,done:!0}]:[2,this.upstream.next()]})})},t}(Uv),$v=function(a){function t(t,e,r){void 0===r&&(r=!0);var o=a.call(this)||this;return o.upstream=t,o.batchSize=e,o.enableSmallLastBatch=r,o.lastRead=Promise.resolve({value:null,done:!1}),o}return _g(t,a),t.prototype.summary=function(){return this.upstream.summary()+" -> RowMajorBatch"},t.prototype.next=function(){return Og(this,void 0,void 0,function(){var e=this;return zg(this,function(){return this.lastRead=this.lastRead.then(function(){return e.serialNext()}),[2,this.lastRead]})})},t.prototype.serialNext=function(){return Og(this,void 0,void 0,function(){var a,n;return zg(this,function(e){switch(e.label){case 0:a=[],e.label=1;case 1:return a.length<this.batchSize?[4,this.upstream.next()]:[3,3];case 2:return(n=e.sent()).done?this.enableSmallLastBatch&&0<a.length?[2,{value:a,done:!1}]:[2,{value:null,done:!0}]:(a.push(n.value),[3,1]);case 3:return[2,{value:a,done:!1}];}})})},t}(Uv),Xv=function(a){function t(t,e){var r=a.call(this)||this;return r.upstream=t,r.predicate=e,r.lastRead=Promise.resolve({value:null,done:!1}),r}return _g(t,a),t.prototype.summary=function(){return this.upstream.summary()+" -> Filter"},t.prototype.next=function(){return Og(this,void 0,void 0,function(){var e=this;return zg(this,function(){return this.lastRead=this.lastRead.then(function(){return e.serialNext()}),[2,this.lastRead]})})},t.prototype.serialNext=function(){return Og(this,void 0,void 0,function(){var a;return zg(this,function(t){switch(t.label){case 0:return[4,this.upstream.next()];case 1:return(a=t.sent()).done||this.predicate(a.value)?[2,a]:(ze(a.value),[3,0]);case 2:return[2];}})})},t}(Uv),Yv=function(a){function t(t,e){var r=a.call(this)||this;return r.upstream=t,r.transform=e,r}return _g(t,a),t.prototype.summary=function(){return this.upstream.summary()+" -> Map"},t.prototype.next=function(){return Og(this,void 0,void 0,function(){var p,s,d,l,u,c,h;return zg(this,function(e){switch(e.label){case 0:return[4,this.upstream.next()];case 1:if((p=e.sent()).done)return[2,{value:null,done:!0}];for(s=xt.getTensorsInContainer(p.value),d=this.transform(p.value),l=xt.getTensorsInContainer(d),u=0,c=s;u<c.length;u++)h=c[u],xt.isTensorInList(h,l)||h.dispose();return[2,{value:d,done:!1}];}})})},t}(Uv),Zv=function(a){function t(t,e){var r=a.call(this)||this;return r.upstream=t,r.handler=e,r.count=0,r.lastRead=Promise.resolve({value:null,done:!1}),r}return _g(t,a),t.prototype.summary=function(){return this.upstream.summary()+" -> handleErrors"},t.prototype.next=function(){return Og(this,void 0,void 0,function(){var e=this;return zg(this,function(){return this.lastRead=this.lastRead.then(function(){return e.serialNext()}),[2,this.lastRead]})})},t.prototype.serialNext=function(){return Og(this,void 0,void 0,function(){var a;return zg(this,function(t){switch(t.label){case 0:t.label=1;case 1:return t.trys.push([1,3,,4]),[4,this.upstream.next()];case 2:return[2,t.sent()];case 3:return a=t.sent(),this.handler(a)?[3,4]:[2,{value:null,done:!0}];case 4:return[3,0];case 5:return[2];}})})},t}(Uv),Qv=function(a){function t(t,e){var r=a.call(this)||this;return r.upstream=t,r.transform=e,r}return _g(t,a),t.prototype.summary=function(){return this.upstream.summary()+" -> AsyncMap"},t.prototype.next=function(){return Og(this,void 0,void 0,function(){var p,d,l,u,c,h,m;return zg(this,function(e){switch(e.label){case 0:return[4,this.upstream.next()];case 1:return(p=e.sent()).done?[2,{value:null,done:!0}]:(d=xt.getTensorsInContainer(p.value),[4,this.transform(p.value)]);case 2:for(l=e.sent(),u=xt.getTensorsInContainer(l),c=0,h=d;c<h.length;c++)m=h[c],xt.isTensorInList(m,u)||m.dispose();return[2,{value:l,done:!1}];}})})},t}(Uv),Jv=function(a){function t(){var t=a.call(this)||this;return t.outputQueue=new Vv,t.lastRead=Promise.resolve({value:null,done:!1}),t}return _g(t,a),t.prototype.next=function(){return Og(this,void 0,void 0,function(){var e=this;return zg(this,function(){return this.lastRead=this.lastRead.then(function(){return e.serialNext()}),[2,this.lastRead]})})},t.prototype.serialNext=function(){return Og(this,void 0,void 0,function(){return zg(this,function(e){switch(e.label){case 0:return 0===this.outputQueue.length()?[4,this.pump()]:[3,2];case 1:return e.sent()?[3,0]:[2,{value:null,done:!0}];case 2:return[2,{value:this.outputQueue.shift(),done:!1}];}})})},t}(Uv),eC=function(a){function t(t,e){var r=a.call(this)||this;return r.upstream=t,r.transform=e,r}return _g(t,a),t.prototype.summary=function(){return this.upstream.summary()+" -> Flatmap"},t.prototype.pump=function(){return Og(this,void 0,void 0,function(){var p,s,d,l,u,c,h;return zg(this,function(e){switch(e.label){case 0:return[4,this.upstream.next()];case 1:if((p=e.sent()).done)return[2,!1];for(s=xt.getTensorsInContainer(p.value),d=this.transform(p.value),l=xt.getTensorsInContainer(d),this.outputQueue.pushAll(d),u=0,c=s;u<c.length;u++)h=c[u],xt.isTensorInList(h,l)||h.dispose();return[2,!0];}})})},t}(Jv),tC=function(a){function t(t,e){var r=a.call(this)||this;return r.baseErrorHandler=e,r.lastRead=null,r.iterator=null,r.moreIterators=t,r}return _g(t,a),t.prototype.summary=function(){return"TODO: fill in upstream of chained summaries -> Chained"},t.prototype.next=function(){return Og(this,void 0,void 0,function(){return zg(this,function(){return this.lastRead=this.readFromChain(this.lastRead),[2,this.lastRead]})})},t.prototype.readFromChain=function(a){return Og(this,void 0,void 0,function(){var t,o;return zg(this,function(e){switch(e.label){case 0:return[4,a];case 1:return e.sent(),null==this.iterator?[4,this.moreIterators.next()]:[3,3];case 2:if((t=e.sent()).done)return[2,{value:null,done:!0}];this.iterator=t.value,null!=this.baseErrorHandler&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler)),e.label=3;case 3:return[4,this.iterator.next()];case 4:return(o=e.sent()).done?(this.iterator=null,[2,this.readFromChain(a)]):[2,o];}})})},t}(Uv),aC;!function(e){e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST"}(aC||(aC={}));var nC=function(a){function t(t,e){void 0===e&&(e=aC.FAIL);var o=a.call(this)||this;return o.iterators=t,o.mismatchMode=e,o.count=0,o.currentPromise=null,o}return _g(t,a),t.prototype.summary=function(){return"{TODO: fill in upstream of zip summaries} -> Zip"},t.prototype.nextState=function(a){return Og(this,void 0,void 0,function(){function t(a){return a instanceof Uv?{value:a.next().then(function(a){return e++,a.done&&s++,a.value}),recurse:!1}:{value:null,recurse:!0}}var e,s,p;return zg(this,function(n){switch(n.label){case 0:return[4,a];case 1:return n.sent(),e=0,s=0,[4,Vg(this.iterators,t)];case 2:if(p=n.sent(),e===s)return[2,{value:null,done:!0}];if(0<s)switch(this.mismatchMode){case aC.FAIL:throw new Error("Zipped streams should have the same length. Mismatched at element "+this.count+".");case aC.SHORTEST:return[2,{value:null,done:!0}];case aC.LONGEST:}return this.count++,[2,{value:p,done:!1}];}})})},t.prototype.next=function(){return Og(this,void 0,void 0,function(){return zg(this,function(e){switch(e.label){case 0:return this.currentPromise=this.nextState(this.currentPromise),[4,this.currentPromise];case 1:return[2,e.sent()];}})})},t}(Uv),rC=function(a){function t(t,e){var r=a.call(this)||this;return r.upstream=t,r.bufferSize=e,r.buffer=new Wv(e),r}return _g(t,a),t.prototype.summary=function(){return this.upstream.summary()+" -> Prefetch"},t.prototype.refill=function(){for(;!this.buffer.isFull();){var e=this.upstream.next();this.buffer.push(e)}},t.prototype.next=function(){return this.refill(),this.buffer.shift()},t}(Uv),oC=function(a){function t(t,e,r){var n=a.call(this,t,e)||this;return n.upstream=t,n.windowSize=e,n.upstreamExhausted=!1,n.random=Mv(r||Of.now().toString()),n.lastRead=Promise.resolve({value:null,done:!1}),n}return _g(t,a),t.prototype.next=function(){return Og(this,void 0,void 0,function(){var e=this;return zg(this,function(){return this.lastRead=this.lastRead.then(function(){return e.serialNext()}),[2,this.lastRead]})})},t.prototype.randomInt=function(e){return Cf(this.random()*e)},t.prototype.chooseIndex=function(){return this.randomInt(this.buffer.length())},t.prototype.serialNext=function(){return Og(this,void 0,void 0,function(){var a,n;return zg(this,function(e){switch(e.label){case 0:this.upstreamExhausted||this.refill(),e.label=1;case 1:return this.buffer.isEmpty()?[3,3]:(a=this.chooseIndex(),[4,this.buffer.shuffleExcise(a)]);case 2:return(n=e.sent()).done?(this.upstreamExhausted=!0,[3,1]):(this.refill(),[2,n]);case 3:return[2,{value:null,done:!0}];}})})},t}(rC),sC=function(){function e(){this.size=null}return e.prototype.batch=function(a,t){var o=this;void 0===t&&(t=!0);var s=this;return Of.assert(0<a,function(){return"batchSize needs to be positive, but it is\n      "+a}),Yg(function(){return Og(o,void 0,void 0,function(){return zg(this,function(e){switch(e.label){case 0:return[4,s.iterator()];case 1:return[2,e.sent().columnMajorBatch(a,t,Zg)];}})})},this.size===1/0||null==this.size?this.size:t?kf(this.size/a):Cf(this.size/a))},e.prototype.concatenate=function(a){var t=this,o=this;return Yg(function(){return Og(t,void 0,void 0,function(){var t,r;return zg(this,function(e){switch(e.label){case 0:return[4,o.iterator()];case 1:return r=(t=e.sent()).concatenate,[4,a.iterator()];case 2:return[2,r.apply(t,[e.sent()])];}})})},this.size===1/0||a.size===1/0?1/0:null!=this.size&&null!=a.size?this.size+a.size:null)},e.prototype.filter=function(a){var t=this,n=this;return Yg(function(){return Og(t,void 0,void 0,function(){return zg(this,function(t){switch(t.label){case 0:return[4,n.iterator()];case 1:return[2,t.sent().filter(function(t){return We(function(){return a(t)})})];}})})},this.size===1/0?1/0:null)},e.prototype.forEachAsync=function(a){return Og(this,void 0,void 0,function(){return zg(this,function(t){switch(t.label){case 0:return[4,this.iterator()];case 1:return[2,t.sent().forEachAsync(a)];}})})},e.prototype.forEach=function(e){return Og(this,void 0,void 0,function(){return zg(this,function(){return _e("dataset.forEach() is deprecated and will be removed. Please use dataset.forEachAsync() instead"),[2,this.forEachAsync(e)]})})},e.prototype.map=function(a){var t=this,n=this;return Yg(function(){return Og(t,void 0,void 0,function(){return zg(this,function(t){switch(t.label){case 0:return[4,n.iterator()];case 1:return[2,t.sent().map(function(t){return We(function(){return a(t)})})];}})})},this.size)},e.prototype.mapAsync=function(a){var t=this,n=this;return Yg(function(){return Og(t,void 0,void 0,function(){return zg(this,function(t){switch(t.label){case 0:return[4,n.iterator()];case 1:return[2,t.sent().mapAsync(a)];}})})},this.size)},e.prototype.prefetch=function(a){var t=this;if(null==a)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");var n=this;return Yg(function(){return Og(t,void 0,void 0,function(){return zg(this,function(t){switch(t.label){case 0:return[4,n.iterator()];case 1:return[2,t.sent().prefetch(a)];}})})},this.size)},e.prototype.repeat=function(a){var t=this,n=this;return Yg(function(){return Og(t,void 0,void 0,function(){var t=this;return zg(this,function(){return[2,Xg($g(function(){return Og(t,void 0,void 0,function(){var a;return zg(this,function(t){switch(t.label){case 0:return a={},[4,n.iterator()];case 1:return[2,(a.value=t.sent(),a.done=!1,a)];}})})}).take(a))]})})},null!=this.size&&0<a?this.size*a:0===a?0:null!=this.size&&(void 0===a||0>a)?1/0:null)},e.prototype.skip=function(a){var t=this,n=this;return Yg(function(){return Og(t,void 0,void 0,function(){return zg(this,function(t){switch(t.label){case 0:return[4,n.iterator()];case 1:return[2,t.sent().skip(a)];}})})},null!=this.size&&0<=a&&this.size>=a?this.size-a:null!=this.size&&(this.size<a||void 0===a||0>a)?0:null)},e.prototype.shuffle=function(a,t,s){var e=this;if(void 0===s&&(s=!0),null==a||0>a)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 p=this,i=Mv(t||Of.now().toString());return Yg(function(){return Og(e,void 0,void 0,function(){var t;return zg(this,function(e){switch(e.label){case 0:return t=i.int32(),s&&(t+=i.int32()),[4,p.iterator()];case 1:return[2,e.sent().shuffle(a,t.toString())];}})})},this.size)},e.prototype.take=function(a){var t=this,n=this;return Yg(function(){return Og(t,void 0,void 0,function(){return zg(this,function(t){switch(t.label){case 0:return[4,n.iterator()];case 1:return[2,t.sent().take(a)];}})})},null!=this.size&&this.size>a?a:null!=this.size&&this.size<=a?this.size:null)},e.prototype.toArray=function(){return Og(this,void 0,void 0,function(){return zg(this,function(e){switch(e.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,e.sent().toArray()];}})})},e.prototype.toArrayForTest=function(){return Og(this,void 0,void 0,function(){return zg(this,function(e){switch(e.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,e.sent().toArrayForTest()];}})})},e.MAX_BUFFER_SIZE=1e4,e}(),iC=function(a){function t(t){var e=a.call(this)||this;return e.input=t,e}return _g(t,a),t.prototype.iterator=function(){return Og(this,void 0,void 0,function(){var a,n;return zg(this,function(e){switch(e.label){case 0:return[4,this.input.iterator()];case 1:return a=e.sent(),n=a.decodeUTF8(),[2,n.split("\n").map(function(e){return e.endsWith("\r")&&(e=e.slice(0,-1)),e})];}})})},t}(sC),pC="\"",dC=Symbol("out"),lC=Symbol("field"),uC=Symbol("quote"),cC=Symbol("quoteafterquote"),hC=Symbol("quoteinquote"),mC=function(a){function t(t,e){var o=a.call(this)||this;return o.input=t,o.hasHeader=!0,o.fullColumnNames=null,o.columnNamesValidated=!1,o.columnConfigs=null,o.configuredColumnsOnly=!1,o.delimiter=",",o.delimWhitespace=!1,o.base=new iC(t),e||(e={}),o.hasHeader=!1!==e.hasHeader,o.fullColumnNames=e.columnNames,o.columnConfigs=e.columnConfigs,o.configuredColumnsOnly=e.configuredColumnsOnly,e.delimWhitespace?(Of.assert(null==e.delimiter,function(){return"Delimiter should not be provided when delimWhitespace is true."}),o.delimWhitespace=!0,o.delimiter=" "):o.delimiter=e.delimiter?e.delimiter:",",o}return _g(t,a),t.prototype.columnNames=function(){return Og(this,void 0,void 0,function(){return zg(this,function(e){switch(e.label){case 0:return this.columnNamesValidated?[3,2]:[4,this.setColumnNames()];case 1:e.sent(),e.label=2;case 2:return[2,this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames];}})})},t.prototype.setColumnNames=function(){return Og(this,void 0,void 0,function(){var s=this,a,p,d,l,u,c;return zg(this,function(e){switch(e.label){case 0:return[4,this.maybeReadHeaderLine()];case 1:if(a=e.sent(),!this.fullColumnNames&&!a)throw new Error("Column names must be provided if there is no header line.");if(this.fullColumnNames&&a&&Of.assert(a.length===this.fullColumnNames.length,function(){return"The length of provided columnNames ("+s.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+a.length.toString()+")."}),this.fullColumnNames||(this.fullColumnNames=a),p=this.fullColumnNames.reduce(function(a,t){return a[t]=a[t]+1||1,a},{}),d=Object.keys(p).filter(function(e){return 1<p[e]}),Of.assert(0===d.length,function(){return"Duplicate column names found: "+d.toString()}),this.columnConfigs)for(l=0,u=Object.keys(this.columnConfigs);l<u.length;l++)if(c=u[l],-1===this.fullColumnNames.indexOf(c))throw new Error("The key \""+c+"\" provided in columnConfigs does not match any of the column names ("+this.fullColumnNames.toString()+").");return this.columnNamesValidated=!0,[2];}})})},t.prototype.maybeReadHeaderLine=function(){return Og(this,void 0,void 0,function(){var a,n;return zg(this,function(e){switch(e.label){case 0:return this.hasHeader?[4,this.base.iterator()]:[3,3];case 1:return[4,e.sent().next()];case 2:if((a=e.sent()).done)throw new Error("No data was found for CSV parsing.");return n=a.value,[2,this.parseRow(n,!1)];case 3:return[2,null];}})})},t.prototype.iterator=function(){return Og(this,void 0,void 0,function(){var a=this,e;return zg(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[4,this.base.iterator()];case 3:return e=t.sent(),this.hasHeader&&(e=e.skip(1)),[2,e.map(function(e){return a.makeDataElement(e)})];}})})},t.prototype.makeDataElement=function(p){for(var t=this.parseRow(p),e={},r={},n=0;n<this.fullColumnNames.length;n++){var d=this.fullColumnNames[n],o=this.columnConfigs?this.columnConfigs[d]:null;if(!this.configuredColumnsOnly||o){var a=t[n],s=null;if(""!==a){var l=+a;if(isNaN(l))s=o&&"bool"===o.dtype?this.getBoolean(a):a;else if(o&&o.dtype)switch(o.dtype){case"float32":s=l;break;case"int32":s=Cf(l);break;case"bool":s=this.getBoolean(a);break;default:s=l;}else s=l}else if(o&&void 0!==o.default)s=o.default;else{if(o&&(o.required||o.isLabel))throw new Error("Required column "+d+" is empty in this line: "+p);s=void 0}o&&o.isLabel?r[d]=s:e[d]=s}}return 0===Object.keys(r).length?e:{xs:e,ys:r}},t.prototype.getBoolean=function(e){return"1"===e||"true"===e.toLowerCase()?1:0},t.prototype.parseRow=function(s,t){void 0===t&&(t=!0);for(var p=[],r=0,d=s.length,i=dC,l=0;l<d;l++)switch(i){case dC:switch(s.charAt(l)){case pC:r=l+1,i=uC;break;case this.delimiter:if(r=l+1," "===this.delimiter&&this.delimWhitespace)break;p.push(""),i=dC;break;default:i=lC,r=l;}break;case lC:switch(s.charAt(l)){case this.delimiter:p.push(s.substring(r,l)),i=dC,r=l+1;}break;case uC:switch(s.charAt(l)){case pC:i=cC;}break;case cC:switch(s.charAt(l)){case this.delimiter:p.push(s.substring(r,l-1)),i=dC,r=l+1;break;case pC:i=uC;break;default:i=hC;}break;case hC:switch(s.charAt(l)){case pC:i=uC;}}if(i===cC?p.push(s.substring(r,d-1)):p.push(s.substring(r)),t&&p.length!==this.fullColumnNames.length)throw new Error("Invalid row in csv file. Should have "+this.fullColumnNames.length+" elements in a row, but got "+p);return p},t}(sC),gC=function(a){function o(t){var e=Math.log2,o=a.call(this)||this;o.microphoneConfig=t,o.isClosed=!1,o.fftSize=t.fftSize||1024;var r=e(o.fftSize);if(0>o.fftSize||4>r||14<r||!Nf(r))throw new Error("Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got "+o.fftSize);if(o.numFrames=t.numFramesPerSpectrogram||43,o.sampleRateHz=t.sampleRateHz,o.columnTruncateLength=t.columnTruncateLength||o.fftSize,o.audioTrackConstraints=t.audioTrackConstraints,o.smoothingTimeConstant=t.smoothingTimeConstant||0,o.includeSpectrogram=!1!==t.includeSpectrogram,o.includeWaveform=!0===t.includeWaveform,!o.includeSpectrogram&&!o.includeWaveform)throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.");return o}return _g(o,a),o.prototype.summary=function(){return"microphone"},o.create=function(e){return void 0===e&&(e={}),Og(this,void 0,void 0,function(){var t;return zg(this,function(a){switch(a.label){case 0:if(_f.get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");return[4,(t=new o(e)).start()];case 1:return a.sent(),[2,t];}})})},o.prototype.start=function(){return Og(this,void 0,void 0,function(){var a,o,s,p;return zg(this,function(e){switch(e.label){case 0:return e.trys.push([0,2,,3]),a=this,[4,navigator.mediaDevices.getUserMedia({audio:null==this.audioTrackConstraints||this.audioTrackConstraints,video:!1})];case 1:return a.stream=e.sent(),[3,3];case 2:throw o=e.sent(),new Error("Error thrown while initializing video stream: "+o.message);case 3:if(!this.stream)throw new Error("Could not obtain audio from microphone.");if(s=window.AudioContext||window.webkitAudioContext,this.audioContext=new s,!this.sampleRateHz)this.sampleRateHz=this.audioContext.sampleRate;else if(this.audioContext.sampleRate!==this.sampleRateHz)throw new Error("Mismatch in sampling rate: Expected: "+this.sampleRateHz+"; Actual: "+this.audioContext.sampleRate);return p=this.audioContext.createMediaStreamSource(this.stream),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2*this.fftSize,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,p.connect(this.analyser),this.freqData=new Float32Array(this.fftSize),this.timeData=new Float32Array(this.fftSize),[2];}})})},o.prototype.next=function(){return Og(this,void 0,void 0,function(){var a,s,p,d,l;return zg(this,function(e){switch(e.label){case 0:return this.isClosed?[2,{value:null,done:!0}]:[4,this.getAudioData()];case 1:return p=e.sent(),this.includeSpectrogram&&(d=this.flattenQueue(p.freqDataQueue),a=this.getTensorFromAudioDataArray(d,[this.numFrames,this.columnTruncateLength,1])),this.includeWaveform&&(l=this.flattenQueue(p.timeDataQueue),s=this.getTensorFromAudioDataArray(l,[this.numFrames*this.fftSize,1])),[2,{value:{spectrogram:a,waveform:s},done:!1}];}})})},o.prototype.capture=function(){return Og(this,void 0,void 0,function(){return zg(this,function(e){switch(e.label){case 0:return[4,this.next()];case 1:return[2,e.sent().value];}})})},o.prototype.getAudioData=function(){return Og(this,void 0,void 0,function(){var a=this,n,s,p;return zg(this,function(){return n=[],s=[],p=0,[2,new Promise(function(e){var t=setInterval(function(){a.includeSpectrogram&&(a.analyser.getFloatFrequencyData(a.freqData),a.freqData[0]===-1/0&&e({freqDataQueue:n,timeDataQueue:s}),n.push(a.freqData.slice(0,a.columnTruncateLength))),a.includeWaveform&&(a.analyser.getFloatTimeDomainData(a.timeData),s.push(a.timeData.slice())),++p===a.numFrames&&(clearInterval(t),e({freqDataQueue:n,timeDataQueue:s}))},1e3*(a.fftSize/a.sampleRateHz))})]})})},o.prototype.stop=function(){this.isClosed=!0,this.analyser.disconnect(),this.audioContext.close(),null!=this.stream&&0<this.stream.getTracks().length&&this.stream.getTracks()[0].stop()},o.prototype.toArray=function(){throw new Error("Can not convert infinite audio stream to array.")},o.prototype.getSampleRate=function(){return this.sampleRateHz},o.prototype.flattenQueue=function(a){var o=a[0].length,e=new Float32Array(a.length*o);return a.forEach(function(a,t){return e.set(a,t*o)}),e},o.prototype.getTensorFromAudioDataArray=function(a,t){var e=new Float32Array(Of.sizeFromShape(t));return e.set(a,e.length-a.length),Zt(e,t)},o}(Uv),fC=function(p){function a(t,e){var r=p.call(this)||this;if(r.webcamVideoElement=t,r.webcamConfig=e,r.isClosed=!0,r.resize=!1,r.needToResize())if(r.resize=!0,r.cropSize=[r.webcamConfig.resizeHeight,r.webcamConfig.resizeWidth],r.cropBoxInd=en([0],"int32"),r.webcamConfig.centerCrop){var n=1*r.webcamConfig.resizeWidth/r.webcamVideoElement.width,i=1*r.webcamConfig.resizeHeight/r.webcamVideoElement.height,o=(1-n)/2,a=(1-i)/2;r.cropBox=tn([a,o,i+a,o+n],[1,4])}else r.cropBox=tn([0,0,1,1],[1,4]);return r}return _g(a,p),a.prototype.summary=function(){return"webcam"},a.create=function(e,o){return void 0===o&&(o={}),Og(this,void 0,void 0,function(){var t;return zg(this,function(n){switch(n.label){case 0:if(_f.get("IS_NODE"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!e){if(e=document.createElement("video"),!o.resizeWidth||!o.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");e.width=o.resizeWidth,e.height=o.resizeHeight}return[4,(t=new a(e,o)).start()];case 1:return n.sent(),[2,t];}})})},a.prototype.start=function(){return Og(this,void 0,void 0,function(){var a=this,r,o;return zg(this,function(e){switch(e.label){case 0:this.webcamConfig.facingMode&&Of.assert("user"===this.webcamConfig.facingMode||"environment"===this.webcamConfig.facingMode,function(){return"Invalid webcam facing mode: "+a.webcamConfig.facingMode+". Please provide 'user' or 'environment'"}),e.label=1;case 1:return e.trys.push([1,3,,4]),r=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 r.stream=e.sent(),[3,4];case 3:throw(o=e.sent()).message="Error thrown while initializing video stream: "+o.message,o;case 4:if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream}catch(e){console.log(e),this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}return this.webcamVideoElement.play(),this.isClosed=!1,[2,new Promise(function(e){a.webcamVideoElement.onloadedmetadata=function(){e()}})];}})})},a.prototype.next=function(){return Og(this,void 0,void 0,function(){var e;return zg(this,function(){if(this.isClosed)return[2,{value:null,done:!0}];try{e=_h.fromPixels(this.webcamVideoElement)}catch(e){throw new Error("Error thrown converting video to pixels: "+JSON.stringify(e))}if(!this.resize)return[2,{value:e,done:!1}];try{return[2,{value:this.cropAndResizeFrame(e),done:!1}]}catch(e){throw new Error("Error thrown cropping the video: "+e.message)}finally{e.dispose()}return[2]})})},a.prototype.needToResize=function(){return this.webcamConfig.resizeWidth&&this.webcamConfig.resizeHeight&&(this.webcamVideoElement.width!==this.webcamConfig.resizeWidth||this.webcamVideoElement.height!==this.webcamConfig.resizeHeight)},a.prototype.cropAndResizeFrame=function(a){var t=this;return We(function(){var e=a.toFloat().expandDims(0),n=(o=Ec.cropAndResize(e,t.cropBox,t.cropBoxInd,t.cropSize,"bilinear")).shape,o;return o.reshape(n.slice(1))})},a.prototype.capture=function(){return Og(this,void 0,void 0,function(){return zg(this,function(e){switch(e.label){case 0:return[4,this.next()];case 1:return[2,e.sent().value];}})})},a.prototype.stop=function(){this.stream.getTracks().forEach(function(e){return e.stop()});try{this.webcamVideoElement.srcObject=null}catch(e){console.log(e),this.webcamVideoElement.src=null}this.isClosed=!0},a.prototype.toArray=function(){throw new Error("Can not convert infinite video stream to array.")},a}(Uv),yC=function(){return function(){}}(),bC=function(a){function t(){return null!==a&&a.apply(this,arguments)||this}return _g(t,a),t.prototype.split=function(e){return new xC(this,e)},t}(Uv),xC=function(a){function t(t,e){var r=a.call(this)||this;return r.upstream=t,r.impl=new vC(t,e),r}return _g(t,a),t.prototype.summary=function(){return this.impl.summary()},t.prototype.next=function(){return Og(this,void 0,void 0,function(){return zg(this,function(){return[2,this.impl.next()]})})},t}(bC),vC=function(a){function t(t,e){var r=a.call(this)||this;return r.upstream=t,r.separator=e,r.carryover="",r}return _g(t,a),t.prototype.summary=function(){return this.upstream.summary()+" -> Split('"+this.separator+"')"},t.prototype.pump=function(){return Og(this,void 0,void 0,function(){var a,s,o,p,d;return zg(this,function(e){switch(e.label){case 0:return[4,this.upstream.next()];case 1:if((a=e.sent()).done)return""===this.carryover?[2,!1]:(this.outputQueue.push(this.carryover),this.carryover="",[2,!0]);for((s=a.value.split(this.separator))[0]=this.carryover+s[0],o=0,p=s.slice(0,-1);o<p.length;o++)d=p[o],this.outputQueue.push(d);return this.carryover=s[s.length-1],[2,!0];}})})},t}(Jv),CC=function(a){function t(){return null!==a&&a.apply(this,arguments)||this}return _g(t,a),t.prototype.decodeUTF8=function(){return new SC(this)},t}(Uv),SC=function(a){function t(t){var e=a.call(this)||this;return e.upstream=t,e.impl=new NC(t),e}return _g(t,a),t.prototype.summary=function(){return this.impl.summary()},t.prototype.next=function(){return Og(this,void 0,void 0,function(){return zg(this,function(){return[2,this.impl.next()]})})},t}(bC),NC=function(a){function t(t){var e=a.call(this)||this;if(e.upstream=t,_f.get("IS_BROWSER"))e.decoder=new TextDecoder("utf-8");else{var r=require("string_decoder").StringDecoder;e.decoder=new r("utf8")}return e}return _g(t,a),t.prototype.summary=function(){return this.upstream.summary()+" -> Utf8"},t.prototype.pump=function(){return Og(this,void 0,void 0,function(){var a,o,s;return zg(this,function(e){switch(e.label){case 0:return[4,this.upstream.next()];case 1:return(a=e.sent()).done?[2,!1]:(o=a.value,s=_f.get("IS_BROWSER")?this.decoder.decode(o,{stream:!0}):this.decoder.write(Buffer.from(o.buffer)),this.outputQueue.push(s),[2,!0]);}})})},t}(Jv),IC=function(a){function t(t,e){void 0===e&&(e={});var o=a.call(this)||this;return o.file=t,o.options=e,Of.assert(t instanceof Uint8Array||!!_f.get("IS_BROWSER")&&(t instanceof File||t instanceof Blob),function(){return"FileChunkIterator only supports File, Blob and Uint8Array right now."}),o.offset=e.offset||0,o.chunkSize=e.chunkSize||1048576,o}return _g(t,a),t.prototype.summary=function(){return"FileChunks "+this.file},t.prototype.next=function(){return Og(this,void 0,void 0,function(){var a=this,r,o;return zg(this,function(e){switch(e.label){case 0:return this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size)?[2,{value:null,done:!0}]:(r=new Promise(function(r,s){var e=a.offset+a.chunkSize;if(a.file instanceof Uint8Array)r(new Uint8Array(a.file.slice(a.offset,e)));else{var t=new FileReader;t.onload=function(){var e=t.result;return(e instanceof ArrayBuffer&&(e=new Uint8Array(e)),!(e instanceof Uint8Array))?s(new TypeError("FileReader returned unknown type.")):void r(e)},t.onabort=function(){return s(new Error("Aborted"))},t.onerror=function(e){return s(new Error(e.type))};var n=a.file.slice(a.offset,e);t.readAsArrayBuffer(n)}a.offset=e}),o={},[4,r]);case 1:return[2,(o.value=e.sent(),o.done=!1,o)];}})})},t}(CC),kC=function(e){return{method:e.method,headers:e.headers,body:e.body,mode:e.mode,credentials:e.credentials,cache:e.cache,redirect:e.redirect,referrer:e.referrer,integrity:e.integrity}},TC=function(a){function t(t,e){void 0===e&&(e={});var o=a.call(this)||this;return o.input=t,o.options=e,o}return _g(t,a),t.prototype.iterator=function(){return Og(this,void 0,void 0,function(){var e;return zg(this,function(){return af(this.input)&&_f.get("IS_NODE")&&(e=require("fs"),this.input=e.readFileSync(this.input.substr(7))),[2,new IC(this.input,this.options)]})})},t}(yC),RC=function(a){function t(t,e){void 0===e&&(e={});var o=a.call(this)||this;return o.url=t,o.fileOptions=e,o}return _g(t,a),t.prototype.iterator=function(){return Og(this,void 0,void 0,function(){return zg(this,function(){return af(this.url)?[2,new TC(this.url,this.fileOptions).iterator()]:[2,Jg(this.url,this.fileOptions)]})})},t}(yC),EC="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},wC=function(e,t,a){[].concat(a).forEach(function(a){if("undefined"==typeof t[a])throw new Error("AutoSuggest: Missing required parameter, "+e+"."+a)})},AC=function(e,t,a,n){[].concat(t[a]).forEach(function(t){if(("undefined"==typeof t?"undefined":EC(t))!==n)throw new TypeError("AutoSuggest: Invalid Type for "+e+"."+a+", expected "+n)})},DC=function(e,t){var a=window.getComputedStyle(e);for(var n in a)a.hasOwnProperty(n)&&t.style.setProperty(n,a[n])},_C=function(e,t){return window.getComputedStyle(e).getPropertyValue(t)},OC=function(e){var t=e,a=0,n=0;do n+=t.offsetLeft,a+=t.offsetTop;while(t=t.offsetParent);return{left:n,top:a}},zC=function(e){if(e.createTextRange){var t=e.createTextRange(),a=window.getComputedStyle(e),n=parseFloat(a.paddingLeft),r=t.getBoundingClientRect();return e.getBoundingClientRect().left+e.clientLeft+n-r.left}return e.scrollLeft},LC=function(e){return[e.selectionStart,e.selectionEnd].sort(function(e,t){return e-t})},FC=function(){var e=window.getSelection().getRangeAt(0),t=e.startContainer,a=e.startOffset;if(t.nodeType!==t.TEXT_NODE){for(t=t.childNodes[a];t&&t.nodeType!==t.TEXT_NODE;)t=t.firstChild;a=0}var n=e.endContainer,r=e.endOffset;if(n.nodeType!==n.TEXT_NODE){for(n=n.childNodes[r];n&&n.nodeType!==n.TEXT_NODE;)n=n.lastChild;r=n?n.nodeValue.length:n}return{startContainer:t,startOffset:a,endContainer:n,endOffset:r}},BC=function(){var e=0,t=[];return function(a,n){for(t[n-e]=a;t[0];)++e,t.shift()()}},PC=function(e,t,a){return t="autosuggest_"+t,"undefined"==typeof a?(a=e.dataset[t],"undefined"==typeof a?a:JSON.parse(e.dataset[t])):void(e.dataset[t]=JSON.stringify(a))},MC=function(e){var t=document.createElement("div");return t.innerHTML=e.trim(),t.firstChild},WC="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e};of.prototype.getMatch=function(e){return e.match(this.regex)[1]};var VC=function(){function e(e,t){for(var a=0,n;a<t.length;a++)n=t[a],n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}return function(t,a,n){return a&&e(t.prototype,a),n&&e(t,n),t}}(),UC=function(){function e(){sf(this,e),this.width=0,this.isEmpty=!0,this.isActive=!1,this.dropdownContent=document.createElement("ul"),this.dropdownContent.className="dropdown-menu dropdown-menu-left",this.dropdown=document.createElement("div"),this.dropdown.className="dropdown open",this.dropdown.style.position="absolute",this.hide(),this.dropdown.appendChild(this.dropdownContent),document.body.appendChild(this.dropdown)}return VC(e,[{key:"show",value:function(e){e&&(this.dropdown.style.left=e.left+"px",this.dropdown.style.top=e.top+"px",e.left+this.width>document.body.offsetWidth?(this.dropdownContent.classList.remove("dropdown-menu-left"),this.dropdownContent.classList.add("dropdown-menu-right")):(this.dropdownContent.classList.remove("dropdown-menu-right"),this.dropdownContent.classList.add("dropdown-menu-left"))),this.dropdown.style.display="block",this.isActive=!0}},{key:"hide",value:function(){this.dropdown.style.display="none",this.isActive=!1}},{key:"empty",value:function(){this.dropdownContent.innerHTML="",this.isEmpty=!0}},{key:"fill",value:function(e,t){var a=this;this.empty(),e.forEach(function(n){var r=MC("<li><a>"+n.show+"</a></li>");a.dropdownContent.append(r),PC(r,"suggestion",n),r.addEventListener("mouseenter",function(){a.getActive().classList.remove("active"),r.classList.add("active")}),r.addEventListener("mousedown",function(r){t(n),a.hide(),r.preventDefault(),r.stopPropagation()})}),this.isActive||this.show(),this.width=this.dropdownContent.offsetWidth,this.isActive||this.hide(),this.setActive(),this.isEmpty=!1}},{key:"showLoader",value:function(e){this.empty(),this.dropdownContent.innerHTML="<div class=\"autosuggest-loader\">Loading...</div>",this.show(e)}},{key:"getActive",value:function(){for(var e=Array.prototype.slice.call(this.dropdownContent.querySelectorAll("li.active"),0);e[1];)e.pop().classList.remove("active");return e[0]}},{key:"getValue",value:function(e){return PC(e||this.getActive(),"suggestion")}},{key:"setActive",value:function(){var e=0<arguments.length&&void 0!==arguments[0]?arguments[0]:this.dropdownContent.firstElementChild,t=arguments[1];t&&t.classList.remove("active"),e.classList.add("active")}},{key:"selectNext",value:function(){var e=this.getActive(),t=e.nextElementSibling||this.dropdownContent.firstElementChild;this.setActive(t,e)}},{key:"selectPrev",value:function(){var e=this.getActive(),t=e.previousElementSibling||this.dropdownContent.lastElementChild;this.setActive(t,e)}}]),e}(),GC=function(){function e(e,t){for(var a=0,n;a<t.length;a++)n=t[a],n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(e,n.key,n)}return function(t,a,n){return a&&e(t.prototype,a),n&&e(t,n),t}}(),qC=function(){function e(e,t){var a=[],n=!0,r=!1,o=void 0;try{for(var s=e[Symbol.iterator](),i;!(n=(i=s.next()).done)&&(a.push(i.value),!(t&&a.length===t));n=!0);}catch(e){r=!0,o=e}finally{try{!n&&s["return"]&&s["return"]()}finally{if(r)throw o}}return a}return function(t,a){if(Array.isArray(t))return t;if(Symbol.iterator in Object(t))return e(t,a);throw new TypeError("Invalid attempt to destructure non-iterable instance")}}(),HC=function(e){for(var t=e.nextSibling||e.parentNode.nextSibling;t.firstChild;)t=t.firstChild;return t},KC=function(e){var t=e.element,a=e.trigger,n=e.suggestion,r=e.onChange,o=n.use,s=n.focus;if(PC(t,"isInput")){var i=LC(t),p=qC(i,2),d=p[0],l=p[1],u=t.value,c=u.slice(0,d),h=c.split(a||/\W/).pop();c=c.slice(0,0-h.length-(a||"").length)+o,t.value=c+u.slice(l),t.focus();var m=c.length;t.setSelectionRange(m+s[0],m+s[1])}else{var g=FC(),f=g.startContainer,y=g.startOffset,b=g.endContainer,x=g.endOffset,v=f.nodeValue.slice(0,y),C=v.split(a||/\W/).pop();v=v.slice(0,0-C.length-(a||"").length)+o,f.nodeValue=v+b.nodeValue.slice(x);var S=f;for(S!==b&&(S=HC(f));S!==b;)S.parentNode.removeChild(S),S=HC(f);b.parentNode.removeChild(b);var N=v.length,I=window.getSelection().getRangeAt(0);I.setStart(f,N+s[0]),I.setEnd(f,N+s[1])}r(t,n)},jC=function(){function e(t){if(pf(this,e),!t)throw new Error("AutoSuggest: Missing required parameter, options");this.inputs=[],this.dropdown=new UC,this.onChange=t.onChange||Function.prototype,this.maxSuggestions=t.maxSuggestions||10,this.suggestionLists=t.suggestions||[];for(var a=0,n;a<this.suggestionLists.length;a++)n=this.suggestionLists[a],n instanceof of||(n.constructor!==Object&&(n={values:n}),!n.hasOwnProperty("caseSensitive")&&t.hasOwnProperty("caseSensitive")&&(n.caseSensitive=t.caseSensitive),this.suggestionLists[a]=new of(n));events:{var r=this,o=null,s=!1;this.onBlurHandler=function(){r.dropdown.hide()},this.onKeyDownHandler=function(t){if(s=!1,r.dropdown.isActive){var e=function(){t.preventDefault(),s=!0};if(13===t.keyCode||9===t.keyCode)return KC({element:this,trigger:o.trigger,suggestion:r.dropdown.getValue(),onChange:r.onChange}),r.dropdown.hide(),e();if(40===t.keyCode)return r.dropdown.selectNext(),e();if(38===t.keyCode)return r.dropdown.selectPrev(),e();if(27===t.keyCode)return r.dropdown.hide(),e()}};var p=0;this.onKeyUpHandler=function(){var e=this;if(!s){var t;if(PC(this,"isInput")){var a=LC(this),n=qC(a,2),i=n[0],d=n[1];if(/[a-zA-Z_0-9]/.test(this.value.charAt(d)||" "))return void r.dropdown.hide();t=this.value.slice(0,i)}else{var l=FC(),u=l.startContainer,c=l.startOffset,h=l.endContainer,m=l.endOffset;if(!u||!h||/[a-zA-Z_0-9]/.test(h.nodeValue.charAt(m)||" "))return void r.dropdown.hide();t=u.nodeValue.slice(0,c)}handleDropdown:(function(){p++,r.dropdown.empty();var a=BC(),n=0,s=void 0,d=!1,l=function(l){l.regex.test(t)&&(d=!0,function(n,i){var d=l.getMatch(t),u=lf(e,l.trigger);r.dropdown.isEmpty&&(s&&clearTimeout(s),s=setTimeout(function(){r.dropdown.showLoader(u)},0)),l.getSuggestions(d,function(t){i!==p||a(function(){s&&clearTimeout(s),r.dropdown.isEmpty&&(t.length?(o=l,r.dropdown.fill(t.slice(0,r.maxSuggestions),function(t){KC({element:e,trigger:l.trigger,suggestion:t,onChange:r.onChange})}),r.dropdown.show(u)):r.dropdown.hide())},n)})}(n++,p))},u=!0,c=!1,h=void 0;try{for(var m=r.suggestionLists[Symbol.iterator](),g,f;!(u=(g=m.next()).done);u=!0)f=g.value,l(f)}catch(e){c=!0,h=e}finally{try{!u&&m.return&&m.return()}finally{if(c)throw h}}d||r.dropdown.hide()})()}}}// initialize events on inputs
  for(var d=arguments.length,l=Array(1<d?d-1:0),u=1;u<d;u++)l[u-1]=arguments[u];this.addInputs.apply(this,l)}return GC(e,[{key:"addInputs",value:function(){for(var e=this,t=arguments.length,a=Array(t),n=0;n<t;n++)a[n]=arguments[n];var r=Array.prototype.concat.apply([],a.map(function(e){return e[0]?Array.prototype.slice.call(e,0):e}));r.forEach(function(t){// validate element
  if(t.isContentEditable)PC(t,"isInput",!1);else if("TEXTAREA"===t.tagName||"INPUT"===t.tagName&&"text"===t.type)PC(t,"isInput",!0);else throw new Error("AutoSuggest: Invalid input: only input[type = text], textarea and contenteditable elements are supported");// init events
  t.addEventListener("blur",e.onBlurHandler),t.addEventListener("keyup",e.onKeyUpHandler),t.addEventListener("click",e.onKeyUpHandler),t.addEventListener("keydown",e.onKeyDownHandler,!0),PC(t,"index",e.inputs.push(t)-1)})}},{key:"removeInputs",value:function(){for(var e=this,t=arguments.length,a=Array(t),n=0;n<t;n++)a[n]=arguments[n];var r=Array.prototype.concat.apply([],a.map(function(e){return e[0]?Array.prototype.slice.call(e,0):e}));r.forEach(function(t){var a=PC(t,"index");isNaN(a)||(e.inputs.splice(a,1),t.removeEventListener("blur",e.onBlurHandler),t.removeEventListener("keyup",e.onKeyUpHandler),t.removeEventListener("click",e.onKeyUpHandler),t.removeEventListener("keydown",e.onKeyDownHandler,!0))})}},{key:"destroy",value:function(){this.removeInputs(this.inputs)}}]),e}();class $C{constructor(e){this.maxSuggestions=10,this.minProbability=1e-5;var t="https://cdn.typelike.me/models/word-predict/"+e+"/";let a=this;var n=new XMLHttpRequest;n.open("GET",t+"tokenizer.json",!0),n.onload=function(){200<=this.status&&400>this.status&&(a.tokenizer=JSON.parse(this.response))},n.send(),(async()=>{this.model=await Hh(t+"model.json")})()}attach(e){let t=this,a="string"==typeof e?document.getElementById(e):e;new jC({caseSensitive:!1,suggestions:[{trigger:" ",caseSensitive:!0,values:function(e,n){e=e.toLowerCase();var r=[];if(!e){var o=a,s="DIV"==o.tagName?o.textContent:o.value,i=o.selectionStart;s=s.slice(0,i);var p=s.lastIndexOf(".")+1;s=s.substring(p),this.latestValues=t.predict(s)}this.latestValues||(this.latestValues=[]),this.latestValues.forEach(function(t){1<=t.length&&!t.indexOf(e)&&t!==e&&-1===r.indexOf(t)&&r.push(" "+t)}),n(r)}}]},a),a.addEventListener("focus",()=>{0==a.value.length&&(a.value=" ")})}predict(e){let t=this;var a=e.trim().split(" ").slice(-2);a=a.map(function(e){return e.toLowerCase()}),console.log(a);for(var n=a.map(e=>t.tokenizer.word_index[e]?t.tokenizer.word_index[e]:0);1>=n.length;)n.unshift(0);console.log(n);var r=Zt([n]),o=this.model.predict(r),s=0,i=o.dataSync().filter(function(e){return t.maxSuggestions++,e>t.minProbability&&s<=t.maxSuggestions}).sort(function(e,t){return t-e});console.log(i);var p=i.map(e=>o.dataSync().indexOf(e)),s=[];return p.forEach(function(e){t.tokenizer.index_word[e]&&s.push(t.tokenizer.index_word[e])}),s}}return Le.predictor=function(e){return new $C(e)},Le}({});
  