text: // @tensorflow/tfjs Copyright 2019 Google
  (function (global, factory) {
    typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
    typeof define === 'function' && define.amd ? define(['exports'], factory) :
    (factory((global.tf = global.tf || {})));
  }(this, (function (exports) { '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 t=function(e,n){return(t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e;}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n]);})(e,n);};function e(e,n){function r(){this.constructor=e;}t(e,n),e.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r());}var n=function(){return(n=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var o in e=arguments[n])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t;}).apply(this,arguments);};function r(t,e,n,r){return new(n||(n=Promise))(function(o,a){function i(t){try{u(r.next(t));}catch(t){a(t);}}function s(t){try{u(r.throw(t));}catch(t){a(t);}}function u(t){t.done?o(t.value):new n(function(e){e(t.value);}).then(i,s);}u((r=r.apply(t,e||[])).next());});}function o(t,e){var n,r,o,a,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1];},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this;}),a;function s(a){return function(s){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&a[0]?r.return:a[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,a[1])).done)return o;switch(r=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return i.label++,{value:a[1],done:!1};case 5:i.label++,r=a[1],a=[0];continue;case 7:a=i.ops.pop(),i.trys.pop();continue;default:if(!(o=(o=i.trys).length>0&&o[o.length-1])&&(6===a[0]||2===a[0])){i=0;continue;}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){i.label=a[1];break;}if(6===a[0]&&i.label<o[1]){i.label=o[1],o=a;break;}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(a);break;}o[2]&&i.ops.pop(),i.trys.pop();continue;}a=e.call(t,i);}catch(t){a=[6,t],r=0;}finally{n=o=0;}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0};}([a,s]);};}}var a=function(){function t(t){this.global=t,this.flags={},this.flagRegistry={},this.urlFlags={},this.populateURLFlags();}return t.prototype.setPlatform=function(t,e){null!=this.platform&&console.warn("Platform "+this.platformName+" has already been set. Overwriting the platform with "+e+"."),this.platformName=t,this.platform=e;},t.prototype.registerFlag=function(t,e,n){if(this.flagRegistry[t]={evaluationFn:e,setHook:n},null!=this.urlFlags[t]){var r=this.urlFlags[t];console.warn("Setting feature override from URL "+t+": "+r+"."),this.set(t,r);}},t.prototype.get=function(t){return t in this.flags?this.flags[t]:(this.flags[t]=this.evaluateFlag(t),this.flags[t]);},t.prototype.getNumber=function(t){return this.get(t);},t.prototype.getBool=function(t){return this.get(t);},t.prototype.getFlags=function(){return this.flags;},Object.defineProperty(t.prototype,"features",{get:function(){return this.flags;},enumerable:!0,configurable:!0}),t.prototype.set=function(t,e){if(null==this.flagRegistry[t])throw new Error("Cannot set flag "+t+" as it has not been registered.");this.flags[t]=e,null!=this.flagRegistry[t].setHook&&this.flagRegistry[t].setHook(e);},t.prototype.evaluateFlag=function(t){if(null==this.flagRegistry[t])throw new Error("Cannot evaluate flag '"+t+"': no evaluation function found.");return this.flagRegistry[t].evaluationFn();},t.prototype.setFlags=function(t){this.flags=Object.assign({},t);},t.prototype.reset=function(){this.flags={},this.urlFlags={},this.populateURLFlags();},t.prototype.populateURLFlags=function(){var t=this;if(void 0!==this.global&&void 0!==this.global.location&&void 0!==this.global.location.search){var e=i(this.global.location.search);if("tfjsflags"in e)e.tfjsflags.split(",").forEach(function(e){var n=e.split(":"),r=n[0],o=n[1];t.urlFlags[r]=function(t,e){if("true"===(e=e.toLowerCase())||"false"===e)return"true"===e;if(""+ +e===e)return+e;throw new Error("Could not parse value flag value "+e+" for flag "+t+".");}(r,o);});}},t;}();function i(t){var e={};return t.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,function(t){for(var n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];return function(t,e,n){t[decodeURIComponent(e)]=decodeURIComponent(n||"");}(e,n[0],n[1]),n.join("=");}),e;}exports.ENV=null;function u(t){exports.ENV=t;}var l=Object.freeze({Environment:a,getQueryParams:i,get ENV(){return exports.ENV;},setEnvironmentGlobal:u});function c(t){for(var e=t.length,n=0,r=0;e>0;)r=Math.random()*e|0,n=t[--e],t[e]=t[r],t[r]=n;}function h(t,e,n){return Math.max(t,Math.min(e,n));}function p(t){return t%2==0?t:t+1;}function f(t){for(var e=0,n=0;n<t.length;n++)e+=t[n];return e;}function d(t,e){if(!t)throw new Error("string"==typeof e?e:e());}function v(t,e,n){void 0===n&&(n=""),d(x(t,e),function(){return n+" Shapes "+t+" and "+e+" must match";});}function m(t){d(null!=t,function(){return"The input to the tensor constructor must be a non-null value.";});}function g(t,e,n){if(void 0===e&&(e=[]),void 0===n&&(n=!1),null==e&&(e=[]),Array.isArray(t)||M(t)&&!n)for(var r=0;r<t.length;++r)g(t[r],e,n);else e.push(t);return e;}function y(t){if(0===t.length)return 1;for(var e=t[0],n=1;n<t.length;n++)e*=t[n];return e;}function x(t,e){if(t===e)return!0;if(null==t||null==e)return!1;if(t.length!==e.length)return!1;for(var n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0;}function b(t){return t%1==0;}function w(t){if(null!=Math.tanh)return Math.tanh(t);if(t===1/0)return 1;if(t===-1/0)return-1;var e=Math.exp(2*t);return(e-1)/(e+1);}function C(t){var e=Math.ceil(Math.sqrt(t));return[e,Math.ceil(t/e)];}function E(t,e){return e<=t.length?t:t+" ".repeat(e-t.length);}function R(t,e,n){return void 0===e&&(e=function(t){return 0;}),new Promise(function(r,o){var a=0,i=function(){if(t())r();else{var s=e(++a);null!=n&&a>=n?o():setTimeout(i,s);}};i();});}function I(t,e){for(var n=1,r=-1,o=0;o<t.length;++o)if(t[o]>=0)n*=t[o];else if(-1===t[o]){if(-1!==r)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+r+" and dim "+o);r=o;}else if(t[o]<0)throw Error("Shapes can not be < 0. Found "+t[o]+" at dim "+o);if(-1===r){if(e>0&&e!==n)throw Error("Size("+e+") must match the product of shape "+t);return t;}if(0===n)throw Error("Cannot infer the missing size in ["+t+"] when there are 0 elements");if(e%n!=0)throw Error("The implicit shape can't be a fractional number. Got "+e+" / "+n);var a=t.slice();return a[r]=e/n,a;}function S(t,e){var n=e.length;return d((t=null==t?e.map(function(t,e){return e;}):[].concat(t)).every(function(t){return t>=-n&&t<n;}),function(){return"All values in axis param must be in range [-"+n+", "+n+") but got axis "+t;}),d(t.every(function(t){return b(t);}),function(){return"All values in axis param must be integers but got axis "+t;}),t.map(function(t){return t<0?n+t:t;});}function N(t,e){for(var n=[],r=[],o=null==e?null:S(e,t).sort(),a=0,i=0;i<t.length;++i){if(null!=o){if(o[a]===i&&1!==t[i])throw new Error("Can't squeeze axis "+i+" since its dim '"+t[i]+"' is not 1");(null==o[a]||o[a]>i)&&1===t[i]&&(n.push(t[i]),r.push(i)),o[a]<=i&&a++;}1!==t[i]&&(n.push(t[i]),r.push(i));}return{newShape:n,keptDims:r};}function k(t,e){var n=null;if(null==t||"float32"===t)n=new Float32Array(e);else if("int32"===t)n=new Int32Array(e);else{if("bool"!==t)throw new Error("Unknown data type "+t);n=new Uint8Array(e);}return n;}function A(t,e){var n=null;if(null==t||"float32"===t)n=new Float32Array(e);else if("int32"===t)n=new Int32Array(e);else if("bool"===t)n=new Uint8Array(e);else{if("string"!==t)throw new Error("Unknown data type "+t);n=new Array(e);}return n;}function T(t,e,n){if("float32"===e)for(var r=0;r<t.length;r++){var o=t[r];if(isNaN(o)||!isFinite(o))throw Error("The result of the '"+n+"' is "+o+".");}}function D(t,e){for(var n=0;n<t.length;n++){var r=t[n];if(isNaN(r)||!isFinite(r))throw Error("A tensor of type "+e+" being uploaded contains "+r+".");}}function _(t){return"bool"===t||"complex64"===t||"float32"===t||"int32"===t||"string"===t;}function O(t,e){return"complex64"!==e&&("float32"!==e||"complex64"===t)&&("int32"!==e||"float32"===t||"complex64"===t)&&("bool"!==e||"bool"!==t);}function M(t){return t instanceof Float32Array||t instanceof Int32Array||t instanceof Uint8Array;}function F(t){if("float32"===t||"int32"===t)return 4;if("complex64"===t)return 8;if("bool"===t)return 1;throw new Error("Unknown dtype "+t);}function B(t){if(null==t)return 0;var e=0;return t.forEach(function(t){return e+=t.length;}),e;}function P(t){return"string"==typeof t||t instanceof String;}function L(t){return"boolean"==typeof t;}function W(t){return"number"==typeof t;}function U(t){return Array.isArray(t)?U(t[0]):t instanceof Float32Array?"float32":t instanceof Int32Array||t instanceof Uint8Array?"int32":W(t)?"float32":P(t)?"string":L(t)?"bool":"float32";}function z(t){return!!(t&&t.constructor&&t.call&&t.apply);}function V(t,e){for(var n=e;n<t;++n)if(t%n==0)return n;return t;}function G(t){var e=t.length;if(e<2)return[];var n=new Array(e-1);n[e-2]=t[e-1];for(var r=e-3;r>=0;--r)n[r]=n[r+1]*t[r+1];return n;}function q(t,e,n){if("string"===e)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(t)&&(t=g(t)),n&&D(t,e),function(t,e){return t instanceof Float32Array&&"float32"===e||t instanceof Int32Array&&"int32"===e||t instanceof Uint8Array&&"bool"===e;}(t,e))return t;if(null==e||"float32"===e||"complex64"===e)return new Float32Array(t);if("int32"===e)return new Int32Array(t);if("bool"===e){for(var r=new Uint8Array(t.length),o=0;o<r.length;++o)0!==Math.round(t[o])&&(r[o]=1);return r;}throw new Error("Unknown data type "+e);}function H(t,e){if(0===t.length)return e[0];var n=t.reduce(function(t,e){return t*e;});if(0===n)return[];if(n!==e.length)throw new Error("["+t+"] does not match the input size.");return function t(e,n,r){var o=new Array();if(1===n.length)for(var a=n[0],i=0;i<a;i++)o[i]=r[e+i];else{a=n[0];var s=n.slice(1),u=s.reduce(function(t,e){return t*e;});for(i=0;i<a;i++)o[i]=t(e+i*u,s,r);}return o;}(0,t,e);}function $(t,e){for(var n=j(t,e),r=0;r<n.length;r++)n[r]=1;return n;}function j(t,e){if(null==e||"float32"===e||"complex64"===e)return new Float32Array(t);if("int32"===e)return new Int32Array(t);if("bool"===e)return new Uint8Array(t);throw new Error("Unknown data type "+e);}function K(){return exports.ENV.platform.now();}function X(t){t.forEach(function(e){d(Number.isInteger(e)&&e>=0,function(){return"Tensor must have a shape comprised of positive integers but got shape ["+t+"].";});});}function Y(t,e){return exports.ENV.platform.fetch(t,e);}function Q(t,e){return void 0===e&&(e="utf-8"),e=e||"utf-8",exports.ENV.platform.encode(t,e);}function J(t,e){return void 0===e&&(e="utf-8"),e=e||"utf-8",exports.ENV.platform.decode(t,e);}var Z=Object.freeze({shuffle:c,clamp:h,nearestLargerEven:p,sum:f,randUniform:function(t,e){var n=Math.random();return e*n+(1-n)*t;},distSquared:function(t,e){for(var n=0,r=0;r<t.length;r++){var o=Number(t[r])-Number(e[r]);n+=o*o;}return n;},assert:d,assertShapesMatch:v,assertNonNull:m,flatten:g,sizeFromShape:y,isScalarShape:function(t){return 0===t.length;},arraysEqual:x,isInt:b,tanh:w,sizeToSquarishShape:C,createShuffledIndices:function(t){for(var e=new Uint32Array(t),n=0;n<t;++n)e[n]=n;return c(e),e;},rightPad:E,repeatedTry:R,inferFromImplicitShape:I,parseAxisParam:S,squeezeShape:N,getTypedArrayFromDType:k,getArrayFromDType:A,checkComputationForErrors:T,checkConversionForErrors:D,isValidDtype:_,hasEncodingLoss:O,isTypedArray:M,bytesPerElement:F,bytesFromStringArray:B,isString:P,isBoolean:L,isNumber:W,inferDtype:U,isFunction:z,nearestDivisor:V,computeStrides:G,toTypedArray:q,toNestedArray:H,makeOnesTypedArray:$,makeZerosTypedArray:j,now:K,assertNonNegativeIntegerDimensions:X,fetch:Y,encodeString:Q,decodeString:J}),tt=function(){function t(t,e){this.backendTimer=t,this.logger=e,null==e&&(this.logger=new et());}return t.prototype.profileKernel=function(t,e){var n,r=this,o=this.backendTimer.time(function(){n=e();});return(Array.isArray(n)?n:[n]).forEach(function(e){var n=e.dataSync();T(n,e.dtype,t),o.then(function(o){var a="";null!=o.getExtraProfileInfo&&(a=o.getExtraProfileInfo()),r.logger.logKernelProfile(t,e,n,o.kernelMs,a);});}),n;},t;}(),et=function(){function t(){}return t.prototype.logKernelProfile=function(t,e,n,r,o){var a=E(r+"ms",9),i=E(t,25),s=e.rank,u=e.size,l=E(e.shape.toString(),14);console.log("%c"+i+"\t%c"+a+"\t%c"+s+"D "+l+"\t%c"+u+"\t%c"+o,"font-weight:bold","color:red","color:blue","color: orange","color: green");},t;}(),nt=20,rt=3,ot=7;function at(t,e,n,r){var o=G(e),a=function(t,e,n,r){var o=y(e),a=r[r.length-1],i=new Array(a).fill(0),s=e.length,u="complex64"===n?ut(t):t;if(s>1)for(var l=0;l<o/a;l++)for(var c=l*a,h=0;h<a;h++)i[h]=Math.max(i[h],it(u[c+h],0,n).length);return i;}(t,e,n,o),i=e.length,s=function t(e,n,r,o,a,i){void 0===i&&(i=!0);var s="complex64"===r?2:1;var u=n[0];var l=n.length;if(0===l){if("complex64"===r){var c=ut(e);return[it(c[0],0,r)];}return"bool"===r?[st(e[0])]:[e[0].toString()];}if(1===l){if(u>nt){var h=rt*s,p=Array.from(e.slice(0,h)),f=Array.from(e.slice(u-rt*s,u));return"complex64"===r&&(p=ut(p),f=ut(f)),["["+p.map(function(t,e){return it(t,a[e],r);}).join(", ")+", ..., "+f.map(function(t,e){return it(t,a[u-rt+e],r);}).join(", ")+"]"];}var d="complex64"===r?ut(e):Array.from(e);return["["+d.map(function(t,e){return it(t,a[e],r);}).join(", ")+"]"];}var v=n.slice(1);var m=o.slice(1);var g=o[0]*s;var y=[];if(u>nt){for(var x=0;x<rt;x++){var b=x*g,w=b+g;y.push.apply(y,t(e.slice(b,w),v,r,m,a,!1));}y.push("...");for(var x=u-rt;x<u;x++){var b=x*g,w=b+g;y.push.apply(y,t(e.slice(b,w),v,r,m,a,x===u-1));}}else for(var x=0;x<u;x++){var b=x*g,w=b+g;y.push.apply(y,t(e.slice(b,w),v,r,m,a,x===u-1));}var C=2===l?",":"";y[0]="["+y[0]+C;for(var x=1;x<y.length-1;x++)y[x]=" "+y[x]+C;var E=",\n";for(var x=2;x<l;x++)E+="\n";y[y.length-1]=" "+y[y.length-1]+"]"+(i?"":E);return y;}(t,e,n,o,a),u=["Tensor"];return r&&(u.push("  dtype: "+n),u.push("  rank: "+i),u.push("  shape: ["+e+"]"),u.push("  values:")),u.push(s.map(function(t){return"    "+t;}).join("\n")),u.join("\n");}function it(t,e,n){return E(Array.isArray(t)?parseFloat(t[0].toFixed(ot))+" + "+parseFloat(t[1].toFixed(ot))+"j":P(t)?"'"+t+"'":"bool"===n?st(t):parseFloat(t.toFixed(ot)).toString(),e);}function st(t){return 0===t?"false":"true";}function ut(t){for(var e=[],n=0;n<t.length;n+=2)e.push([t[n],t[n+1]]);return e;}var lt=function(){function t(t,e,n){var r=this;if(this.dtype=e,this.shape=t.slice(),this.size=y(t),null!=n){var o=n.length;d(o===this.size,function(){return"Length of values '"+o+"' does not match the size inferred by the shape '"+r.size+"'.";});}if("complex64"===e)throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||A(e,this.size),this.strides=G(t);}return t.prototype.set=function(t){for(var e=this,n=[],r=1;r<arguments.length;r++)n[r-1]=arguments[r];0===n.length&&(n=[0]),d(n.length===this.rank,function(){return"The number of provided coordinates ("+n.length+") must match the rank ("+e.rank+")";});var o=this.locToIndex(n);this.values[o]=t;},t.prototype.get=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];0===t.length&&(t=[0]);for(var n=0,r=0,o=t;r<o.length;r++){var a=o[r];if(a<0||a>=this.shape[n]){var i="Requested out of range element at "+t+".   Buffer shape="+this.shape;throw new Error(i);}n++;}for(var s=t[t.length-1],u=0;u<t.length-1;++u)s+=this.strides[u]*t[u];return this.values[s];},t.prototype.locToIndex=function(t){if(0===this.rank)return 0;if(1===this.rank)return t[0];for(var e=t[t.length-1],n=0;n<t.length-1;++n)e+=this.strides[n]*t[n];return e;},t.prototype.indexToLoc=function(t){if(0===this.rank)return[];if(1===this.rank)return[t];for(var e=new Array(this.shape.length),n=0;n<e.length-1;++n)e[n]=Math.floor(t/this.strides[n]),t-=e[n]*this.strides[n];return e[e.length-1]=t,e;},Object.defineProperty(t.prototype,"rank",{get:function(){return this.shape.length;},enumerable:!0,configurable:!0}),t.prototype.toTensor=function(){return ft.make(this.shape,{values:this.values},this.dtype);},t;}(),ct=null,ht=null,pt=null;var ft=function(){function t(t,e,n,r,o){this.kept=!1,this.isDisposedInternal=!1,this.shape=t.slice(),this.dtype=e||"float32",this.size=y(t),this.strides=G(t),this.dataId=null!=r?r:{},this.id=ct().nextTensorId(),this.rankType=this.rank<5?this.rank.toString():"higher",ct().registerTensor(this,o),null!=n&&ct().write(o,this.dataId,n);}return t.make=function(e,n,r,o){var a=n.values;return null!=n.values&&"string"===r&&P(n.values[0])&&(a=n.values.map(function(t){return Q(t);})),new t(e,r,a,n.dataId,o);},t.prototype.flatten=function(){return this.throwIfDisposed(),this.as1D();},t.prototype.asScalar=function(){return this.throwIfDisposed(),d(1===this.size,function(){return"The array must have only 1 element.";}),this.reshape([]);},t.prototype.as1D=function(){return this.throwIfDisposed(),this.reshape([this.size]);},t.prototype.as2D=function(t,e){return this.throwIfDisposed(),this.reshape([t,e]);},t.prototype.as3D=function(t,e,n){return this.throwIfDisposed(),this.reshape([t,e,n]);},t.prototype.as4D=function(t,e,n,r){return this.throwIfDisposed(),this.reshape([t,e,n,r]);},t.prototype.as5D=function(t,e,n,r,o){return this.throwIfDisposed(),this.reshape([t,e,n,r,o]);},t.prototype.asType=function(t){return this.throwIfDisposed(),ht.cast(this,t);},Object.defineProperty(t.prototype,"rank",{get:function(){return this.shape.length;},enumerable:!0,configurable:!0}),t.prototype.buffer=function(){return r(this,void 0,void 0,function(){var t;return o(this,function(e){switch(e.label){case 0:return[4,this.data()];case 1:return t=e.sent(),[2,ht.buffer(this.shape,this.dtype,t)];}});});},t.prototype.bufferSync=function(){return ht.buffer(this.shape,this.dtype,this.dataSync());},t.prototype.array=function(){return r(this,void 0,void 0,function(){var t;return o(this,function(e){switch(e.label){case 0:return[4,this.data()];case 1:return t=e.sent(),[2,H(this.shape,t)];}});});},t.prototype.arraySync=function(){return H(this.shape,this.dataSync());},t.prototype.data=function(){return r(this,void 0,void 0,function(){var t,e;return o(this,function(n){switch(n.label){case 0:return this.throwIfDisposed(),t=ct().read(this.dataId),"string"!==this.dtype?[3,2]:[4,t];case 1:e=n.sent();try{return[2,e.map(function(t){return J(t);})];}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().");}n.label=2;case 2:return[2,t];}});});},t.prototype.dataSync=function(){this.throwIfDisposed();var t=ct().readSync(this.dataId);if("string"===this.dtype)try{return t.map(function(t){return J(t);});}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().");}return t;},t.prototype.bytes=function(){return r(this,void 0,void 0,function(){var t;return o(this,function(e){switch(e.label){case 0:return this.throwIfDisposed(),[4,ct().read(this.dataId)];case 1:return t=e.sent(),"string"===this.dtype?[2,t]:[2,new Uint8Array(t.buffer)];}});});},t.prototype.dispose=function(){this.isDisposed||(ct().disposeTensor(this),this.isDisposedInternal=!0);},Object.defineProperty(t.prototype,"isDisposed",{get:function(){return this.isDisposedInternal;},enumerable:!0,configurable:!0}),t.prototype.throwIfDisposed=function(){if(this.isDisposed)throw new Error("Tensor is disposed.");},t.prototype.toFloat=function(){return this.asType("float32");},t.prototype.toInt=function(){return this.asType("int32");},t.prototype.toBool=function(){return this.asType("bool");},t.prototype.print=function(t){return void 0===t&&(t=!1),ht.print(this,t);},t.prototype.reshape=function(t){return this.throwIfDisposed(),ht.reshape(this,t);},t.prototype.reshapeAs=function(t){return this.throwIfDisposed(),this.reshape(t.shape);},t.prototype.expandDims=function(t){return void 0===t&&(t=0),ht.expandDims(this,t);},t.prototype.cumsum=function(t,e,n){return void 0===t&&(t=0),void 0===e&&(e=!1),void 0===n&&(n=!1),ht.cumsum(this,t,e,n);},t.prototype.squeeze=function(t){return this.throwIfDisposed(),ht.squeeze(this,t);},t.prototype.clone=function(){return this.throwIfDisposed(),ht.clone(this);},t.prototype.oneHot=function(t,e,n){return this.throwIfDisposed(),ht.oneHot(this,t,e,n);},t.prototype.toString=function(t){return void 0===t&&(t=!1),at(this.dataSync(),this.shape,this.dtype,t);},t.prototype.tile=function(t){return this.throwIfDisposed(),ht.tile(this,t);},t.prototype.gather=function(t,e){return void 0===e&&(e=0),this.throwIfDisposed(),ht.gather(this,t,e);},t.prototype.matMul=function(t,e,n){return void 0===e&&(e=!1),void 0===n&&(n=!1),this.throwIfDisposed(),ht.matMul(this,t,e,n);},t.prototype.dot=function(t){return this.throwIfDisposed(),ht.dot(this,t);},t.prototype.norm=function(t,e,n){return void 0===t&&(t="euclidean"),void 0===e&&(e=null),void 0===n&&(n=!1),this.throwIfDisposed(),ht.norm(this,t,e,n);},t.prototype.slice=function(t,e){return this.throwIfDisposed(),ht.slice(this,t,e);},t.prototype.reverse=function(t){return this.throwIfDisposed(),ht.reverse(this,t);},t.prototype.concat=function(e,n){return void 0===n&&(n=0),this.throwIfDisposed(),e instanceof t&&(e=[e]),ht.concat([this].concat(e),n);},t.prototype.split=function(t,e){return void 0===e&&(e=0),this.throwIfDisposed(),ht.split(this,t,e);},t.prototype.stack=function(t,e){return void 0===e&&(e=0),ht.stack([this,t],e);},t.prototype.unstack=function(t){return void 0===t&&(t=0),ht.unstack(this,t);},t.prototype.pad=function(t,e){return void 0===e&&(e=0),ht.pad(this,t,e);},t.prototype.batchNormalization=function(t,e,n,r,o){return void 0===n&&(n=.001),pt("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon"),this.batchNorm(t,e,o,r,n);},t.prototype.batchNorm=function(t,e,n,r,o){return void 0===o&&(o=.001),this.throwIfDisposed(),ht.batchNorm(this,t,e,n,r,o);},t.prototype.all=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),ht.all(this,t,e);},t.prototype.any=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),ht.any(this,t,e);},t.prototype.logSumExp=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),ht.logSumExp(this,t,e);},t.prototype.sum=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),ht.sum(this,t,e);},t.prototype.prod=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),ht.prod(this,t,e);},t.prototype.mean=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),ht.mean(this,t,e);},t.prototype.min=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),ht.min(this,t,e);},t.prototype.max=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),ht.max(this,t,e);},t.prototype.argMin=function(t){return void 0===t&&(t=null),this.throwIfDisposed(),ht.argMin(this,t);},t.prototype.argMax=function(t){return void 0===t&&(t=null),this.throwIfDisposed(),ht.argMax(this,t);},t.prototype.cast=function(t){return this.throwIfDisposed(),ht.cast(this,t);},t.prototype.add=function(t){return this.throwIfDisposed(),ht.add(this,t);},t.prototype.addStrict=function(t){return this.throwIfDisposed(),ht.addStrict(this,t);},t.prototype.atan2=function(t){return this.throwIfDisposed(),ht.atan2(this,t);},t.prototype.sub=function(t){return this.throwIfDisposed(),ht.sub(this,t);},t.prototype.subStrict=function(t){return this.throwIfDisposed(),ht.subStrict(this,t);},t.prototype.pow=function(t){return this.throwIfDisposed(),ht.pow(this,t);},t.prototype.powStrict=function(t){return this.throwIfDisposed(),ht.powStrict(this,t);},t.prototype.mul=function(t){return this.throwIfDisposed(),ht.mul(this,t);},t.prototype.mulStrict=function(t){return this.throwIfDisposed(),ht.mulStrict(this,t);},t.prototype.div=function(t){return this.throwIfDisposed(),ht.div(this,t);},t.prototype.floorDiv=function(t){return this.throwIfDisposed(),ht.floorDiv(this,t);},t.prototype.divStrict=function(t){return this.throwIfDisposed(),ht.divStrict(this,t);},t.prototype.minimum=function(t){return this.throwIfDisposed(),ht.minimum(this,t);},t.prototype.minimumStrict=function(t){return this.throwIfDisposed(),ht.minimumStrict(this,t);},t.prototype.maximum=function(t){return this.throwIfDisposed(),ht.maximum(this,t);},t.prototype.maximumStrict=function(t){return this.throwIfDisposed(),ht.maximumStrict(this,t);},t.prototype.mod=function(t){return this.throwIfDisposed(),ht.mod(this,t);},t.prototype.modStrict=function(t){return this.throwIfDisposed(),ht.modStrict(this,t);},t.prototype.squaredDifference=function(t){return this.throwIfDisposed(),ht.squaredDifference(this,t);},t.prototype.squaredDifferenceStrict=function(t){return this.throwIfDisposed(),ht.squaredDifferenceStrict(this,t);},t.prototype.transpose=function(t){return this.throwIfDisposed(),ht.transpose(this,t);},t.prototype.notEqual=function(t){return this.throwIfDisposed(),ht.notEqual(this,t);},t.prototype.notEqualStrict=function(t){return this.throwIfDisposed(),ht.notEqualStrict(this,t);},t.prototype.less=function(t){return this.throwIfDisposed(),ht.less(this,t);},t.prototype.lessStrict=function(t){return this.throwIfDisposed(),ht.lessStrict(this,t);},t.prototype.equal=function(t){return this.throwIfDisposed(),ht.equal(this,t);},t.prototype.equalStrict=function(t){return this.throwIfDisposed(),ht.equalStrict(this,t);},t.prototype.lessEqual=function(t){return this.throwIfDisposed(),ht.lessEqual(this,t);},t.prototype.lessEqualStrict=function(t){return this.throwIfDisposed(),ht.lessEqualStrict(this,t);},t.prototype.greater=function(t){return this.throwIfDisposed(),ht.greater(this,t);},t.prototype.greaterStrict=function(t){return this.throwIfDisposed(),ht.greaterStrict(this,t);},t.prototype.greaterEqual=function(t){return this.throwIfDisposed(),ht.greaterEqual(this,t);},t.prototype.greaterEqualStrict=function(t){return this.throwIfDisposed(),ht.greaterEqualStrict(this,t);},t.prototype.logicalAnd=function(t){return this.throwIfDisposed(),ht.logicalAnd(this,t);},t.prototype.logicalOr=function(t){return this.throwIfDisposed(),ht.logicalOr(this,t);},t.prototype.logicalNot=function(){return this.throwIfDisposed(),ht.logicalNot(this);},t.prototype.logicalXor=function(t){return this.throwIfDisposed(),ht.logicalXor(this,t);},t.prototype.where=function(t,e){return this.throwIfDisposed(),ht.where(t,this,e);},t.prototype.neg=function(){return this.throwIfDisposed(),ht.neg(this);},t.prototype.ceil=function(){return this.throwIfDisposed(),ht.ceil(this);},t.prototype.floor=function(){return this.throwIfDisposed(),ht.floor(this);},t.prototype.sign=function(){return this.throwIfDisposed(),ht.sign(this);},t.prototype.isNaN=function(){return this.throwIfDisposed(),ht.isNaN(this);},t.prototype.isInf=function(){return this.throwIfDisposed(),ht.isInf(this);},t.prototype.isFinite=function(){return this.throwIfDisposed(),ht.isFinite(this);},t.prototype.exp=function(){return this.throwIfDisposed(),ht.exp(this);},t.prototype.expm1=function(){return this.throwIfDisposed(),ht.expm1(this);},t.prototype.log=function(){return this.throwIfDisposed(),ht.log(this);},t.prototype.log1p=function(){return this.throwIfDisposed(),ht.log1p(this);},t.prototype.sqrt=function(){return this.throwIfDisposed(),ht.sqrt(this);},t.prototype.rsqrt=function(){return this.throwIfDisposed(),ht.rsqrt(this);},t.prototype.square=function(){return this.throwIfDisposed(),ht.square(this);},t.prototype.reciprocal=function(){return this.throwIfDisposed(),ht.reciprocal(this);},t.prototype.abs=function(){return this.throwIfDisposed(),ht.abs(this);},t.prototype.clipByValue=function(t,e){return this.throwIfDisposed(),ht.clipByValue(this,t,e);},t.prototype.relu=function(){return this.throwIfDisposed(),ht.relu(this);},t.prototype.elu=function(){return this.throwIfDisposed(),ht.elu(this);},t.prototype.selu=function(){return this.throwIfDisposed(),ht.selu(this);},t.prototype.leakyRelu=function(t){return void 0===t&&(t=.2),this.throwIfDisposed(),ht.leakyRelu(this,t);},t.prototype.prelu=function(t){return this.throwIfDisposed(),ht.prelu(this,t);},t.prototype.sigmoid=function(){return this.throwIfDisposed(),ht.sigmoid(this);},t.prototype.logSigmoid=function(){return this.throwIfDisposed(),ht.logSigmoid(this);},t.prototype.softplus=function(){return this.throwIfDisposed(),ht.softplus(this);},t.prototype.zerosLike=function(){return this.throwIfDisposed(),ht.zerosLike(this);},t.prototype.onesLike=function(){return this.throwIfDisposed(),ht.onesLike(this);},t.prototype.sin=function(){return this.throwIfDisposed(),ht.sin(this);},t.prototype.cos=function(){return this.throwIfDisposed(),ht.cos(this);},t.prototype.tan=function(){return this.throwIfDisposed(),ht.tan(this);},t.prototype.asin=function(){return this.throwIfDisposed(),ht.asin(this);},t.prototype.acos=function(){return this.throwIfDisposed(),ht.acos(this);},t.prototype.atan=function(){return this.throwIfDisposed(),ht.atan(this);},t.prototype.sinh=function(){return this.throwIfDisposed(),ht.sinh(this);},t.prototype.cosh=function(){return this.throwIfDisposed(),ht.cosh(this);},t.prototype.tanh=function(){return this.throwIfDisposed(),ht.tanh(this);},t.prototype.asinh=function(){return this.throwIfDisposed(),ht.asinh(this);},t.prototype.acosh=function(){return this.throwIfDisposed(),ht.acosh(this);},t.prototype.atanh=function(){return this.throwIfDisposed(),ht.atanh(this);},t.prototype.erf=function(){return this.throwIfDisposed(),ht.erf(this);},t.prototype.round=function(){return this.throwIfDisposed(),ht.round(this);},t.prototype.step=function(t){return void 0===t&&(t=0),this.throwIfDisposed(),ht.step(this,t);},t.prototype.softmax=function(t){return void 0===t&&(t=-1),this.throwIfDisposed(),ht.softmax(this,t);},t.prototype.logSoftmax=function(t){return void 0===t&&(t=-1),this.throwIfDisposed(),ht.logSoftmax(this,t);},t.prototype.resizeBilinear=function(t,e){return void 0===e&&(e=!1),this.throwIfDisposed(),ht.image.resizeBilinear(this,t,e);},t.prototype.resizeNearestNeighbor=function(t,e){return void 0===e&&(e=!1),this.throwIfDisposed(),ht.image.resizeNearestNeighbor(this,t,e);},t.prototype.conv1d=function(t,e,n,r,o,a){return void 0===r&&(r="NWC"),void 0===o&&(o=1),this.throwIfDisposed(),ht.conv1d(this,t,e,n,r,o,a);},t.prototype.conv2d=function(t,e,n,r,o,a){return void 0===r&&(r="NHWC"),void 0===o&&(o=[1,1]),this.throwIfDisposed(),ht.conv2d(this,t,e,n,r,o,a);},t.prototype.conv2dTranspose=function(t,e,n,r,o){return this.throwIfDisposed(),ht.conv2dTranspose(this,t,e,n,r,o);},t.prototype.depthwiseConv2D=function(t,e,n,r,o,a){return void 0===r&&(r="NHWC"),void 0===o&&(o=[1,1]),this.throwIfDisposed(),ht.depthwiseConv2d(this,t,e,n,r,o,a);},t.prototype.separableConv2d=function(t,e,n,r,o,a){return void 0===o&&(o=[1,1]),void 0===a&&(a="NHWC"),this.throwIfDisposed(),ht.separableConv2d(this,t,e,n,r,o,a);},t.prototype.avgPool=function(t,e,n,r){return this.throwIfDisposed(),ht.avgPool(this,t,e,n,r);},t.prototype.maxPool=function(t,e,n,r){return this.throwIfDisposed(),ht.maxPool(this,t,e,n,r);},t.prototype.localResponseNormalization=function(t,e,n,r){return void 0===t&&(t=5),void 0===e&&(e=1),void 0===n&&(n=1),void 0===r&&(r=.5),ht.localResponseNormalization(this,t,e,n,r);},t.prototype.pool=function(t,e,n,r,o){return this.throwIfDisposed(),ht.pool(this,t,e,n,r,o);},t.prototype.variable=function(t,e,n){return void 0===t&&(t=!0),this.throwIfDisposed(),dt.variable(this,t,e,n);},t.prototype.unsortedSegmentSum=function(t,e){return this.throwIfDisposed(),ht.unsortedSegmentSum(this,t,e);},t.prototype.batchToSpaceND=function(t,e){return this.throwIfDisposed(),ht.batchToSpaceND(this,t,e);},t.prototype.spaceToBatchND=function(t,e){return this.throwIfDisposed(),ht.spaceToBatchND(this,t,e);},t.prototype.topk=function(t,e){return void 0===t&&(t=1),void 0===e&&(e=!0),this.throwIfDisposed(),ht.topk(this,t,e);},t.prototype.stridedSlice=function(t,e,n,r,o,a,i,s){return void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=0),void 0===i&&(i=0),void 0===s&&(s=0),this.throwIfDisposed(),ht.stridedSlice(this,t,e,n,r,o,a,i,s);},t.prototype.depthToSpace=function(t,e){return this.throwIfDisposed(),ht.depthToSpace(this,t,e);},t.prototype.fft=function(){return this.throwIfDisposed(),ht.spectral.fft(this);},t.prototype.ifft=function(){return this.throwIfDisposed(),ht.spectral.ifft(this);},t.prototype.rfft=function(){return this.throwIfDisposed(),ht.spectral.rfft(this);},t.prototype.irfft=function(){return this.throwIfDisposed(),ht.spectral.irfft(this);},t;}();Object.defineProperty(ft,Symbol.hasInstance,{value:function(t){return!!t&&null!=t.dataId&&null!=t.shape&&null!=t.dtype;}});var dt=function(t){function n(e,n,r){void 0===n&&(n=!0);var o=t.call(this,e.shape,e.dtype,null,e.dataId)||this;o.trainable=n,o.name=r,null==o.name&&(o.name=ct().nextVariableId().toString());try{ct().registerVariable(o);}catch(t){throw ct().disposeTensor(o),t;}return o;}return e(n,t),n.variable=function(t,e,r,o){return void 0===e&&(e=!0),null!=o&&o!==t.dtype&&(t=t.asType(o)),new n(t,e,r);},n.prototype.assign=function(t){if(t.dtype!==this.dtype)throw new Error("dtype of the new value ("+t.dtype+") and previous value ("+this.dtype+") must match");if(!x(t.shape,this.shape))throw new Error("shape of the new value ("+t.shape+") and previous value ("+this.shape+") must match");ct().disposeTensor(this),this.dataId=t.dataId,ct().registerTensor(this);},n.prototype.dispose=function(){ct().disposeVariable(this),this.isDisposedInternal=!0;},n;}(ft);Object.defineProperty(dt,Symbol.hasInstance,{value:function(t){return t instanceof ft&&null!=t.assign&&t.assign instanceof Function;}});var mt,gt,yt,xt,bt=dt.variable;!function(t){t.R0="R0",t.R1="R1",t.R2="R2",t.R3="R3",t.R4="R4",t.R5="R5",t.R6="R6";}(exports.Rank||(exports.Rank={})),function(t){t.float32="float32",t.int32="int32",t.bool="int32",t.complex64="complex64";}(mt||(mt={})),function(t){t.float32="float32",t.int32="int32",t.bool="bool",t.complex64="complex64";}(gt||(gt={})),function(t){t.float32="float32",t.int32="float32",t.bool="float32",t.complex64="complex64";}(yt||(yt={})),function(t){t.float32="complex64",t.int32="complex64",t.bool="complex64",t.complex64="complex64";}(xt||(xt={}));var wt={float32:yt,int32:mt,bool:gt,complex64:xt};function Ct(t,e){if("string"===t||"string"===e){if("string"===t&&"string"===e)return"string";throw new Error("Can not upcast "+t+" with "+e);}return wt[t][e];}function Et(t){return Ct(t,"int32");}function Rt(t,e){if(t.dtype===e.dtype)return[t,e];var n=Ct(t.dtype,e.dtype);return[t.cast(n),e.cast(n)];}function It(t,e){d(t.dtype===e.dtype,function(){return"The dtypes of the first("+t.dtype+") and second("+e.dtype+") input must match";});}function St(t){var e=[];return function t(e,n,r){if(null==e)return;if(e instanceof ft)return void n.push(e);if(o=e,!Array.isArray(o)&&"object"!=typeof o)return;var o;var a=e;for(var i in a){var s=a[i];r.has(s)||(r.add(s),t(s,n,r));}}(t,e,new Set()),e;}var Nt,kt=Object.freeze({makeTypesMatch:Rt,assertTypesMatch:It,isTensorInList:function(t,e){for(var n=0;n<e.length;n++)if(e[n].id===t.id)return!0;return!1;},getTensorsInContainer:St}),At=function(){function t(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap(),this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null};}return t.prototype.dispose=function(){for(var t in this.registeredVariables)this.registeredVariables[t].dispose();},t;}(),Tt=function(){function t(t){this.ENV=t,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new At();}return t.prototype.ready=function(){return r(this,void 0,void 0,function(){var t,e,n;return o(this,function(r){switch(r.label){case 0:if(null!=this.pendingBackendInit)return[2,this.pendingBackendInit.then(function(){})];if(null!=this.backendInstance)return[2];t=this.getSortedBackends(),e=0,r.label=1;case 1:return e<t.length?(n=t[e],[4,this.initializeBackend(n).success]):[3,5];case 2:return r.sent()?[4,this.setBackend(n)]:[3,4];case 3:return r.sent(),[2];case 4:return e++,[3,1];case 5:throw new Error("Could not initialize any backends, all backend initializations failed.");}});});},Object.defineProperty(t.prototype,"backend",{get:function(){if(null!=this.pendingBackendInit)throw new Error("Backend '"+this.backendName+"' has not yet been initialized. Make sure to await tf.ready() before calling other methods");if(null==this.backendInstance){var t=this.initializeBackendsAndReturnBest(),e=t.name;if(t.asyncInit)throw new Error("The highest priority backend '"+e+"' has not yet been initialized. Make sure to await tf.ready() before calling other methods");this.setBackend(e);}return this.backendInstance;},enumerable:!0,configurable:!0}),t.prototype.backendNames=function(){return Object.keys(this.registryFactory);},t.prototype.findBackend=function(t){if(!(t in this.registry)){if(!(t in this.registryFactory))return null;if(this.initializeBackend(t).asyncInit)return null;}return this.registry[t];},t.prototype.findBackendFactory=function(t){return t in this.registryFactory?this.registryFactory[t].factory:null;},t.prototype.registerBackend=function(t,e,n){return void 0===n&&(n=1),t in this.registryFactory?(console.warn(t+" backend was already registered. Reusing existing backend factory."),!1):(this.registryFactory[t]={factory:e,priority:n},!0);},t.prototype.setBackend=function(t){return r(this,void 0,void 0,function(){var e,n,r;return o(this,function(o){switch(o.label){case 0:if(null==this.registryFactory[t])throw new Error("Backend name '"+t+"' not found in registry");return this.backendName=t,null!=this.registry[t]?[3,4]:(this.backendInstance=null,e=this.initializeBackend(t),n=e.success,e.asyncInit?[4,n]:[3,2]);case 1:return r=o.sent(),[3,3];case 2:r=n,o.label=3;case 3:if(!r)return[2,!1];o.label=4;case 4:return this.backendInstance=this.registry[t],this.profiler=new tt(this.backendInstance),[2,!0];}});});},t.prototype.initializeBackend=function(t){var e=this,n=this.registryFactory[t];if(null==n)throw new Error("Cannot initialize backend "+t+", no registration found.");try{var r=n.factory();if(Promise.resolve(r)===r){var o=++this.pendingBackendInitId,a=r.then(function(n){return!(o<e.pendingBackendInitId)&&(e.registry[t]=n,e.pendingBackendInit=null,!0);}).catch(function(n){return!(o<e.pendingBackendInitId)&&(e.pendingBackendInit=null,console.warn("Initialization of backend "+t+" failed"),console.warn(n.stack||n.message),!1);});return this.pendingBackendInit=a,{success:a,asyncInit:!0};}return this.registry[t]=r,{success:!0,asyncInit:!1};}catch(e){return console.warn("Initialization of backend "+t+" failed"),console.warn(e.stack||e.message),{success:!1,asyncInit:!1};}},t.prototype.removeBackend=function(t){if(!(t in this.registryFactory))throw new Error(t+" backend not found in registry");this.backendName===t&&null!=this.pendingBackendInit&&this.pendingBackendInitId++,t in this.registry&&(this.registry[t].dispose(),delete this.registry[t]),delete this.registryFactory[t],this.backendName===t&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null);},t.prototype.getSortedBackends=function(){var t=this;if(0===Object.keys(this.registryFactory).length)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort(function(e,n){return t.registryFactory[n].priority-t.registryFactory[e].priority;});},t.prototype.initializeBackendsAndReturnBest=function(){for(var t=this.getSortedBackends(),e=0;e<t.length;e++){var n=t[e],r=this.initializeBackend(n),o=r.success,a=r.asyncInit;if(a||o)return{name:n,asyncInit:a};}throw new Error("Could not initialize any backends, all backend initializations failed.");},t.prototype.moveData=function(t,e){this.write(t,e,this.readSync(e));},t.prototype.tidy=function(t,e){var n,r=this,o=null;if(null==e){if("function"!=typeof t)throw new Error("Please provide a function to tidy()");e=t;}else{if("string"!=typeof t&&!(t instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!=typeof e)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");o=t;}return this.scopedRun(function(){return r.startScope(o);},function(){return r.endScope(n);},function(){return(n=e())instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n;});},t.prototype.scopedRun=function(t,e,n){t();try{var r=n();return e(),r;}catch(t){throw e(),t;}},t.prototype.nextTensorId=function(){return t.nextTensorId++;},t.prototype.nextVariableId=function(){return t.nextVariableId++;},t.prototype.clone=function(t){var e=ft.make(t.shape,{dataId:t.dataId},t.dtype);return this.addTapeNode([t],e,function(t){return[t.toFloat()];}),e;},t.prototype.runKernel=function(t,e,n){var r,o=this,a=[],i=this.isTapeOn(),s=null!=this.state.activeScope?this.state.activeScope.name:"",u=function(t){i&&(a=t.map(function(t){return o.keep(o.clone(t));}));},l=this.state.numBytes,c=this.state.numTensors;if(this.scopedRun(function(){return o.state.kernelDepth++;},function(){return o.state.kernelDepth--;},function(){r=o.ENV.getBool("DEBUG")?o.profiler.profileKernel(s,function(){return t(o.backend,u);}):t(o.backend,u);}),i){var h={id:this.state.nextTapeNodeId++,name:s,inputs:e,outputs:Array.isArray(r)?r:[r],saved:a};null!=n&&(h.gradient=function(t){return n(t,a);}),this.state.activeTape.push(h);}return this.state.profiling&&this.state.activeProfile.kernels.push({name:s,bytesAdded:this.state.numBytes-l,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-c,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(e).map(function(t){return e[t].shape;}),outputShape:Array.isArray(r)?r.map(function(t){return t.shape;}):r.shape}),r;},t.prototype.registerTensor=function(t,e){var n=this.state.tensorInfo.has(t.dataId)?this.state.tensorInfo.get(t.dataId).refCount:0;if(this.state.numTensors++,"string"===t.dtype&&this.state.numStringTensors++,0===n){this.state.numDataBuffers++;var r=0;"complex64"!==t.dtype&&"string"!==t.dtype&&(r=t.size*F(t.dtype)),this.state.tensorInfo.set(t.dataId,{backend:null!=e?e:this.backend,dtype:t.dtype,shape:t.shape,bytes:r,refCount:0}),this.state.numBytes+=r,null!=e?e.register(t.dataId,t.shape,t.dtype):this.backend.register(t.dataId,t.shape,t.dtype);}this.state.tensorInfo.get(t.dataId).refCount++,t instanceof dt||this.track(t);},t.prototype.registerVariable=function(t){if(null!=this.state.registeredVariables[t.name])throw new Error("Variable with name "+t.name+" was already registered");this.state.registeredVariables[t.name]=t;},t.prototype.disposeTensor=function(t){if(this.state.tensorInfo.has(t.dataId)){this.state.numTensors--,"string"===t.dtype&&this.state.numStringTensors--;var e=this.state.tensorInfo.get(t.dataId);e.refCount<=1?("complex64"!==t.dtype&&(this.state.numBytes-=e.bytes),this.state.numDataBuffers--,e.backend.disposeData(t.dataId),this.state.tensorInfo.delete(t.dataId)):this.state.tensorInfo.get(t.dataId).refCount--;}},t.prototype.disposeVariables=function(){for(var t in this.state.registeredVariables){var e=this.state.registeredVariables[t];this.disposeVariable(e);}},t.prototype.disposeVariable=function(t){this.disposeTensor(t),null!=this.state.registeredVariables[t.name]&&delete this.state.registeredVariables[t.name];},t.prototype.memory=function(){var t=this.backend.memory();return t.numTensors=this.state.numTensors,t.numDataBuffers=this.state.numDataBuffers,t.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(t.unreliable=!0,null==t.reasons&&(t.reasons=[]),t.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),t;},t.prototype.profile=function(t){return r(this,void 0,void 0,function(){var e,n;return o(this,function(r){return this.state.profiling=!0,e=this.state.numBytes,n=this.state.numTensors,this.state.activeProfile.kernels=[],this.state.activeProfile.result=t(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max.apply(Math,this.state.activeProfile.kernels.map(function(t){return t.totalBytesSnapshot;})),this.state.activeProfile.newBytes=this.state.numBytes-e,this.state.activeProfile.newTensors=this.state.numTensors-n,[2,this.state.activeProfile];});});},t.prototype.isTapeOn=function(){return this.state.gradientDepth>0&&0===this.state.kernelDepth;},t.prototype.addTapeNode=function(t,e,n){var r={};t.forEach(function(t,e){r[e]=t;});var o={id:this.state.nextTapeNodeId++,name:this.state.activeScope.name,inputs:r,outputs:[e],gradient:function(t){var e=n(t),r={};return e.forEach(function(t,e){r[e]=function(){return t;};}),r;}};this.state.activeTape.push(o);},t.prototype.keep=function(t){return t.kept=!0,t;},t.prototype.startTape=function(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++;},t.prototype.endTape=function(){this.state.gradientDepth--;},t.prototype.startScope=function(t){var e={track:[],name:"unnamed scope",id:this.state.nextScopeId++};t&&(e.name=t),this.state.scopeStack.push(e),this.state.activeScope=e;},t.prototype.endScope=function(t){for(var e=this,n=St(t),r=new Set(n.map(function(t){return t.id;})),o=0;o<this.state.activeScope.track.length;o++){var a=this.state.activeScope.track[o];a.kept||r.has(a.id)||a.dispose();}var i=this.state.scopeStack.pop();this.state.activeScope=0===this.state.scopeStack.length?null:this.state.scopeStack[this.state.scopeStack.length-1],n.forEach(function(t){t.kept||t.scopeId!==i.id||e.track(t);});},t.prototype.gradients=function(t,e,n,r){var o=this;if(void 0===r&&(r=!1),d(e.length>0,function(){return"gradients() received an empty list of xs.";}),null!=n&&"float32"!==n.dtype)throw new Error("dy must have 'float32' dtype, but has '"+n.dtype+"'");var a=this.scopedRun(function(){return o.startTape();},function(){return o.endTape();},function(){return o.tidy("forward",t);});d(a instanceof ft,function(){return"The result y returned by f() must be a tensor.";});var i=function(t,e,n){for(var r={},o={},a=0;a<e.length;a++)r[e[a].id]=!0;for(a=0;a<t.length;a++){var i=(d=t[a]).inputs;for(var s in i){for(var u=i[s],l=!1,c=0;c<e.length;c++)if(r[u.id]){d.outputs.forEach(function(t){return r[t.id]=!0;}),l=!0,o[d.id]=!0;break;}if(l)break;}}var h={};h[n.id]=!0;var p={};for(a=t.length-1;a>=0;a--)for(i=(d=t[a]).inputs,c=0;c<d.outputs.length;c++)if(h[d.outputs[c].id]){for(var s in i)h[i[s].id]=!0,p[d.id]=!0;break;}var f=[];for(a=0;a<t.length;a++){var d;if(o[(d=t[a]).id]&&p[d.id]){var v={};for(var s in d.inputs){var m=d.inputs[s];r[m.id]&&(v[s]=m);}var g=Object.assign({},d);g.inputs=v,g.outputs=d.outputs,f.push(g);}}return f;}(this.state.activeTape,e,a);if(!r&&0===i.length&&e.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",function(){var t,r,s={};s[a.id]=null==n?(t=a.shape,r=$(y(t),"float32"),ft.make(t,{values:r})):n,function(t,e,n){for(var r=function(r){var o=e[r],a=[];if(o.outputs.forEach(function(e){var n=t[e.id];if(null!=n)a.push(n);else{var r=ft.make(e.shape,{values:j(e.size,e.dtype)},e.dtype);a.push(r);}}),null==o.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+o.name+".");var i=o.gradient(1===o.outputs.length?a[0]:a),s=function(e){if(!(e in i))throw new Error("Cannot backprop through input "+e+". Available gradients found: "+Object.keys(i)+".");var r=n(function(){return i[e]();});if("float32"!==r.dtype)throw new Error("Error in gradient for op "+o.name+". The gradient of input "+e+" must have 'float32' dtype, but has '"+r.dtype+"'");var a=o.inputs[e];if(!x(r.shape,a.shape))throw new Error("Error in gradient for op "+o.name+". The gradient of input '"+e+"' has shape '"+r.shape+"', which does not match the shape of the input '"+a.shape+"'");if(null==t[a.id])t[a.id]=r;else{var s=t[a.id];t[a.id]=s.add(r),s.dispose();}};for(var u in o.inputs)s(u);},o=e.length-1;o>=0;o--)r(o);}(s,i,function(t){return o.tidy(t);});var u=e.map(function(t){return s[t.id];});return 0===o.state.gradientDepth&&(o.state.activeTape.forEach(function(t){for(var e in t.saved)t.saved[e].dispose();}),o.state.activeTape=null),{value:a,grads:u};});},t.prototype.customGrad=function(t){var e=this;return d(z(t),function(){return"The f passed in customGrad(f) must be a function.";}),function(){for(var n,r=[],o=0;o<arguments.length;o++)r[o]=arguments[o];d(r.every(function(t){return t instanceof ft;}),function(){return"The args passed in customGrad(f)(x1, x2,...) must all be tensors";});var a={};return r.forEach(function(t,e){a[e]=t;}),e.runKernel(function(e,o){return d((n=t.apply(void 0,r.concat([o]))).value instanceof ft,function(){return"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor";}),d(z(n.gradFunc),function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function.";}),n.value;},a,function(t,e){var o=n.gradFunc(t,e),a=Array.isArray(o)?o:[o];d(a.length===r.length,function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...).";}),d(a.every(function(t){return t instanceof ft;}),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 i={};return a.forEach(function(t,e){i[e]=function(){return t;};}),i;});};},t.prototype.write=function(t,e,n){var r=this.state.tensorInfo.get(e),o=r.backend;if(t=t||this.backend,"string"===r.dtype){var a=B(n);this.state.numBytes+=a-r.bytes,r.bytes=a;}t!==o&&(o.disposeData(e),r.backend=t,t.register(e,r.shape,r.dtype)),t.write(e,n);},t.prototype.readSync=function(t){return this.state.tensorInfo.get(t).backend.readSync(t);},t.prototype.read=function(t){return this.state.tensorInfo.get(t).backend.read(t);},t.prototype.fromPixels=function(t,e){return this.backend.fromPixels(t,e);},t.prototype.time=function(t){return r(this,void 0,void 0,function(){var e,n;return o(this,function(r){switch(r.label){case 0:return e=K(),[4,this.backend.time(t)];case 1:return(n=r.sent()).wallMs=K()-e,[2,n];}});});},t.prototype.track=function(t){return null!=this.state.activeScope&&(t.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(t)),t;},Object.defineProperty(t.prototype,"registeredVariables",{get:function(){return this.state.registeredVariables;},enumerable:!0,configurable:!0}),t.prototype.reset=function(){for(var t in this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new At(),this.registry)this.registry[t].dispose(),delete this.registry[t];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null;},t.nextTensorId=0,t.nextVariableId=0,t;}();var Dt=function(){var t=function(){if(null==Nt){var t=void 0;if("undefined"!=typeof window)t=window;else if("undefined"!=typeof global)t=global;else if("undefined"!=typeof process)t=process;else{if("undefined"==typeof self)throw new Error("Could not find a global object");t=self;}Nt=t;}return Nt;}();if(null==t._tfengine){var e=new a(t);t._tfengine=new Tt(e);}return u(t._tfengine.ENV),ct=function(){return t._tfengine;},t._tfengine;}();function _t(){return"undefined"!=typeof window&&null!=window.document||"undefined"!=typeof WorkerGlobalScope;}exports.ENV.registerFlag("DEBUG",function(){return!1;},function(t){t&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.");}),exports.ENV.registerFlag("IS_BROWSER",function(){return _t();}),exports.ENV.registerFlag("IS_NODE",function(){return"undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node;}),exports.ENV.registerFlag("IS_CHROME",function(){return"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor);}),exports.ENV.registerFlag("PROD",function(){return!1;}),exports.ENV.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",function(){return exports.ENV.getBool("DEBUG");}),exports.ENV.registerFlag("DEPRECATION_WARNINGS_ENABLED",function(){return!0;}),exports.ENV.registerFlag("IS_TEST",function(){return!1;});var Ot={},Mt={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function Ft(t,e){Ot[t]=e;}function Bt(t){t in Ot||(Ot[t]=function(t){if(1!==t&&2!==t)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");var e=Pt(t);if(e.addEventListener("webglcontextlost",function(e){e.preventDefault(),delete Ot[t];},!1),1===t)return e.getContext("webgl",Mt)||e.getContext("experimental-webgl",Mt);return e.getContext("webgl2",Mt);}(t));var e=Ot[t];return e.isContextLost()?(delete Ot[t],Bt(t)):(e.disable(e.DEPTH_TEST),e.disable(e.STENCIL_TEST),e.disable(e.BLEND),e.disable(e.DITHER),e.disable(e.POLYGON_OFFSET_FILL),e.disable(e.SAMPLE_COVERAGE),e.enable(e.SCISSOR_TEST),e.enable(e.CULL_FACE),e.cullFace(e.BACK),Ot[t]);}function Pt(t){if("undefined"!=typeof OffscreenCanvas&&2===t)return new OffscreenCanvas(300,150);if("undefined"!=typeof document)return document.createElement("canvas");throw new Error("Cannot create a canvas in this context");}function Lt(t,e,n){var r=n();return e&&function(t){var e=t.getError();if(e!==t.NO_ERROR)throw new Error("WebGL Error: "+Vt(t,e));}(t),r;}var Wt=5.96e-8,Ut=65504;function zt(t){return!!(exports.ENV.getBool("WEBGL_RENDER_FLOAT32_ENABLED")||0===t||Wt<Math.abs(t)&&Math.abs(t)<Ut);}function Vt(t,e){switch(e){case t.NO_ERROR:return"NO_ERROR";case t.INVALID_ENUM:return"INVALID_ENUM";case t.INVALID_VALUE:return"INVALID_VALUE";case t.INVALID_OPERATION:return"INVALID_OPERATION";case t.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case t.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case t.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return"Unknown error code "+e;}}function Gt(t,e,n){return pe(t,e,function(){return t.getExtension(n);},'Extension "'+n+'" not supported on this browser.');}function qt(t,e,n){var r=pe(t,e,function(){return t.createShader(t.VERTEX_SHADER);},"Unable to create vertex WebGLShader.");if(Lt(t,e,function(){return t.shaderSource(r,n);}),Lt(t,e,function(){return t.compileShader(r);}),!1===t.getShaderParameter(r,t.COMPILE_STATUS))throw console.log(t.getShaderInfoLog(r)),new Error("Failed to compile vertex shader.");return r;}function Ht(t,e,n){var r=pe(t,e,function(){return t.createShader(t.FRAGMENT_SHADER);},"Unable to create fragment WebGLShader.");if(Lt(t,e,function(){return t.shaderSource(r,n);}),Lt(t,e,function(){return t.compileShader(r);}),!1===t.getShaderParameter(r,t.COMPILE_STATUS))throw function(t,e){var n=Kt.exec(e);if(null==n)return console.log("Couldn't parse line number in error: "+e),void console.log(t);for(var r=+n[1],o=t.split("\n"),a=o.length.toString().length+2,i=o.map(function(t,e){return E((e+1).toString(),a)+t;}),s=0,u=0;u<i.length;u++)s=Math.max(i[u].length,s);var l=i.slice(0,r-1),c=i.slice(r-1,r),h=i.slice(r);console.log(l.join("\n")),console.log(e.split("\n")[0]),console.log("%c "+E(c[0],s),"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(h.join("\n"));}(n,t.getShaderInfoLog(r)),new Error("Failed to compile fragment shader.");return r;}var $t,jt,Kt=/ERROR: [0-9]+:([0-9]+):/g;function Xt(t,e){return pe(t,e,function(){return t.createProgram();},"Unable to create WebGLProgram.");}function Yt(t,e,n){if(Lt(t,e,function(){return t.linkProgram(n);}),!1===t.getProgramParameter(n,t.LINK_STATUS))throw console.log(t.getProgramInfoLog(n)),new Error("Failed to link vertex and fragment shaders.");}function Qt(t,e,n){if(Lt(t,e,function(){return t.validateProgram(n);}),!1===t.getProgramParameter(n,t.VALIDATE_STATUS))throw console.log(t.getProgramInfoLog(n)),new Error("Shader program validation failed.");}function Jt(t,e,n){var r=pe(t,e,function(){return t.createBuffer();},"Unable to create WebGLBuffer");return Lt(t,e,function(){return t.bindBuffer(t.ARRAY_BUFFER,r);}),Lt(t,e,function(){return t.bufferData(t.ARRAY_BUFFER,n,t.STATIC_DRAW);}),r;}function Zt(t,e,n){var r=pe(t,e,function(){return t.createBuffer();},"Unable to create WebGLBuffer");return Lt(t,e,function(){return t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,r);}),Lt(t,e,function(){return t.bufferData(t.ELEMENT_ARRAY_BUFFER,n,t.STATIC_DRAW);}),r;}function te(t,e){return pe(t,e,function(){return t.createTexture();},"Unable to create WebGLTexture.");}function ee(t,e){var n=exports.ENV.getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t<=0||e<=0){var r="["+t+"x"+e+"]";throw new Error("Requested texture size "+r+" is invalid.");}if(t>n||e>n){r="["+t+"x"+e+"]";throw new Error("Requested texture size "+r+" greater than WebGL maximum on this browser / GPU "+("["+n+"x"+n+"]")+".");}}function ne(t,e){return pe(t,e,function(){return t.createFramebuffer();},"Unable to create WebGLFramebuffer.");}function re(t,e,n,r,o,a,i,s){var u=t.getAttribLocation(n,r);return-1!==u&&(Lt(t,e,function(){return t.bindBuffer(t.ARRAY_BUFFER,o);}),Lt(t,e,function(){return t.vertexAttribPointer(u,a,t.FLOAT,!1,i,s);}),Lt(t,e,function(){return t.enableVertexAttribArray(u);}),!0);}function oe(t,e,n,r){fe(t,r),Lt(t,e,function(){return t.activeTexture(t.TEXTURE0+r);}),Lt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,n);});}function ae(t,e,n,r){return pe(t,e,function(){return t.getUniformLocation(n,r);},'uniform "'+r+'" not present in program.');}function ie(t,e,n){return t.getUniformLocation(e,n);}function se(t,e,n,r,o,a){Lt(t,e,function(){return oe(t,e,r,a);}),Lt(t,e,function(){return t.uniform1i(o,a);});}function ue(t,e,n,r){Lt(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,r);}),Lt(t,e,function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0);});}function le(t,e,n){Lt(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,n);}),Lt(t,e,function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,null,0);});}function ce(t){var e=t.checkFramebufferStatus(t.FRAMEBUFFER);if(e!==t.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+he(t,e));}function he(t,e){switch(e){case t.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case t.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case t.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case t.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return"unknown error "+e;}}function pe(t,e,n,r){var o=Lt(t,e,function(){return n();});if(null==o)throw new Error(r);return o;}function fe(t,e){var n=t.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=e+t.TEXTURE0;if(r<t.TEXTURE0||r>n)throw new Error("textureUnit must be in "+("[gl.TEXTURE0, gl.TEXTURE"+n+"]")+".");}function de(t,e){return void 0===e&&(e=2),y(t.slice(0,t.length-e));}function ve(t){if(0===t.length)throw Error("Cannot get rows and columns of an empty shape array.");return[t.length>1?t[t.length-2]:1,t[t.length-1]];}function me(t){var e=[1,1,1];return 0===t.length||1===t.length&&1===t[0]||(e=[de(t)].concat(ve(t))),e;}function ge(t,e){var n;void 0===e&&(e=!1);var r=exports.ENV.getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e&&(r*=2,1===(t=t.map(function(e,n){return n>=t.length-2?p(t[n]):t[n];})).length&&(t=[2,t[0]])),2!==t.length){var o=N(t);t=o.newShape;}var a=y(t);if(t.length<=1&&a<=r)return[1,a];if(2===t.length&&t[0]<=r&&t[1]<=r)return t;if(3===t.length&&t[0]*t[1]<=r&&t[2]<=r)return[t[0]*t[1],t[2]];if(3===t.length&&t[0]<=r&&t[1]*t[2]<=r)return[t[0],t[1]*t[2]];if(4===t.length&&t[0]*t[1]*t[2]<=r&&t[3]<=r)return[t[0]*t[1]*t[2],t[3]];if(4===t.length&&t[0]<=r&&t[1]*t[2]*t[3]<=r)return[t[0],t[1]*t[2]*t[3]];if(e){var i=de(t),u=2,l=2;return t.length&&(u=(n=ve(t))[0],l=n[1]),C(a=i*(u/2)*(l/2)).map(function(t){return 2*t;});}return C(a);}function ye(t){return t%2==0;}function xe(t,e){if(x(t=t.slice(-2),e=e.slice(-2)))return!0;if(!t.length||!e.length)return!0;if(0===t[0]||0===t[1]||0===e[0]||0===e[1])return!0;if(t.length!==e.length){var n=t.slice(-1)[0],r=e.slice(-1)[0];if(n===r)return!0;if(ye(n)&&ye(r)&&(1===t[0]||1===e[0]))return!0;}return t[1]===e[1]&&ye(t[0])&&ye(e[0]);}function be(t){if(null==$t){var e=Bt(t);$t=e.getParameter(e.MAX_TEXTURE_SIZE);}return $t;}function we(t){if(null==jt){var e=Bt(t);jt=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS);}return Math.min(16,jt);}function Ce(t){if(0===t)return 0;var e=Bt(t);return Ee(e,"EXT_disjoint_timer_query_webgl2")&&2===t?2:Ee(e,"EXT_disjoint_timer_query")?1:0;}function Ee(t,e){return null!=t.getExtension(e);}function Re(t){try{if(null!=Bt(t))return!0;}catch(t){return!1;}return!1;}function Ie(t){if(0===t)return!1;var e=Bt(t);if(1===t){if(!Ee(e,"OES_texture_float"))return!1;}else if(!Ee(e,"EXT_color_buffer_float"))return!1;return Ne(e,t);}function Se(t){if(0===t)return!1;var e=Bt(t);if(1===t){if(!Ee(e,"OES_texture_float"))return!1;if(!Ee(e,"WEBGL_color_buffer_float"))return!1;}else if(!Ee(e,"EXT_color_buffer_float"))return!1;return Ne(e,t);}function Ne(t,e){var n=t.createFramebuffer(),r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r);var o=2===e?t.RGBA32F:t.RGBA;t.texImage2D(t.TEXTURE_2D,0,o,1,1,0,t.RGBA,t.FLOAT,null),t.bindFramebuffer(t.FRAMEBUFFER,n),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,r,0);var a=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;return t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteTexture(r),t.deleteFramebuffer(n),a;}function ke(t){return 2===t&&null!=Bt(t).fenceSync;}var Ae=Object.freeze({callAndCheck:Lt,canBeRepresented:zt,getWebGLErrorMessage:Vt,getExtensionOrThrow:Gt,createVertexShader:qt,createFragmentShader:Ht,createProgram:Xt,linkProgram:Yt,validateProgram:Qt,createStaticVertexBuffer:Jt,createStaticIndexBuffer:Zt,getNumChannels:function(){return 2===exports.ENV.getNumber("WEBGL_VERSION")?1:4;},createTexture:te,validateTextureSize:ee,createFramebuffer:ne,bindVertexBufferToProgramAttribute:re,bindTextureUnit:oe,unbindTextureUnit:function(t,e,n){fe(t,n),Lt(t,e,function(){return t.activeTexture(t.TEXTURE0+n);}),Lt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null);});},getProgramUniformLocationOrThrow:ae,getProgramUniformLocation:ie,bindTextureToProgramUniformSampler:se,bindCanvasToFramebuffer:function(t,e){Lt(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,null);}),Lt(t,e,function(){return t.viewport(0,0,t.canvas.width,t.canvas.height);}),Lt(t,e,function(){return t.scissor(0,0,t.canvas.width,t.canvas.height);});},bindColorTextureToFramebuffer:ue,unbindColorTextureFromFramebuffer:le,validateFramebuffer:ce,getFramebufferErrorMessage:he,getBatchDim:de,getRowsCols:ve,getShapeAs3D:me,getTextureShapeFromLogicalShape:ge,isReshapeFree:xe,get MAX_TEXTURE_SIZE(){return $t;},get MAX_TEXTURES_IN_SHADER(){return jt;},getWebGLMaxTextureSize:be,getMaxTexturesInShader:we,getWebGLDisjointQueryTimerVersion:Ce,isWebGLVersionEnabled:Re,isRenderToFloatTextureEnabled:Ie,isDownloadFloatTextureEnabled:Se,isWebGLFenceEnabled:ke});function Te(){exports.ENV.set("PROD",!0);}function De(){exports.ENV.set("DEBUG",!0);}function _e(){exports.ENV.set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.");}function Oe(t){exports.ENV.getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(t+" You can disable deprecation warnings with tf.disableDeprecationWarnings().");}function Me(){Dt.disposeVariables();}function Fe(){return Dt.memory();}function Be(t){return Dt.profile(t);}function Pe(t,e){return Dt.tidy(t,e);}function Le(t){St(t).forEach(function(t){return t.dispose();});}function We(t){return Dt.keep(t);}function Ue(t){return Dt.time(t);}function ze(t){return Dt.setBackend(t);}function Ve(){return Dt.ready();}function Ge(){return Dt.backendName;}function qe(t){Dt.removeBackend(t);}function He(t){return Dt.findBackend(t);}function $e(t){return Dt.findBackendFactory(t);}function je(t,e,n){return void 0===n&&(n=1),Dt.registerBackend(t,e,n);}function Ke(){return Dt.backend;}function Xe(t,e){exports.ENV.setPlatform(t,e);}function Ye(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];exports.ENV.getBool("IS_TEST")||console.warn.apply(console,t);}function Qe(t,e){var n=t;if(M(t))return"string"===e?[]:[t.length];if(!Array.isArray(t))return[];for(var r=[];Array.isArray(n)||M(n)&&"string"!==e;)r.push(n.length),n=n[0];return Array.isArray(t)&&exports.ENV.getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&function t(e,n,r){r=r||[];if(!Array.isArray(e)&&!M(e))return void d(0===n.length,function(){return"Element arr["+r.join("][")+"] is a primitive, but should be an array/TypedArray of "+n[0]+" elements";});d(n.length>0,function(){return"Element arr["+r.join("][")+"] should be a primitive, but is an array of "+e.length+" elements";});d(e.length===n[0],function(){return"Element arr["+r.join("][")+"] should have "+n[0]+" elements, but has "+e.length+" elements";});var o=n.slice(1);for(var a=0;a<e.length;++a)t(e[a],o,r.concat(a));}(t,r,[]),r;}function Je(t,e,n,r){if(null!=t&&("numeric"!==t&&t!==e||"numeric"===t&&"string"===e))throw new Error("Argument '"+n+"' passed to '"+r+"' must be "+t+" tensor, but got "+e+" tensor");}function Ze(t,e,n,r){if(void 0===r&&(r="numeric"),t instanceof ft)return Je(r,t.dtype,e,n),t;var o=U(t);if("string"!==o&&["bool","int32","float32"].indexOf(r)>=0&&(o=r),Je(r,o,e,n),null==t||!M(t)&&!Array.isArray(t)&&"number"!=typeof t&&"boolean"!=typeof t&&"string"!=typeof t){var a=null==t?"null":t.constructor.name;throw new Error("Argument '"+e+"' passed to '"+n+"' must be a Tensor or TensorLike, but got '"+a+"'");}var i=Qe(t,o);M(t)||Array.isArray(t)||(t=[t]);var u="string"!==o?q(t,o,exports.ENV.getBool("DEBUG")):g(t,[],!0);return ft.make(i,{values:u},o);}function tn(t,e,n,r){if(void 0===r&&(r="numeric"),!Array.isArray(t))throw new Error("Argument "+e+" passed to "+n+" must be a `Tensor[]` or `TensorLike[]`");return t.map(function(t,r){return Ze(t,e+"["+r+"]",n);},r);}function en(t,e){for(var n=0;n<t.length;++n)if(t[t.length-n-1]!==e-1-n)return!1;return!0;}function nn(t,e,n){for(var r=t.length+e.length,o=[],a=0,i=0,s=0;s<r;s++)-1===n.indexOf(s)?o.push(t[a++]):o.push(e[i++]);return o;}function rn(t,e){for(var n=[],r=t.length,o=0;o<r;o++)-1===e.indexOf(o)&&n.push(t[o]);return[n,e.map(function(e){return t[e];})];}function on(t,e){return nn(t,e.map(function(t){return 1;}),e);}function an(t,e,n){d(en(e,n),function(){return t+" supports only inner-most axes for now. Got axes "+e+" and rank-"+n+" input.";});}function sn(t,e){if(en(t,e))return null;for(var n=[],r=0;r<e;++r)-1===t.indexOf(r)&&n.push(r);return t.forEach(function(t){return n.push(t);}),n;}function un(t){return t.map(function(t,e){return[e,t];}).sort(function(t,e){return t[1]-e[1];}).map(function(t){return t[0];});}function ln(t,e){for(var n=[],r=e-t;r<e;++r)n.push(r);return n;}function cn(t,e){var n=t[0].length;t.forEach(function(t,e){d(t.length===n,function(){return"Error in concat"+n+"D: rank of tensors["+e+"] must be the same as the rank of the rest ("+n+")";});}),d(e>=0&&e<n,function(){return"Error in concat"+n+"D: axis must be between 0 and "+(n-1)+".";});var r=t[0];t.forEach(function(t,o){for(var a=0;a<n;a++)d(a===e||t[a]===r[a],function(){return"Error in concat"+n+"D: Shape of tensors["+o+"] ("+t+") does not match the shape of the rest ("+r+") along the non-concatenated axis "+o+".";});});}function hn(t,e){for(var n=t[0].slice(),r=1;r<t.length;r++)n[e]+=t[r][e];return n;}function pn(t){var e=Object.keys(t);if(1!==e.length)throw new Error("Please provide an object with a single key (operation name) mapping to a function. Got an object with "+e.length+" keys.");var n=e[0],r=t[n];n.endsWith("_")&&(n=n.substring(0,n.length-1));var o=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];Dt.startScope(n);try{var o=r.apply(void 0,t);return o instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),Dt.endScope(o),o;}catch(t){throw Dt.endScope(null),t;}};return Object.defineProperty(o,"name",{value:n,configurable:!0}),o;}exports.ENV.registerFlag("HAS_WEBGL",function(){return exports.ENV.getNumber("WEBGL_VERSION")>0;}),exports.ENV.registerFlag("WEBGL_VERSION",function(){return Re(2)?2:Re(1)?1:0;}),exports.ENV.registerFlag("WEBGL_BUFFER_SUPPORTED",function(){return 2===exports.ENV.get("WEBGL_VERSION");}),exports.ENV.registerFlag("WEBGL_CPU_FORWARD",function(){return!0;}),exports.ENV.registerFlag("WEBGL_PACK",function(){return exports.ENV.getBool("HAS_WEBGL");}),exports.ENV.registerFlag("WEBGL_PACK_NORMALIZATION",function(){return exports.ENV.getBool("WEBGL_PACK");}),exports.ENV.registerFlag("WEBGL_PACK_CLIP",function(){return exports.ENV.getBool("WEBGL_PACK");}),exports.ENV.registerFlag("WEBGL_PACK_DEPTHWISECONV",function(){return!1;}),exports.ENV.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",function(){return exports.ENV.getBool("WEBGL_PACK");}),exports.ENV.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",function(){return exports.ENV.getBool("WEBGL_PACK");}),exports.ENV.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",function(){return exports.ENV.getBool("WEBGL_PACK");}),exports.ENV.registerFlag("WEBGL_PACK_REDUCE",function(){return exports.ENV.getBool("WEBGL_PACK");}),exports.ENV.registerFlag("WEBGL_LAZILY_UNPACK",function(){return exports.ENV.getBool("WEBGL_PACK");}),exports.ENV.registerFlag("WEBGL_CONV_IM2COL",function(){return exports.ENV.getBool("WEBGL_PACK");}),exports.ENV.registerFlag("WEBGL_MAX_TEXTURE_SIZE",function(){return be(exports.ENV.getNumber("WEBGL_VERSION"));}),exports.ENV.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",function(){return we(exports.ENV.getNumber("WEBGL_VERSION"));}),exports.ENV.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",function(){var t=exports.ENV.getNumber("WEBGL_VERSION");return 0===t?0:Ce(t);}),exports.ENV.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",function(){return exports.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&(t=navigator.userAgent||navigator.vendor||window.opera,!(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4))));var t;}),exports.ENV.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",function(){return Ie(exports.ENV.getNumber("WEBGL_VERSION"));}),exports.ENV.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",function(){return Se(exports.ENV.getNumber("WEBGL_VERSION"));}),exports.ENV.registerFlag("WEBGL_FENCE_API_ENABLED",function(){return ke(exports.ENV.getNumber("WEBGL_VERSION"));}),exports.ENV.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",function(){return exports.ENV.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0;}),pt=Oe;var fn=pn({complex_:function(t,e){var n=Ze(t,"real","complex"),r=Ze(e,"imag","complex");return v(n.shape,r.shape,"real and imag shapes, "+n.shape+" and "+r.shape+", must match in call to tf.complex()."),Dt.runKernel(function(t){return t.complex(n,r);},{$real:n,$imag:r});}}),dn=pn({real_:function(t){var e=Ze(t,"input","real");return Dt.runKernel(function(t){return t.real(e);},{$input:e});}}),vn=pn({imag_:function(t){var e=Ze(t,"input","imag");return Dt.runKernel(function(t){return t.imag(e);},{$input:e});}});function mn(t,e,n){return gn(t,e,Qe(t,n),n);}function gn(t,e,n,r){if(null==r&&(r=U(t)),"complex64"===r)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!M(t)&&!Array.isArray(t)&&"number"!=typeof t&&"boolean"!=typeof t&&"string"!=typeof t)throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(null!=e){X(e);var o=y(e),a=y(n);d(o===a,function(){return"Based on the provided shape, ["+e+"], the tensor should have "+o+" values but has "+a;});for(var i=0;i<n.length;++i){var u=n[i],l=i!==n.length-1||u!==y(e.slice(i));d(n[i]===e[i]||!l,function(){return"Error creating a new Tensor. Inferred shape ("+n+") does not match the provided shape ("+e+"). ";});}}return M(t)||Array.isArray(t)||(t=[t]),e=e||n,t="string"!==r?q(t,r,exports.ENV.getBool("DEBUG")):g(t,[],!0),ft.make(e,{values:t},r);}function yn(t,e){if((M(t)&&"string"!==e||Array.isArray(t))&&"complex64"!==e)throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if("string"===e&&M(t)&&!(t instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return gn(t,[],[],e);}function xn(t,e){m(t);var n=Qe(t,e);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return gn(t,null,n,e);}function bn(t,e,n){if(m(t),null!=e&&2!==e.length)throw new Error("tensor2d() requires shape to have two numbers");var r=Qe(t,n);if(2!==r.length&&1!==r.length)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return gn(t,e,r,n);}function wn(t,e,n){if(m(t),null!=e&&3!==e.length)throw new Error("tensor3d() requires shape to have three numbers");var r=Qe(t,n);if(3!==r.length&&1!==r.length)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return gn(t,e,r,n);}function Cn(t,e,n){if(m(t),null!=e&&4!==e.length)throw new Error("tensor4d() requires shape to have four numbers");var r=Qe(t,n);if(4!==r.length&&1!==r.length)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return gn(t,e,r,n);}function En(t,e,n){if(m(t),null!=e&&5!==e.length)throw new Error("tensor5d() requires shape to have five numbers");var r=Qe(t,n);if(5!==r.length&&1!==r.length)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return gn(t,e,r,n);}function Rn(t,e,n){if(m(t),null!=e&&6!==e.length)throw new Error("tensor6d() requires shape to have six numbers");var r=Qe(t,n);if(6!==r.length&&1!==r.length)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(1===r.length&&null==e)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return gn(t,e=e||r,r,n);}function In(t,e){if(void 0===e&&(e="float32"),"complex64"===e){var n=In(t,"float32"),r=Sn(t,"float32");return fn(n,r);}var o=$(y(t),e);return ft.make(t,{values:o},e);}function Sn(t,e){if(void 0===e&&(e="float32"),"complex64"===e){var n=Sn(t,"float32"),r=Sn(t,"float32");return fn(n,r);}var o=j(y(t),e);return ft.make(t,{values:o},e);}function Nn(t,e,n){return Dt.runKernel(function(r){return r.fill(t,e,n);},{});}function kn(t,e,n){if(n<=0)throw new Error("The number of values should be positive.");return Dt.runKernel(function(r){return r.linspace(t,e,n);},{});}function An(t,e,n,r){if(void 0===n&&(n=1),void 0===r&&(r="float32"),0===n)throw new Error("Cannot have a step of zero");if(t===e||t<e&&n<0||e<t&&n>1)return Sn([0],r);var o=j(Math.abs(Math.ceil((e-t)/n)),r);e<t&&1===n&&(n=-1),o[0]=t;for(var a=1;a<o.length;a++)o[a]=o[a-1]+n;return xn(o,r);}var Tn=pn({onesLike_:function(t){var e=Ze(t,"x","onesLike");if("complex64"===e.dtype){var n=Tn(dn(e)),r=Dn(vn(e));return fn(n,r);}return Dt.runKernel(function(t){return t.onesLike(e);},{$x:e},function(t,e){return{$x:function(){return Dn(t);}};});}}),Dn=pn({zerosLike_:function(t){var e=Ze(t,"x","zerosLike");return Dt.runKernel(function(t){return t.zerosLike(e);},{$x:e},function(t,e){return{$x:function(){return Dn(t);}};});}});var _n=pn({concat_:function(t,e){void 0===e&&(e=0),d(t.length>=1,function(){return"Pass at least one tensor to concat";});var n=tn(t,"tensors","concat");e=S(e,n[0].shape)[0];var r=hn(n.map(function(t){return t.shape;}),e);if(0===y(r))return mn([],r);if(1===(n=n.filter(function(t){return t.size>0;})).length)return n[0];var o=n.map(function(t){return t.shape;});cn(o,e);var a=n;return Dt.runKernel(function(t){return t.concat(n,e);},a,function(t){var n=o.map(function(t){return t[e];});return Pn(t,n,e).map(function(t){return function(){return t;};});});}}),On=pn({concat1d_:function(t){return _n(t,0);}}),Mn=pn({concat2d_:function(t,e){return _n(t,e);}}),Fn=pn({concat3d_:function(t,e){return _n(t,e);}}),Bn=pn({concat4d_:function(t,e){return _n(t,e);}}),Pn=pn({split_:function(t,e,n){void 0===n&&(n=0);var r,o=Ze(t,"x","split");return n=S(n,o.shape)[0],"number"==typeof e?(d(o.shape[n]%e==0,function(){return"Number of splits must evenly divide the axis.";}),r=new Array(e).fill(o.shape[n]/e)):(d(o.shape[n]===e.reduce(function(t,e){return t+e;}),function(){return"The sum of sizes must match the size of the axis dimension.";}),r=e),Dt.runKernel(function(t){return t.split(o,r,n);},{$x:o},function(t){return{$x:function(){return _n(t,n);}};});}});function Ln(t,e){return t(e={exports:{}},e.exports),e.exports;}var Wn=Ln(function(t){!function(t,e,n){function r(t){var e,n=this,r=(e=4022871197,function(t){t=t.toString();for(var n=0;n<t.length;n++){var r=.02519603282416938*(e+=t.charCodeAt(n));r-=e=r>>>0,e=(r*=e)>>>0,e+=4294967296*(r-=e);}return 2.3283064365386963e-10*(e>>>0);});n.next=function(){var t=2091639*n.s0+2.3283064365386963e-10*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=t-(n.c=0|t);},n.c=1,n.s0=r(" "),n.s1=r(" "),n.s2=r(" "),n.s0-=r(t),n.s0<0&&(n.s0+=1),n.s1-=r(t),n.s1<0&&(n.s1+=1),n.s2-=r(t),n.s2<0&&(n.s2+=1),r=null;}function o(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e;}function a(t,e){var n=new r(t),a=e&&e.state,i=n.next;return i.int32=function(){return 4294967296*n.next()|0;},i.double=function(){return i()+1.1102230246251565e-16*(2097152*i()|0);},i.quick=i,a&&("object"==typeof a&&o(a,n),i.state=function(){return o(n,{});}),i;}e&&e.exports?e.exports=a:n&&n.amd?n(function(){return a;}):this.alea=a;}(0,t,!1);}),Un=Ln(function(t){!function(t,e,n){function r(t){var e=this,n="";e.x=0,e.y=0,e.z=0,e.w=0,e.next=function(){var t=e.x^e.x<<11;return e.x=e.y,e.y=e.z,e.z=e.w,e.w^=e.w>>>19^t^t>>>8;},t===(0|t)?e.x=t:n+=t;for(var r=0;r<n.length+64;r++)e.x^=0|n.charCodeAt(r),e.next();}function o(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e;}function a(t,e){var n=new r(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296;};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);}while(0===t);return t;},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&o(a,n),i.state=function(){return o(n,{});}),i;}e&&e.exports?e.exports=a:n&&n.amd?n(function(){return a;}):this.xor128=a;}(0,t,!1);}),zn=Ln(function(t){!function(t,e,n){function r(t){var e=this,n="";e.next=function(){var t=e.x^e.x>>>2;return e.x=e.y,e.y=e.z,e.z=e.w,e.w=e.v,(e.d=e.d+362437|0)+(e.v=e.v^e.v<<4^t^t<<1)|0;},e.x=0,e.y=0,e.z=0,e.w=0,e.v=0,t===(0|t)?e.x=t:n+=t;for(var r=0;r<n.length+64;r++)e.x^=0|n.charCodeAt(r),r==n.length&&(e.d=e.x<<10^e.x>>>4),e.next();}function o(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e.v=t.v,e.d=t.d,e;}function a(t,e){var n=new r(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296;};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);}while(0===t);return t;},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&o(a,n),i.state=function(){return o(n,{});}),i;}e&&e.exports?e.exports=a:n&&n.amd?n(function(){return a;}):this.xorwow=a;}(0,t,!1);}),Vn=Ln(function(t){!function(t,e,n){function r(t){var e=this;e.next=function(){var t,n,r=e.x,o=e.i;return t=r[o],n=(t^=t>>>7)^t<<24,n^=(t=r[o+1&7])^t>>>10,n^=(t=r[o+3&7])^t>>>3,n^=(t=r[o+4&7])^t<<7,t=r[o+7&7],n^=(t^=t<<13)^t<<9,r[o]=n,e.i=o+1&7,n;},function(t,e){var n,r=[];if(e===(0|e))r[0]=e;else for(e=""+e,n=0;n<e.length;++n)r[7&n]=r[7&n]<<15^e.charCodeAt(n)+r[n+1&7]<<13;for(;r.length<8;)r.push(0);for(n=0;n<8&&0===r[n];++n);for(8==n?r[7]=-1:r[n],t.x=r,t.i=0,n=256;n>0;--n)t.next();}(e,t);}function o(t,e){return e.x=t.x.slice(),e.i=t.i,e;}function a(t,e){null==t&&(t=+new Date());var n=new r(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296;};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);}while(0===t);return t;},i.int32=n.next,i.quick=i,a&&(a.x&&o(a,n),i.state=function(){return o(n,{});}),i;}e&&e.exports?e.exports=a:n&&n.amd?n(function(){return a;}):this.xorshift7=a;}(0,t,!1);}),Gn=Ln(function(t){!function(t,e,n){function r(t){var e=this;e.next=function(){var t,n,r=e.w,o=e.X,a=e.i;return e.w=r=r+1640531527|0,n=o[a+34&127],t=o[a=a+1&127],n^=n<<13,t^=t<<17,n^=n>>>15,t^=t>>>12,n=o[a]=n^t,e.i=a,n+(r^r>>>16)|0;},function(t,e){var n,r,o,a,i,s=[],u=128;for(e===(0|e)?(r=e,e=null):(e+="\0",r=0,u=Math.max(u,e.length)),o=0,a=-32;a<u;++a)e&&(r^=e.charCodeAt((a+32)%e.length)),0===a&&(i=r),r^=r<<10,r^=r>>>15,r^=r<<4,r^=r>>>13,a>=0&&(i=i+1640531527|0,o=0==(n=s[127&a]^=r+i)?o+1:0);for(o>=128&&(s[127&(e&&e.length||0)]=-1),o=127,a=512;a>0;--a)r=s[o+34&127],n=s[o=o+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[o]=r^n;t.w=i,t.X=s,t.i=o;}(e,t);}function o(t,e){return e.i=t.i,e.w=t.w,e.X=t.X.slice(),e;}function a(t,e){null==t&&(t=+new Date());var n=new r(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296;};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);}while(0===t);return t;},i.int32=n.next,i.quick=i,a&&(a.X&&o(a,n),i.state=function(){return o(n,{});}),i;}e&&e.exports?e.exports=a:n&&n.amd?n(function(){return a;}):this.xor4096=a;}(0,t,!1);}),qn=Ln(function(t){!function(t,e,n){function r(t){var e=this,n="";e.next=function(){var t=e.b,n=e.c,r=e.d,o=e.a;return t=t<<25^t>>>7^n,n=n-r|0,r=r<<24^r>>>8^o,o=o-t|0,e.b=t=t<<20^t>>>12^n,e.c=n=n-r|0,e.d=r<<16^n>>>16^o,e.a=o-t|0;},e.a=0,e.b=0,e.c=-1640531527,e.d=1367130551,t===Math.floor(t)?(e.a=t/4294967296|0,e.b=0|t):n+=t;for(var r=0;r<n.length+20;r++)e.b^=0|n.charCodeAt(r),e.next();}function o(t,e){return e.a=t.a,e.b=t.b,e.c=t.c,e.d=t.d,e;}function a(t,e){var n=new r(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296;};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21);}while(0===t);return t;},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&o(a,n),i.state=function(){return o(n,{});}),i;}e&&e.exports?e.exports=a:n&&n.amd?n(function(){return a;}):this.tychei=a;}(0,t,!1);}),Hn=Ln(function(t){!function(e,n){var r,o=this,a=256,i=6,s="random",u=n.pow(a,i),l=n.pow(2,52),c=2*l,h=a-1;function p(t,h,p){var g=[],y=v(function t(e,n){var r,o=[],a=typeof e;if(n&&"object"==a)for(r in e)try{o.push(t(e[r],n-1));}catch(t){}return o.length?o:"string"==a?e:e+"\0";}((h=1==h?{entropy:!0}:h||{}).entropy?[t,m(e)]:null==t?function(){try{var t;return r&&(t=r.randomBytes)?t=t(a):(t=new Uint8Array(a),(o.crypto||o.msCrypto).getRandomValues(t)),m(t);}catch(t){var n=o.navigator,i=n&&n.plugins;return[+new Date(),o,i,o.screen,m(e)];}}():t,3),g),x=new f(g),b=function(){for(var t=x.g(i),e=u,n=0;t<l;)t=(t+n)*a,e*=a,n=x.g(1);for(;t>=c;)t/=2,e/=2,n>>>=1;return(t+n)/e;};return b.int32=function(){return 0|x.g(4);},b.quick=function(){return x.g(4)/4294967296;},b.double=b,v(m(x.S),e),(h.pass||p||function(t,e,r,o){return o&&(o.S&&d(o,x),t.state=function(){return d(x,{});}),r?(n[s]=t,e):t;})(b,y,"global"in h?h.global:this==n,h.state);}function f(t){var e,n=t.length,r=this,o=0,i=r.i=r.j=0,s=r.S=[];for(n||(t=[n++]);o<a;)s[o]=o++;for(o=0;o<a;o++)s[o]=s[i=h&i+t[o%n]+(e=s[o])],s[i]=e;(r.g=function(t){for(var e,n=0,o=r.i,i=r.j,s=r.S;t--;)e=s[o=h&o+1],n=n*a+s[h&(s[o]=s[i=h&i+e])+(s[i]=e)];return r.i=o,r.j=i,n;})(a);}function d(t,e){return e.i=t.i,e.j=t.j,e.S=t.S.slice(),e;}function v(t,e){for(var n,r=t+"",o=0;o<r.length;)e[h&o]=h&(n^=19*e[h&o])+r.charCodeAt(o++);return m(e);}function m(t){return String.fromCharCode.apply(0,t);}if(n["seed"+s]=p,v(n.random(),e),t.exports){t.exports=p;try{r=require("crypto");}catch(t){}}}([],Math);});Hn.alea=Wn,Hn.xor128=Un,Hn.xorwow=zn,Hn.xorshift7=Vn,Hn.xor4096=Gn,Hn.tychei=qn;var $n=Hn.alea,jn=function(){function t(t,e,n,r,o){this.mean=t,this.stdDev=e,this.dtype=n,this.nextVal=NaN,this.truncated=r,this.truncated&&(this.upper=this.mean+2*this.stdDev,this.lower=this.mean-2*this.stdDev);var a=o||Math.random();this.random=$n(a.toString());}return t.prototype.nextValue=function(){if(!isNaN(this.nextVal)){var t=this.nextVal;return this.nextVal=NaN,t;}for(var e,n,r=!1;!r;){var o=void 0,a=void 0,i=void 0;do{i=(o=2*this.random()-1)*o+(a=2*this.random()-1)*a;}while(i>=1||0===i);var s=Math.sqrt(-2*Math.log(i)/i);e=this.mean+this.stdDev*o*s,n=this.mean+this.stdDev*a*s,this.truncated&&!this.isValidTruncated(e)||(r=!0);}return this.truncated&&!this.isValidTruncated(n)||(this.nextVal=this.convertValue(n)),this.convertValue(e);},t.prototype.convertValue=function(t){return null==this.dtype||"float32"===this.dtype?t:Math.round(t);},t.prototype.isValidTruncated=function(t){return t<=this.upper&&t>=this.lower;},t;}(),Kn=function(){function t(t,e,n,r){void 0===t&&(t=0),void 0===e&&(e=1);var o=this;if(this.canReturnFloat=function(){return null==o.dtype||"float32"===o.dtype;},this.min=t,this.range=e-t,this.dtype=n,null==r&&(r=Math.random()),"number"==typeof r&&(r=r.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error("The difference between "+t+" - "+e+" <= 1 and dtype is not float");this.random=$n(r);}return t.prototype.convertValue=function(t){return this.canReturnFloat()?t:Math.round(t);},t.prototype.nextValue=function(){return this.convertValue(this.min+this.range*this.random());},t;}();function Xn(t,e,n){return void 0===e&&(e="float32"),e=e||"float32",X(t),new lt(t,e,n);}function Yn(t,e){void 0===e&&(e=!1),console.log(t.toString(e));}var Qn=pn({batchToSpaceND_:function(t,e,n){var r=Ze(t,"x","batchToSpaceND"),o=e.reduce(function(t,e){return t*e;});return d(r.rank>=1+e.length,function(){return"input rank is "+r.rank+" but should be > than blockShape.length "+e.length;}),d(n.length===e.length,function(){return"crops.length is "+n.length+" but should be equal to blockShape.length  "+e.length;}),d(r.shape[0]%o==0,function(){return"input tensor batch is "+r.shape[0]+" but is not divisible by the product of the elements of blockShape "+e.join(" * ")+" === "+o;}),Dt.runKernel(function(t){return t.batchToSpaceND(r,e,n);},{$x:r},function(t){return{$x:function(){return t.spaceToBatchND(e,n);}};});}}),Jn=pn({cast_:function(t,e){var n=Ze(t,"x","cast");if(!_(e))throw new Error("Failed to cast to unknown dtype "+e);if("string"===e&&"string"!==n.dtype||"string"!==e&&"string"===n.dtype)throw new Error("Only strings can be casted to strings");return Dt.runKernel(function(t){return t.cast(n,e);},{$x:n},function(t){return{$x:function(){return t.clone();}};});}}),Zn=pn({clone_:function(t){var e=Ze(t,"x","clone",null);return Dt.runKernel(function(t){return ft.make(e.shape,{dataId:e.dataId},e.dtype);},{$x:e},function(t){return{$x:function(){return t.toFloat();}};});}}),tr=pn({cumsum_:function(t,e,n,r){void 0===e&&(e=0),void 0===n&&(n=!1),void 0===r&&(r=!1);var o=Ze(t,"x","cumsum"),a=sn([e|=0],o.rank),i=o;null!=a&&(i=o.transpose(a));var s=ln(1,o.rank)[0],u=Dt.runKernel(function(t){return t.cumsum(i,s,n,r);},{permutedX:i},function(t){return{permutedX:function(){return t.cumsum(e,n,!r);}};});return null!=a&&(u=u.transpose(a)),u;}}),er=pn({depthToSpace_:function(t,e,n){void 0===n&&(n="NHWC");var r=Ze(t,"x","depthToSpace"),o="NHWC"===n?r.shape[1]:r.shape[2],a="NHWC"===n?r.shape[2]:r.shape[3],i="NHWC"===n?r.shape[3]:r.shape[1];return d(o*e>=0,function(){return"Negative dimension size caused by overflow when multiplying\n      "+o+" and "+e+"  for depthToSpace with input shape\n      "+r.shape;}),d(a*e>=0,function(){return"Negative dimension size caused by overflow when multiplying\n      "+a+" and "+e+" for depthToSpace with input shape\n          "+r.shape;}),d(i%(e*e)==0,function(){return"Dimension size must be evenly divisible by "+e*e+" but is "+i+" for depthToSpace with input shape "+r.shape;}),Dt.runKernel(function(t){return t.depthToSpace(r,e,n);},{$x:r});}}),nr=pn({expandDims_:function(t,e){void 0===e&&(e=0);var n=Ze(t,"x","expandDims",null);d(e<=n.rank,function(){return"Axis must be <= rank of the tensor";});var r=n.shape.slice();return e<0&&(d(-(n.rank+1)<=e,function(){return"Axis must be in the interval ["+-(n.rank+1)+", "+n.rank+"]";}),e=n.rank+e+1),r.splice(e,0,1),dr(n,r);}}),rr=pn({eye_:function(t,e,n,r){void 0===r&&(r="float32"),null==e&&(e=t);for(var o=Xn([t,e],r),a=t<=e?t:e,i=0;i<a;++i)o.set(1,i,i);var s=o.toTensor().as2D(t,e);if(null==n)return s;if(1===n.length)return yr(nr(s,0),[n[0],1,1]);if(2===n.length)return yr(nr(nr(s,0),0),[n[0],n[1],1,1]);if(3===n.length)return yr(nr(nr(nr(s,0),0),0),[n[0],n[1],n[2],1,1]);throw new Error("eye() currently supports only 1D and 2D batchShapes, but received "+n.length+"D.");}}),or=pn({multinomial_:function(t,e,n,r){void 0===r&&(r=!1);var o=Ze(t,"logits","multinomial"),a=o.size,i=o.rank;if(a<2)throw new Error("Error in multinomial: you need at least 2 outcomes, but got "+a+".");if(i>2)throw new Error("Rank of probabilities must be 1 or 2, but is "+i);n=n||Math.random();var s=1===i?o.as2D(1,-1):o,u=Dt.runKernel(function(t){return t.multinomial(s,r,e,n);},{logits2D:s});return 1===i?u.as1D():u;}}),ar=pn({oneHot_:function(t,e,n,r){if(void 0===n&&(n=1),void 0===r&&(r=0),e<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+e);var o=Ze(t,"indices","oneHot","int32"),a=o.shape.concat([e]);return o=o.flatten(),Dt.runKernel(function(t){return t.oneHot(o,e,n,r);},{$indices:o},function(t){return{$indices:function(){return Sn(o.shape,"float32");}};}).reshape(a);}}),ir=pn({pad_:function(t,e,n){void 0===n&&(n=0);var r=Ze(t,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var o=e.map(function(t){return t[0];});return Dt.runKernel(function(t){return t.pad(r,e,n);},{$x:r},function(t){return{$x:function(){return t.slice(o,r.shape);}};});}}),sr=pn({pad1d_:function(t,e,n){return void 0===n&&(n=0),d(2===e.length,function(){return"Invalid number of paddings. Must be length of 2.";}),ir(t,[e],n);}}),ur=pn({pad2d_:function(t,e,n){return void 0===n&&(n=0),d(2===e.length&&2===e[0].length&&2===e[1].length,function(){return"Invalid number of paddings. Must be length of 2 each.";}),ir(t,e,n);}}),lr=pn({pad3d_:function(t,e,n){return void 0===n&&(n=0),d(3===e.length&&2===e[0].length&&2===e[1].length&&2===e[2].length,function(){return"Invalid number of paddings. Must be length of 2 each.";}),ir(t,e,n);}}),cr=pn({pad4d_:function(t,e,n){return void 0===n&&(n=0),d(4===e.length&&2===e[0].length&&2===e[1].length&&2===e[2].length&&2===e[3].length,function(){return"Invalid number of paddings. Must be length of 2 each.";}),ir(t,e,n);}}),hr=pn({rand_:function(t,e,n){var r=y(t),o=null;if(null==n||"float32"===n)o=new Float32Array(r);else if("int32"===n)o=new Int32Array(r);else{if("bool"!==n)throw new Error("Unknown data type "+n);o=new Uint8Array(r);}for(var a=0;a<r;a++)o[a]=e();return ft.make(t,{values:o},n);}}),pr=pn({randomNormal_:function(t,e,n,r,o){if(void 0===e&&(e=0),void 0===n&&(n=1),null!=r&&"bool"===r)throw new Error("Unsupported data type "+r);for(var a=new jn(e,n,r,!1,o),i=Xn(t,r),s=0;s<i.values.length;s++)i.values[s]=a.nextValue();return i.toTensor();}}),fr=pn({randomUniform_:function(t,e,n,r,o){void 0===e&&(e=0),void 0===n&&(n=1),void 0===r&&(r="float32");for(var a=Xn(t,r),i=new Kn(e,n,null,o),s=0;s<a.values.length;s++)a.values[s]=i.nextValue();return a.toTensor();}}),dr=pn({reshape_:function(t,e){var n=Ze(t,"x","reshape",null);return e=I(e,n.size),d(n.size===y(e),function(){return"new shape and old shape must have the same number of elements.";}),Dt.runKernel(function(t){return t.reshape(n,e);},{$x:n},function(t){return{$x:function(){return t.reshape(n.shape);}};});}}),vr=pn({spaceToBatchND_:function(t,e,n){var r=Ze(t,"x","spaceToBatchND");return d(r.rank>=1+e.length,function(){return"input rank "+r.rank+" should be > than [blockShape] "+e.length;}),d(n.length===e.length,function(){return"paddings.shape[0] "+n.length+" must be equal to [blockShape] "+e.length;}),d(r.shape.reduce(function(t,r,o){return o>0&&o<=e.length?t&&(r+n[o-1][0]+n[o-1][1])%e[o-1]==0:t;},!0),function(){return"input spatial dimensions "+r.shape.slice(1)+" with paddings "+n.toString()+" must be divisible by blockShapes "+e.toString();}),Dt.runKernel(function(t){return t.spaceToBatchND(r,e,n);},{$x:r},function(t){return{$x:function(){return t.batchToSpaceND(e,n);}};});}}),mr=pn({squeeze_:function(t,e){var n=Ze(t,"x","squeeze");return dr(n,N(n.shape,e).newShape);}}),gr=pn({stack_:function(t,e){void 0===e&&(e=0);var n=tn(t,"tensors","stack");if(d(n.length>=1,function(){return"Pass at least one tensor to tf.stack";}),1===n.length)return n[0].expandDims(e);var r=n[0].rank,o=n[0].shape,a=n[0].dtype;d(e<=r,function(){return"Axis must be <= rank of the tensor";}),n.forEach(function(t){v(o,t.shape,"All tensors passed to stack must have matching shapes");}),n.forEach(function(t){d(a===t.dtype,function(){return"All tensors passed to stack must have matching dtypes";});});var i=n.map(function(t){return t.expandDims(e);});return _n(i,e);}}),yr=pn({tile_:function(t,e){var n=Ze(t,"x","tile",null);return d(n.rank===e.length,function(){return"Error in transpose: rank of input "+n.rank+" must match length of reps "+e+".";}),Dt.runKernel(function(t,r){var o=t.tile(n,e);return r([n]),o;},{$x:n},function(t,n){var r=n[0];return{$x:function(){var n=Dn(r);if(1===r.rank)for(var o=0;o<e[0];++o)n=n.add(t.slice([o*r.shape[0]],[r.shape[0]]));else if(2===r.rank)for(o=0;o<e[0];++o)for(var a=0;a<e[1];++a)n=n.add(t.slice([o*r.shape[0],a*r.shape[1]],[r.shape[0],r.shape[1]]));else if(3===r.rank)for(o=0;o<e[0];++o)for(a=0;a<e[1];++a)for(var i=0;i<e[2];++i)n=n.add(t.slice([o*r.shape[0],a*r.shape[1],i*r.shape[2]],[r.shape[0],r.shape[1],r.shape[2]]));else{if(4!==r.rank)throw new Error("Gradient for tile operation is not implemented for rank-"+r.rank+" tensors yet.");for(o=0;o<e[0];++o)for(a=0;a<e[1];++a)for(i=0;i<e[2];++i)for(var s=0;s<e[3];++s)n=n.add(t.slice([o*r.shape[0],a*r.shape[1],i*r.shape[2],s*r.shape[3]],[r.shape[0],r.shape[1],r.shape[2],r.shape[3]]));}return n;}};});}}),xr=pn({truncatedNormal_:function(t,e,n,r,o){if(void 0===e&&(e=0),void 0===n&&(n=1),null!=r&&"bool"===r)throw new Error("Unsupported data type "+r);for(var a=new jn(e,n,r,!0,o),i=Xn(t,r),s=0;s<i.values.length;s++)i.values[s]=a.nextValue();return i.toTensor();}}),br=pn({unstack_:function(t,e){void 0===e&&(e=0),e=e||0;var n=Ze(t,"x","unstack");return d(e>=-n.shape.length&&e<n.shape.length,function(){return"Axis = "+e+" is not in [-"+n.shape.length+", "+n.shape.length+")";}),e<0&&(e+=n.shape.length),Dt.runKernel(function(t){return t.unstack(n,e);},{$x:n},function(t){return{$x:function(){return gr(t,e);}};});}}),wr=function(t,e){return r(this,void 0,void 0,function(){var n,r,a,i,s,u,l,c,h,p;return o(this,function(o){switch(o.label){case 0:return n=Ze(t,"x","setdiff1d"),r=Ze(e,"y","setdiff1d"),d(n.dtype===r.dtype,function(){return"x and y should have the same dtype, but got x ("+n.dtype+") and y ("+r.dtype+").";}),d(1===n.rank,function(){return"x should be 1D tensor, but got x ("+n.shape+").";}),d(1===r.rank,function(){return"y should be 1D tensor, but got y ("+r.shape+").";}),[4,n.data()];case 1:return a=o.sent(),[4,r.data()];case 2:for(i=o.sent(),s=new Set(i),u=0,h=0;h<a.length;h++)s.has(a[h])||u++;for(l=new lt([u],n.dtype),c=new lt([u],"int32"),h=0,p=0;h<a.length;h++)s.has(a[h])||(l.values[p]=a[h],c.values[p]=h,p++);return[2,[l.toTensor(),c.toTensor()]];}});});};function Cr(t,e,n,r){void 0===r&&(r=!0);var o=[];if(r)(o=o.concat(e.slice(0))).push(t[0]/n),o=o.concat(t.slice(1));else{o=o.concat(t[0]);for(var a=e.length,i=0;i<a;++i)o=o.concat([t[i+1]/e[i],e[i]]);o=o.concat(t.slice(a+1));}return o;}function Er(t,e,n){void 0===n&&(n=!0);var r=[];if(n){r.push(e);for(var o=e+1;o<t;++o)o<=2*e?(r.push(o),r.push(o-(e+1))):r.push(o);}else{var a=[],i=[];for(o=1;o<t;++o)o>=2*e+1||o%2==1?i.push(o):a.push(o);r.push.apply(r,a),r.push(0),r.push.apply(r,i);}return r;}function Rr(t,e,n,r){void 0===r&&(r=!0);var o=[];r?o.push(t[0]/n):o.push(t[0]*n);for(var a=1;a<t.length;++a)a<=e.length?r?o.push(e[a-1]*t[a]):o.push(t[a]/e[a-1]):o.push(t[a]);return o;}function Ir(t,e){for(var n=[0],r=0;r<e;++r)n.push(t[r][0]);return n;}function Sr(t,e,n){for(var r=t.slice(0,1),o=0;o<n;++o)r.push(t[o+1]-e[o][0]-e[o][1]);return r;}function Nr(t,e){if(t.rank<1)throw new Error("tf.gatherND() expects the input to be rank 1 or higher, but the rank was "+t.rank+".");if(e.rank<1)throw new Error("tf.gatherND() expects the indices to be rank 1 or higher, but the rank was "+e.rank+".");if("int32"!==e.dtype)throw new Error("tf.gatherND() expects the indices to be int32 type, but the dtype was "+e.dtype+".");if(e.shape[e.rank-1]>t.rank)throw new Error("index innermost dimension length must be <= tensor rank; saw: "+e.shape[e.rank-1]+" vs. "+t.rank);if(0===t.size)throw new Error("Requested more than 0 entries, but input is empty. Input shape: "+t.shape+".");for(var n=e.shape,r=n[n.length-1],o=1,a=0;a<n.length-1;++a)o*=n[a];var i=t.shape,s=n.slice();s.pop();var u=1;for(a=r;a<t.rank;++a)u*=i[a],s.push(i[a]);var l=G(t.shape).map(function(t){return t/u;}).concat([1]).slice(0,r);return[s,o,u,l];}var kr=30;function Ar(t){return t<=kr?t:V(t,Math.floor(Math.sqrt(t)));}function Tr(t,e,n){if(e.rank<1)throw new Error("tf.scatterND() expects the indices to be rank 1 or higher, but the rank was "+e.rank+".");if(t.rank<1)throw new Error("tf.scatterND() expects the updates to be rank 1 or higher, but the rank was "+t.rank+".");if("int32"!==e.dtype)throw new Error("The dtype of 'indices' should be int32, but got dtype: "+e.dtype);if(n.length<1)throw new Error("Output rank must be greater or equal to 1, but got shape: "+n);if(0===n.length){if(0===e.size)throw new Error("Indices specified for empty output. indices shape: "+e.shape);if(0===t.size)throw new Error("Updates specified for empty output. updates shape: "+t.shape);}!function(t,e,n){var r=e.rank>1?e.shape[e.rank-1]:1,o=e.rank>1?e.rank-1:1,a="Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: "+n.shape+", indices.shape: "+e.shape+", shape: "+t+", sliceDim: "+r+", and batchDim: "+o+".";if(n.rank<o)throw new Error(a+" update.rank < "+o+". ");if(t.length<r+(n.rank-o))throw new Error(a+" Output shape length < "+(r+(n.rank-o)));if(n.rank!==o+t.length-r)throw new Error(a+" update.rank != "+(o+t.length-r));for(var i=0;i<o;++i)if(n.shape[i]!==e.shape[i])throw new Error(a+" updates.shape["+i+"] ("+n.shape[i]+") != indices.shape["+i+"] ("+e.shape[i]+").");for(i=0;i<n.rank-o;++i)if(n.shape[i+o]!==t[i+r])throw new Error(a+" updates.shape["+(i+o)+"] ("+n.shape[i+o]+") != shape["+(i+o)+"] ("+t[i+o]+")");}(n,e,t);}function Dr(t,e,n){for(var r=e.rank>1?e.shape[e.rank-1]:1,o=n.length,a=1,i=r;i<o;++i)a*=n[i];var s=r<1?1:r;return{sliceRank:r,numUpdates:e.size/s,sliceSize:a,strides:G(n.slice(0,r)).concat([1]),outputSize:y(n)};}function _r(t,e,n,r,o,a,i,s,u){if(void 0===o&&(o=0),void 0===a&&(a=0),void 0===i&&(i=0),void 0===s&&(s=0),void 0===u&&(u=0),0!==i)throw new Error("ellipsis mask is not yet supported");if(0!==s)throw new Error("new axis mask is not yet supported");for(var l=[],c=[],h=[],p=0;p<t.length;p++)l[p]=Or(o,e,r,t,p),c[p]=Mr(a,n,r,t,p),u&1<<p&&(c[p]=l[p]+1,h.push(p));var f=new Array(t.length).fill(0);return f=f.map(function(t,e){for(var n=0,o=r[e]||1,a=l[e];!(o>0?a>=c[e]:a<=c[e]);a+=o)n+=1;return n;}),[l,f,h];}function Or(t,e,n,r,o){var a=e[o],i=n[o]||1;(t&1<<o||null==a)&&(a=i>0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var s=r[o];return a<0&&(a+=s),a=h(0,a,s-1);}function Mr(t,e,n,r,o){var a=e[o],i=n[o]||1;(t&1<<o||null==a)&&(a=i>0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var s=r[o];return a<0&&(a+=s),a=i>0?h(0,a,s):h(-1,a,s-1);}function Fr(t,e,n){for(var r=n.length,o=0;o<n.length;o++)if(n[o]>1){r=o;break;}for(o=r+1;o<n.length;o++)if(e[o]>0||n[o]!==t[o])return!1;return!0;}function Br(t,e){for(var n=t.length>0?t[t.length-1]:1,r=0;r<t.length-1;r++)n+=t[r]*e[r];return n;}function Pr(t){return d(z(t),function(){return"The f passed in grad(f) must be a function";}),function(e,n){var r=Ze(e,"x","tf.grad",null),o=null!=n?Ze(n,"dy","tf.grad"):null;return Dt.tidy(function(){var e=Dt.gradients(function(){return t(r);},[r],o),n=e.value,a=e.grads;return null!=o&&v(n.shape,o.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Gr(a),a[0];});};}function Lr(t){return d(z(t),function(){return"The f passed in grads(f) must be a function";}),function(e,n){d(Array.isArray(e),function(){return"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s";});var r=tn(e,"args","tf.grads",null),o=null!=n?Ze(n,"dy","tf.grads"):null;return Dt.tidy(function(){var e=Dt.gradients(function(){return t.apply(void 0,r);},r,o),n=e.value,a=e.grads;return null!=o&&v(n.shape,o.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Gr(a),a;});};}function Wr(t){return d(z(t),function(){return"The f passed in valueAndGrad(f) must be a function";}),function(e,n){d(e instanceof ft,function(){return"The x passed in valueAndGrad(f)(x) must be a tensor";}),d(null==n||n instanceof ft,function(){return"The dy passed in valueAndGrad(f)(x, dy) must be a tensor";});var r=Dt.gradients(function(){return t(e);},[e],n),o=r.grads,a=r.value;return Gr(o),{grad:o[0],value:a};};}function Ur(t){return d(z(t),function(){return"The f passed in valueAndGrads(f) must be a function";}),function(e,n){d(Array.isArray(e)&&e.every(function(t){return t instanceof ft;}),function(){return"The args passed in valueAndGrads(f)(args) must be array of tensors";}),d(null==n||n instanceof ft,function(){return"The dy passed in valueAndGrads(f)(args, dy) must be a tensor";});var r=Dt.gradients(function(){return t.apply(void 0,e);},e,n);return null!=n&&v(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Gr(r.grads),r;};}function zr(t,e){d(z(t),function(){return"The f passed in variableGrads(f) must be a function";}),d(null==e||Array.isArray(e)&&e.every(function(t){return t instanceof dt;}),function(){return"The varList passed in variableGrads(f, varList) must be an array of variables";});var n=null!=e;if(!n)for(var r in e=[],Dt.registeredVariables)e.push(Dt.registeredVariables[r]);var o=n?e.filter(function(t){return!t.trainable;}):null,a=e.length;d((e=e.filter(function(t){return t.trainable;})).length>0,function(){return"variableGrads() expects at least one of the input variables to be trainable, but none of the "+a+" variables is trainable.";});var i=Dt.gradients(t,e,null,!0),s=i.value,u=i.grads;d(u.some(function(t){return null!=t;}),function(){return"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize().";}),d(0===s.rank,function(){return"The f passed in variableGrads(f) must return a scalar, but it returned a rank-"+s.rank+" tensor";});var l={};return e.forEach(function(t,e){null!=u[e]&&(l[t.name]=u[e]);}),null!=o&&o.forEach(function(t){return l[t.name]=null;}),{value:s,grads:l};}function Vr(t){return Dt.customGrad(t);}function Gr(t){if(t.filter(function(t){return null==t;}).length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that\n    the f you passed encloses all operations that lead from x to y.");}var qr=pn({softmax_:function(t,e){void 0===e&&(e=-1);var n=Ze(t,"logits","softmax");if(-1===e&&(e=n.rank-1),e!==n.rank-1)throw Error("Softmax along a non-last dimension is not yet supported. Logits was rank "+n.rank+" and dim was "+e);return Vr(function(t,n){var r=t.logSumExp([e],!0),o=t.toFloat().sub(r).exp();return n([o]),{value:o,gradFunc:function(t,n){var r=n[0],o=t.mul(r);return o.sub(o.sum([e],!0).mul(r));}};})(n);}}),Hr=pn({logSoftmax_:function(t,e){void 0===e&&(e=-1);var n=Ze(t,"logits","logSoftmax");if(-1===e&&(e=n.rank-1),e!==n.rank-1)throw Error("Log Softmax along a non-last dimension is not yet supported. Logits was rank "+n.rank+" and axis was "+e);return Vr(function(t,n){var r=t.max(e,!0),o=t.sub(r),a=o.toFloat().sub(o.exp().sum(e,!0).log());return n([a]),{value:a,gradFunc:function(t,n){var r=n[0].exp();return t.sub(t.sum(e,!0).mul(r));}};})(n);}}),$r=function(){function t(t,e){this.backend=t,this.dataMover=e,this.data=new WeakMap();}return t.prototype.get=function(t){return this.data.has(t)||this.dataMover.moveData(this.backend,t),this.data.get(t);},t.prototype.set=function(t,e){this.data.set(t,e);},t.prototype.has=function(t){return this.data.has(t);},t.prototype.delete=function(t){return this.data.delete(t);},t;}(),jr=function(){function t(){}return t.prototype.time=function(t){throw new Error("Not yet implemented.");},t.prototype.read=function(t){throw new Error("Not yet implemented.");},t.prototype.readSync=function(t){throw new Error("Not yet implemented.");},t.prototype.disposeData=function(t){throw new Error("Not yet implemented.");},t.prototype.write=function(t,e){throw new Error("Not yet implemented.");},t.prototype.fromPixels=function(t,e){throw new Error("Not yet implemented.");},t.prototype.register=function(t,e,n){throw new Error("Not yet implemented.");},t.prototype.memory=function(){throw new Error("Not yet implemented.");},t.prototype.floatPrecision=function(){throw new Error("Not yet implemented");},t.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4;},t.prototype.batchMatMul=function(t,e,n,r){throw new Error("Not yet implemented");},t.prototype.fusedBatchMatMul=function(t,e,n,r,o,a){throw new Error("Not yet implemented");},t.prototype.slice=function(t,e,n){throw new Error("Not yet implemented");},t.prototype.stridedSlice=function(t,e,n,r,o,a,i,s,u){throw new Error("Not yet implemented");},t.prototype.unstack=function(t,e){throw new Error("Not yet implemented");},t.prototype.reverse=function(t,e){throw new Error("Not yet implemented");},t.prototype.concat=function(t,e){throw new Error("Not yet implemented");},t.prototype.neg=function(t){throw new Error("Not yet implemented");},t.prototype.add=function(t,e){throw new Error("Not yet implemented");},t.prototype.addN=function(t){throw new Error("Not yet implemented");},t.prototype.subtract=function(t,e){throw new Error("Not yet implemented");},t.prototype.multiply=function(t,e){throw new Error("Not yet implemented");},t.prototype.realDivide=function(t,e){throw new Error("Not yet implemented");},t.prototype.floorDiv=function(t,e){throw new Error("Not yet implemented");},t.prototype.sum=function(t,e){throw new Error("Not yet implemented");},t.prototype.prod=function(t,e){throw new Error("Not yet implemented");},t.prototype.unsortedSegmentSum=function(t,e,n){throw new Error("Not yet implemented");},t.prototype.argMin=function(t,e){throw new Error("Not yet implemented");},t.prototype.argMax=function(t,e){throw new Error("Not yet implemented");},t.prototype.equal=function(t,e){throw new Error("Not yet implemented");},t.prototype.notEqual=function(t,e){throw new Error("Not yet implemented");},t.prototype.less=function(t,e){throw new Error("Not yet implemented");},t.prototype.lessEqual=function(t,e){throw new Error("Not yet implemented");},t.prototype.greater=function(t,e){throw new Error("Not yet implemented");},t.prototype.greaterEqual=function(t,e){throw new Error("Not yet implemented");},t.prototype.logicalNot=function(t){throw new Error("Not yet implemented");},t.prototype.logicalAnd=function(t,e){throw new Error("Not yet implemented");},t.prototype.logicalOr=function(t,e){throw new Error("Not yet implemented");},t.prototype.where=function(t){throw new Error("Not yet implemented");},t.prototype.select=function(t,e,n){throw new Error("Not yet implemented");},t.prototype.topk=function(t,e,n){throw new Error("Not yet implemented");},t.prototype.min=function(t,e){throw new Error("Not yet implemented");},t.prototype.minimum=function(t,e){throw new Error("Not yet implemented");},t.prototype.mod=function(t,e){throw new Error("Not yet implemented");},t.prototype.max=function(t,e){throw new Error("Not yet implemented");},t.prototype.maximum=function(t,e){throw new Error("Not yet implemented");},t.prototype.all=function(t,e){throw new Error("Not yet implemented");},t.prototype.any=function(t,e){throw new Error("Not yet implemented");},t.prototype.squaredDifference=function(t,e){throw new Error("Not yet implemented");},t.prototype.ceil=function(t){throw new Error("Not yet implemented");},t.prototype.floor=function(t){throw new Error("Not yet implemented");},t.prototype.round=function(t){throw new Error("Not yet implemented");},t.prototype.sign=function(t){throw new Error("Not yet implemented");},t.prototype.isNaN=function(t){throw new Error("Not yet implemented");},t.prototype.isInf=function(t){throw new Error("Not yet implemented");},t.prototype.isFinite=function(t){throw new Error("Not yet implemented");},t.prototype.pow=function(t,e){throw new Error("Not yet implemented");},t.prototype.exp=function(t){throw new Error("Not yet implemented");},t.prototype.expm1=function(t){throw new Error("Not yet implemented");},t.prototype.log=function(t){throw new Error("Not yet implemented");},t.prototype.log1p=function(t){throw new Error("Not yet implemented");},t.prototype.sqrt=function(t){throw new Error("Not yet implemented");},t.prototype.rsqrt=function(t){throw new Error("Not yet implemented");},t.prototype.square=function(t){throw new Error("Not yet implemented");},t.prototype.reciprocal=function(t){throw new Error("Not yet implemented");},t.prototype.relu=function(t){throw new Error("Not yet implemented");},t.prototype.prelu=function(t,e){throw new Error("Not yet implemented");},t.prototype.elu=function(t){throw new Error("Not yet implemented");},t.prototype.eluDer=function(t,e){throw new Error("Not yet implemented");},t.prototype.selu=function(t){throw new Error("Not yet implemented");},t.prototype.int=function(t){throw new Error("Not yet implemented");},t.prototype.clip=function(t,e,n){throw new Error("Not yet implemented");},t.prototype.abs=function(t){throw new Error("Not yet implemented");},t.prototype.complexAbs=function(t){throw new Error("Not yet implemented");},t.prototype.sigmoid=function(t){throw new Error("Not yet implemented");},t.prototype.softplus=function(t){throw new Error("Not yet implemented");},t.prototype.sin=function(t){throw new Error("Not yet implemented");},t.prototype.cos=function(t){throw new Error("Not yet implemented");},t.prototype.tan=function(t){throw new Error("Not yet implemented");},t.prototype.asin=function(t){throw new Error("Not yet implemented");},t.prototype.acos=function(t){throw new Error("Not yet implemented");},t.prototype.atan=function(t){throw new Error("Not yet implemented");},t.prototype.atan2=function(t,e){throw new Error("Not yet implemented");},t.prototype.sinh=function(t){throw new Error("Not yet implemented");},t.prototype.cosh=function(t){throw new Error("Not yet implemented");},t.prototype.tanh=function(t){throw new Error("Not yet implemented");},t.prototype.asinh=function(t){throw new Error("Not yet implemented");},t.prototype.acosh=function(t){throw new Error("Not yet implemented");},t.prototype.atanh=function(t){throw new Error("Not yet implemented");},t.prototype.erf=function(t){throw new Error("Not yet implemented");},t.prototype.step=function(t,e){throw new Error("Not yet implemented");},t.prototype.conv2d=function(t,e,n){throw new Error("Not yet implemented");},t.prototype.conv2dDerInput=function(t,e,n){throw new Error("Not yet implemented");},t.prototype.conv2dDerFilter=function(t,e,n){throw new Error("Not yet implemented");},t.prototype.depthwiseConv2D=function(t,e,n){throw new Error("Not yet implemented");},t.prototype.depthwiseConv2DDerInput=function(t,e,n){throw new Error("Not yet implemented");},t.prototype.depthwiseConv2DDerFilter=function(t,e,n){throw new Error("Not yet implemented");},t.prototype.conv3d=function(t,e,n){throw new Error("Not yet implemented");},t.prototype.conv3dDerInput=function(t,e,n){throw new Error("Not yet implemented");},t.prototype.conv3dDerFilter=function(t,e,n){throw new Error("Not yet implemented");},t.prototype.maxPool=function(t,e){throw new Error("Not yet implemented");},t.prototype.maxPoolBackprop=function(t,e,n,r){throw new Error("Not yet implemented");},t.prototype.avgPool=function(t,e){throw new Error("Not yet implemented");},t.prototype.avgPoolBackprop=function(t,e,n){throw new Error("Not yet implemented");},t.prototype.reshape=function(t,e){throw new Error("Not yet implemented");},t.prototype.cast=function(t,e){throw new Error("Not yet implemented");},t.prototype.tile=function(t,e){throw new Error("Not yet implemented");},t.prototype.pad=function(t,e,n){throw new Error("Not yet implemented");},t.prototype.transpose=function(t,e){throw new Error("Not yet implemented");},t.prototype.gather=function(t,e,n){throw new Error("Not yet implemented");},t.prototype.gatherND=function(t,e){throw new Error("Not yet implemented");},t.prototype.scatterND=function(t,e,n){throw new Error("Not yet implemented");},t.prototype.batchToSpaceND=function(t,e,n){throw new Error("Not yet implemented");},t.prototype.spaceToBatchND=function(t,e,n){throw new Error("Not yet implemented");},t.prototype.resizeBilinear=function(t,e,n,r){throw new Error("Not yet implemented");},t.prototype.resizeBilinearBackprop=function(t,e,n){throw new Error("Not yet implemented");},t.prototype.resizeNearestNeighbor=function(t,e,n,r){throw new Error("Not yet implemented");},t.prototype.resizeNearestNeighborBackprop=function(t,e,n){throw new Error("Not yet implemented");},t.prototype.batchNormalization=function(t,e,n,r,o,a){throw new Error("Not yet implemented");},t.prototype.localResponseNormalization4D=function(t,e,n,r,o){throw new Error("Not yet implemented");},t.prototype.LRNGrad=function(t,e,n,r,o,a,i){throw new Error("Not yet implemented");},t.prototype.multinomial=function(t,e,n,r){throw new Error("Not yet implemented");},t.prototype.oneHot=function(t,e,n,r){throw new Error("Not yet implemented");},t.prototype.cumsum=function(t,e,n,r){throw new Error("Not yet implemented");},t.prototype.nonMaxSuppression=function(t,e,n,r,o){throw new Error("Not yet implemented");},t.prototype.fft=function(t){throw new Error("Not yet implemented");},t.prototype.ifft=function(t){throw new Error("Not yet implemented");},t.prototype.complex=function(t,e){throw new Error("Not yet implemented");},t.prototype.real=function(t){throw new Error("Not yet implemented");},t.prototype.imag=function(t){throw new Error("Not yet implemented");},t.prototype.cropAndResize=function(t,e,n,r,o,a){throw new Error("Not yet implemented");},t.prototype.depthToSpace=function(t,e,n){throw new Error("Not yet implemented");},t.prototype.split=function(t,e,n){throw new Error("Not yet implemented");},t.prototype.sparseToDense=function(t,e,n,r){throw new Error("Not yet implemented");},t.prototype.fill=function(t,e,n){throw new Error("Not yet implemented.");},t.prototype.onesLike=function(t){throw new Error("Not yet implemented");},t.prototype.zerosLike=function(t){throw new Error("Not yet implemented");},t.prototype.linspace=function(t,e,n){throw new Error("Not yet implemented");},t.prototype.dispose=function(){throw new Error("Not yet implemented");},t;}();function Kr(t,e){for(var n=t.length,r=[],o=0;o<n;o++){var a=n-1-o,i=t[a]||1;(e[e.length-1-o]||1)>1&&1===i&&r.unshift(a);}return r;}function Xr(t,e){for(var n=[],r=0;r<e.length;r++){var o=t[t.length-r-1],a=e.length-r-1,i=e[a];(null==o||1===o&&i>1)&&n.unshift(a);}return n;}function Yr(t,e){for(var n=[],r=Math.max(t.length,e.length),o=0;o<r;o++){var a=t[t.length-o-1];null==a&&(a=1);var i=e[e.length-o-1];if(null==i&&(i=1),1===a)n.unshift(i);else if(1===i)n.unshift(a);else{if(a!==i)throw Error("Operands could not be broadcast together with shapes "+t+" and "+e+".");n.unshift(a);}}return n;}function Qr(t,e,n,r,o,a,i){void 0===i&&(i="channelsLast");var s,u=eo(e),l=u[0],c=u[1];if("channelsLast"===i)s=[l,c,t[3],t[3]];else{if("channelsFirst"!==i)throw new Error("Unknown dataFormat "+i);s=[l,c,t[1],t[1]];}return Jr(t,s,n,r,o,a,!1,i);}function Jr(t,e,n,r,o,a,i,s){void 0===i&&(i=!1),void 0===s&&(s="channelsLast");var u=[-1,-1,-1,-1],l=u[0],c=u[1],h=u[2],p=u[3];if("channelsLast"===s)l=t[0],c=t[1],h=t[2],p=t[3];else{if("channelsFirst"!==s)throw new Error("Unknown dataFormat "+s);l=t[0],p=t[1],c=t[2],h=t[3];}var f,v=e[0],m=e[1],g=e[3],y=eo(n),x=y[0],w=y[1],C=eo(r),E=C[0],R=C[1],I=ro(v,E),S=ro(m,R),N=function(t,e,n,r,o,a,i,s){var u,l,c;if("number"==typeof t){var h=0===t?"VALID":"NUMBER";u={top:t,bottom:t,left:t,right:t,type:h};var p=function(t,e,n,r,o){null==r&&(r=to(t,e,n));var a=t[0],i=t[1],s=oo((a-e+2*r)/n+1,o);d(b(s),function(){return"The output # of rows ("+s+") must be an integer. Change the stride and/or zero pad parameters";});var u=oo((i-e+2*r)/n+1,o);return d(b(u),function(){return"The output # of columns ("+u+") must be an integer. Change the stride and/or zero pad parameters";}),[s,u];}([e,n],a,r,t,s);l=p[0],c=p[1];}else if("same"===t){l=Math.ceil(e/r),c=Math.ceil(n/o);var f=Math.max(0,(l-1)*r+a-e),v=Math.max(0,(c-1)*o+i-n),m=Math.floor(f/2),g=f-m,y=Math.floor(v/2),x=v-y;u={top:m,bottom:g,left:y,right:x,type:"SAME"};}else{if("valid"!==t)throw Error("Unknown padding parameter: "+t);u={top:0,bottom:0,left:0,right:0,type:"VALID"},l=Math.ceil((e-a+1)/r),c=Math.ceil((n-i+1)/o);}return{padInfo:u,outHeight:l,outWidth:c};}(o,c,h,x,w,I,S,a),k=N.padInfo,A=N.outHeight,T=N.outWidth,D=i?g*p:g;return"channelsFirst"===s?f=[l,D,A,T]:"channelsLast"===s&&(f=[l,A,T,D]),{batchSize:l,dataFormat:s,inHeight:c,inWidth:h,inChannels:p,outHeight:A,outWidth:T,outChannels:D,padInfo:k,strideHeight:x,strideWidth:w,filterHeight:v,filterWidth:m,effectiveFilterHeight:I,effectiveFilterWidth:S,dilationHeight:E,dilationWidth:R,inShape:t,outShape:f,filterShape:e};}function Zr(t,e,n,r,o,a,i){void 0===a&&(a=!1),void 0===i&&(i="channelsLast");var s=[-1,-1,-1,-1,-1],u=s[0],l=s[1],c=s[2],h=s[3],p=s[4];if("channelsLast"===i)u=t[0],l=t[1],c=t[2],h=t[3],p=t[4];else{if("channelsFirst"!==i)throw new Error("Unknown dataFormat "+i);u=t[0],p=t[1],l=t[2],c=t[3],h=t[4];}var f,d=e[0],v=e[1],m=e[2],g=e[4],y=no(n),x=y[0],b=y[1],w=y[2],C=no(r),E=C[0],R=C[1],I=C[2],S=function(t,e,n,r,o,a,i,s,u,l){var c,h,p,f;if("same"===t){h=Math.ceil(e/o),p=Math.ceil(n/a),f=Math.ceil(r/i);var d=(h-1)*o+s-e,v=(p-1)*a+u-n,m=(f-1)*i+l-r,g=Math.floor(d/2),y=d-g,x=Math.floor(v/2),b=v-x,w=Math.floor(m/2),C=m-w;c={top:x,bottom:b,left:w,right:C,front:g,back:y,type:"SAME"};}else{if("valid"!==t)throw Error("Unknown padding parameter: "+t);c={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},h=Math.ceil((e-s+1)/o),p=Math.ceil((n-u+1)/a),f=Math.ceil((r-l+1)/i);}return{padInfo:c,outDepth:h,outHeight:p,outWidth:f};}(o,l,c,h,x,b,w,ro(d,E),ro(v,R),ro(m,I)),N=S.padInfo,k=S.outDepth,A=S.outHeight,T=S.outWidth,D=a?g*p:g;return"channelsFirst"===i?f=[u,D,k,A,T]:"channelsLast"===i&&(f=[u,k,A,T,D]),{batchSize:u,dataFormat:i,inDepth:l,inHeight:c,inWidth:h,inChannels:p,outDepth:k,outHeight:A,outWidth:T,outChannels:D,padInfo:N,strideDepth:x,strideHeight:b,strideWidth:w,filterDepth:d,filterHeight:v,filterWidth:m,dilationDepth:E,dilationHeight:R,dilationWidth:I,inShape:t,outShape:f,filterShape:e};}function to(t,e,n,r){void 0===r&&(r=1);var o=ro(e,r);return Math.floor((t[0]*(n-1)-n+o)/2);}function eo(t){return"number"==typeof t?[t,t]:t;}function no(t){return"number"==typeof t?[t,t,t]:t;}function ro(t,e){return e<=1?t:t+(t-1)*(e-1);}function oo(t,e){if(!e)return t;switch(e){case"round":return Math.round(t);case"ceil":return Math.ceil(t);case"floor":return Math.floor(t);default:throw new Error("Unknown roundingMode "+e);}}function ao(t){var e=eo(t),n=e[0],r=e[1];return 1===n&&1===r;}function io(t,e){return ao(t)||ao(e);}function so(t,e,n){if("complex64"===e){if("complex64"===t.dtype)return t.clone();var r=Sn(t.shape),o=t.toFloat(),a=n.complex(o,r);return r.dispose(),o.dispose(),a;}if(!O(t.dtype,e))return ft.make(t.shape,{dataId:t.dataId},e);if("complex64"===t.dtype){var i=n.real(t);a=i.cast(e);return i.dispose(),a;}if("int32"===e)return n.int(t);if("bool"===e){var s=yn(0,t.dtype);a=n.notEqual(t,s);return s.dispose(),a;}throw new Error("Error in Cast: failed to cast "+t.dtype+" to "+e);}function uo(t,e){return ft.make(e,{dataId:t.dataId},t.dtype);}function lo(t,e,n){var r=(e-t)/(n-1),o=j(n,"float32");o[0]=t;for(var a=1;a<o.length;a++)o[a]=o[a-1]+r;return xn(o,"float32");}var co=Object.freeze({castTensor:so,reshapeTensor:uo,linspaceImpl:lo,upcastType:Ct,axesAreInnerMostDims:en,combineLocations:nn,computeOutAndReduceShapes:rn,expandShapeToKeepDim:on,assertAxesAreInnerMostDims:an,getAxesPermutation:sn,getUndoAxesPermutation:un,getInnerMostAxes:ln,getBroadcastDims:Kr,getReductionAxes:Xr,assertAndGetBroadcastShape:Yr,assertParamsConsistent:cn,computeOutShape:hn,computePool2DInfo:Qr,computeConv2DInfo:Jr,computeConv3DInfo:Zr,computeDefaultPad:to,tupleValuesAreOne:ao,eitherStridesOrDilationsAreOne:io});function ho(t,e){if(t.length!==e.length)throw new Error("Cannot merge real and imag arrays of different lengths. real:"+t.length+", imag: "+e.length+".");for(var n=new Float32Array(2*t.length),r=0;r<n.length;r+=2)n[r]=t[r/2],n[r+1]=e[r/2];return n;}function po(t,e){return{real:t[2*e],imag:t[2*e+1]};}function fo(t,e,n,r){t[2*r]=e,t[2*r+1]=n;}function vo(t,e,n){var r=(n?2:-2)*Math.PI*(t/e);return{real:Math.cos(r),imag:Math.sin(r)};}function mo(t,e,n,r,o){for(var a=Array.from(e).map(function(t,e){return{score:t,boxIndex:e};}).filter(function(t){return t.score>o;}).sort(function(t,e){return e.score-t.score;}),i=[],s=0;s<a.length;s++){var u=a[s],l=u.score,c=u.boxIndex;if(l<o)break;for(var h=!1,p=i.length-1;p>=0;--p){if(go(t,c,i[p])>=r){h=!0;break;}}if(!h&&(i.push(c),i.length>=n))break;}return xn(i,"int32");}function go(t,e,n){var r=t.subarray(4*e,4*e+4),o=t.subarray(4*n,4*n+4),a=Math.min(r[0],r[2]),i=Math.min(r[1],r[3]),s=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),l=Math.min(o[0],o[2]),c=Math.min(o[1],o[3]),h=Math.max(o[0],o[2]),p=Math.max(o[1],o[3]),f=(s-a)*(u-i),d=(h-l)*(p-c);if(f<=0||d<=0)return 0;var v=Math.max(a,l),m=Math.max(i,c),g=Math.min(s,h),y=Math.min(u,p),x=Math.max(g-v,0)*Math.max(y-m,0);return x/(f+d-x);}function yo(t,e,n){var r=new Array(t.rank).fill(0),o=t.shape.slice();return e.map(function(e){o[n]=e;var a=t.slice(r,o);return r[n]+=e,a;});}function xo(t,e){for(var n=new Array(t.rank),r=0;r<n.length;r++)n[r]=t.shape[r]*e[r];var o=Xn(n,t.dtype);for(r=0;r<o.values.length;++r){for(var a=o.indexToLoc(r),i=new Array(t.rank),s=0;s<i.length;s++)i[s]=a[s]%t.shape[s];var u=t.locToIndex(i);o.values[r]=t.values[u];}return o.toTensor();}function bo(t,e,n,r,o){for(var a=e[e.length-1],i=[t.length/a,a],s=i[0],u=i[1],l=k(n,s*r),c=k("int32",s*r),h=0;h<s;h++){for(var p=h*u,f=t.subarray(p,p+u),d=[],v=0;v<f.length;v++)d.push({value:f[v],index:v});d.sort(function(t,e){return e.value-t.value;});var m=h*r,g=l.subarray(m,m+r),y=c.subarray(m,m+r);for(v=0;v<r;v++)g[v]=d[v].value,y[v]=d[v].index;}var x=e.slice();return x[x.length-1]=r,[mn(l,x,n),mn(c,x,"int32")];}function wo(t,e){for(var n=[],r=0;r<e.length;r++)e[r]&&n.push(r);var o=Xn(t,"int32"),a=Xn([n.length,t.length],"int32");for(r=0;r<n.length;r++){var i=o.indexToLoc(n[r]),s=r*t.length;a.values.set(i,s);}return a.toTensor();}var Co=function(){return function(t,e){this.outputShape=[],this.outputShape=t,this.variableNames=e.map(function(t,e){return"T"+e;});var n=[];this.variableNames.forEach(function(t){n.push("float v"+t+" = get"+t+"AtOutCoords();");});var r=this.variableNames.map(function(t){return"v"+t;}).join(" + ");this.userCode="\n      void main() {\n        "+n.join("\n        ")+"\n\n        float result = "+r+";\n        setOutput(result);\n      }\n    ";};}(),Eo=function(){return function(t,e){this.outputShape=[],this.usesPackedTextures=!0,this.outputShape=t,this.variableNames=e.map(function(t,e){return"T"+e;});var n=[];this.variableNames.forEach(function(t){n.push("vec4 v"+t+" = get"+t+"AtOutCoords();");});var r=this.variableNames.map(function(t){return"v"+t;}).join(" + ");this.userCode="\n      void main() {\n        "+n.join("\n        ")+"\n\n        vec4 result = "+r+";\n        setOutput(result);\n      }\n    ";};}(),Ro=function(){return function(t,e,n){this.variableNames=["A"];var r=t.windowSize,o=t.batchSize,a=t.inSize,i=Math.ceil(a/r);n||this.variableNames.push("bestIndicesA"),this.outputShape=[o,i];var s="max"===e?">":"<",u=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode="\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int batch = coords[0];\n        int outIdx = coords[1];\n        int inOffset = outIdx * "+r+";\n\n        int bestIndex = inOffset;\n        float bestValue = getA(batch, bestIndex);\n\n        for (int i = 0; i < "+r+"; i++) {\n          int inIdx = "+u+";\n          float candidate = getA(batch, inIdx);\n          if (candidate "+s+" bestValue) {\n            bestValue = candidate;\n            bestIndex = inIdx;\n          }\n        }\n        setOutput(float(bestIndex));\n      }\n    ";};}();function Io(t,e){return["x","y","z","w","u","v"].slice(0,e).map(function(e){return t+"."+e;});}function So(t,e){return 1===e?[t]:Io(t,e);}function No(){var t,e,n,r,o,a,i,u,l,c;return 2===exports.ENV.getNumber("WEBGL_VERSION")?(t="#version 300 es",e="in",n="out",r="in",o="texture",a="outputColor",i="out vec4 outputColor;",u="\n      bool isnan_custom(float val) {\n        return (val > 0. || val < 0. || val == 0.) ? false : true;\n      }\n    ",l="\n      const float INFINITY = uintBitsToFloat(uint(0x7f800000));\n    ",c="\n      #define round(value) newRound(value)\n      int newRound(float value) {\n        return int(floor(value + 0.5));\n      }\n\n      ivec4 newRound(vec4 value) {\n        return ivec4(floor(value + vec4(0.5)));\n      }\n    "):(t="",e="attribute",n="varying",r="varying",o="texture2D",a="gl_FragColor",i="",u="\n      bool isnan_custom(float val) {\n        return (val > 0. || val < 1. || val == 0.) ? false : true;\n      }\n    ",l="\n      uniform float INFINITY;\n\n      bool isinf(float val) {\n        return abs(val) == INFINITY;\n      }\n      bvec4 isinf(vec4 val) {\n        return equal(abs(val), vec4(INFINITY));\n      }\n    ",c="\n      int round(float value) {\n        return int(floor(value + 0.5));\n      }\n\n      ivec4 round(vec4 value) {\n        return ivec4(floor(value + vec4(0.5)));\n      }\n    "),{version:t,attribute:e,varyingVs:n,varyingFs:r,texture2D:o,output:a,defineOutput:i,defineSpecialNaN:u,defineSpecialInf:l,defineRound:c};}function ko(t,e,n){void 0===n&&(n="index");var r=G(e);return r.map(function(e,o){return"int "+t[o]+" = "+n+" / "+e+"; "+(o===r.length-1?"int "+t[o+1]+" = "+n+" - "+t[o]+" * "+e:"index -= "+t[o]+" * "+e)+";";}).join("");}function Ao(t){var e=G(t).map(function(t){return t.toString();});return"\n  int getFlatIndex(ivec3 coords) {\n    return coords.x * "+e[0]+" + coords.y * "+e[1]+" + coords.z;\n  }\n";}var To="\n  const float FLOAT_MAX = 1.70141184e38;\n  const float FLOAT_MIN = 1.17549435e-38;\n\n  lowp vec4 encode_float(highp float v) {\n    if (isnan(v)) {\n      return vec4(255, 255, 255, 255);\n    }\n\n    highp float av = abs(v);\n\n    if(av < FLOAT_MIN) {\n      return vec4(0.0, 0.0, 0.0, 0.0);\n    } else if(v > FLOAT_MAX) {\n      return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n    } else if(v < -FLOAT_MAX) {\n      return vec4(0.0, 0.0,  128.0, 255.0) / 255.0;\n    }\n\n    highp vec4 c = vec4(0,0,0,0);\n\n    highp float e = floor(log2(av));\n    highp float m = exp2(fract(log2(av))) - 1.0;\n\n    c[2] = floor(128.0 * m);\n    m -= c[2] / 128.0;\n    c[1] = floor(32768.0 * m);\n    m -= c[1] / 32768.0;\n    c[0] = floor(8388608.0 * m);\n\n    highp float ebias = e + 127.0;\n    c[3] = floor(ebias / 2.0);\n    ebias -= c[3] * 2.0;\n    c[2] += floor(ebias) * 128.0;\n\n    c[3] += 128.0 * step(0.0, -v);\n\n    return c / 255.0;\n  }\n";function Do(t,e,n,r){var o=[];t.forEach(function(t){var e=y(t.shapeInfo.logicalShape);t.shapeInfo.isUniform?o.push("uniform float "+t.name+(e>1?"["+e+"]":"")+";"):(o.push("uniform sampler2D "+t.name+";"),o.push("uniform int offset"+t.name+";"));});var a,i,s=o.join("\n"),u=t.map(function(t){return function(t,e,n){void 0===n&&(n=!1);var r="";r+=n?Oo(t):_o(t);var o=t.shapeInfo.logicalShape,a=e.logicalShape;o.length<=a.length&&(r+=n?function(t,e){var n,r=t.name,o=r.charAt(0).toUpperCase()+r.slice(1),a="get"+o+"AtOutCoords",i=t.shapeInfo.logicalShape.length,s=e.logicalShape.length,u=Kr(t.shapeInfo.logicalShape,e.logicalShape),l=Uo(s),c=s-i,h=["x","y","z","w","u","v"];n=0===i?"":s<2&&u.length>=1?"coords = 0;":u.map(function(t){return"coords."+h[t+c]+" = 0;";}).join("\n");var p="";p=s<2&&i>0?"coords":t.shapeInfo.logicalShape.map(function(t,e){return"coords."+h[e+c];}).join(", ");var f="return outputValue;",d=1===y(t.shapeInfo.logicalShape),v=1===y(e.logicalShape);if(1!==i||d||v){if(d&&!v)f=1===s?"\n        return vec4(outputValue.x, outputValue.x, 0., 0.);\n      ":"\n        return vec4(outputValue.x);\n      ";else if(u.length){var m=i-2,g=i-1;u.indexOf(m)>-1&&u.indexOf(g)>-1?f="return vec4(outputValue.x);":u.indexOf(m)>-1?f="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":u.indexOf(g)>-1&&(f="return vec4(outputValue.xx, outputValue.zz);");}}else f="\n      return vec4(outputValue.xy, outputValue.xy);\n    ";return"\n    vec4 "+a+"() {\n      "+l+" coords = getOutputCoords();\n      "+n+"\n      vec4 outputValue = get"+o+"("+p+");\n      "+f+"\n    }\n  ";}(t,e):function(t,e){var n=t.name,r=n.charAt(0).toUpperCase()+n.slice(1),o="get"+r+"AtOutCoords",a=e.texShape,i=t.shapeInfo.texShape,s=t.shapeInfo.logicalShape.length,u=e.logicalShape.length;if(!t.shapeInfo.isUniform&&s===u&&null==t.shapeInfo.flatOffset&&x(i,a))return"\n      float "+o+"() {\n        return sampleTexture("+n+", resultUV);\n      }\n    ";var l,c=Uo(u),h=Kr(t.shapeInfo.logicalShape,e.logicalShape),p=u-s,f=["x","y","z","w","u","v"];l=0===s?"":u<2&&h.length>=1?"coords = 0;":h.map(function(t){return"coords."+f[t+p]+" = 0;";}).join("\n");var d="";d=u<2&&s>0?"coords":t.shapeInfo.logicalShape.map(function(t,e){return"coords."+f[e+p];}).join(", ");return"\n    float "+o+"() {\n      "+c+" coords = getOutputCoords();\n      "+l+"\n      return get"+r+"("+d+");\n    }\n  ";}(t,e));return r;}(t,e,r);}).join("\n"),l=e.texShape,c=No(),h=function(t){return"\n    float sampleTexture(sampler2D textureSampler, vec2 uv) {\n      return "+t.texture2D+"(textureSampler, uv).r;\n    }\n  ";}(c),p=function(t){return t.version+"\n    precision highp float;\n    precision highp int;\n    precision highp sampler2D;\n    "+t.varyingFs+" vec2 resultUV;\n    "+t.defineOutput+"\n    const vec2 halfCR = vec2(0.5, 0.5);\n\n    struct ivec5\n    {\n      int x;\n      int y;\n      int z;\n      int w;\n      int u;\n    };\n\n    struct ivec6\n    {\n      int x;\n      int y;\n      int z;\n      int w;\n      int u;\n      int v;\n    };\n\n    uniform float NAN;\n    #define isnan(value) isnan_custom(value)\n    "+t.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    "+t.defineSpecialInf+"\n    "+t.defineRound+"\n\n    int imod(int x, int y) {\n      return x - y * (x / y);\n    }\n\n    int idiv(int a, int b, float sign) {\n      int res = a / b;\n      int mod = imod(a, b);\n      if (sign < 0. && mod != 0) {\n        res -= 1;\n      }\n      return res;\n    }\n\n    //Based on the work of Dave Hoskins\n    //https://www.shadertoy.com/view/4djSRW\n    #define HASHSCALE1 443.8975\n    float random(float seed){\n      vec2 p = resultUV * seed;\n      vec3 p3  = fract(vec3(p.xyx) * HASHSCALE1);\n      p3 += dot(p3, p3.yzx + 19.19);\n      return fract((p3.x + p3.y) * p3.z);\n    }\n\n    "+Mo+"\n    "+Fo+"\n    "+Bo+"\n  ";}(c);return e.isPacked?(a=function(t,e){switch(t.length){case 0:return"\n    int getOutputCoords() {\n      return 0;\n    }\n  ";case 1:return function(t,e){var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];if(1===n[0])return"\n      int getOutputCoords() {\n        return 2 * int(resultUV.x * "+n[1]+".0);\n      }\n    ";if(1===n[1])return"\n      int getOutputCoords() {\n        return 2 * int(resultUV.y * "+n[0]+".0);\n      }\n    ";return"\n    int getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2("+n[0]+", "+n[1]+"));\n      return 2 * (resTexRC.x * "+n[1]+" + resTexRC.y);\n    }\n  ";}(0,e);case 2:return function(t,e){var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];if(x(t,e))return"\n      ivec2 getOutputCoords() {\n        return 2 * ivec2(resultUV.yx * vec2("+n[0]+", "+n[1]+"));\n      }\n    ";var r=Math.ceil(t[1]/2);return"\n    ivec2 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2("+n[0]+", "+n[1]+"));\n\n      int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n      int r = 2 * (index / "+r+");\n      int c = imod(index, "+r+") * 2;\n\n      return ivec2(r, c);\n    }\n  ";}(t,e);case 3:return n=t,r=e,o=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],a=Math.ceil(n[2]/2),i=a*Math.ceil(n[1]/2),"\n    ivec3 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2("+o[0]+", "+o[1]+"));\n      int index = resTexRC.x * "+o[1]+" + resTexRC.y;\n\n      int b = index / "+i+";\n      index -= b * "+i+";\n\n      int r = 2 * (index / "+a+");\n      int c = imod(index, "+a+") * 2;\n\n      return ivec3(b, r, c);\n    }\n  ";default:return function(t,e){for(var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)],r=Math.ceil(t[t.length-1]/2),o=r*Math.ceil(t[t.length-2]/2),a=o,i="",s="b, r, c",u=2;u<t.length-1;u++)a*=t[t.length-u-1],i="\n      int b"+u+" = index / "+a+";\n      index -= b"+u+" * "+a+";\n    "+i,s="b"+u+", "+s;return"\n    ivec"+t.length+" getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2("+n[0]+", "+n[1]+"));\n      int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n\n      "+i+"\n\n      int b = index / "+o+";\n      index -= b * "+o+";\n\n      int r = 2 * (index / "+r+");\n      int c = imod(index, "+r+") * 2;\n\n      return ivec"+t.length+"("+s+");\n    }\n  ";}(t,e);}var n,r,o,a,i;}(e.logicalShape,l),i=function(t){return"\n    void setOutput(vec4 val) {\n      "+t.output+" = val;\n    }\n  ";}(c)):(a=function(t,e){switch(t.length){case 0:return"\n    int getOutputCoords() {\n      return 0;\n    }\n  ";case 1:return function(t,e){if(1===e[0])return"\n      int getOutputCoords() {\n        return int(resultUV.x * "+e[1]+".0);\n      }\n    ";if(1===e[1])return"\n      int getOutputCoords() {\n        return int(resultUV.y * "+e[0]+".0);\n      }\n    ";return"\n    int getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2("+e[0]+", "+e[1]+"));\n      return resTexRC.x * "+e[1]+" + resTexRC.y;\n    }\n  ";}(0,e);case 2:return function(t,e){if(x(t,e))return"\n      ivec2 getOutputCoords() {\n        return ivec2(resultUV.yx * vec2("+e[0]+", "+e[1]+"));\n      }\n    ";if(1===t[1])return"\n      ivec2 getOutputCoords() {\n        ivec2 resTexRC = ivec2(resultUV.yx *\n                               vec2("+e[0]+", "+e[1]+"));\n        int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n        return ivec2(index, 0);\n      }\n    ";if(1===t[0])return"\n      ivec2 getOutputCoords() {\n        ivec2 resTexRC = ivec2(resultUV.yx *\n                               vec2("+e[0]+", "+e[1]+"));\n        int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n        return ivec2(0, index);\n      }\n    ";return"\n    ivec2 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2("+e[0]+", "+e[1]+"));\n      int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n      int r = index / "+t[1]+";\n      int c = index - r * "+t[1]+";\n      return ivec2(r, c);\n    }\n  ";}(t,e);case 3:return n=e,r=ko(["r","c","d"],t),"\n    ivec3 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2("+n[0]+", "+n[1]+"));\n      int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n      "+r+"\n      return ivec3(r, c, d);\n    }\n  ";case 4:return function(t,e){var n=ko(["r","c","d","d2"],t);return"\n    ivec4 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n        vec2("+e[0]+", "+e[1]+"));\n      int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n      "+n+"\n      return ivec4(r, c, d, d2);\n    }\n  ";}(t,e);case 5:return function(t,e){var n=ko(["r","c","d","d2","d3"],t);return"\n    ivec5 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx * vec2("+e[0]+",\n                             "+e[1]+"));\n\n      int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n\n      "+n+"\n\n      ivec5 outShape = ivec5(r, c, d, d2, d3);\n      return outShape;\n    }\n  ";}(t,e);case 6:return function(t,e){var n=ko(["r","c","d","d2","d3","d4"],t);return"\n    ivec6 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n        vec2("+e[0]+", "+e[1]+"));\n      int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n\n      "+n+"\n\n      ivec6 result = ivec6(r, c, d, d2, d3, d4);\n      return result;\n    }\n  ";}(t,e);default:throw new Error(t.length+"-D output sampling is not yet supported");}var n,r;}(e.logicalShape,l),i=function(t){return"\n    void setOutput(float val) {\n      "+t.output+" = vec4(val, 0, 0, 0);\n    }\n  ";}(c)),r&&(p+=Po),[p,h,i,s,a,u,n].join("\n");}function _o(t){var e=t.shapeInfo.logicalShape;switch(e.length){case 0:return function(t){var e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1);if(t.shapeInfo.isUniform)return"float "+n+"() {return "+e+";}";var r=t.shapeInfo.texShape,o=r[0],a=r[1];if(1===o&&1===a)return"\n      float "+n+"() {\n        return sampleTexture("+e+", halfCR);\n      }\n    ";var i=t.shapeInfo.texShape,s=i[0],u=i[1],l=Lo(e);return"\n    float "+n+"() {\n      vec2 uv = uvFromFlat("+s+", "+u+", "+l+");\n      return sampleTexture("+e+", uv);\n    }\n  ";}(t);case 1:return function(t){var e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1);if(t.shapeInfo.isUniform)return"\n      float "+n+"(int index) {\n        "+Wo(t)+"\n      }\n    ";var r=t.shapeInfo.texShape,o=r[0],a=r[1];if(1===a&&1===o)return"\n      float "+n+"(int index) {\n        return sampleTexture("+e+", halfCR);\n      }\n    ";var i=Lo(e);if(1===a)return"\n      float "+n+"(int index) {\n        vec2 uv = vec2(0.5, (float(index + "+i+") + 0.5) / "+o+".0);\n        return sampleTexture("+e+", uv);\n      }\n    ";if(1===o)return"\n      float "+n+"(int index) {\n        vec2 uv = vec2((float(index + "+i+") + 0.5) / "+a+".0, 0.5);\n        return sampleTexture("+e+", uv);\n      }\n    ";return"\n    float "+n+"(int index) {\n      vec2 uv = uvFromFlat("+o+", "+a+", index + "+i+");\n      return sampleTexture("+e+", uv);\n    }\n  ";}(t);case 2:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=t.shapeInfo.texShape;if(null!=o&&x(e,o)){var a=o[0],i=o[1];return"\n    float "+r+"(int row, int col) {\n      vec2 uv = (vec2(col, row) + halfCR) / vec2("+i+".0, "+a+".0);\n      return sampleTexture("+n+", uv);\n    }\n  ";}var s=N(e),u=s.newShape,l=s.keptDims,c=u;if(c.length<e.length){var h=zo(t,c);return"\n      "+_o(h)+"\n      float "+r+"(int row, int col) {\n        return "+r+"("+Vo(["row","col"],l)+");\n      }\n    ";}if(t.shapeInfo.isUniform)return"\n      float "+r+"(int row, int col) {\n        int index = round(dot(vec2(row, col), vec2("+e[1]+", 1)));\n        "+Wo(t)+"\n      }\n    ";var p=o[0],f=o[1],d=Lo(n);if(1===f)return"\n    float "+r+"(int row, int col) {\n      float index = dot(vec3(row, col, "+d+"), vec3("+e[1]+", 1, 1));\n      vec2 uv = vec2(0.5, (index + 0.5) / "+p+".0);\n      return sampleTexture("+n+", uv);\n    }\n  ";if(1===p)return"\n    float "+r+"(int row, int col) {\n      float index = dot(vec3(row, col, "+d+"), vec3("+e[1]+", 1, 1));\n      vec2 uv = vec2((index + 0.5) / "+f+".0, 0.5);\n      return sampleTexture("+n+", uv);\n    }\n  ";return"\n  float "+r+"(int row, int col) {\n    // Explicitly use integer operations as dot() only works on floats.\n    int index = row * "+e[1]+" + col + "+d+";\n    vec2 uv = uvFromFlat("+p+", "+f+", index);\n    return sampleTexture("+n+", uv);\n  }\n";}(t);case 3:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=e[1]*e[2],a=e[2],i=N(e),s=i.newShape,u=i.keptDims,l=s;if(l.length<e.length){var c=zo(t,l);return"\n        "+_o(c)+"\n        float "+r+"(int row, int col, int depth) {\n          return "+r+"("+Vo(["row","col","depth"],u)+");\n        }\n      ";}if(t.shapeInfo.isUniform)return"\n      float "+r+"(int row, int col, int depth) {\n        int index = round(dot(vec3(row, col, depth),\n                          vec3("+o+", "+a+", 1)));\n        "+Wo(t)+"\n      }\n    ";var h=t.shapeInfo.texShape,p=h[0],f=h[1],d=t.shapeInfo.flatOffset;if(f===o&&null==d)return"\n        float "+r+"(int row, int col, int depth) {\n          float texR = float(row);\n          float texC = dot(vec2(col, depth), vec2("+a+", 1));\n          vec2 uv = (vec2(texC, texR) + halfCR) /\n                     vec2("+f+".0, "+p+".0);\n          return sampleTexture("+n+", uv);\n        }\n      ";if(f===a&&null==d)return"\n    float "+r+"(int row, int col, int depth) {\n      float texR = dot(vec2(row, col), vec2("+e[1]+", 1));\n      float texC = float(depth);\n      vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+f+".0, "+p+".0);\n      return sampleTexture("+n+", uv);\n    }\n  ";var v=Lo(n);return"\n      float "+r+"(int row, int col, int depth) {\n        // Explicitly use integer operations as dot() only works on floats.\n        int index = row * "+o+" + col * "+a+" + depth + "+v+";\n        vec2 uv = uvFromFlat("+p+", "+f+", index);\n        return sampleTexture("+n+", uv);\n      }\n  ";}(t);case 4:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=e[3],a=e[2]*o,i=e[1]*a,s=N(e),u=s.newShape,l=s.keptDims;if(u.length<e.length){var c=zo(t,u);return"\n      "+_o(c)+"\n      float "+r+"(int row, int col, int depth, int depth2) {\n        return "+r+"("+Vo(["row","col","depth","depth2"],l)+");\n      }\n    ";}if(t.shapeInfo.isUniform)return"\n      float "+r+"(int row, int col, int depth, int depth2) {\n        int index = round(dot(vec4(row, col, depth, depth2),\n                          vec4("+i+", "+a+", "+o+", 1)));\n        "+Wo(t)+"\n      }\n    ";var h=t.shapeInfo.flatOffset,p=t.shapeInfo.texShape,f=p[0],d=p[1];if(d===i&&null==h)return"\n      float "+r+"(int row, int col, int depth, int depth2) {\n        float texR = float(row);\n        float texC =\n            dot(vec3(col, depth, depth2),\n                vec3("+a+", "+o+", 1));\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                   vec2("+d+".0, "+f+".0);\n        return sampleTexture("+n+", uv);\n      }\n    ";if(d===o&&null==h)return"\n      float "+r+"(int row, int col, int depth, int depth2) {\n        float texR = dot(vec3(row, col, depth),\n                         vec3("+e[1]*e[2]+", "+e[2]+", 1));\n        float texC = float(depth2);\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                  vec2("+d+".0, "+f+".0);\n        return sampleTexture("+n+", uv);\n      }\n    ";var v=Lo(n);return"\n    float "+r+"(int row, int col, int depth, int depth2) {\n      // Explicitly use integer operations as dot() only works on floats.\n      int index = row * "+i+" + col * "+a+" +\n          depth * "+o+" + depth2;\n      vec2 uv = uvFromFlat("+f+", "+d+", index + "+v+");\n      return sampleTexture("+n+", uv);\n    }\n  ";}(t);case 5:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=e[4],a=e[3]*o,i=e[2]*a,s=e[1]*i,u=N(e),l=u.newShape,c=u.keptDims;if(l.length<e.length){var h=zo(t,l);return"\n      "+_o(h)+"\n      float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n        return "+r+"("+Vo(["row","col","depth","depth2","depth3"],c)+");\n      }\n    ";}if(t.shapeInfo.isUniform)return"\n      float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n        float index = dot(\n          vec4(row, col, depth, depth2),\n          vec4("+s+", "+i+", "+a+", "+o+")) +\n          depth3;\n        "+Wo(t)+"\n      }\n    ";var p=t.shapeInfo.flatOffset,f=t.shapeInfo.texShape,d=f[0],v=f[1];if(v===s&&null==p)return"\n      float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n        int texR = row;\n        float texC = dot(vec4(col, depth, depth2, depth3),\n                         vec4("+i+", "+a+", "+o+", 1));\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                   vec2("+v+".0, "+d+".0);\n        return sampleTexture("+n+", uv);\n      }\n    ";if(v===o&&null==p)return"\n      float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n        float texR = dot(\n          vec4(row, col, depth, depth2),\n          vec4("+e[1]*e[2]*e[3]+",\n               "+e[2]*e[3]+", "+e[3]+", 1));\n        int texC = depth3;\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                  vec2("+v+".0, "+d+".0);\n        return sampleTexture("+n+", uv);\n      }\n    ";var m=Lo(n);return"\n    float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n      // Explicitly use integer operations as dot() only works on floats.\n      int index = row * "+s+" + col * "+i+" + depth * "+a+" +\n          depth2 * "+o+" + depth3 + "+m+";\n      vec2 uv = uvFromFlat("+d+", "+v+", index);\n      return sampleTexture("+n+", uv);\n    }\n  ";}(t);case 6:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=N(e),a=o.newShape,i=o.keptDims;if(a.length<e.length){var s=zo(t,a);return"\n      "+_o(s)+"\n      float "+r+"(int row, int col, int depth,\n                    int depth2, int depth3, int depth4) {\n        return "+r+"("+Vo(["row","col","depth","depth2","depth3","depth4"],i)+");\n      }\n    ";}var u=e[5],l=e[4]*u,c=e[3]*l,h=e[2]*c,p=e[1]*h;if(t.shapeInfo.isUniform)return"\n      float "+r+"(int row, int col, int depth,\n                  int depth2, int depth3, int depth4) {\n        int index = round(dot(\n          vec4(row, col, depth, depth2),\n          vec4("+p+", "+h+", "+c+", "+l+")) +\n          dot(\n            vec2(depth3, depth4),\n            vec2("+u+", 1)));\n        "+Wo(t)+"\n      }\n    ";var f=t.shapeInfo.flatOffset,d=t.shapeInfo.texShape,v=d[0],m=d[1];if(m===p&&null==f)return"\n      float "+r+"(int row, int col, int depth,\n                    int depth2, int depth3, int depth4) {\n        int texR = row;\n        float texC = dot(vec4(col, depth, depth2, depth3),\n          vec4("+h+", "+c+", "+l+", "+u+")) +\n               float(depth4);\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                   vec2("+m+".0, "+v+".0);\n        return sampleTexture("+n+", uv);\n      }\n    ";if(m===u&&null==f)return"\n      float "+r+"(int row, int col, int depth,\n                    int depth2, int depth3, int depth4) {\n        float texR = dot(vec4(row, col, depth, depth2),\n          vec4("+e[1]*e[2]*e[3]*e[4]+",\n               "+e[2]*e[3]*e[4]+",\n               "+e[3]*e[4]+",\n               "+e[4]+")) + float(depth3);\n        int texC = depth4;\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                  vec2("+m+".0, "+v+".0);\n        return sampleTexture("+n+", uv);\n      }\n    ";var g=Lo(n);return"\n    float "+r+"(int row, int col, int depth,\n                  int depth2, int depth3, int depth4) {\n      // Explicitly use integer operations as dot() only works on floats.\n      int index = row * "+p+" + col * "+h+" + depth * "+c+" +\n          depth2 * "+l+" + depth3 * "+u+" + depth4 + "+g+";\n      vec2 uv = uvFromFlat("+v+", "+m+", index);\n      return sampleTexture("+n+", uv);\n    }\n  ";}(t);default:throw new Error(e.length+"-D input sampling is not yet supported");}}function Oo(t){var e,n,r;switch(t.shapeInfo.logicalShape.length){case 0:return e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1),r=No(),"\n    vec4 "+n+"() {\n      return "+r.texture2D+"("+e+", halfCR);\n    }\n  ";case 1:return function(t){var e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1),r=t.shapeInfo.texShape,o=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],a=No();return"\n    vec4 "+n+"(int index) {\n      vec2 uv = packedUVfrom1D(\n        "+o[0]+", "+o[1]+", index);\n      return "+a.texture2D+"("+e+", uv);\n    }\n  ";}(t);case 2:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=t.shapeInfo.texShape,a=o[0],i=o[1],s=No();if(null!=o&&x(e,o))return"\n      vec4 "+r+"(int row, int col) {\n        vec2 uv = (vec2(col, row) + halfCR) / vec2("+i+".0, "+a+".0);\n\n        return "+s.texture2D+"("+n+", uv);\n      }\n    ";var u=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],l=Math.ceil(e[1]/2);return"\n    vec4 "+r+"(int row, int col) {\n      vec2 uv = packedUVfrom2D("+l+", "+u[0]+", "+u[1]+", row, col);\n      return "+s.texture2D+"("+n+", uv);\n    }\n  ";}(t);case 3:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=t.shapeInfo.texShape,a=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)];if(1===e[0]){var i=e.slice(1),s=zo(t,i);return"\n        "+Oo(s)+"\n        vec4 "+r+"(int b, int row, int col) {\n          return "+r+"("+Vo(["b","row","col"],[1,2])+");\n        }\n      ";}var u=a[0],l=a[1],c=Math.ceil(e[2]/2),h=c*Math.ceil(e[1]/2),p=No();return"\n    vec4 "+r+"(int b, int row, int col) {\n      vec2 uv = packedUVfrom3D(\n        "+u+", "+l+", "+h+", "+c+", b, row, col);\n      return "+p.texture2D+"("+n+", uv);\n    }\n  ";}(t);default:return function(t){for(var e=t.shapeInfo.logicalShape,n=e.length,r=t.name,o="get"+r.charAt(0).toUpperCase()+r.slice(1),a=t.shapeInfo.texShape,i=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],s=i[0],u=i[1],l=Math.ceil(e[n-1]/2),c=l*Math.ceil(e[n-2]/2),h="int b, int row, int col",p="b * "+c+" + (row / 2) * "+l+" + (col / 2)",f=2;f<n-1;f++)h="int b"+f+", "+h,c*=e[n-f-1],p="b"+f+" * "+c+" + "+p;var d=No();return"\n    vec4 "+o+"("+h+") {\n      int index = "+p+";\n      int texR = index / "+u+";\n      int texC = index - texR * "+u+";\n      vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+u+", "+s+");\n      return "+d.texture2D+"("+r+", uv);\n    }\n  ";}(t);}}var Mo="\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",Fo="\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",Bo="\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",Po="\n  float getChannel(vec4 frag, vec2 innerDims) {\n    vec2 modCoord = mod(innerDims, 2.);\n    return modCoord.x == 0. ?\n      (modCoord.y == 0. ? frag.r : frag.g) :\n      (modCoord.y == 0. ? frag.b : frag.a);\n  }\n  float getChannel(vec4 frag, int dim) {\n    float modCoord = mod(float(dim), 2.);\n    return modCoord == 0. ? frag.r : frag.g;\n  }\n";function Lo(t){return"offset"+t;}function Wo(t){var e=t.name,n=y(t.shapeInfo.logicalShape);return n<2?"return "+e+";":"\n    for (int i = 0; i < "+n+"; i++) {\n      if (i == index) {\n        return "+e+"[i];\n      }\n    }\n  ";}function Uo(t){if(t<=1)return"int";if(2===t)return"ivec2";if(3===t)return"ivec3";if(4===t)return"ivec4";if(5===t)return"ivec5";if(6===t)return"ivec6";throw Error("GPU for rank "+t+" is not yet supported");}function zo(t,e){var n=JSON.parse(JSON.stringify(t));return n.shapeInfo.logicalShape=e,n;}function Vo(t,e){return e.map(function(e){return t[e];}).join(", ");}var Go=function(){return function(t,e,n,r){this.variableNames=["A"],this.usesPackedTextures=!0,d(t.length>2,function(){return"Packed arg"+(n.charAt(0).toUpperCase()+n.slice(1))+" supports only inputs with rank above 2.";});var o=t[t.length-1],a=Math.ceil(o/e);this.outputShape=t.slice(0,-1),a>1&&this.outputShape.push(a),r||this.variableNames.push("bestIndicesA");var i,s,u=this.outputShape,l=u.length,c=Uo(l),h=So("coords",l);if(1===a){var p=Uo(s=l+1);i="\n        "+p+" sourceLocR = "+p+"("+h.join()+", 0);\n        ++"+h[l-1]+";\n        "+p+" sourceLocG = "+p+"("+h.join()+", 0);\n        ++"+h[l-2]+";\n        "+p+" sourceLocA = "+p+"("+h.join()+", 0);\n        --"+h[l-1]+";\n        "+p+" sourceLocB = "+p+"("+h.join()+", 0);\n        --"+h[l-2]+";";}else s=l,i="\n        "+c+" sourceLocR = coords;\n        ++"+h[l-1]+";\n        "+c+" sourceLocG = coords;\n        ++"+h[l-2]+";\n        "+c+" sourceLocA = coords;\n        --"+h[l-1]+";\n        "+c+" sourceLocB = coords;\n        --"+h[l-2]+";";var f=["x","y","z","w","u","v"].slice(0,s),v="."+f[s-1],m=f.map(function(t){return"int "+t;}),g=So("sourceLocR",s-1).concat("inIdx.r"),y=So("sourceLocG",s-1).concat("inIdx.g"),x=So("sourceLocB",s-1).concat("inIdx.b"),b=So("sourceLocA",s-1).concat("inIdx.a"),w="max"===n?"greaterThan":"lessThan",C=r?"":"\n          inIdx = round(vec4(getBestIndicesAChannel("+g.join()+"),\n                             getBestIndicesAChannel("+y.join()+"),\n                             getBestIndicesAChannel("+x.join()+"),\n                             getBestIndicesAChannel("+b.join()+")));",E="vec4(\n            getAChannel("+g.join()+"),\n            hasNextCol ? getAChannel("+y.join()+") : 0.,\n            hasNextRow ? getAChannel("+x.join()+") : 0.,\n            hasNextRow && hasNextCol ? getAChannel("+b.join()+") : 0.)",R=r?"":"\n      float getBestIndicesAChannel("+m.join()+") {\n        return getChannel(getBestIndicesA("+f.join()+"),\n                                          vec2("+f.slice(-2).join()+"));\n      }";this.userCode="\n      float getAChannel("+m.join()+") {\n        return getChannel(getA("+f.join()+"),\n                               vec2("+f.slice(-2).join()+"));\n      }\n      "+R+"\n      void main() {\n        "+c+" coords = getOutputCoords();\n        bool hasNextCol = "+h[l-1]+" < "+(u[l-1]-1)+";\n        bool hasNextRow = "+h[l-2]+" < "+(u[l-2]-1)+";\n        "+i+"\n        ivec4 srcIdx = ivec4(sourceLocR"+v+", sourceLocG"+v+",\n          sourceLocB"+v+", sourceLocA"+v+") * "+e+";\n        ivec4 inIdx = srcIdx;\n        vec4 bestIndex = vec4(inIdx);\n        vec4 bestValue = "+E+";\n\n        for (int i = 0; i < "+e+"; i++) {\n          inIdx = srcIdx;\n          "+C+"\n          vec4 candidate = "+E+";\n          bvec4 nan = isnan(candidate);\n          bvec4 replace = bvec4(\n            vec4("+w+"(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    ";};}(),qo=function(){return function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,o=t.strideWidth,a=t.dilationHeight,i=t.dilationWidth,s=t.effectiveFilterHeight,u=t.effectiveFilterWidth,l=s-1-t.padInfo.top,c=u-1-t.padInfo.left,h=1/(e*n);this.userCode="\n      const ivec2 pads = ivec2("+l+", "+c+");\n      const float avgMultiplier = float("+h+");\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n\n        ivec2 dyRCCorner = coords.yz - pads;\n        int dyRCorner = dyRCCorner.x;\n        int dyCCorner = dyRCCorner.y;\n\n        // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        for (int wR = 0; wR < "+s+";\n            wR += "+a+") {\n          float dyR = float(dyRCorner + wR) / "+r+".0;\n\n          if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          for (int wC = 0; wC < "+u+";\n            wC+= "+i+") {\n            float dyC = float(dyCCorner + wC) / "+o+".0;\n\n            if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n                fract(dyC) > 0.0) {\n              continue;\n            }\n            int idyC = int(dyC);\n\n            float dyValue = getDy(b, idyR, idyC, d);\n\n            dotProd += dyValue * avgMultiplier;\n          }\n        }\n        setOutput(dotProd);\n      }\n    ";};}(),Ho=function(){return function(t,e,n,r,o,a){this.outputShape=[],this.variableNames=["x","mean","variance"],Yr(t,e),Yr(t,n);var i="0.0";null!=r&&(Yr(t,r),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");var s="1.0";null!=o&&(Yr(t,o),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n      void main() {\n        float x = getXAtOutCoords();\n        float mean = getMeanAtOutCoords();\n        float variance = getVarianceAtOutCoords();\n        float offset = "+i+";\n        float scale = "+s+";\n        float inv = scale * inversesqrt(variance + float("+a+"));\n        setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n      }\n    ";};}(),$o=function(){return function(t,e,n,r,o,a){this.usesPackedTextures=!0,this.variableNames=["x","mean","variance"],Yr(t,e),Yr(t,n);var i="vec4(0.0)";null!=r&&(Yr(t,r),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");var s="vec4(1.0)";null!=o&&(Yr(t,o),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n      void main() {\n        vec4 offset = "+i+";\n        vec4 scale = "+s+";\n\n        vec4 x = getXAtOutCoords();\n        vec4 mean = getMeanAtOutCoords();\n        vec4 variance = getVarianceAtOutCoords();\n\n        vec4 inv = scale * inversesqrt(variance + vec4("+a+"));\n\n        setOutput((x - mean) * inv + offset);\n      }\n    ";};}(),jo="return areal * breal - aimag * bimag;",Ko="return areal * bimag + aimag * breal;",Xo=function(){return function(t,e,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=Yr(e,n),this.userCode="\n      float binaryOpComplex(\n          float areal, float aimag, float breal, float bimag) {\n        "+t+"\n      }\n\n      void main() {\n        float areal = getARealAtOutCoords();\n        float aimag = getAImagAtOutCoords();\n        float breal = getBRealAtOutCoords();\n        float bimag = getBImagAtOutCoords();\n        setOutput(binaryOpComplex(areal, aimag, breal, bimag));\n      }\n    ";};}(),Yo="return a + b;",Qo="return a - b;",Jo="return a * b;",Zo=function(){return function(t,e,n){this.variableNames=["A","B"],this.outputShape=Yr(e,n),this.userCode="\n      float binaryOperation(float a, float b) {\n        "+t+"\n      }\n\n      void main() {\n        float a = getAAtOutCoords();\n        float b = getBAtOutCoords();\n        setOutput(binaryOperation(a, b));\n      }\n    ";};}(),ta=function(){return function(t,e,n,r){void 0===r&&(r=!1),this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.usesPackedTextures=!0,this.outputShape=Yr(e,n);var o=this.outputShape.length,a="";if(r)if(0===o||1===y(this.outputShape))a="\n          result.y = 0.;\n          result.z = 0.;\n          result.w = 0.;\n        ";else if(a="\n          "+Uo(o)+" coords = getOutputCoords();\n        ",1===o)a+="\n            result.y = (coords + 1) >= "+this.outputShape[0]+" ? 0. : result.y;\n            result.z = 0.;\n            result.w = 0.;\n          ";else{var i=So("coords",o);a+="\n            bool nextRowOutOfBounds =\n              ("+i[o-2]+" + 1) >= "+this.outputShape[o-2]+";\n            bool nextColOutOfBounds =\n              ("+i[o-1]+" + 1) >= "+this.outputShape[o-1]+";\n            result.y = nextColOutOfBounds ? 0. : result.y;\n            result.z = nextRowOutOfBounds ? 0. : result.z;\n            result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n          ";}this.userCode="\n      vec4 binaryOperation(vec4 a, vec4 b) {\n        "+t+"\n      }\n\n      void main() {\n        vec4 a = getAAtOutCoords();\n        vec4 b = getBAtOutCoords();\n\n        vec4 result = binaryOperation(a, b);\n        "+a+"\n\n        setOutput(result);\n      }\n    ";};}(),ea=function(){function t(t){this.variableNames=["A"],this.outputShape=t,this.userCode="\n      uniform float min;\n      uniform float max;\n\n      void main() {\n        float value = getAAtOutCoords();\n        if (isnan(value)) {\n          setOutput(value);\n          return;\n        }\n\n        setOutput(clamp(value, min, max));\n      }\n    ";}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,o){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(o,"min"),n.maxLoc=r.getUniformLocationNoThrow(o,"max")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e);};},t;}(),na=function(){function t(t){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t,this.userCode="\n      uniform float min;\n      uniform float max;\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(min), vec4(max)));\n      }\n    ";}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,o){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(o,"min"),n.maxLoc=r.getUniformLocationNoThrow(o,"max")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e);};},t;}(),ra=function(){return function(t){this.variableNames=["real","imag"],this.outputShape=t,this.userCode="\n      void main() {\n        float re = abs(getRealAtOutCoords());\n        float im = abs(getImagAtOutCoords());\n        float mx = max(re, im);\n\n        // sadly the length function in glsl is not underflow-safe\n        // (at least not on Intel GPUs). So the safe solution is\n        // to ensure underflow-safety in all cases.\n        setOutput(\n          mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))\n        );\n      }\n    ";};}(),oa=function(){return function(t){this.outputShape=[],this.outputShape=hn(t,1),this.variableNames=t.map(function(t,e){return"T"+e;});var e=new Array(t.length-1);e[0]=t[0][1];for(var n=1;n<e.length;n++)e[n]=e[n-1]+t[n][1];var r=["if (yC < "+e[0]+") setOutput(getT0(yR, yC));"];for(n=1;n<e.length;n++){var o=e[n-1];r.push("else if (yC < "+e[n]+") setOutput(getT"+n+"(yR, yC-"+o+"));");}var a=e.length,i=e[e.length-1];r.push("else setOutput(getT"+a+"(yR, yC-"+i+"));"),this.userCode="\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int yR = coords.x;\n        int yC = coords.y;\n\n        "+r.join("\n        ")+"\n      }\n    ";};}(),aa=function(){return function(t,e){this.usesPackedTextures=!0,this.outputShape=[],this.outputShape=hn(t,e);var n=this.outputShape,r=n.length,o=Uo(r),a=So("coords",r),i=["x","y","z","w","u","v"].slice(0,r);this.variableNames=t.map(function(t,e){return"T"+e;});var s=new Array(t.length-1);s[0]=t[0][e];for(var u=1;u<s.length;u++)s[u]=s[u-1]+t[u][e];var l=i[e],c="vec2("+i.slice(-2).join()+")",h=i.join(),p="if ("+l+" < "+s[0]+")\n          return getChannel(getT0("+h+"), "+c+");";for(u=1;u<s.length;u++){var f=s[u-1];p+="\n        else if ("+l+" < "+s[u]+") {\n          "+l+" -= "+f+";\n          return getChannel(getT"+u+"("+h+"), "+c+");\n        }";}var d=s.length;p+="\n        else {\n          "+l+" -= "+s[s.length-1]+";\n          return getChannel(getT"+d+"("+h+"), "+c+");\n        }",this.userCode="\n      float getValue("+i.map(function(t){return"int "+t;})+") {\n        "+p+"\n      }\n\n      void main() {\n        "+o+" coords = getOutputCoords();\n        vec4 result = vec4(getValue("+a+"), 0., 0., 0.);\n        if (++"+a[r-1]+" < "+n[r-1]+") {\n          result.g = getValue("+a+");\n        }\n        if (++"+a[r-2]+" < "+n[r-2]+") {\n          result.a = getValue("+a+");\n        }\n        if ("+a[r-2]+" < "+n[r-2]+" &&\n            --"+a[r-1]+" < "+n[r-1]+") {\n          result.b = getValue("+a+");\n        }\n        setOutput(result);\n      }\n    ";};}(),ia=function(){return function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,n=t.strideWidth,r=t.padInfo.top,o=t.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 < "+t.batchSize+"; b++) {\n          for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n            int xR = wR + yR * "+e+" - "+r+";\n\n            if (xR < 0 || xR >= "+t.inHeight+") {\n              continue;\n            }\n\n            for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n              int xC = wC + yC * "+n+" - "+o+";\n\n              if (xC < 0 || xC >= "+t.inWidth+") {\n                continue;\n              }\n\n              float dyValue = getDy(b, yR, yC, d2);\n              float xValue = getX(b, xR, xC, d1);\n              dotProd += (xValue * dyValue);\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    ";};}(),sa=function(){return function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,o=t.strideWidth,a=e-1-t.padInfo.top,i=n-1-t.padInfo.left;this.userCode="\n      const ivec2 pads = ivec2("+a+", "+i+");\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d1 = coords[3];\n\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 < "+e+"; wR++) {\n          float dyR = float(dyRCorner + wR) / "+r+".0;\n\n          if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          int wRPerm = "+e+" - 1 - wR;\n\n          for (int wC = 0; wC < "+n+"; wC++) {\n            float dyC = float(dyCCorner + wC) / "+o+".0;\n\n            if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n                fract(dyC) > 0.0) {\n              continue;\n            }\n            int idyC = int(dyC);\n\n            int wCPerm = "+n+" - 1 - wC;\n\n            for (int d2 = 0; d2 < "+t.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    ";};}(),ua=function(){return function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideDepth,n=t.strideHeight,r=t.strideWidth,o=t.padInfo.front,a=t.padInfo.top,i=t.padInfo.left;this.userCode="\n      void main() {\n        ivec5 coords = getOutputCoords();\n        int wF = coords.x;\n        int wR = coords.y;\n        int wC = coords.z;\n        int d1 = coords.w;\n        int d2 = coords.u;\n\n        float dotProd = 0.0;\n\n        for (int b = 0; b < "+t.batchSize+"; b++) {\n          for (int yF = 0; yF < "+t.outDepth+"; yF++) {\n            int xF = wF + yF * "+e+" - "+o+";\n\n            if (xF < 0 || xF >= "+t.inDepth+") {\n              continue;\n            }\n\n            for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n              int xR = wR + yR * "+n+" - "+a+";\n\n              if (xR < 0 || xR >= "+t.inHeight+") {\n                continue;\n              }\n\n              for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n                int xC = wC + yC * "+r+" - "+i+";\n\n                if (xC < 0 || xC >= "+t.inWidth+") {\n                  continue;\n                }\n\n                float dyValue = getDy(b, yF, yR, yC, d2);\n                float xValue = getX(b, xF, xR, xC, d1);\n                dotProd += (xValue * dyValue);\n              }\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    ";};}(),la=function(){return function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,r=t.filterWidth,o=t.strideDepth,a=t.strideHeight,i=t.strideWidth,s=e-1-t.padInfo.front,u=n-1-t.padInfo.top,l=r-1-t.padInfo.left;this.userCode="\n      const ivec3 pads = ivec3("+s+", "+u+", "+l+");\n\n      void main() {\n        ivec5 coords = getOutputCoords();\n        int batch = coords.x;\n        int d1 = coords.u;\n\n\n        ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n        int dyFCorner = dyCorner.x;\n        int dyRCorner = dyCorner.y;\n        int dyCCorner = dyCorner.z;\n\n        float dotProd = 0.0;\n        for (int wF = 0; wF < "+e+"; wF++) {\n          float dyF = float(dyFCorner + wF) / "+o+".0;\n\n          if (dyF < 0.0 || dyF >= "+t.outDepth+".0 || fract(dyF) > 0.0) {\n            continue;\n          }\n          int idyF = int(dyF);\n\n          int wFPerm = "+e+" - 1 - wF;\n\n          for (int wR = 0; wR < "+n+"; wR++) {\n            float dyR = float(dyRCorner + wR) / "+a+".0;\n\n            if (dyR < 0.0 || dyR >= "+t.outHeight+".0 ||\n              fract(dyR) > 0.0) {\n              continue;\n            }\n            int idyR = int(dyR);\n\n            int wRPerm = "+n+" - 1 - wR;\n\n            for (int wC = 0; wC < "+r+"; wC++) {\n              float dyC = float(dyCCorner + wC) / "+i+".0;\n\n              if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n                  fract(dyC) > 0.0) {\n                continue;\n              }\n              int idyC = int(dyC);\n\n              int wCPerm = "+r+" - 1 - wC;\n\n              for (int d2 = 0; d2 < "+t.outChannels+"; d2++) {\n                float xValue = getDy(batch, idyF, idyR, idyC, d2);\n                float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);\n                dotProd += xValue * wValue;\n              }\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    ";};}(),ca=function(){return function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,n=t.strideWidth,r=t.padInfo.top,o=t.padInfo.left,a=t.outChannels/t.inChannels;this.userCode="\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int wR = coords.x;\n        int wC = coords.y;\n        int d1 = coords.z;\n        int dm = coords.w;\n        int d2 = d1 * "+a+" + dm;\n\n        float dotProd = 0.0;\n\n        // TODO: Vec4 over the batch size\n        for (int b = 0; b < "+t.batchSize+"; b++) {\n          for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n            int xR = wR + yR * "+e+" - "+r+";\n\n            if (xR < 0 || xR >= "+t.inHeight+") {\n              continue;\n            }\n\n            for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n              int xC = wC + yC * "+n+" - "+o+";\n\n              if (xC < 0 || xC >= "+t.inWidth+") {\n                continue;\n              }\n\n              float dyValue = getDy(b, yR, yC, d2);\n              float xValue = getX(b, xR, xC, d1);\n              dotProd += (xValue * dyValue);\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    ";};}(),ha=function(){return function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,o=t.strideWidth,a=e-1-t.padInfo.top,i=n-1-t.padInfo.left,s=t.outChannels/t.inChannels;this.userCode="\n      const ivec2 pads = ivec2("+a+", "+i+");\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d1 = coords[3];\n        ivec2 dyCorner = coords.yz - pads;\n        int dyRCorner = dyCorner.x;\n        int dyCCorner = dyCorner.y;\n\n        float dotProd = 0.0;\n\n        for (int wR = 0; wR < "+e+"; wR++) {\n          float dyR = float(dyRCorner + wR) / "+r+".0;\n\n          if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          int wRPerm = "+e+" - 1 - wR;\n\n          for (int wC = 0; wC < "+n+"; wC++) {\n            float dyC = float(dyCCorner + wC) / "+o+".0;\n\n            if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n                fract(dyC) > 0.0) {\n              continue;\n            }\n            int idyC = int(dyC);\n\n            int wCPerm = "+n+" - 1 - wC;\n\n            // TODO: Vec4 over the channelMul\n            for (int dm = 0; dm < "+s+"; dm++) {\n              int d2 = d1 * "+s+" + dm;\n              float xValue = getDy(batch, idyR, idyC, d2);\n              float wValue = getW(wRPerm, wCPerm, d1, dm);\n              dotProd += xValue * wValue;\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    ";};}(),pa=function(){return function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.padInfo.top,n=t.padInfo.left,r=t.strideHeight,o=t.strideWidth,a=t.dilationHeight,i=t.dilationWidth,s=t.filterHeight,u=t.filterWidth,l=4*Math.floor(t.inChannels/4),c=t.inChannels%4;this.userCode="\n      const ivec2 strides = ivec2("+r+", "+o+");\n      const ivec2 pads = ivec2("+e+", "+n+");\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d2 = coords[3];\n\n        ivec2 xRCCorner = coords.yz * strides - pads;\n        int xRCorner = xRCCorner.x;\n        int xCCorner = xRCCorner.y;\n\n        // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        for (int wR = 0; wR < "+s+"; wR++) {\n          int xR = xRCorner + wR * "+a+";\n\n          if (xR < 0 || xR >= "+t.inHeight+") {\n            continue;\n          }\n\n          for (int wC = 0; wC < "+u+"; wC++) {\n            int xC = xCCorner + wC * "+i+";\n\n            if (xC < 0 || xC >= "+t.inWidth+") {\n              continue;\n            }\n\n            for (int d1 = 0; d1 < "+l+"; d1 += 4) {\n              vec4 xValues = vec4(\n                getX(batch, xR, xC, d1),\n                getX(batch, xR, xC, d1 + 1),\n                getX(batch, xR, xC, d1 + 2),\n                getX(batch, xR, xC, d1 + 3)\n              );\n              vec4 wValues = vec4(\n                getW(wR, wC, d1, d2),\n                getW(wR, wC, d1 + 1, d2),\n                getW(wR, wC, d1 + 2, d2),\n                getW(wR, wC, d1 + 3, d2)\n              );\n\n              dotProd += dot(xValues, wValues);\n            }\n\n            if ("+(1===c)+") {\n              dotProd +=\n                getX(batch, xR, xC, "+l+") *\n                getW(wR, wC, "+l+", d2);\n            } else if ("+(2===c)+") {\n              vec2 xValues = vec2(\n                getX(batch, xR, xC, "+l+"),\n                getX(batch, xR, xC, "+l+" + 1)\n              );\n              vec2 wValues = vec2(\n                getW(wR, wC, "+l+", d2),\n                getW(wR, wC, "+l+" + 1, d2)\n              );\n              dotProd += dot(xValues, wValues);\n            } else if ("+(3===c)+") {\n              vec3 xValues = vec3(\n                getX(batch, xR, xC, "+l+"),\n                getX(batch, xR, xC, "+l+" + 1),\n                getX(batch, xR, xC, "+l+" + 2)\n              );\n              vec3 wValues = vec3(\n                getW(wR, wC, "+l+", d2),\n                getW(wR, wC, "+l+" + 1, d2),\n                getW(wR, wC, "+l+" + 2, d2)\n              );\n              dotProd += dot(xValues, wValues);\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    ";};}(),fa=function(){return function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.padInfo.front,n=t.padInfo.top,r=t.padInfo.left,o=t.strideDepth,a=t.strideHeight,i=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,l=t.dilationWidth,c=t.filterDepth,h=t.filterHeight,p=t.filterWidth,f=4*Math.floor(t.inChannels/4),d=t.inChannels%4;this.userCode="\n      const ivec3 strides = ivec3("+o+", "+a+", "+i+");\n      const ivec3 pads = ivec3("+e+", "+n+", "+r+");\n\n      void main() {\n        ivec5 coords = getOutputCoords();\n        int batch = coords.x;\n        int d2 = coords.u;\n\n        ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n        int xFCorner = xFRCCorner.x;\n        int xRCorner = xFRCCorner.y;\n        int xCCorner = xFRCCorner.z;\n\n        // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get\n        // y(yF, yR, yC, d2). ? = to be determined. : = across all\n        // values in that axis.\n        float dotProd = 0.0;\n        for (int wF = 0; wF < "+c+"; wF++) {\n          int xF = xFCorner + wF * "+s+";\n\n          if (xF < 0 || xF >= "+t.inDepth+") {\n            continue;\n          }\n\n          for (int wR = 0; wR < "+h+"; wR++) {\n            int xR = xRCorner + wR * "+u+";\n\n            if (xR < 0 || xR >= "+t.inHeight+") {\n              continue;\n            }\n\n            for (int wC = 0; wC < "+p+"; wC++) {\n              int xC = xCCorner + wC * "+l+";\n\n              if (xC < 0 || xC >= "+t.inWidth+") {\n                continue;\n              }\n\n              for (int d1 = 0; d1 < "+f+"; d1 += 4) {\n                vec4 xValues = vec4(\n                  getX(batch, xF, xR, xC, d1),\n                  getX(batch, xF, xR, xC, d1 + 1),\n                  getX(batch, xF, xR, xC, d1 + 2),\n                  getX(batch, xF, xR, xC, d1 + 3)\n                );\n                vec4 wValues = vec4(\n                  getW(wF, wR, wC, d1, d2),\n                  getW(wF, wR, wC, d1 + 1, d2),\n                  getW(wF, wR, wC, d1 + 2, d2),\n                  getW(wF, wR, wC, d1 + 3, d2)\n                );\n\n                dotProd += dot(xValues, wValues);\n              }\n\n              if ("+(1===d)+") {\n                dotProd +=\n                  getX(batch, xF, xR, xC, "+f+") *\n                  getW(wF, wR, wC, "+f+", d2);\n              } else if ("+(2===d)+") {\n                vec2 xValues = vec2(\n                  getX(batch, xF, xR, xC, "+f+"),\n                  getX(batch, xF, xR, xC, "+f+" + 1)\n                );\n                vec2 wValues = vec2(\n                  getW(wF, wR, wC, "+f+", d2),\n                  getW(wF, wR, wC, "+f+" + 1, d2)\n                );\n                dotProd += dot(xValues, wValues);\n              } else if ("+(3===d)+") {\n                vec3 xValues = vec3(\n                  getX(batch, xF, xR, xC, "+f+"),\n                  getX(batch, xF, xR, xC, "+f+" + 1),\n                  getX(batch, xF, xR, xC, "+f+" + 2)\n                );\n                vec3 wValues = vec3(\n                  getW(wF, wR, wC, "+f+", d2),\n                  getW(wF, wR, wC, "+f+" + 1, d2),\n                  getW(wF, wR, wC, "+f+" + 2, d2)\n                );\n                dotProd += dot(xValues, wValues);\n              }\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    ";};}(),da=function(){return function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.inHeight,n=t.inWidth,r=t.padInfo.top,o=t.padInfo.left,a=t.strideHeight,i=t.strideWidth,s=t.dilationHeight,u=t.dilationWidth,l=t.filterHeight,c=t.filterWidth,h=t.outChannels/t.inChannels;this.userCode="\n      const ivec2 strides = ivec2("+a+", "+i+");\n      const ivec2 pads = ivec2("+r+", "+o+");\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 / "+h+";\n        int q = d2 - d1 * "+h+";\n\n        int xRCorner = xRCCorner.x;\n        int xCCorner = xRCCorner.y;\n\n        // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        // TODO(dsmilkov): Flatten the two for loops and vec4 the operations.\n        for (int wR = 0; wR < "+l+"; wR++) {\n          int xR = xRCorner + wR * "+s+";\n\n          if (xR < 0 || xR >= "+e+") {\n            continue;\n          }\n\n          for (int wC = 0; wC < "+c+"; wC++) {\n            int xC = xCCorner + wC * "+u+";\n\n            if (xC < 0 || xC >= "+n+") {\n              continue;\n            }\n\n            float xVal = getX(batch, xR, xC, d1);\n            float wVal = getW(wR, wC, d1, q);\n            dotProd += xVal * wVal;\n          }\n        }\n        setOutput(dotProd);\n      }\n    ";};}(),va=function(){return function(t){this.variableNames=["x","W"],this.usesPackedTextures=!0,this.outputShape=t.outShape;for(var e=t.inHeight,n=t.inWidth,r=t.padInfo.top,o=t.padInfo.left,a=t.strideHeight,i=t.strideWidth,s=t.dilationHeight,u=t.dilationWidth,l=t.filterHeight,c=t.filterWidth,h=c,f="int xR; int xC; int xCOffset;",d=0;d<l;d++)for(var v=0;v<c;v++)f+="\n          vec4 xTexelR"+d+"C"+2*v+" = vec4(0.);\n          vec4 wR"+d+"C"+v+" = vec4(0.);\n          vec4 xR"+d+"C"+v+" = vec4(0.);";for(d=0;d<l;d++)for(var m=0;m<h;m++){if(f+="\n          xR = xRCorner + "+d*s+";\n          xC = xCCorner + "+(v=2*m)*u+";\n        ",1===i){if(v<c&&(f+=o%2==1?"\n                xCOffset = xC + 1;\n                if(xR >= 0 && xR < "+e+" && xCOffset >= 0 && xCOffset < "+n+") {\n                  xTexelR"+d+"C"+v+" = getX(batch, xR, xCOffset, d1);\n                } else {\n                  xTexelR"+d+"C"+v+" = vec4(0.);\n                }\n\n                xCOffset = xC + 1 - 2;\n                if(xR >= 0 && xR < "+e+" && xCOffset >= 0 && xCOffset < "+n+") {\n                  vec4 previous = getX(batch, xR, xCOffset, d1);\n                  xR"+d+"C"+v+" = vec4(previous.zw, xTexelR"+d+"C"+v+".xy);\n                } else {\n                  xR"+d+"C"+v+" = vec4(0, 0, xTexelR"+d+"C"+v+".xy);\n                }\n              ":"\n                if(xR >= 0 && xR < "+e+" && xC >= 0 && xC < "+n+") {\n                  xTexelR"+d+"C"+v+" = getX(batch, xR, xC, d1);\n                } else {\n                  xTexelR"+d+"C"+v+" = vec4(0.);\n                }\n\n                xR"+d+"C"+v+" = xTexelR"+d+"C"+v+";\n              ",v+1<c)){var g=o%2==0?p(u):u;u%2==0&&o%2==1||u%2!=0&&o%2!=1?(f+="\n                  xCOffset = xC + "+o%2+" + "+g+";\n\n                  if(xR >= 0 && xR < "+e+" &&\n                    xCOffset >= 0 && xCOffset < "+n+") {\n                    xTexelR"+d+"C"+(v+2)+" = getX(batch, xR, xCOffset, d1);\n                  }\n                ",u>1&&(f+="\n                    xCOffset -= 2;\n                    if(xR >= 0 && xR < "+e+" &&\n                      xCOffset >= 0 && xCOffset < "+n+") {\n                      xTexelR"+d+"C"+v+" = getX(batch, xR, xCOffset, d1);\n                    } else {\n                      xTexelR"+d+"C"+v+" = vec4(0.);\n                    }\n                  "),f+="\n                  xR"+d+"C"+(v+1)+" = vec4(\n                    xTexelR"+d+"C"+v+".zw, xTexelR"+d+"C"+(v+2)+".xy);\n                "):f+="\n                  xCOffset = xC + "+g+";\n\n                  if(xR >= 0 && xR < "+e+" &&\n                    xCOffset >= 0 && xCOffset < "+n+") {\n                    xTexelR"+d+"C"+(v+2)+" = getX(batch, xR, xCOffset, d1);\n                  }\n\n                  xR"+d+"C"+(v+1)+" = xTexelR"+d+"C"+(v+2)+";\n                ";}}else v<c&&(f+="\n              if(xR >= 0 && xR < "+e+") {\n            ",o%2==1?(f+="\n                xCOffset = xC + 1 - "+i+";\n                if(xCOffset >= 0 && xCOffset < "+n+") {\n                  xTexelR"+d+"C"+v+" = getX(batch, xR, xCOffset, d1);\n                } else {\n                  xTexelR"+d+"C"+v+" = vec4(0.);\n                }\n\n                if(xC + 1 >= 0 && xC + 1 < "+n+") {\n                  xTexelR"+d+"C"+(v+2)+" = getX(batch, xR, xC + 1, d1);\n                } else {\n                  xTexelR"+d+"C"+(v+2)+" = vec4(0.);\n                }\n\n                xR"+d+"C"+v+" = vec4(\n                  xTexelR"+d+"C"+v+".zw, xTexelR"+d+"C"+(v+2)+".zw);\n              ",v+1<c&&(f+="\n                  vec4 final = vec4(0.);\n                  xCOffset = xC + 1 + "+i+";\n                  if(xCOffset >= 0 && xCOffset < "+n+") {\n                    final = getX(batch, xR, xCOffset, d1);\n                  }\n                  xR"+d+"C"+(v+1)+" = vec4(xTexelR"+d+"C"+(v+2)+".xy, final.xy);\n                ")):(f+="\n                if(xC >= 0 && xC < "+n+") {\n                  xTexelR"+d+"C"+v+" = getX(batch, xR, xC, d1);\n                } else {\n                  xTexelR"+d+"C"+v+" = vec4(0.);\n                }\n\n                xCOffset = xC + "+i+";\n                if(xCOffset >= 0 && xCOffset < "+n+") {\n                  xTexelR"+d+"C"+(v+2)+" = getX(batch, xR, xCOffset, d1);\n                } else {\n                  xTexelR"+d+"C"+(v+2)+" = vec4(0.);\n                }\n\n                xR"+d+"C"+v+" = vec4(\n                  xTexelR"+d+"C"+v+".xy, xTexelR"+d+"C"+(v+2)+".xy);\n              ",v+1<c&&(f+="\n                  xR"+d+"C"+(v+1)+" = vec4(\n                    xTexelR"+d+"C"+v+".zw, xTexelR"+d+"C"+(v+2)+".zw);\n                ")),f+="}");v<c&&(f+="\n            vec4 wTexelR"+d+"C"+v+" = getW("+d+", "+v+", d1, q);\n            wR"+d+"C"+v+" = vec4(wTexelR"+d+"C"+v+".xz, wTexelR"+d+"C"+v+".xz);\n          ",v+1<c&&(f+="\n              vec4 wTexelR"+d+"C"+(v+1)+" = getW("+d+", "+(v+1)+", d1, q);\n              wR"+d+"C"+(v+1)+" =\n                vec4(wTexelR"+d+"C"+(v+1)+".xz, wTexelR"+d+"C"+(v+1)+".xz);"));}for(d=0;d<l;d++)for(v=0;v<c;v++)f+="result += xR"+d+"C"+v+" * wR"+d+"C"+v+";";this.userCode="\n      const ivec2 strides = ivec2("+a+", "+i+");\n      const ivec2 pads = ivec2("+r+", "+o+");\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    ";};}(),ma=function(){return function(t,e,n,r,o){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];var a=t[0],i=t[1],s=t[2],u=t[3],l=e[0],c=n[0],h=n[1];this.outputShape=[l,c,h,u];var p="bilinear"===r?1:0,f=[i-1+".0",s-1+".0"],d=f[0],v=f[1],m=c>1?[""+(i-1)/(c-1),"(y2-y1) * height_ratio","y1*"+d+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+d],g=m[0],y=m[1],x=m[2],b=h>1?[""+(s-1)/(h-1),"(x2-x1) * width_ratio","x1*"+v+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+v],w=b[0],C=b[1],E=b[2];this.userCode="\n      const float height_ratio = float("+g+");\n      const float width_ratio = float("+w+");\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int y = coords[1];\n        int x = coords[2];\n        int d = coords[3];\n\n        // get box vals\n        float y1 = getBoxes(b,0);\n        float x1 = getBoxes(b,1);\n        float y2 = getBoxes(b,2);\n        float x2 = getBoxes(b,3);\n\n        // get image in batch index\n        int bInd = round(getBoxInd(b));\n        if(bInd < 0 || bInd >= "+a+") {\n          return;\n        }\n\n        float height_scale = "+y+";\n        float width_scale = "+C+";\n\n        float in_y = "+x+";\n        if( in_y < 0.0 || in_y > "+d+" ) {\n          setOutput(float("+o+"));\n          return;\n        }\n        float in_x = "+E+";\n        if( in_x < 0.0 || in_x > "+v+" ) {\n          setOutput(float("+o+"));\n          return;\n        }\n\n        vec2 sourceFracIndexCR = vec2(in_x,in_y);\n        if("+p+" == 1) {\n          // Compute the four integer indices.\n          ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);\n          ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));\n\n          float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);\n          float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);\n          float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);\n          float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);\n\n          vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);\n\n          float top = topLeft + (topRight - topLeft) * fracCR.x;\n          float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;\n          float newValue = top + (bottom - top) * fracCR.y;\n          setOutput(newValue);\n        } else {\n          // Compute the coordinators of nearest neighbor point.\n          ivec2 sourceNearestCR = ivec2(floor(\n            sourceFracIndexCR + vec2(0.5,0.5)));\n          float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);\n          setOutput(newValue);\n        }\n      }\n    ";};}(),ga=function(){return function(t,e,n){this.variableNames=["x"],this.outputShape=t;var r=t.length,o=t[t.length-1],a=n?"<":">";this.userCode="\n      int getIndex(int i) {\n        "+(n?"return "+o+" -i - 1;":"return i;")+"\n      }\n\n      void main() {\n        "+Uo(r)+" coords = getOutputCoords();\n        int end = "+ya(r,"coords")+";\n        float val = 0.0;\n        for (int i = "+o+" - 1; i >= 0; i -= 1) {\n          int idx = getIndex(i);\n          if (idx "+a+" end) {\n            continue;\n          }\n          if (idx == end && "+e+") {\n            continue;\n          }\n          "+ya(r,"coords")+" = idx;\n          val += getX("+function(t,e){if(1===t)return""+e;if(2===t)return e+".x, "+e+".y";if(3===t)return e+".x, "+e+".y, "+e+".z";if(4===t)return e+".x, "+e+".y, "+e+".z, "+e+".w";throw Error("Cumulative sum for rank "+t+" is not yet supported");}(r,"coords")+");\n        }\n        setOutput(val);\n      }\n    ";};}();function ya(t,e){if(1===t)return""+e;if(2===t)return e+".y";if(3===t)return e+".z";if(4===t)return e+".w";throw Error("Cumulative sum for rank "+t+" is not yet supported");}var xa=function(){return function(t,e){this.variableNames=["A"];var n=No();this.outputShape=t,this.userCode="\n      ivec3 outCoordsFromFlatIndex(int index) {\n        "+ko(["r","c","d"],t)+"\n        return ivec3(r, c, d);\n      }\n\n      void main() {\n        ivec2 resTexRC = ivec2(resultUV.yx *\n          vec2("+e[0]+", "+e[1]+"));\n        int index = 4 * (resTexRC.x * "+e[1]+" + resTexRC.y);\n\n        vec4 result = vec4(0.);\n\n        for (int i=0; i<4; i++) {\n          int flatIndex = index + i;\n          ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n          result[i] = getA(rc.x, rc.y, rc.z);\n        }\n\n        "+n.output+" = result;\n      }\n    ";};}(),ba=function(){return function(t,e){this.variableNames=["A"],this.usesPackedTextures=!0;var n=No();this.outputShape=t,this.userCode="\n      ivec3 outCoordsFromFlatIndex(int index) {\n        "+ko(["r","c","d"],t)+"\n        return ivec3(r, c, d);\n      }\n\n      void main() {\n        ivec2 resTexRC = ivec2(resultUV.yx *\n          vec2("+e[0]+", "+e[1]+"));\n        int index = 4 * (resTexRC.x * "+e[1]+" + resTexRC.y);\n\n        vec4 result = vec4(0.);\n\n        for (int i=0; i<4; i++) {\n          int flatIndex = index + i;\n          ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n          result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));\n        }\n\n        "+n.output+" = result;\n      }\n    ";};}(),wa=function(){function t(t,e,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=t,this.blockSize=e,this.dataFormat=n,this.userCode="\n    void main() {\n      ivec4 coords = getOutputCoords();\n      int b = coords[0];\n      int h = "+this.getHeightCoordString()+";\n      int w = "+this.getWidthCoordString()+";\n      int d = "+this.getDepthCoordString()+";\n\n      int in_h = h / "+e+";\n      int offset_h = imod(h, "+e+");\n      int in_w = w / "+e+";\n      int offset_w = imod(w, "+e+");\n      int offset_d = (offset_h * "+e+" + offset_w) *\n        "+this.getOutputDepthSize()+";\n      int in_d = d + offset_d;\n\n      float result = "+this.getInputSamplingString()+";\n      setOutput(result);\n    }\n  ";}return t.prototype.getHeightCoordString=function(){return"NHWC"===this.dataFormat?"coords[1]":"coords[2]";},t.prototype.getWidthCoordString=function(){return"NHWC"===this.dataFormat?"coords[2]":"coords[3]";},t.prototype.getDepthCoordString=function(){return"NHWC"===this.dataFormat?"coords[3]":"coords[1]";},t.prototype.getOutputDepthSize=function(){return"NHWC"===this.dataFormat?this.outputShape[3]:this.outputShape[1];},t.prototype.getInputSamplingString=function(){return"NHWC"===this.dataFormat?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)";},t;}(),Ca=function(){return function(t){this.variableNames=["A"];var e=No();this.outputShape=t,this.userCode="\n      "+To+"\n\n      void main() {\n        float x = getAAtOutCoords();\n        "+e.output+" = encode_float(x);\n      }\n    ";};}(),Ea=function(){return function(t){this.variableNames=["A"],this.usesPackedTextures=!0;var e=No();this.outputShape=t,this.userCode="\n      "+To+"\n\n      void main() {\n        ivec3 coords = getOutputCoords();\n        float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\n        "+e.output+" = encode_float(x);\n      }\n    ";};}(),Ra=function(){return function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"];var r=No(),o=e[0],a=e[1];this.outputShape=t;var i="result";n&&(i="floor(result * 255. + 0.5)"),this.userCode="\n      "+Ao(t)+"\n\n      void main() {\n        ivec3 coords = getOutputCoords();\n\n        int flatIndex = getFlatIndex(coords);\n        int offset = imod(flatIndex, 4);\n\n        flatIndex /= 4;\n        int r = flatIndex / "+a+";\n        int c = imod(flatIndex, "+a+");\n        vec2 uv = (vec2(c, r) + halfCR) / vec2("+a+".0, "+o+".0);\n        vec4 values = "+r.texture2D+"(A, uv);\n\n        float result;\n\n        if(offset == 0) {\n          result = values[0];\n        } else if(offset == 1) {\n          result = values[1];\n        } else if(offset == 2) {\n          result = values[2];\n        } else {\n          result = values[3];\n        }\n\n        "+r.output+" = vec4("+i+", 0., 0., 0.);\n      }\n    ";};}(),Ia=function(){return function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"];var r=No(),o=e[0],a=e[1];this.outputShape=t;var i="",s="result";n&&(s="floor(result * 255. + 0.5)");for(var u=0;u<=1;u++)for(var l=0;l<=1;l++){var c=2*u+l;i+="\n          localCoords = coords;\n          if(localCoords[2] + "+l+" < "+t[2]+") {\n            localCoords[2] += "+l+";\n            if(localCoords[1] + "+u+" < "+t[1]+") {\n              localCoords[1] += "+u+";\n\n              flatIndex = getFlatIndex(localCoords);\n              offset = imod(flatIndex, 4);\n    \n              flatIndex /= 4;\n              r = flatIndex / "+a+";\n              c = imod(flatIndex, "+a+");\n              uv = (vec2(c, r) + halfCR) / vec2("+a+".0, "+o+".0);\n              values = "+r.texture2D+"(A, uv);\n\n              if(offset == 0) {\n                result["+c+"] = values[0];\n              } else if(offset == 1) {\n                result["+c+"] = values[1];\n              } else if(offset == 2) {\n                result["+c+"] = values[2];\n              } else {\n                result["+c+"] = values[3];\n              }\n            }\n          }\n        ";}this.userCode="\n      "+Ao(t)+"\n\n      void main() {\n        ivec3 coords = getOutputCoords();\n\n        vec4 result = vec4(0.);\n        int flatIndex, r, c, offset;\n        ivec3 localCoords;\n        vec2 uv;\n        vec4 values;\n        \n        "+i+"\n\n        "+r.output+" = "+s+";\n      }\n    ";};}(),Sa="return real * expR - imag * expI;",Na="return real * expI + imag * expR;",ka=function(){return function(t,e,n){this.variableNames=["real","imag"];var r=e[1];this.outputShape=e;var o=n?"2.0 * "+Math.PI:"-2.0 * "+Math.PI,a=n?r+".0":"1.0";this.userCode="\n      const float exponentMultiplier = "+o+";\n\n      float unaryOpComplex(float real, float expR, float imag, float expI) {\n        "+t+"\n      }\n\n      float mulMatDFT(int batch, int index) {\n        float indexRatio = float(index) / float("+r+");\n        float exponentMultiplierTimesIndexRatio =\n            exponentMultiplier * indexRatio;\n\n        float result = 0.0;\n\n        for (int i = 0; i < "+r+"; i++) {\n          // x = (-2|2 * PI / N) * index * i;\n          float x = exponentMultiplierTimesIndexRatio * float(i);\n          float expR = cos(x);\n          float expI = sin(x);\n          float real = getReal(batch, i);\n          float imag = getImag(batch, i);\n\n          result +=\n              unaryOpComplex(real, expR, imag, expI) / "+a+";\n        }\n\n        return result;\n      }\n\n      void main() {\n        ivec2 coords = getOutputCoords();\n        setOutput(mulMatDFT(coords[0], coords[1]));\n      }\n    ";};}(),Aa=function(){function t(t,e){this.outputShape=[],this.variableNames=["x"],this.outputShape=t,this.userCode="\n      uniform float value;\n      void main() {\n        // Input can be obtained from uniform value.\n        setOutput(value);\n      }\n    ";}return t.prototype.getCustomSetupFunc=function(t){var e=this;return function(n,r){null==e.valueLoc&&(e.valueLoc=n.getUniformLocationNoThrow(r,"value")),n.gl.uniform1f(e.valueLoc,t);};},t;}(),Ta=function(){return function(t){this.variableNames=["A"];var e=No(),n=t[0],r=t[1];this.outputShape=t,this.userCode="\n      void main() {\n        ivec3 coords = getOutputCoords();\n        int texR = coords[0];\n        int texC = coords[1];\n        int depth = coords[2];\n        vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+r+".0, "+n+".0);\n\n        vec4 values = "+e.texture2D+"(A, uv);\n        float value;\n        if (depth == 0) {\n          value = values.r;\n        } else if (depth == 1) {\n          value = values.g;\n        } else if (depth == 2) {\n          value = values.b;\n        } else if (depth == 3) {\n          value = values.a;\n        }\n\n        setOutput(floor(value * 255.0 + 0.5));\n      }\n    ";};}(),Da=function(){return function(t){this.variableNames=["A"];var e=No(),n=t[0],r=t[1];this.outputShape=t,this.userCode="\n      void main() {\n        ivec3 coords = getOutputCoords();\n        int texR = coords[0];\n        int texC = coords[1];\n        int depth = coords[2];\n\n        vec4 result = vec4(0.);\n\n        for(int row=0; row<=1; row++) {\n          for(int col=0; col<=1; col++) {\n            texC = coords[1] + row;\n            depth = coords[2] + col;\n\n            vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+r+".0, "+n+".0);\n            vec4 values = "+e.texture2D+"(A, uv);\n            float value;\n            if (depth == 0) {\n              value = values.r;\n            } else if (depth == 1) {\n              value = values.g;\n            } else if (depth == 2) {\n              value = values.b;\n            } else if (depth == 3) {\n              value = values.a;\n            }\n\n            result[row * 2 + col] = floor(value * 255.0 + 0.5);\n          }\n        }\n\n        "+e.output+" = result;\n      }\n    ";};}(),_a=function(){return function(t,e,n){this.variableNames=["A","indices"];var r=t.slice();r[n]=e,this.outputShape=r,this.rank=r.length;var o=Uo(this.rank),a=function(t,e){var n=t.length;if(n>4)throw Error("Gather for rank "+n+" is not yet supported");if(1===n)return"int(getIndices(resRC))";for(var r=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[],a=0;a<t.length;a++)a===e?o.push("int(getIndices("+r[a]+"))"):o.push(""+r[a]);return o.join();}(t,n);this.userCode="\n      void main() {\n        "+o+" resRC = getOutputCoords();\n        setOutput(getA("+a+"));\n      }\n    ";};}();var Oa,Ma,Fa=function(){return function(t,e,n){this.sliceDim=t,this.strides=e,this.variableNames=["x","indices"],this.outputShape=n;var r=Uo(e.length),o=Uo(n.length),a=this.sliceDim>1?"strides[j]":"strides";this.userCode="\n        "+r+" strides = "+r+"("+this.strides+");\n         void main() {\n          "+o+" 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 * "+a+";\n          }\n          setOutput(getX(flattenIndex, coords[1]));\n        }\n      ";};}();function Ba(t,e){return[e,t];}function Pa(t){var e=y(t);return C(Math.ceil(e/4));}function La(t,e){return[Math.max(1,Math.ceil(e/2)),Math.max(1,Math.ceil(t/2))];}function Wa(t,e){var n=No();return qt(t,e,n.version+"\n    precision highp float;\n    "+n.attribute+" vec3 clipSpacePos;\n    "+n.attribute+" vec2 uv;\n    "+n.varyingVs+" vec2 resultUV;\n\n    void main() {\n      gl_Position = vec4(clipSpacePos, 1);\n      resultUV = uv;\n    }");}function Ua(t,e){return Jt(t,e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]));}function za(t,e){return Zt(t,e,new Uint16Array([0,1,2,2,1,3]));}function Va(t,e){var n,r,o,a,i,u,l,c,h=t;return 2===exports.ENV.getNumber("WEBGL_VERSION")?(n=h.R32F,r=h.R16F,o=h.RGBA16F,a=h.RGBA32F,i=h.RED,u=4,l=1,c=h.HALF_FLOAT):(n=t.RGBA,r=t.RGBA,o=t.RGBA,a=h.RGBA,i=t.RGBA,u=4,l=4,c=null!=e?e.HALF_FLOAT_OES:null),{internalFormatFloat:n,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:o,internalFormatPackedFloat:a,textureFormatFloat:i,downloadTextureFormat:t.RGBA,downloadUnpackNumChannels:u,defaultNumChannels:l,textureTypeHalfFloat:c};}function Ga(t,e,n,r,o,a,i){ee(n,r);var s=te(t,e),u=t.TEXTURE_2D;return Lt(t,e,function(){return t.bindTexture(u,s);}),Lt(t,e,function(){return t.texParameteri(u,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE);}),Lt(t,e,function(){return t.texParameteri(u,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE);}),Lt(t,e,function(){return t.texParameteri(u,t.TEXTURE_MIN_FILTER,t.NEAREST);}),Lt(t,e,function(){return t.texParameteri(u,t.TEXTURE_MAG_FILTER,t.NEAREST);}),Lt(t,e,function(){return t.texImage2D(u,0,o,n,r,0,a,i,null);}),Lt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null);}),s;}function qa(t,e,n,r,o){var a=Ba(n,r);return Ga(t,e,a[0],a[1],o.internalFormatFloat,o.textureFormatFloat,t.FLOAT);}function Ha(t,e,n,r,o){var a=Ba(n,r);return Ga(t,e,a[0],a[1],o.internalFormatHalfFloat,o.textureFormatFloat,o.textureTypeHalfFloat);}function $a(t,e,n,r,o){var a=Ba(n,r);return Ga(t,e,a[0],a[1],t.RGBA,t.RGBA,t.UNSIGNED_BYTE);}function ja(t,e,n,r,o){var a=La(n,r);return Ga(t,e,a[0],a[1],o.internalFormatPackedFloat,t.RGBA,t.FLOAT);}function Ka(t,e,n,r,o){var a=La(n,r);return Ga(t,e,a[0],a[1],o.internalFormatPackedHalfFloat,t.RGBA,o.textureTypeHalfFloat);}function Xa(t,e,n,r){return Lt(t,e,function(){return t.bindBuffer(t.ARRAY_BUFFER,r);}),re(t,e,n,"clipSpacePos",r,3,20,0)&&re(t,e,n,"uv",r,2,20,12);}function Ya(t,e,n,r,o,a,i){var s,u,l;Lt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,n);}),a instanceof Uint8Array?(s=new Uint8Array(r*o*4),u=t.UNSIGNED_BYTE,l=t.RGBA):(s=new Float32Array(r*o*4),u=t.FLOAT,l=i.internalFormatPackedFloat),s.set(a),Lt(t,e,function(){return t.texImage2D(t.TEXTURE_2D,0,l,r,o,0,t.RGBA,u,s);}),Lt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null);});}function Qa(t,e,n,r){Lt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,n);}),r.data instanceof Uint8Array?Lt(t,e,function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,r.width,r.height,0,t.RGBA,t.UNSIGNED_BYTE,r.data);}):Lt(t,e,function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r);}),Lt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null);});}function Ja(t,e,n,r,o){var a=t.createBuffer();Lt(t,e,function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,a);});var i=16*n*r;return Lt(t,e,function(){return t.bufferData(t.PIXEL_PACK_BUFFER,i,t.STREAM_READ);}),Lt(t,e,function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,0);}),Lt(t,e,function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,null);}),a;}function Za(t,e,n){var r=t,o=new Float32Array(n);return r.bindBuffer(r.PIXEL_PACK_BUFFER,e),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,o),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),o;}function ti(t,e,n,r,o){var a=Ba(n,r),i=a[0],s=a[1],u=new Uint8Array(n*r*4);return Lt(t,e,function(){return t.readPixels(0,0,i,s,o.downloadTextureFormat,t.UNSIGNED_BYTE,u);}),new Float32Array(u.buffer);}function ei(t,e,n,r,o,a,i,s){var u=t,l=new Float32Array(function(t,e){var n=La(t,e);return n[0]*n[1]*4;}(a,i));return u.bindBuffer(u.PIXEL_PACK_BUFFER,e),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,l),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),l;}function ni(t,e,n,r){var o=new Float32Array(n*r*4);return Lt(t,e,function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,o);}),o;}!function(t){t[t.RENDER=0]="RENDER",t[t.UPLOAD=1]="UPLOAD",t[t.PIXELS=2]="PIXELS",t[t.DOWNLOAD=3]="DOWNLOAD";}(Oa||(Oa={})),function(t){t[t.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",t[t.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",t[t.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",t[t.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",t[t.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16";}(Ma||(Ma={}));var ri=Object.freeze({createVertexShader:Wa,createVertexBuffer:Ua,createIndexBuffer:za,getTextureConfig:Va,createFloat32MatrixTexture:qa,createFloat16MatrixTexture:Ha,createUnsignedBytesMatrixTexture:$a,createPackedMatrixTexture:ja,createFloat16PackedMatrixTexture:Ka,bindVertexProgramAttributeStreams:Xa,uploadDenseMatrixToTexture:Ya,uploadPixelDataToTexture:Qa,createBufferFromOutputTexture:Ja,downloadFloat32MatrixFromBuffer:Za,downloadByteEncodedFloatMatrixFromOutputTexture:ti,downloadPackedMatrixFromBuffer:ei,downloadMatrixFromPackedOutputTexture:ni}),oi=function(){function t(t){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];var e=exports.ENV.getNumber("WEBGL_VERSION");null!=t?(this.gl=t,Ft(e,t)):this.gl=Bt(e),1===exports.ENV.getNumber("WEBGL_VERSION")?(this.textureFloatExtension=Gt(this.gl,this.debug,"OES_texture_float"),this.colorBufferFloatExtension=this.gl.getExtension("WEBGL_color_buffer_float"),exports.ENV.getBool("WEBGL_RENDER_FLOAT32_ENABLED")||(this.textureHalfFloatExtension=Gt(this.gl,this.debug,"OES_texture_half_float"),this.colorBufferHalfFloatExtension=this.gl.getExtension("EXT_color_buffer_half_float"))):this.colorBufferFloatExtension=Gt(this.gl,this.debug,"EXT_color_buffer_float"),this.vertexBuffer=Ua(this.gl,this.debug),this.indexBuffer=za(this.gl,this.debug),this.framebuffer=ne(this.gl,this.debug),this.textureConfig=Va(this.gl,this.textureHalfFloatExtension);}return Object.defineProperty(t.prototype,"debug",{get:function(){return exports.ENV.getBool("DEBUG");},enumerable:!0,configurable:!0}),t.prototype.dispose=function(){var t=this;if(!this.disposed){null!=this.program&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),null!=this.outputTexture&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture.  This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");var e=this.gl;Lt(e,this.debug,function(){return e.finish();}),Lt(e,this.debug,function(){return e.bindFramebuffer(e.FRAMEBUFFER,null);}),Lt(e,this.debug,function(){return e.deleteFramebuffer(t.framebuffer);}),Lt(e,this.debug,function(){return e.bindBuffer(e.ARRAY_BUFFER,null);}),Lt(e,this.debug,function(){return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null);}),Lt(e,this.debug,function(){return e.deleteBuffer(t.indexBuffer);}),this.disposed=!0;}},t.prototype.createFloat32MatrixTexture=function(t,e){return this.throwIfDisposed(),qa(this.gl,this.debug,t,e,this.textureConfig);},t.prototype.createFloat16MatrixTexture=function(t,e){return this.throwIfDisposed(),Ha(this.gl,this.debug,t,e,this.textureConfig);},t.prototype.createUnsignedBytesMatrixTexture=function(t,e){return this.throwIfDisposed(),$a(this.gl,this.debug,t,e,this.textureConfig);},t.prototype.uploadPixelDataToTexture=function(t,e){this.throwIfDisposed(),Qa(this.gl,this.debug,t,e);},t.prototype.uploadDenseMatrixToTexture=function(t,e,n,r){this.throwIfDisposed(),Ya(this.gl,this.debug,t,e,n,r,this.textureConfig);},t.prototype.createFloat16PackedMatrixTexture=function(t,e){return this.throwIfDisposed(),Ka(this.gl,this.debug,t,e,this.textureConfig);},t.prototype.createPackedMatrixTexture=function(t,e){return this.throwIfDisposed(),ja(this.gl,this.debug,t,e,this.textureConfig);},t.prototype.deleteMatrixTexture=function(t){var e=this;this.throwIfDisposed(),this.outputTexture===t&&(le(this.gl,this.debug,this.framebuffer),this.outputTexture=null),Lt(this.gl,this.debug,function(){return e.gl.deleteTexture(t);});},t.prototype.downloadByteEncodedFloatMatrixFromOutputTexture=function(t,e,n){var r=this;return this.downloadMatrixDriver(t,function(){return ti(r.gl,r.debug,e,n,r.textureConfig);});},t.prototype.downloadPackedMatrixFromBuffer=function(t,e,n,r,o,a){return ei(this.gl,t,0,0,0,o,a,this.textureConfig);},t.prototype.downloadFloat32MatrixFromBuffer=function(t,e){return Za(this.gl,t,e);},t.prototype.createBufferFromTexture=function(t,e,n){this.bindTextureToFrameBuffer(t);var r=Ja(this.gl,this.debug,e,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),r;},t.prototype.createAndWaitForFence=function(){var t=this.createFence(this.gl);return this.pollFence(t);},t.prototype.createFence=function(t){var e,n,r=this;if(exports.ENV.getBool("WEBGL_FENCE_API_ENABLED")){var o=t,a=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);t.flush(),n=function(){var t=o.clientWaitSync(a,0,0);return t===o.ALREADY_SIGNALED||t===o.CONDITION_SATISFIED;},e=a;}else exports.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(e=this.beginQuery(),this.endQuery(),n=function(){return r.isQueryAvailable(e,exports.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"));}):n=function(){return!0;};return{query:e,isFencePassed:n};},t.prototype.downloadMatrixFromPackedTexture=function(t,e,n){var r=this;return this.downloadMatrixDriver(t,function(){return ni(r.gl,r.debug,e,n);});},t.prototype.createProgram=function(t){this.throwIfDisposed();var e=this.gl,n=Ht(e,this.debug,t),r=Wa(e,this.debug),o=Xt(e,this.debug);return Lt(e,this.debug,function(){return e.attachShader(o,r);}),Lt(e,this.debug,function(){return e.attachShader(o,n);}),Yt(e,this.debug,o),this.debug&&Qt(e,this.debug,o),this.vertexAttrsAreBound||(this.setProgram(o),this.vertexAttrsAreBound=Xa(e,this.debug,this.program,this.vertexBuffer)),o;},t.prototype.deleteProgram=function(t){var e=this;this.throwIfDisposed(),t===this.program&&(this.program=null),null!=t&&Lt(this.gl,this.debug,function(){return e.gl.deleteProgram(t);});},t.prototype.setProgram=function(t){var e=this;this.throwIfDisposed(),this.program=t,null!=this.program&&this.debug&&Qt(this.gl,this.debug,this.program),Lt(this.gl,this.debug,function(){return e.gl.useProgram(t);});},t.prototype.getUniformLocation=function(t,e,n){return void 0===n&&(n=!0),this.throwIfDisposed(),n?ae(this.gl,this.debug,t,e):ie(this.gl,t,e);},t.prototype.getAttributeLocation=function(t,e){var n=this;return this.throwIfDisposed(),Lt(this.gl,this.debug,function(){return n.gl.getAttribLocation(t,e);});},t.prototype.getUniformLocationNoThrow=function(t,e){return this.throwIfDisposed(),this.gl.getUniformLocation(t,e);},t.prototype.setInputMatrixTexture=function(t,e,n){this.throwIfDisposed(),this.throwIfNoProgram(),se(this.gl,this.debug,this.program,t,e,n);},t.prototype.setOutputMatrixTexture=function(t,e,n){this.setOutputMatrixTextureDriver(t,n,e);},t.prototype.setOutputPackedMatrixTexture=function(t,e,n){this.throwIfDisposed();var r=La(e,n),o=r[0],a=r[1];this.setOutputMatrixTextureDriver(t,o,a);},t.prototype.setOutputMatrixWriteRegion=function(t,e,n,r){this.setOutputMatrixWriteRegionDriver(n,t,r,e);},t.prototype.setOutputPackedMatrixWriteRegion=function(t,e,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.");},t.prototype.debugValidate=function(){null!=this.program&&Qt(this.gl,this.debug,this.program),ce(this.gl);},t.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var t=this.gl;this.debug&&this.debugValidate(),Lt(t,this.debug,function(){return t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0);});},t.prototype.blockUntilAllProgramsCompleted=function(){var t=this;this.throwIfDisposed(),Lt(this.gl,this.debug,function(){return t.gl.finish();});},t.prototype.getQueryTimerExtension=function(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=Gt(this.gl,this.debug,2===exports.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension;},t.prototype.getQueryTimerExtensionWebGL2=function(){return this.getQueryTimerExtension();},t.prototype.getQueryTimerExtensionWebGL1=function(){return this.getQueryTimerExtension();},t.prototype.beginQuery=function(){if(2===exports.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var t=this.gl,e=this.getQueryTimerExtensionWebGL2(),n=t.createQuery();return t.beginQuery(e.TIME_ELAPSED_EXT,n),n;}var r=this.getQueryTimerExtensionWebGL1(),o=r.createQueryEXT();return r.beginQueryEXT(r.TIME_ELAPSED_EXT,o),o;},t.prototype.endQuery=function(){if(2!==exports.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var t=this.getQueryTimerExtensionWebGL1();t.endQueryEXT(t.TIME_ELAPSED_EXT);}else{var e=this.gl,n=this.getQueryTimerExtensionWebGL2();e.endQuery(n.TIME_ELAPSED_EXT);}},t.prototype.waitForQueryAndGetTime=function(t){return r(this,void 0,void 0,function(){var e=this;return o(this,function(n){switch(n.label){case 0:return[4,R(function(){return e.disposed||e.isQueryAvailable(t,exports.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"));})];case 1:return n.sent(),[2,this.getQueryTime(t,exports.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))];}});});},t.prototype.getQueryTime=function(t,e){if(0===e)return null;if(2===e){var n=this.gl;return n.getQueryParameter(t,n.QUERY_RESULT)/1e6;}var r=this.getQueryTimerExtensionWebGL1();return r.getQueryObjectEXT(t,r.QUERY_RESULT_EXT)/1e6;},t.prototype.isQueryAvailable=function(t,e){if(0===e)return!0;if(2===e){var n=this.gl,r=this.getQueryTimerExtensionWebGL2(),o=n.getQueryParameter(t,n.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),o&&!this.disjoint;}o=(r=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(t,r.QUERY_RESULT_AVAILABLE_EXT);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),o&&!this.disjoint;},t.prototype.pollFence=function(t){var e=this;return new Promise(function(n){e.addItemToPoll(function(){return t.isFencePassed();},function(){return n();});});},t.prototype.pollItems=function(){for(var t=function(t){for(var e=0;e<t.length;++e){var n=t[e]();if(!n)break;}return e-1;}(this.itemsToPoll.map(function(t){return t.isDoneFn;})),e=0;e<=t;++e){(0, this.itemsToPoll[e].resolveFn)();}this.itemsToPoll=this.itemsToPoll.slice(t+1);},t.prototype.addItemToPoll=function(t,e){var n=this;this.itemsToPoll.push({isDoneFn:t,resolveFn:e}),this.itemsToPoll.length>1||R(function(){return n.pollItems(),0===n.itemsToPoll.length;});},t.prototype.bindTextureToFrameBuffer=function(t){this.throwIfDisposed(),ue(this.gl,this.debug,t,this.framebuffer),this.debug&&ce(this.gl);},t.prototype.unbindTextureToFrameBuffer=function(){null!=this.outputTexture?(ue(this.gl,this.debug,this.outputTexture,this.framebuffer),this.debug&&ce(this.gl)):le(this.gl,this.debug,this.framebuffer);},t.prototype.downloadMatrixDriver=function(t,e){this.bindTextureToFrameBuffer(t);var n=e();return this.unbindTextureToFrameBuffer(),n;},t.prototype.setOutputMatrixTextureDriver=function(t,e,n){this.throwIfDisposed();var r=this.gl;ue(r,this.debug,t,this.framebuffer),this.debug&&ce(r),this.outputTexture=t,Lt(r,this.debug,function(){return r.viewport(0,0,e,n);}),Lt(r,this.debug,function(){return r.scissor(0,0,e,n);});},t.prototype.setOutputMatrixWriteRegionDriver=function(t,e,n,r){var o=this;this.throwIfDisposed(),Lt(this.gl,this.debug,function(){return o.gl.scissor(t,e,n,r);});},t.prototype.throwIfDisposed=function(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.");},t.prototype.throwIfNoProgram=function(){if(null==this.program)throw new Error("No GPU program is currently set.");},t;}();function ai(t,e){if(t.length!==e.length)throw Error("Binary was compiled with "+t.length+" inputs, but was executed with "+e.length+" inputs");t.forEach(function(t,n){var r=t.logicalShape,o=e[n],a=o.shape;if(!x(r,a))throw Error("Binary was compiled with different shapes than the current args. Shapes "+r+" and "+a+" must match");if(!t.isUniform||!o.isUniform){var i=t.texShape,s=o.isUniform?null:o.texData.texShape;if(!x(i,s))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+i+" and "+s+" must match");}});}var ii=function(){return function(t,e,n){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t;var r=n.filterWidth,o=n.inChannels,a=n.strideWidth,i=n.strideHeight,s=n.padInfo,u=n.outWidth,l=n.dilationWidth,c=n.dilationHeight,h=s.left,p=s.top,f=o*r,d=No();this.userCode="\n      void main() {\n        ivec2 rc = getOutputCoords();\n\n        vec4 result = vec4(0);\n\n        for(int row=0; row<=1; row++) {\n          for(int col=0; col<=1; col++) {\n            int blockIndex = rc.y + col;\n            int pos = rc.x + row;\n\n            if(blockIndex >= "+t[1]+" || pos >= "+t[0]+") continue;\n\n            int offsetY = int(blockIndex / ("+u+")) * "+i+" - "+p+";\n            int d0 = offsetY + "+c+" * (pos / "+f+");\n\n            if(d0 >= "+e[0]+" || d0 < 0) continue;\n\n            int offsetX = int(mod(float(blockIndex), "+u+".) * "+a+". - "+h+".);\n            int d1 = offsetX + "+l+" * (int(mod(float(pos), "+f+".) / "+o+".));\n\n            if(d1 >= "+e[1]+" || d1 < 0) continue;\n\n            vec2 innerDims = vec2(d1, int(mod(float(pos), "+o+".)));\n            result[row * 2 + col] = getChannel(getA(d0, int(innerDims.x),\n                                              int(innerDims.y)), innerDims);\n          }\n        }\n\n        "+d.output+" = result;\n      }\n    ";};}(),si=function(){return function(t,e,n,r,o){this.variableNames=["x"],this.outputShape=[];var a,i=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";a=.5===o?"inversesqrt("+u+")":1===o?"1.0/("+u+")":"exp(log("+u+") * float(-"+o+"));",this.userCode="\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int r = coords[1];\n        int c = coords[2];\n        int d = coords[3];\n        float x = getX(b, r, c, d);\n        float sum = 0.0;\n        for (int j = -"+i+"; j <= "+i+"; j++) {\n          int idx = d + j;\n          if (idx >= 0 && idx <=  "+s+") {\n            float z = getX(b, r, c, idx);\n            sum += z * z;\n          }\n        }\n        float val = x * "+a+";\n        setOutput(val);\n      }\n    ";};}(),ui=function(){return function(t,e,n,r,o){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=t,this.depth=t[3],this.depthRadius=e,this.bias=n,this.alpha=r,this.beta=o,this.userCode="\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int r = coords[1];\n        int c = coords[2];\n\n        float result = 0.0;\n        for (int d = 0; d < "+this.depth+"; ++d) {\n          int depthBegin = int(max(0.0, float(d - "+e+")));\n          int depthEnd = int(min(float("+this.depth+"),\n              float(d + "+e+" + 1)));\n\n          const int MIN_DEPTH_BEGIN = 0;\n          const int MAX_DEPTH_END = "+this.depth+";\n\n          float norm = 0.0;\n          for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {\n            if (k < depthBegin){\n              continue;\n            }\n            else if (k >= depthBegin && k < depthEnd) {\n              norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);\n            }\n            else {\n              break;\n            }\n          }\n\n          norm = float("+r+") * norm + float("+n+");\n\n          for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){\n            if (k < depthBegin){\n              continue;\n            }\n            else if (k >= depthBegin && k < depthEnd){\n              float dyi = -2.0 * float("+r+")\n                * float("+o+")\n                * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)\n                / norm;\n              if (k == d) {\n                dyi += pow(norm, -1.0 * "+o+");\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    ";};}(),li=function(){return function(t,e,n,r,o){this.variableNames=["x"],this.outputShape=[],this.usesPackedTextures=!0;var a,i=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";a=.5===o?"inversesqrt("+u+")":1===o?"1.0/("+u+")":"exp(log("+u+") * float(-"+o+"));",this.userCode="\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords.x;\n        int r = coords.y;\n        int c = coords.z;\n        int d = coords.w;\n\n        bool hasNextCol = d < "+this.outputShape[3]+";\n        bool hasNextRow = c < "+this.outputShape[2]+";\n\n        vec4 sum = vec4(0.);\n        vec4 xFragAtOutputCoords = getX(b, r, c, d);\n\n        vec4 xAtOutputCoords = vec4(\n          getChannel(xFragAtOutputCoords, vec2(c, d)),\n          hasNextCol ?\n            getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,\n          hasNextRow ?\n            getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0\n        );\n\n        int firstChannel = d - "+i+";\n        vec2 cache = vec2(0.);\n        if(firstChannel >= 0){\n          vec4 firstChannelFrag = getX(b, r, c, firstChannel);\n          cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));\n            if(hasNextRow){\n              cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));\n            }\n        }\n\n        ivec2 depth = ivec2(d, d + 1);\n        for (int j = - "+i+"; j <= "+i+"; j++) {\n          ivec2 idx = depth + j;\n          bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\n          bvec2 belowUpperBound = lessThanEqual(idx, ivec2("+s+"));\n\n          bool depthInRange = aboveLowerBound.x && belowUpperBound.x;\n          bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;\n\n          if(depthInRange || depthPlusOneInRange){\n            vec4 z = vec4(0.);\n            vec4 xFragAtCurrentDepth;\n            z.xz = cache.xy;\n            if(depthPlusOneInRange && hasNextCol){\n              xFragAtCurrentDepth = idx.y != d ?\n                getX(b, r, c, idx.y) : xFragAtOutputCoords;\n              z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));\n              if(hasNextRow){\n                z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));\n              }\n            }\n            cache.xy = z.yw;\n            sum += z * z;\n          }\n        }\n        vec4 result = xAtOutputCoords * "+a+";\n        setOutput(result);\n      }\n    ";};}(),ci=function(){return function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideHeight,n=t.strideWidth,r=t.dilationHeight,o=t.effectiveFilterHeight,a=t.effectiveFilterWidth,i=o-1-t.padInfo.top,s=a-1-t.padInfo.left,u=o*a-1;this.userCode="\n      const ivec2 pads = ivec2("+i+", "+s+");\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n\n        ivec2 dyRCCorner = coords.yz - pads;\n        int dyRCorner = dyRCCorner.x;\n        int dyCCorner = dyRCCorner.y;\n\n        // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        for (int wR = 0; wR < "+o+";\n          wR += "+r+") {\n          float dyR = float(dyRCorner + wR) / "+e+".0;\n\n          if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          for (int wC = 0; wC < "+a+"; wC++) {\n            float dyC = float(dyCCorner + wC) / "+n+".0;\n\n            if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n                fract(dyC) > 0.0) {\n              continue;\n            }\n            int idyC = int(dyC);\n\n            float dyValue = getDy(b, idyR, idyC, d);\n            int maxPosValue = "+u+" - int(getMaxPos(b, idyR, idyC, d));\n\n            // Get the current value, check it against the value from the\n            // position matrix.\n            int curPosValue = wR * "+a+" + wC;\n            float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n            dotProd += dyValue * mask;\n          }\n        }\n        setOutput(dotProd);\n      }\n    ";};}(),hi=function(){return function(t,e,n,r,o,a){void 0===n&&(n=!1),void 0===r&&(r=!1),void 0===o&&(o=!1),void 0===a&&(a=null),this.variableNames=["matrixA","matrixB"],this.usesPackedTextures=!0,this.outputShape=e;var i=n?t[1]:t[2],s=Math.ceil(i/2),u=n?"i * 2, rc.y":"rc.y, i * 2",l=r?"rc.z, i * 2":"i * 2, rc.z",c=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],h=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],p="",f="";a&&(p="vec4 activation(vec4 x) {\n        "+a+"\n      }",f="result = activation(result);");var d=o?"result += getBiasAtOutCoords();":"";o&&this.variableNames.push("bias"),this.userCode="\n      "+p+"\n\n      const float sharedDimension = "+s+".0;\n\n      vec4 dot2x2ARowBCol(ivec3 rc) {\n        vec4 result = vec4(0);\n        for (int i = 0; i < "+s+"; i++) {\n          vec4 a = getMatrixA(rc.x, "+u+");\n          vec4 b = getMatrixB(rc.x, "+l+");\n\n          result += ("+c[0]+" * "+h[0]+") + ("+c[1]+" * "+h[1]+");\n        }\n        return result;\n      }\n\n      void main() {\n        ivec3 rc = getOutputCoords();\n        vec4 result = dot2x2ARowBCol(rc);\n\n        "+d+"\n\n        "+f+"\n\n        setOutput(result);\n      }\n    ";};}(),pi=function(){function t(t,e,n){this.variableNames=["probs"],this.outputShape=[t,n],this.userCode="\n      uniform float seed;\n\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int batch = coords[0];\n\n        float r = random(seed);\n        float cdf = 0.0;\n\n        for (int i = 0; i < "+(e-1)+"; i++) {\n          cdf += getProbs(batch, i);\n\n          if (r < cdf) {\n            setOutput(float(i));\n            return;\n          }\n        }\n\n        // If no other event happened, last event happened.\n        setOutput(float("+(e-1)+"));\n      }\n    ";}return t.prototype.getCustomSetupFunc=function(t){var e=this;return function(n,r){null==e.seedLoc&&(e.seedLoc=n.getUniformLocation(r,"seed")),n.gl.uniform1f(e.seedLoc,t);};},t;}(),fi=function(){return function(t,e,n,r){this.variableNames=["indices"],this.outputShape=[t,e],this.userCode="\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int index = round(getIndices(coords.x));\n        setOutput(mix(float("+r+"), float("+n+"),\n                      float(index == coords.y)));\n      }\n    ";};}(),di=function(){return function(t){this.variableNames=["A"],this.outputShape=t;var e=t.length;if(0===e)this.userCode="\n        void main() {\n          setOutput(vec4(getA(), 0., 0., 0.));\n        }\n      ";else{var n=So("rc",e),r=Uo(e),o=function(t,e,n){if(1===t)return"rc > "+e[0];for(var r="",o=t-2;o<t;o++)r+=n[o]+" >= "+e[o],o<t-1&&(r+="||");return r;}(e,t,n),a=function(t,e,n,r){if(1===t)return"";var o=r.slice(-2);return"\n    int r = "+o[0]+";\n    int c = "+o[1]+";\n    int rp1 = r + 1;\n    int cp1 = c + 1;\n\n    bool cEdge = cp1 >= "+e+";\n    bool rEdge = rp1 >= "+n+";\n  ";}(e,t[t.length-1],t[t.length-2],n),i=function(t,e){var n=t.length,r=function(t,e){for(var n=[],r=0;r<=1;r++)for(var o=0;o<=1;o++){for(var a=(0===r?"r":"rp1")+", "+(0===o?"c":"cp1"),i=2;i<t;i++)a=e[e.length-1-i]+","+a;n.push(a);}return n;}(n,e);return 1===n?"getA(rc),\n            rc + 1 >= "+t[0]+" ? 0. : getA(rc + 1),\n            0, 0":"getA("+r[0]+"),\n          cEdge ? 0. : getA("+r[1]+"),\n          rEdge ? 0. : getA("+r[2]+"),\n          rEdge || cEdge ? 0. : getA("+r[3]+")";}(t,n);this.userCode="\n        void main() {\n          "+r+" rc = getOutputCoords();\n\n          if("+o+") {\n            setOutput(vec4(0));\n          } else {\n            "+a+"\n\n            setOutput(vec4("+i+"));\n          }\n        }\n      ";}};}();var vi=function(){return function(t,e,n){this.variableNames=["x"],this.outputShape=e.map(function(e,n){return e[0]+t[n]+e[1];});var r=t.length,o=Uo(r),a=e.map(function(t){return t[0];}).join(","),i=e.map(function(e,n){return e[0]+t[n];}).join(","),s=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);this.userCode=1!==r?"\n      "+o+" start = "+o+"("+a+");\n      "+o+" end = "+o+"("+i+");\n\n      void main() {\n        "+o+" outC = getOutputCoords();\n        if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n          setOutput(float("+n+"));\n        } else {\n          "+o+" coords = outC - start;\n          setOutput(getX("+s+"));\n        }\n      }\n    ":"\n        int start = "+a+";\n        int end = "+i+";\n\n        void main() {\n          int outC = getOutputCoords();\n          if (outC < start || outC >= end) {\n            setOutput(float("+n+"));\n          } else {\n            setOutput(getX(outC - start));\n          }\n        }\n      ";};}(),mi=function(){return function(t,e,n){this.variableNames=["x"],this.usesPackedTextures=!0,this.outputShape=e.map(function(e,n){return e[0]+t[n]+e[1];});for(var r=t.length,o=Uo(r),a=e.map(function(t){return t[0];}).join(","),i=e.map(function(e,n){return e[0]+t[n];}).join(","),s=So("rc",r),u=So("source",r),l=s[r-1]+" < "+this.outputShape[r-1],c=1===r?"source":"vec2("+u.slice(-2).join()+")",h=[o+" rc = outputLoc;",s[r-1]+" += 1;\n       if("+l+") {\n      ",1===r?"":"}\n       rc = outputLoc;\n       "+s[r-2]+" += 1;\n       if("+s[r-2]+" < "+this.outputShape[r-2]+") {",1===r?"":"  "+s[r-1]+" += 1;\n         if("+l+") {"],p=1===r?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",f="",d=0,v=1===r?2:4;d<v;d++)f+="\n        "+h[d]+"\n        if ("+p+") {\n          result["+d+"] = float("+n+");\n        } else {\n          "+o+" source = rc - start;\n          result["+d+"] = getChannel(getX("+u.join()+"), "+c+");\n        }\n      ";f+=1===r?"} ":"}}",this.userCode="\n      const "+o+" start = "+o+"("+a+");\n      const "+o+" end = "+o+"("+i+");\n\n      void main() {\n        "+o+" outputLoc = getOutputCoords();\n        vec4 result = vec4(0.);\n        "+f+"\n        setOutput(result);\n      }\n    ";};}(),gi=function(){return function(t,e,n){if(this.variableNames=["x"],"avg"===e&&n)throw new Error("Cannot compute positions for average pool.");var r=t.filterWidth,o=t.strideHeight,a=t.strideWidth,i=t.dilationHeight,s=t.dilationWidth,u=t.effectiveFilterHeight,l=t.effectiveFilterWidth,c=t.padInfo.top,h=t.padInfo.left;this.outputShape=t.outShape;var p="avg"===e,f="0.0";if(p||(f="-1.0 / 1e-20"),n)this.userCode="\n        const ivec2 strides = ivec2("+o+", "+a+");\n        const ivec2 pads = ivec2("+c+", "+h+");\n\n        void main() {\n          ivec4 coords = getOutputCoords();\n          int batch = coords[0];\n          int d = coords[3];\n\n          ivec2 xRCCorner = coords.yz * strides - pads;\n          int xRCorner = xRCCorner.x;\n          int xCCorner = xRCCorner.y;\n\n          // max/min x(?, ?, d) to get y(yR, yC, d).\n          // ? = to be determined\n          float minMaxValue = 0.0;\n          float minMaxValueFound = 0.0;\n          int minMaxPosition = 0;\n          float avgValue = 0.0;\n\n          for (int wR = 0; wR < "+u+";\n              wR += "+i+") {\n            int xR = xRCorner + wR;\n\n            if (xR < 0 || xR >= "+t.inHeight+") {\n              continue;\n            }\n\n            for (int wC = 0; wC < "+l+";\n                wC += "+s+") {\n              int xC = xCCorner + wC;\n\n              if (xC < 0 || xC >= "+t.inWidth+") {\n                continue;\n              }\n\n              float value = getX(batch, xR, xC, d);\n\n              // If a min / max value has already been found, use it. If not,\n              // use the current value.\n              float currMinMaxValue = mix(\n                  value, minMaxValue, minMaxValueFound);\n              if (value >= currMinMaxValue) {\n                minMaxValue = value;\n                minMaxValueFound = 1.0;\n                minMaxPosition = wR * "+l+" + wC;\n              }\n            }\n          }\n          setOutput(float(minMaxPosition));\n        }\n      ";else{var d=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===e&&(d="avgValue / count");var v=4*Math.floor(r/4),m=r%4,g="\n      if ("+p+") {\n        avgValue += dot(values, ones);\n      } else {\n        minMaxValue = max(values, minMaxValue);\n      }\n    ";this.userCode="\n      const ivec2 strides = ivec2("+o+", "+a+");\n      const ivec2 pads = ivec2("+c+", "+h+");\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 >= "+t.inWidth+") {\n          return initializationValue;\n        }\n        count += 1.0;\n        return getX(batch, xR, xC, d);\n      }\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d = coords[3];\n\n        ivec2 xRCCorner = coords.yz * strides - pads;\n        int xRCorner = xRCCorner.x;\n        int xCCorner = xRCCorner.y;\n\n        // max/min x(?, ?, d) to get y(yR, yC, d).\n        // ? = to be determined\n        vec4 minMaxValue = vec4("+f+");\n        float avgValue = 0.0;\n        count = 0.0;\n\n        for (int wR = 0; wR < "+u+";\n            wR += "+i+") {\n          int xR = xRCorner + wR;\n\n          if (xR < 0 || xR >= "+t.inHeight+") {\n            continue;\n          }\n\n          for (int wC = 0; wC < "+v+"; wC += 4) {\n            int xC = xCCorner + wC * "+s+";\n\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              getValue(batch, xR, xC + "+s+", d),\n              getValue(batch, xR, xC + 2 * "+s+", d),\n              getValue(batch, xR, xC + 3 * "+s+", d)\n            );\n\n            "+g+"\n          }\n\n          int xC = xCCorner + "+v+";\n          if ("+(1===m)+") {\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              initializationValue,\n              initializationValue,\n              initializationValue\n            );\n\n            "+g+"\n          } else if ("+(2===m)+") {\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              getValue(batch, xR, xC + "+s+", d),\n              initializationValue,\n              initializationValue\n            );\n\n            "+g+"\n          } else if ("+(3===m)+") {\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              getValue(batch, xR, xC + "+s+", d),\n              getValue(batch, xR, xC + 2 * "+s+", d),\n              initializationValue\n            );\n\n            "+g+"\n          }\n        }\n        setOutput("+d+");\n      }\n    ";}};}(),yi=function(){return function(t,e){this.variableNames=["x"];var n=t.windowSize,r=t.batchSize,o=t.inSize,a=Math.ceil(o/n);this.outputShape=[r,a];var i="0.0",s="";"prod"===e?i="1.0":"min"===e?(i="1.0 / 1e-20",s="min"):"max"===e&&(i="-1.0 / 1e-20",s="max");var u=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"sum"===e?u="sumValue":"prod"===e?u="prodValue":"all"===e?u="allValue":"any"===e&&(u="anyValue");var l=4*Math.floor(n/4),c=n%4,h="\n      if ("+("sum"===e)+") {\n        sumValue += dot(values, ones);\n      } else if ("+("prod"===e)+") {\n        vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n        prodValue *= tmp[0] * tmp[1];\n      } else {\n        minMaxValue = "+s+"(values, minMaxValue);\n      }\n    ",p="vec4";"all"===e?(i="1.0",h="\n        bool reducedAllValue = all(values);\n        float floatedReducedAllValue = float(reducedAllValue);\n        allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n      ",p="bvec4"):"any"===e&&(i="0.0",h="\n        bool reducedAnyValue = any(values);\n        float floatedReducedAnyValue = float(reducedAnyValue);\n        anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n      ",p="bvec4");var f="";o%n>0&&(f="\n        if (inIdx < 0 || inIdx >= "+o+") {\n          return initializationValue;\n        }\n      "),this.userCode="\n      const float initializationValue = "+i+";\n      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n      float getValue(int batch, int inIdx) {\n        "+f+"\n        return getX(batch, inIdx);\n      }\n\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int batch = coords[0];\n        int outIdx = coords[1];\n        int inOffset = outIdx * "+n+";\n\n        vec4 minMaxValue = vec4("+i+");\n        float prodValue = 1.0;\n        float sumValue = 0.0;\n        float allValue = 1.0;\n        float anyValue = 0.0;\n\n        for (int i = 0; i < "+l+"; i += 4) {\n          int inIdx = inOffset + i;\n          "+p+" values = "+p+"(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            getValue(batch, inIdx + 3)\n          );\n\n          "+h+"\n        }\n\n        int inIdx = inOffset + "+l+";\n        if ("+(1===c)+") {\n          "+p+" values = "+p+"(\n            getValue(batch, inIdx),\n            initializationValue,\n            initializationValue,\n            initializationValue\n          );\n\n          "+h+"\n        } else if ("+(2===c)+") {\n          "+p+" values = "+p+"(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            initializationValue,\n            initializationValue\n          );\n\n          "+h+"\n        } else if ("+(3===c)+") {\n          "+p+" values = "+p+"(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            initializationValue\n          );\n\n          "+h+"\n        }\n        setOutput("+u+");\n      }\n    ";};}(),xi=function(){return function(t,e){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t;for(var n="",r=0;r<4;r++){var o="thisRC = rc;";r%2==1&&(o+="thisRC.z += 1;"),r>1&&(o+="thisRC.y += 1;"),n+="\n        "+o+"\n        "+(r>0?"if(thisRC.y < rows && thisRC.z < cols){":"")+"\n          int flatIndex = getFlatIndex(thisRC);\n\n          ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);\n          vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n          result["+r+"] =\n            getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n        "+(r>0?"}":"")+"\n      ";}this.userCode="\n      \n    ivec3 inputCoordsFromReshapedOutCoords(int index) {\n      "+ko(["r","c","d"],e)+"\n      return ivec3(r, c, d);\n    }\n  \n      "+Ao(t)+"\n\n      void main() {\n        ivec3 rc = getOutputCoords();\n\n        vec4 result = vec4(0.);\n\n        ivec3 thisRC;\n        int rows = "+t[1]+";\n        int cols = "+t[2]+";\n\n        "+n+"\n\n        setOutput(result);\n      }\n    ";};}();var bi=function(){return function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,o=r[1],a=r[2],i=t.shape,s=i[1],u=i[2],l=[n&&s>1?o-1:o,n&&u>1?a-1:a],c=[n&&s>1?s-1:s,n&&u>1?u-1:u],h=l[0]/c[0],p=l[1]/c[1],f=1/h,d=1/p,v=2*Math.ceil(f)+2,m=2*Math.ceil(d)+2;this.userCode="\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n        int r = coords[1];\n        int c = coords[2];\n\n        float accumulator = 0.0;\n\n        const float heightScale = float("+h+");\n        const float widthScale = float("+p+");\n\n        const float invHeightScale = float("+f+");\n        const float invWidthScale = float("+d+");\n\n        const int winHeight = int("+v+");\n        const int winWidth = int("+m+");\n\n        // Compute bounds for where in dy we will look\n        float startRLerp = floor(float(r) * invHeightScale);\n        int startDyR = int(startRLerp - float(winHeight / 2));\n\n        float startCLerp = floor(float(c) * invWidthScale);\n        int startDyC = int(startCLerp - float(winWidth / 2));\n\n        // Loop over dy\n        for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n          int dyR = dyROffset + startDyR;\n\n          // Guard against the window exceeding the bounds of dy\n          if (dyR < 0 || dyR >= "+s+") {\n            continue;\n          }\n\n          for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n            int dyC = dyCOffset + startDyC;\n\n            // Guard against the window exceeding the bounds of dy\n            if (dyC < 0 || dyC >= "+u+") {\n              continue;\n            }\n\n            float dxR = float(dyR) * heightScale;\n            int topDxRIndex = int(floor(dxR));\n            int bottomDxRIndex = int(min(ceil(dxR), "+(o-1)+".0));\n            float dxRLerp = dxR - float(topDxRIndex);\n            float inverseDxRLerp = 1.0 - dxRLerp;\n\n            float dxC = float(dyC) * widthScale;\n            int leftDxCIndex = int(floor(dxC));\n            int rightDxCIndex = int(min(ceil(dxC), "+(a-1)+".0));\n            float dxCLerp = dxC - float(leftDxCIndex);\n            float inverseDxCLerp = 1.0 - dxCLerp;\n\n            if (r == topDxRIndex && c == leftDxCIndex) {\n              // topLeft\n              accumulator +=\n                getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;\n            }\n\n            if (r == topDxRIndex && c == rightDxCIndex) {\n              // topRight\n              accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;\n            }\n\n            if (r == bottomDxRIndex && c == leftDxCIndex) {\n              // bottomLeft\n              accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;\n            }\n\n            if (r == bottomDxRIndex && c == rightDxCIndex) {\n              // bottomRight\n              accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;\n            }\n          }\n        }\n        // End loop over dy\n\n        setOutput(accumulator);\n      }\n    ";};}(),wi=function(){return function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var o=t[0],a=t[1],i=t[2],s=t[3];this.outputShape=[o,e,n,s];var u=[r&&e>1?a-1:a,r&&n>1?i-1:i],l=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n      const vec2 effectiveInputOverOutputRatioRC = vec2(\n          "+u[0]/l[0]+",\n          "+u[1]/l[1]+");\n      const vec2 inputShapeRC = vec2("+a+".0, "+i+".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    ";};}(),Ci=function(){return function(t,e,n,r){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=[];var o=t[0],a=t[1],i=t[2],s=t[3];this.outputShape=[o,e,n,s];var u=[r&&e>1?a-1:a,r&&n>1?i-1:i],l=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n      const vec3 effectiveInputOverOutputRatioRC = vec3(\n          "+u[0]/l[0]+",\n          "+u[1]/l[1]+",\n          "+u[1]/l[1]+");\n      const vec3 inputShapeRC = vec3("+a+".0, "+i+".0,\n                                     "+i+".0);\n\n      float getAValue(int b, int r, int c, int d) {\n        return getChannel(getA(b, r, c, d), vec2(c, d));\n      }\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n        // Calculate values for next column in yRC.z.\n        ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n        // Fractional source index.\n        vec3 sourceFracIndexRC = vec3(yRC) * effectiveInputOverOutputRatioRC;\n\n        // Compute the four integer indices.\n        ivec3 sourceFloorRC = ivec3(sourceFracIndexRC);\n        ivec3 sourceCeilRC = ivec3(\n          min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n        \n        // Should we calculate next column and row elements in 2x2 packed cell.\n        bool hasNextCol = d < "+(s-1)+"; \n        bool hasNextRow = coords.z < "+(n-1)+";\n\n        // In parallel, construct four corners for all four components in\n        // packed 2x2 cell.\n        vec4 topLeft = vec4(\n          getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),\n          hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)\n                     : 0.0,\n          hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)\n                     : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n        vec4 bottomLeft = vec4(\n          getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),\n          hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)\n                     : 0.0,\n          hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)\n                     : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n        vec4 topRight = vec4(\n          getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),\n          hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)\n                     : 0.0,\n          hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)\n                     : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n        vec4 bottomRight = vec4(\n          getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),\n          hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)\n                     : 0.0,\n          hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)\n                     : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n        vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);\n\n        vec4 top = mix(topLeft, topRight, fracRC.yyzz);\n        vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);\n        vec4 newValue = mix(top, bottom, fracRC.x);\n\n        setOutput(newValue);\n      }\n    ";};}(),Ei=function(){return function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,o=r[1],a=r[2],i=t.shape,s=i[1],u=i[2],l=[n&&s>1?o-1:o,n&&u>1?a-1:a],c=[n&&s>1?s-1:s,n&&u>1?u-1:u],h=l[0]/c[0],p=l[1]/c[1],f=1/h,d=1/p,v=2*Math.ceil(f)+2,m=2*Math.ceil(d)+2;this.userCode="\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n        int r = coords[1];\n        int c = coords[2];\n\n        float accumulator = 0.0;\n\n        const float heightScale = float("+h+");\n        const float widthScale = float("+p+");\n\n        const float invHeightScale = float("+f+");\n        const float invWidthScale = float("+d+");\n\n        const int winHeight = int("+v+");\n        const int winWidth = int("+m+");\n\n        // Compute bounds for where in dy we will look\n        float startRLerp = floor(float(r) * invHeightScale);\n        int startDyR = int(floor(startRLerp - float(winHeight / 2)));\n\n        float startCLerp = floor(float(c) * invWidthScale);\n        int startDyC = int(floor(startCLerp - float(winWidth / 2)));\n\n        // Loop over dy\n        for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n          int dyR = dyROffset + startDyR;\n\n          // Guard against the window exceeding the bounds of dy\n          if (dyR < 0 || dyR >= "+s+") {\n            continue;\n          }\n\n          for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n            int dyC = dyCOffset + startDyC;\n\n            // Guard against the window exceeding the bounds of dy\n            if (dyC < 0 || dyC >= "+u+") {\n              continue;\n            }\n\n            float sourceFracRow =\n              float("+l[0]+") *\n                (float(dyR) / float("+c[0]+"));\n\n            float sourceFracCol =\n                float("+l[1]+") *\n                  (float(dyC) / float("+c[1]+"));\n\n            int sourceNearestRow = int(min(\n                float(int("+o+") - 1),\n                "+n+" ? float(round(sourceFracRow)) :\n                                  float(floor(sourceFracRow))));\n\n            int sourceNearestCol = int(min(\n                float(int("+a+") - 1),\n                "+n+" ? float(round(sourceFracCol)) :\n                                  float(floor(sourceFracCol))));\n\n            if (r == sourceNearestRow && c == sourceNearestCol) {\n              accumulator += getDy(b, dyR, dyC, d);\n            }\n          }\n        }\n        // End loop over dy\n\n        setOutput(accumulator);\n      }\n    ";};}(),Ri=function(){return function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var o=t[0],a=t[1],i=t[2],s=t[3];this.outputShape=[o,e,n,s];var u=[r&&e>1?a-1:a,r&&n>1?i-1:i],l=[r&&e>1?e-1:e,r&&n>1?n-1:n],c=r?"0.5":"0.0";this.userCode="\n      const vec2 effectiveInputOverOutputRatioRC = vec2(\n          "+u[0]/l[0]+",\n          "+u[1]/l[1]+");\n      const vec2 inputShapeRC = vec2("+a+".0, "+i+".0);\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n        ivec2 yRC = coords.yz;\n\n        // Fractional source index.\n        vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n        // Compute the coordinators of nearest neighbor point.\n        ivec2 sourceNearestRC = ivec2(\n          min(inputShapeRC - 1.0, floor(sourceFracIndexRC + "+c+")));\n\n        float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n        setOutput(newValue);\n      }\n    ";};}(),Ii=function(){return function(t,e){this.variableNames=["x"];var n=t.length;if(n>4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");if(this.outputShape=t,1!==n){var r=t.map(function(n,r){return function(n){return-1!==e.indexOf(n)&&1!==t[n]?t[n]+" - coords["+n+"] - 1":"coords["+n+"]";}(r);}).join(","),o=Uo(n);this.userCode="\n      void main() {\n        "+o+" coords = getOutputCoords();\n        setOutput(getX("+r+"));\n      }\n    ";}else this.userCode="\n        void main() {\n          int coord = getOutputCoords();\n          setOutput(getX("+t[0]+" - coord - 1));\n        }\n      ";};}(),Si=function(){return function(t,e){this.variableNames=["x"],this.usesPackedTextures=!0;var n=t.length;if(n>4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");this.outputShape=t;var r=So("rc",n),o=r[n-1]+" + 1 < "+this.outputShape[n-1],a=r[n-2]+" + 1 < "+this.outputShape[n-2],i=Uo(n);function s(n){var r=t.map(function(r,o){return function(n,r){return-1!==e.indexOf(n)&&1!==t[n]?t[n]+" - "+r[n]+" - 1":""+r[n];}(o,n);});return"getChannel(getX("+r.join(",")+"), vec2("+r.slice(-2).join(",")+"))";}this.userCode=1===n?"\n        void main(){\n          int rc = getOutputCoords();\n          vec4 result = vec4(0.);\n          result.r = getChannel(getX("+t[0]+" - rc - 1),\n            "+t[0]+" - rc - 1);\n          if("+o+"){\n              result.g = getChannel(getX("+t[0]+" - (rc  + 1) - 1),\n                "+t[0]+" - (rc  + 1) - 1);\n          }\n          setOutput(result);\n        }\n      ":"\n        void main() {\n          "+i+" rc = getOutputCoords();\n          vec4 result = vec4(0.);\n          result.r = "+function(t){return s(t);}(r.slice())+";\n          if("+o+"){\n            result.g = "+function(t){return t[n-1]="("+t[n-1]+" + 1)",s(t);}(r.slice())+";\n          }\n          if("+a+") {\n            result.b = "+function(t){return t[n-2]="("+t[n-2]+" + 1)",s(t);}(r.slice())+";\n            if("+o+") {\n              result.a = "+function(t){return t[n-1]="("+t[n-1]+" + 1)",t[n-2]="("+t[n-2]+" + 1)",s(t);}(r.slice())+";\n            }\n          }\n          setOutput(result);\n        }\n    ";};}(),Ni=function(){return function(t,e,n,r,o,a,i){void 0===i&&(i=!0),this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;var s=Uo(o.length),u=Uo(a.length),l="";1===n?l="i":2===n&&(l="i, j");var c="getIndices("+l+")",h="";1===r?h="i":2===r&&(h="i, coords[1]");var p="getUpdates("+h+")",f=e>1?"strides[j]":"strides";this.userCode="\n        "+s+" strides = "+s+"("+o+");\n\n        void main() {\n          "+u+" coords = getOutputCoords();\n          float sum = 0.0;\n          bool found = false;\n          for (int i = 0; i < "+t+"; i++) {\n            int flattenedIndex = 0;\n            for (int j = 0; j < "+e+"; j++) {\n              int index = round("+c+");\n              flattenedIndex += index * "+f+";\n            }\n            if (flattenedIndex == coords[0]) {\n              sum += "+p+";\n              found = true;\n            }\n          }\n          setOutput(mix(getDefaultValue(), sum, float(found)));\n        }\n      ";};}(),ki=function(){return function(t,e){this.variableNames=["x","segmentIds"];var n=t.windowSize,r=t.batchSize,o=t.inSize,a=t.numSegments,i=a*Math.ceil(o/n);this.outputShape=[r,i];var s=4*Math.floor(n/4),u=n%4,l="\n        sumValue += dot(values, segFilter);\n    ",c="";o%n>0&&(c="\n        if (inIdx < 0 || inIdx >= "+o+") {\n          return initializationValue;\n        }\n      ");var h="";o%n>0&&(h="\n        if (inIdx < 0 || inIdx >= "+o+") {\n          return -1.0;\n        }\n      "),this.userCode="\n      const float initializationValue = 0.0;\n\n      float getValue(int batch, int inIdx) {\n        "+c+"\n        return getX(batch, inIdx);\n      }\n\n      float getSegmentIdAtIndex(int inIdx) {\n        "+h+"\n        return getSegmentIds(inIdx);\n      }\n\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int batch = coords[0];\n        int outIdx = coords[1];\n        int inOffset = int(floor(float(outIdx) / float(\n          "+a+")) * float("+n+"));\n        int currentSeg = int(mod(float(outIdx), float("+a+")));\n\n        float sumValue = 0.0;\n\n        for (int i = 0; i < "+s+"; i += 4) {\n          int inIdx = inOffset + i;\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            getValue(batch, inIdx + 3)\n          );\n\n          vec4 segFilter = vec4(\n            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n            int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n            int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n            int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0\n          );\n\n          "+l+"\n        }\n\n        int inIdx = inOffset + "+s+";\n        if ("+(1===u)+") {\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            initializationValue,\n            initializationValue,\n            initializationValue\n          );\n\n          int inIdxSeg = int(getSegmentIdAtIndex(inIdx));\n\n          vec4 segFilter = vec4(\n            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n            0,\n            0,\n            0\n          );\n\n          "+l+"\n        } else if ("+(2===u)+") {\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            initializationValue,\n            initializationValue\n          );\n\n          vec4 segFilter = vec4(\n            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n            int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n              0,\n              0\n          );\n\n          "+l+"\n        } else if ("+(3===u)+") {\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            initializationValue\n          );\n\n          vec4 segFilter = vec4(\n            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n            int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n            int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n            0\n          );\n\n          "+l+"\n        }\n        setOutput(sumValue);\n      }\n    ";};}(),Ai=function(){return function(t,e,n){var r,o;if(this.variableNames=["c","a","b"],this.outputShape=e,n>4)throw Error("Where for rank "+n+" is not yet supported");if(1===n)o="resRC",r="resRC";else{for(var a=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],s=[],u=0;u<e.length;u++)s.push(""+a[u]),u<t&&i.push(""+a[u]);r=i.join(),o=s.join();}var l=Uo(n);this.userCode="\n      void main() {\n        "+l+" resRC = getOutputCoords();\n        float cVal = getC("+r+");\n        if (cVal >= 1.0) {\n          setOutput(getA("+o+"));\n        } else {\n          setOutput(getB("+o+"));\n        }\n      }\n    ";};}(),Ti=function(){function t(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;var e,n=Uo(this.rank),r="uniform int start["+this.rank+"];",o=function(t){if(1===t)return"sourceLoc";if(t<=6)return Di.slice(0,t).map(function(t){return"sourceLoc."+t;}).join(",");throw Error("Slicing for rank "+t+" is not yet supported");}(this.rank);e="\n        "+n+" sourceLoc;\n        "+n+" coords = getOutputCoords();\n        "+t.map(function(t,e){return"sourceLoc."+Di[e]+" = start["+e+"] + coords."+Di[e]+";";}).join("\n")+"\n      ",this.userCode="\n      "+r+"\n      void main() {\n        "+e+"\n        setOutput(getSource("+o+"));\n      }\n    ";}return t.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+t.length+")");return function(n,r){null==e.startLoc&&(e.startLoc=n.getUniformLocationNoThrow(r,"start"),null==e.startLoc)||n.gl.uniform1iv(e.startLoc,t);};},t;}(),Di=["x","y","z","w","u","v"];var _i=function(){function t(t){this.variableNames=["source"],this.usesPackedTextures=!0,this.outputShape=t,this.rank=t.length;var e=Uo(this.rank),n=So("coords",this.rank),r=So("sourceLoc",this.rank),o=1===this.rank?"sourceLoc":"vec2("+r.slice(-2).join()+")",a="getChannel(getSource("+r.join()+"), "+o+")",i="\n      result.x = "+a+";\n      if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n        ++"+r[this.rank-1]+";\n        result.y = "+a+";\n        --"+r[this.rank-1]+";\n      }\n    ",s=1===this.rank?"":"\n      --"+n[this.rank-1]+";\n      if (++"+n[this.rank-2]+" < "+t[this.rank-2]+") {\n        ++"+r[this.rank-2]+";\n        result.z = "+a+";\n        if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n          ++"+r[this.rank-1]+";\n          result.w = "+a+";\n        }\n      }\n    ",u=this.rank<=4?"sourceLoc = coords +\n            "+e+"("+t.map(function(t,e){return"start["+e+"]";}).join()+");":t.map(function(t,e){return r[e]+" = "+n[e]+" + start["+e+"];";}).join("\n");this.userCode="\n      uniform int start["+this.rank+"];\n      void main() {\n        "+e+" coords = getOutputCoords();\n        "+e+" sourceLoc;\n        "+u+" \n        vec4 result = vec4(0.);\n        "+i+"\n        "+s+"\n        setOutput(result);\n      }\n    ";}return t.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+t.length+")");return function(n,r){null==e.startLoc&&(e.startLoc=n.getUniformLocationNoThrow(r,"start"),null==e.startLoc)||n.gl.uniform1iv(e.startLoc,t);};},t;}(),Oi=function(){return function(t,e,n,r){this.variableNames=["x"];var o=n.filter(function(t,e){return-1===r.indexOf(e);});this.outputShape=o;var a=n.length,i=Uo(n.length),s=Uo(o.length),u="";if(1===a)u="coords * strides + begin";else{var l=0;u=n.map(function(t,e){return-1===r.indexOf(e)?(l++,1===o.length?"coords * strides["+e+"] + begin["+e+"]":"coords["+(l-1)+"] * strides["+e+"] + begin["+e+"]"):"begin["+e+"]";}).join(",");}this.userCode="\n      "+i+" begin = "+i+"("+t+");\n      "+i+" strides = "+i+"("+e+");\n\n      void main() {\n        "+s+" coords = getOutputCoords();\n        setOutput(getX("+u+"));\n      }\n    ";};}(),Mi=function(){function t(t){this.gpgpu=t,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={};}return t.prototype.acquireTexture=function(t,e,n){var r,o=Fi(e,n),a=Bi(t,o,n);if(a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]),this.freeTextures[a].length>0){this.numFreeTextures--,this.numUsedTextures++,this.log();var i=this.freeTextures[a].shift();return this.usedTextures[a].push(i),i;}return this.numUsedTextures++,this.log(),o===Ma.PACKED_2X2_FLOAT32?r=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):o===Ma.PACKED_2X2_FLOAT16?r=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):o===Ma.UNPACKED_FLOAT32?r=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):o===Ma.UNPACKED_FLOAT16?r=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):o===Ma.PACKED_4X1_UNSIGNED_BYTE&&(r=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[a].push(r),r;},t.prototype.releaseTexture=function(t,e,n,r){if(null!=this.freeTextures){var o=Bi(e,Fi(n,r),r);o in this.freeTextures||(this.freeTextures[o]=[]),this.freeTextures[o].push(t),this.numFreeTextures++,this.numUsedTextures--;var a=this.usedTextures[o],i=a.indexOf(t);if(i<0)throw new Error("Cannot release a texture that was never provided by this texture manager");a.splice(i,1),this.log();}},t.prototype.log=function(){if(this.logEnabled){var t=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+t+")");}},t.prototype.getNumUsedTextures=function(){return this.numUsedTextures;},t.prototype.getNumFreeTextures=function(){return this.numFreeTextures;},t.prototype.dispose=function(){var t=this;if(null!=this.freeTextures){for(var e in this.freeTextures)this.freeTextures[e].forEach(function(e){t.gpgpu.deleteMatrixTexture(e);});for(var e in this.usedTextures)this.usedTextures[e].forEach(function(e){t.gpgpu.deleteMatrixTexture(e);});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0;}},t;}();function Fi(t,e){if(t===Oa.UPLOAD)return Ma.PACKED_2X2_FLOAT32;if(t===Oa.RENDER||null==t)return e?exports.ENV.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?Ma.PACKED_2X2_FLOAT32:Ma.PACKED_2X2_FLOAT16:exports.ENV.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?Ma.UNPACKED_FLOAT32:Ma.UNPACKED_FLOAT16;if(t===Oa.DOWNLOAD||t===Oa.PIXELS)return Ma.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+t);}function Bi(t,e,n){return t[0]+"_"+t[1]+"_"+e+"_"+n;}var Pi=function(){return function(t,e){this.variableNames=["A"];for(var n=new Array(t.length),r=0;r<n.length;r++)n[r]=t[r]*e[r];this.outputShape=n,this.rank=n.length;var o=Uo(this.rank),a=function(t){var e=t.length;if(e>5)throw Error("Tile for rank "+e+" is not yet supported");if(1===e)return"imod(resRC, "+t[0]+")";for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],r=[],o=0;o<t.length;o++)r.push("imod("+n[o]+", "+t[o]+")");return r.join();}(t);this.userCode="\n      void main() {\n        "+o+" resRC = getOutputCoords();\n        setOutput(getA("+a+"));\n      }\n    ";};}();var Li=function(){return function(t,e){this.variableNames=["A"];for(var n=new Array(t.length),r=0;r<n.length;r++)n[r]=t[e[r]];this.outputShape=n,this.rank=n.length;var o=Uo(this.rank),a=function(t){var e=t.length;if(e>6)throw Error("Transpose for rank "+e+" is not yet supported");for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(e),o=0;o<t.length;o++)r[t[o]]=n[o];return r.join();}(e);this.userCode="\n    void main() {\n      "+o+" resRC = getOutputCoords();\n      setOutput(getA("+a+"));\n    }\n    ";};}();var Wi=function(){return function(t,e){this.variableNames=["A"],this.usesPackedTextures=!0;for(var n=new Array(t.length),r=0;r<n.length;r++)n[r]=t[e[r]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");var o=Uo(this.rank),a=Io("rc",this.rank),i=new Array(this.rank);for(r=0;r<e.length;r++)i[e[r]]=a[r];var s="vec2("+i.slice(-2).join()+")",u="++"+a[this.rank-1]+" < "+n[this.rank-1],l="getChannel(getA("+i.join()+"), "+s+")";this.userCode="\n    void main() {\n      "+o+" rc = getOutputCoords();\n      vec4 result = vec4(0.);\n      result[0] = "+l+";\n      if("+u+") {\n        result[1] = "+l+";\n      }\n      --"+a[this.rank-1]+";\n      if(++"+a[this.rank-2]+" < "+n[this.rank-2]+") {\n        result[2] = "+l+";\n        if("+u+") {\n          result[3] = "+l+";\n        }\n      }  \n      setOutput(result);\n    }\n    ";};}(),Ui=1.7580993408473768,zi=1.0507009873554805,Vi=function(){return function(t,e){this.variableNames=["A"],this.outputShape=t,this.userCode="\n      float unaryOperation(float x) {\n        "+e+"\n      }\n\n      void main() {\n        float x = getAAtOutCoords();\n        float y = unaryOperation(x);\n\n        setOutput(y);\n      }\n    ";};}(),Gi="if (isnan(x)) return x;",qi="return x;",Hi=Gi+"\n  return (x < 0.0) ? 0.0 : x;\n",$i="\n  // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n  // see: https://arxiv.org/abs/1706.02515\n  float scaleAlpha = "+Ui+";\n  float scale = "+zi+";\n  return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n";var ji="return exp(x);",Ki=Gi+"\n  return sin(x);\n",Xi=Gi+"\n  return cos(x);\n",Yi=Gi+"\n  return atan(x);\n",Qi=Gi+"\n  if (x < 1.0) return NAN;\n  return log(x + sqrt(x * x - 1.0));",Ji=Gi+"\n  if ((x < -1.0) || (x > 1.0)) return NAN;\n  return (log(1.0 + x) - log(1.0 - x)) / 2.0;",Zi="return x;",ts="\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",es=function(){return function(t,e){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t,this.userCode="\n      vec4 unaryOperation(vec4 x) {\n        "+e+"\n      }\n\n      void main() {\n        vec4 x = getAAtOutCoords();\n        vec4 y = unaryOperation(x);\n\n        setOutput(y);\n      }\n    ";};}(),ns=function(){return function(t){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t;var e=t.length,n=So("rc",e),r=Uo(e),o=function(t,e){if(1===t)return"rc";for(var n="",r=0;r<t;r++)n+=e[r],r<t-1&&(n+=",");return n;}(e,n),a=n.slice(-2),i=e<=1?"rc":"vec2("+a.join(",")+")";this.userCode="\n      void main() {\n        "+r+" rc = getOutputCoords();\n        vec4 packedInput = getA("+o+");\n\n        setOutput(getChannel(packedInput, "+i+"));\n      }\n    ";};}(),rs={};var os=600;var as=function(){function t(t){if(this.gpgpu=t,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,!exports.ENV.getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(null==t){var e=Bt(exports.ENV.getNumber("WEBGL_VERSION"));this.binaryCache=(n=exports.ENV.getNumber("WEBGL_VERSION"))in rs?rs[n]:(rs[n]={},rs[n]),this.gpgpu=new oi(e),this.canvas=e.canvas,this.gpgpuCreatedLocally=!0;}else this.binaryCache={},this.gpgpuCreatedLocally=!1,this.canvas=t.gl.canvas;var n;this.textureManager=new Mi(this.gpgpu),this.numMBBeforeWarning=null==exports.ENV.global.screen?1024:exports.ENV.global.screen.height*exports.ENV.global.screen.width*window.devicePixelRatio*os/1024/1024,this.texData=new $r(this,Dt);}return t.prototype.register=function(t,e,n){if(this.texData.has(t))throw new Error("Data buffer is already registered");this.texData.set(t,{shape:e,dtype:n});},t.prototype.fromPixels=function(t,e){if(null==t)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var n=[t.height,t.width],r=[t.height,t.width,e],o="undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement,a=t.data instanceof Uint8Array,i="undefined"!=typeof ImageData&&t instanceof ImageData,u="undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement,l="undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement;if(!(o||a||i||u||l))throw new Error("pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was "+t.constructor.name);if(l||u){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=Pt(exports.ENV.getNumber("WEBGL_VERSION")).getContext("2d");}this.fromPixels2DContext.canvas.width=t.width,this.fromPixels2DContext.canvas.height=t.height,this.fromPixels2DContext.drawImage(t,0,0,t.width,t.height),t=this.fromPixels2DContext.canvas;}var c,h,p=this.makeTensorHandle(n,"int32");if(this.texData.get(p.dataId).usage=Oa.PIXELS,this.gpgpu.uploadPixelDataToTexture(this.getTexture(p.dataId),t),exports.ENV.getBool("WEBGL_PACK")){c=new Da(r);var f=this.makePackedTensor(c.outputShape,p.dtype);h=this.compileAndRun(c,[p],f);}else c=new Ta(r),h=this.compileAndRun(c,[p]);return this.disposeData(p.dataId),h;},t.prototype.makeTensorHandle=function(t,e){var n={};return this.register(n,t,e),{dataId:n,shape:t,dtype:e};},t.prototype.write=function(t,e){if(null==e)throw new Error("MathBackendWebGL.write(): values can not be null");if(exports.ENV.getBool("DEBUG"))for(var n=0;n<e.length;n++){var r=e[n];if(!zt(r))throw Error("The value "+r+" cannot be represented on this device.");}var o=this.texData.get(t);if("complex64"===o.dtype)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.releaseGPUData(t),o.usage=Oa.UPLOAD,o.values=e;},t.prototype.readSync=function(t){var e=this.texData.get(t),n=e.values,r=e.dtype,o=e.complexTensors,a=e.slice,i=e.shape;if(null!=a){var s=new Vi(i,"return x;"),u=this.compileAndRun(s,[{dataId:t,shape:i,dtype:r}]),l=this.readSync(u.dataId);return u.dispose(),l;}if(null!=n)return this.convertAndCacheOnCPU(t);if("string"===r)return n;var c,h,p=null!=this.activeTimers;(p&&(c=K()),"complex64"===r)?h=ho(o.real.dataSync(),o.imag.dataSync()):h=this.getValuesFromTexture(t);return p&&(this.downloadWaitMs+=K()-c),this.convertAndCacheOnCPU(t,h);},t.prototype.read=function(t){return r(this,void 0,void 0,function(){var e,n,r,a,i,u,l,c,h,p,f,d,v,m,g,x,b,w,C,E,R;return o(this,function(o){switch(o.label){case 0:if(this.pendingRead.has(t))return n=this.pendingRead.get(t),[2,new Promise(function(t){return n.push(t);})];if(r=this.texData.get(t),a=r.values,i=r.shape,u=r.slice,l=r.dtype,c=r.complexTensors,null!=u)return h=new Vi(i,"return x;"),p=this.compileAndRun(h,[{dataId:t,shape:i,dtype:l}]),f=this.read(p.dataId),p.dispose(),[2,f];if(null!=a)return[2,this.convertAndCacheOnCPU(t)];if(!exports.ENV.getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===exports.ENV.getNumber("WEBGL_VERSION"))throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");return d=null,"complex64"!==l&&exports.ENV.get("WEBGL_BUFFER_SUPPORTED")&&(v=this.decode(t),t=v.dataId,m=this.texData.get(v.dataId),d=(e=this.gpgpu).createBufferFromTexture.apply(e,[m.texture].concat(Pa(i)))),this.pendingRead.set(t,[]),"complex64"===l?[3,2]:[4,this.gpgpu.createAndWaitForFence()];case 1:o.sent(),o.label=2;case 2:return"complex64"!==l?[3,4]:[4,Promise.all([c.real.data(),c.imag.data()])];case 3:return x=o.sent(),b=x[0],w=x[1],g=ho(b,w),[3,5];case 4:null==d?g=this.getValuesFromTexture(t):(C=y(i),g=this.gpgpu.downloadFloat32MatrixFromBuffer(d,C),this.disposeData(t)),o.label=5;case 5:return E=this.convertAndCacheOnCPU(t,g),R=this.pendingRead.get(t),this.pendingRead.delete(t),R.forEach(function(t){return t(E);}),this.pendingDisposal.has(t)&&(this.pendingDisposal.delete(t),this.disposeData(t)),[2,E];}});});},t.prototype.getValuesFromTexture=function(t){var e,n=this,r=this.texData.get(t),o=r.shape,a=r.dtype,i=r.isPacked,u=y(o);if(exports.ENV.getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){var l=this.decode(t),c=this.texData.get(l.dataId),h=(e=this.gpgpu).downloadMatrixFromPackedTexture.apply(e,[c.texture].concat(Pa(o))).subarray(0,u);return this.disposeData(l.dataId),h;}var p=exports.ENV.getBool("WEBGL_PACK")&&!0===i,f=p?me(o):o,d=this.makeTensorHandle(f,"float32");d.size=y(o),this.texData.get(d.dataId).usage=Oa.DOWNLOAD;var v=Pe(function(){var e=p?new Ea(f):new Ca(f);return n.compileAndRun(e,[{shape:f,dtype:a,dataId:t}],d,null);}),m=this.texData.get(v.dataId),g=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(m.texture,m.texShape[0],m.texShape[1]).subarray(0,u);return this.disposeData(d.dataId),g;},t.prototype.time=function(t){return r(this,void 0,void 0,function(){var e,n,r,a,i,s,u;return o(this,function(o){switch(o.label){case 0:return e=this.activeTimers,n=[],r=!1,null==this.programTimersStack?(this.programTimersStack=n,r=!0):this.activeTimers.push(n),this.activeTimers=n,t(),a=g(this.activeTimers.map(function(t){return t.query;})).filter(function(t){return null!=t;}),i=g(this.activeTimers.map(function(t){return t.name;})).filter(function(t){return null!=t;}),this.activeTimers=e,r&&(this.programTimersStack=null),[4,Promise.all(a)];case 1:return s=o.sent(),u={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:f(s),getExtraProfileInfo:function(){return s.map(function(t,e){return{name:i[e],ms:t};}).map(function(t){return t.name+": "+t.ms;}).join(", ");},wallMs:null},this.uploadWaitMs=0,this.downloadWaitMs=0,[2,u];}});});},t.prototype.memory=function(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU};},t.prototype.startTimer=function(){return exports.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?this.gpgpu.beginQuery():{startMs:K(),endMs:null};},t.prototype.endTimer=function(t){return exports.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(this.gpgpu.endQuery(),t):(t.endMs=K(),t);},t.prototype.getQueryTime=function(t){return r(this,void 0,void 0,function(){var e;return o(this,function(n){return exports.ENV.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?[2,this.gpgpu.waitForQueryAndGetTime(t)]:[2,(e=t).endMs-e.startMs];});});},t.prototype.disposeData=function(t){if(!this.pendingDisposal.has(t))if(this.pendingRead.has(t))this.pendingDisposal.add(t);else if(this.texData.has(t)){this.releaseGPUData(t);var e=this.texData.get(t).complexTensors;null!=e&&(e.real.dispose(),e.imag.dispose()),this.texData.delete(t);}},t.prototype.releaseGPUData=function(t){var e=this.texData.get(t),n=e.texture,r=e.dtype,o=e.texShape,a=e.usage,i=e.isPacked,s=e.slice,u=s&&s.origDataId||t,l=this.dataRefCount.get(u);l>1?this.dataRefCount.set(u,l-1):(this.dataRefCount.delete(u),null!=n&&(this.numBytesInGPU-=this.computeBytes(o,r),this.textureManager.releaseTexture(n,o,a,i)));var c=this.texData.get(t);c.texture=null,c.texShape=null,c.isPacked=!1,c.slice=null;},t.prototype.getTexture=function(t){return this.uploadToGPU(t),this.texData.get(t).texture;},t.prototype.getCPUBackend=function(){return exports.ENV.getBool("WEBGL_CPU_FORWARD")?(null==this.cpuBackend&&(this.cpuBackend=Dt.findBackend("cpu")),this.cpuBackend):null;},t.prototype.shouldExecuteOnCPU=function(t,e){var n=this;return void 0===e&&(e=128),null!=this.getCPUBackend()&&t.every(function(t){return null==n.texData.get(t.dataId).texture&&t.size<e;});},t.prototype.getGPGPUContext=function(){return this.gpgpu;},t.prototype.complex=function(t,e){var n=this.makeOutputArray(t.shape,"complex64");return this.texData.get(n.dataId).complexTensors={real:Dt.keep(t.clone()),imag:Dt.keep(e.clone())},n;},t.prototype.real=function(t){return this.texData.get(t.dataId).complexTensors.real.clone();},t.prototype.imag=function(t){return this.texData.get(t.dataId).complexTensors.imag.clone();},t.prototype.slice=function(t,e,n){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.slice(t,e,n);if(0===y(n))return mn([],n,t.dtype);var r=this.texData.get(t.dataId).isPacked,o=Fr(t.shape,e,n);if(r||!o){var a=exports.ENV.getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new _i(n):new Ti(n),i=a.getCustomSetupFunc(e);return this.compileAndRun(a,[t],null,i);}return this.uploadToGPU(t.dataId),this.shallowSlice(t,e,n);},t.prototype.shallowSlice=function(t,e,n){var r=this.texData.get(t.dataId),o=ft.make(n,{},t.dtype,this),a=this.texData.get(o.dataId);Object.assign(a,r),a.shape=n,a.dtype=t.dtype;var i=Br(e,t.strides);r.slice&&(i+=r.slice.flatOffset),a.slice={flatOffset:i,origDataId:r.slice&&r.slice.origDataId||t.dataId};var s=this.dataRefCount.get(a.slice.origDataId)||1;return this.dataRefCount.set(a.slice.origDataId,s+1),o;},t.prototype.stridedSlice=function(t,e,n,r,o,a,i,s,u){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.stridedSlice(t,e,n,r,o,a,i,s,u);var l=_r(t.shape,e,n,r,o,a,i,s,u),c=l[0],h=l[1],p=l[2],f=h.filter(function(t,e){return-1===p.indexOf(e);});if(f.some(function(t){return 0===t;}))return mn([],f);var d=new Oi(c,r,h,p);return this.compileAndRun(d,[t]);},t.prototype.reverse=function(t,e){var n=exports.ENV.getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Si(t.shape,e):new Ii(t.shape,e);return this.compileAndRun(n,[t]);},t.prototype.concat=function(t,e){if(this.shouldExecuteOnCPU(t))return this.cpuBackend.concat(t,e);if(1===t.length)return t[0];if(t.length>exports.ENV.getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var n=Math.floor(t.length/2),r=this.concat(t.slice(0,n),e),o=this.concat(t.slice(n),e);return this.concat([r,o],e);}if(exports.ENV.getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&t[0].rank>1){var a=new aa(t.map(function(t){return t.shape;}),e);return this.compileAndRun(a,t);}var i=hn(t.map(function(t){return t.shape;}),e),u=t.map(function(t){return t.as2D(-1,y(t.shape.slice(e)));}),l=new oa(u.map(function(t){return t.shape;}));return this.compileAndRun(l,u).reshape(i);},t.prototype.neg=function(t){var e=new Vi(t.shape,"return -x;");return this.compileAndRun(e,[t]);},t.prototype.batchMatMul=function(t,e,n,r){var o=n?t.shape[2]:t.shape[1],a=r?e.shape[1]:e.shape[2],i=n?t.shape[1]:t.shape[2],s=t.shape[0];if((1===o||1===a)&&i>1e3){n&&(t=t.transpose([0,2,1])),r&&(e=e.transpose([0,2,1]));var u=1===a?t:t.as3D(s,i,1),l=1===a?2:1,c=1===a?e.as3D(s,1,i):e;return this.multiply(u,c).sum(l,!0);}var h=Ct(t.dtype,e.dtype),p=new hi(t.shape,[s,o,a],n,r),f=this.makePackedTensor(p.outputShape,h);return this.compileAndRun(p,[t,e],f);},t.prototype.fusedBatchMatMul=function(t,e,n,r,o,a){var i=n?t.shape[2]:t.shape[1],s=r?e.shape[1]:e.shape[2],u=t.shape[0],l=Ct(t.dtype,e.dtype),c=new hi(t.shape,[u,i,s],n,r,!!o,a?function(t,e){if(void 0===e&&(e=!1),"linear"===t)return e?Zi:qi;if("relu"===t)return e?ts:Hi;throw new Error("Activation "+t+" has not been implemented for the WebGL backend.");}(a,!0):null),h=this.makePackedTensor(c.outputShape,l),p=[t,e];return o&&p.push(o),this.compileAndRun(c,p,h);},t.prototype.multiply=function(t,e){if("complex64"===t.dtype){var n=this.texData.get(t.dataId),r=this.texData.get(e.dataId),o=new Xo(jo,t.shape,e.shape),a=new Xo(Ko,t.shape,e.shape),i=[this.makeComplexComponentTensorHandle(t,n.complexTensors.real),this.makeComplexComponentTensorHandle(t,n.complexTensors.imag),this.makeComplexComponentTensorHandle(e,r.complexTensors.real),this.makeComplexComponentTensorHandle(e,r.complexTensors.imag)],u=this.compileAndRun(o,i),l=this.compileAndRun(a,i),c=this.complex(u,l);return u.dispose(),l.dispose(),c;}if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.multiply(t,e);if(exports.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,Jo,t.dtype);var h=new Zo(Jo,t.shape,e.shape),p=this.makeOutputArray(h.outputShape,t.dtype);return this.compileAndRun(h,[t,e],p);},t.prototype.batchNormalization=function(t,e,n,r,o,a){var i=[t,e,n],u=null;null!=a&&(u=a.shape,i.push(a));var l=null;if(null!=o&&(l=o.shape,i.push(o)),exports.ENV.getBool("WEBGL_PACK_NORMALIZATION")){var c=new $o(t.shape,e.shape,n.shape,u,l,r);return this.compileAndRun(c,i);}var h=new Ho(t.shape,e.shape,n.shape,u,l,r);return this.compileAndRun(h,i);},t.prototype.localResponseNormalization4D=function(t,e,n,r,o){var a=exports.ENV.getBool("WEBGL_PACK_NORMALIZATION")?new li(t.shape,e,n,r,o):new si(t.shape,e,n,r,o);return this.compileAndRun(a,[t]);},t.prototype.LRNGrad=function(t,e,n,r,o,a,i){var s=new ui(e.shape,r,o,a,i);return this.compileAndRun(s,[e,n,t]);},t.prototype.tile=function(t,e){if("string"===t.dtype){var n=this.readSync(t.dataId).map(function(t){return J(t);});return xo(Xn(t.shape,t.dtype,n),e);}var r=new Pi(t.shape,e);return this.compileAndRun(r,[t]);},t.prototype.pad=function(t,e,n){var r=exports.ENV.getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new mi(t.shape,e,n):new vi(t.shape,e,n);return this.compileAndRun(r,[t]);},t.prototype.transpose=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.transpose(t,e);var n=exports.ENV.getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Wi(t.shape,e):new Li(t.shape,e);return this.compileAndRun(n,[t]);},t.prototype.gather=function(t,e,n){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.gather(t,e,n);var r=new _a(t.shape,e.size,n);return this.compileAndRun(r,[t,e]);},t.prototype.batchToSpaceND=function(t,e,n){d(t.rank<=4,function(){return"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet";});var r=e.reduce(function(t,e){return t*e;}),o=Cr(t.shape,e,r),a=Er(o.length,e.length),i=Rr(t.shape,e,r),s=Ir(n,e.length),u=Sr(i,n,e.length);return t.reshape(o).transpose(a).reshape(i).slice(s,u);},t.prototype.spaceToBatchND=function(t,e,n){d(t.rank<=4,function(){return"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet";});var r=e.reduce(function(t,e){return t*e;}),o=[[0,0]];o.push.apply(o,n);for(var a=1+e.length;a<t.shape.length;++a)o.push([0,0]);var i=t.pad(o),s=Cr(i.shape,e,r,!1),u=Er(s.length,e.length,!1),l=Rr(i.shape,e,r,!1);return i.reshape(s).transpose(u).reshape(l);},t.prototype.reduce=function(t,e,n){var r=t.shape[0],o=t.shape[1],a=Ar(o),i=new yi({windowSize:a,inSize:o,batchSize:r},e),s=i.outputShape,u=s[0],l=s[1],c=this.makeOutputArray([u,l],n);return this.compileAndRun(i,[t],c),1===c.shape[1]?c:this.reduce(c,e,n);},t.prototype.argReduce=function(t,e,n){void 0===n&&(n=null);var r=t.shape[0],o=t.shape[1];null!=n&&(r=n.shape[0],o=n.shape[1]);var a=Ar(o),i=new Ro({windowSize:a,inSize:o,batchSize:r},e,null==n),s=i.outputShape,u=s[0],l=s[1],c=this.makeOutputArray([u,l],"int32"),h=[t];return null!=n&&h.push(n),this.compileAndRun(i,h,c),1===c.shape[1]?c:this.argReduce(t,e,c);},t.prototype.argReducePacked=function(t,e,n){void 0===n&&(n=null);var r=null!=n?n.shape:t.shape,o=Ar(r[r.length-1]),a=new Go(r,o,e,null==n),i=this.makePackedTensor(a.outputShape,"int32"),s=null==n?[t]:[t,n];return this.compileAndRun(a,s,i),i.rank===t.rank?this.argReducePacked(t,e,i):i;},t.prototype.sum=function(t,e){an("sum",e,t.rank);var n=rn(t.shape,e),r=n[0],o=y(n[1]),a=t.as2D(-1,o),i=Et(t.dtype);return this.reduce(a,"sum",i).reshape(r);},t.prototype.prod=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.prod(t,e);var n=rn(t.shape,e),r=n[0],o=y(n[1]),a=t.as2D(-1,o),i=Et(t.dtype);return this.reduce(a,"prod",i).reshape(r);},t.prototype.unsortedSegmentSum=function(t,e,n){var r=0,o=sn([r],t.rank),a=t;null!=o&&(a=t.transpose(o),r=ln(1,t.rank)[0]);var i=function(t,e,n){for(var r=[],o=t.length,a=0;a<o;a++)a!==e?r.push(t[a]):r.push(n);return r;}(a.shape,r,n),s=y([a.shape[r]]),u=a.as2D(-1,s),l=Et(t.dtype),c=this.segOpCompute(u,"unsortedSegmentSum",e,l,n).reshape(i);return null!=o&&(c=c.transpose(un(o))),c;},t.prototype.segOpCompute=function(t,e,n,r,o){var a=t.shape[0],i=t.shape[1],s=function(t,e){var n,r=!1;for(t<=kr?(n=t,r=!0):n=V(t,Math.floor(Math.sqrt(t)));!r;)n>e||n===t?r=!0:n=V(t,n+1);return n;}(i,o),u=new ki({windowSize:s,inSize:i,batchSize:a,numSegments:o},e),l=u.outputShape,c=l[0],h=l[1],p=this.makeOutputArray([c,h],r);return this.compileAndRun(u,[t,n],p),p.shape[1]===o?p:(n=An(0,o).tile([i/s]),this.segOpCompute(p,e,n,r,o));},t.prototype.argMinMaxReduce=function(t,e,n){var r=[e];if(an("arg"+n.charAt(0).toUpperCase()+n.slice(1),r,t.rank),!exports.ENV.getBool("WEBGL_PACK_REDUCE")||t.rank<=2){var o=rn(t.shape,r),a=o[0],i=y(o[1]),u=t.as2D(-1,i);return this.argReduce(u,n).reshape(a);}return this.argReducePacked(t,n);},t.prototype.argMin=function(t,e){return this.argMinMaxReduce(t,e,"min");},t.prototype.argMax=function(t,e){return this.argMinMaxReduce(t,e,"max");},t.prototype.cumsum=function(t,e,n,r){if(e!==t.rank-1)throw new Error("WebGL cumsum shader expects an inner-most axis="+(t.rank-1)+" but got axis="+e);var o=new ga(t.shape,n,r);return this.compileAndRun(o,[t]);},t.prototype.equal=function(t,e){if(exports.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  return vec4(equal(a, b));\n","bool");var n=new Zo("return float(a == b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r);},t.prototype.notEqual=function(t,e){if(exports.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  return vec4(notEqual(a, b));\n","bool");var n=new Zo("return float(a != b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r);},t.prototype.less=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.less(t,e);if(exports.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  return vec4(lessThan(a, b));\n","bool");var n=new Zo("return float(a < b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r);},t.prototype.lessEqual=function(t,e){if(exports.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  return vec4(lessThanEqual(a, b));\n","bool");var n=new Zo("return float(a <= b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r);},t.prototype.greater=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.greater(t,e);if(exports.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  return vec4(greaterThan(a, b));\n","bool");var n=new Zo("return float(a > b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r);},t.prototype.greaterEqual=function(t,e){if(exports.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  return vec4(greaterThanEqual(a, b));\n","bool");var n=new Zo("return float(a >= b);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r);},t.prototype.logicalNot=function(t){var e=new Vi(t.shape,"return float(!(x >= 1.0));");return this.compileAndRun(e,[t]);},t.prototype.logicalAnd=function(t,e){if(exports.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  return vec4(\n    vec4(greaterThanEqual(a, vec4(1.0))) *\n    vec4(greaterThanEqual(b, vec4(1.0))));\n","bool");var n=new Zo("return float(a >= 1.0 && b >= 1.0);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r);},t.prototype.logicalOr=function(t,e){if(exports.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  return min(\n    vec4(greaterThanEqual(a, vec4(1.0))) +\n    vec4(greaterThanEqual(b, vec4(1.0))),\n    vec4(1.0));\n","bool");var n=new Zo("return float(a >= 1.0 || b >= 1.0);",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"bool");return this.compileAndRun(n,[t,e],r);},t.prototype.select=function(t,e,n){var r=new Ai(t.rank,e.shape,e.rank),o=this.makeOutputArray(r.outputShape,Ct(e.dtype,n.dtype));return this.compileAndRun(r,[t,e,n],o);},t.prototype.where=function(t){Ye("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var e=t.dataSync();return wo(t.shape,e);},t.prototype.topk=function(t,e,n){return bo(t.dataSync(),t.shape,t.dtype,e);},t.prototype.min=function(t,e){an("min",e,t.rank);var n=rn(t.shape,e),r=n[0],o=y(n[1]),a=t.as2D(-1,o);return this.reduce(a,"min",a.dtype).reshape(r);},t.prototype.minimum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.minimum(t,e);var n=exports.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ta("\n  vec4 result = vec4(min(a, b));\n  vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n  \n  result.r = isNaN.r > 0. ? NAN : result.r;\n  result.g = isNaN.g > 0. ? NAN : result.g;\n  result.b = isNaN.b > 0. ? NAN : result.b;\n  result.a = isNaN.a > 0. ? NAN : result.a;\n\n  return result;\n",t.shape,e.shape):new Zo("\n  if (isnan(a)) return a;\n  if (isnan(b)) return b;\n\n  return min(a, b);\n",t.shape,e.shape);return this.compileAndRun(n,[t,e]);},t.prototype.mod=function(t,e){var n=exports.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ta("\n  vec4 result = mod(a, b);\n  vec4 isNaN = vec4(equal(b, vec4(0.0)));\n  \n  result.r = isNaN.r > 0. ? NAN : result.r;\n  result.g = isNaN.g > 0. ? NAN : result.g;\n  result.b = isNaN.b > 0. ? NAN : result.b;\n  result.a = isNaN.a > 0. ? NAN : result.a;\n\n  return result;\n",t.shape,e.shape):new Zo("if (b == 0.0) return NAN;\n  return mod(a, b);",t.shape,e.shape);return this.compileAndRun(n,[t,e]);},t.prototype.max=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.max(t,e);an("max",e,t.rank);var n=rn(t.shape,e),r=n[0],o=y(n[1]),a=t.as2D(-1,o);return this.reduce(a,"max",a.dtype).reshape(r);},t.prototype.maximum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.maximum(t,e);var n=exports.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ta("\n  vec4 result = vec4(max(a, b));\n  vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n  \n  result.r = isNaN.r > 0. ? NAN : result.r;\n  result.g = isNaN.g > 0. ? NAN : result.g;\n  result.b = isNaN.b > 0. ? NAN : result.b;\n  result.a = isNaN.a > 0. ? NAN : result.a;\n\n  return result;\n",t.shape,e.shape):new Zo("\n  if (isnan(a)) return a;\n  if (isnan(b)) return b;\n\n  return max(a, b);\n",t.shape,e.shape);return this.compileAndRun(n,[t,e]);},t.prototype.all=function(t,e){an("all",e,t.rank);var n=rn(t.shape,e),r=n[0],o=y(n[1]),a=t.as2D(-1,o);return this.reduce(a,"all",a.dtype).reshape(r);},t.prototype.any=function(t,e){an("any",e,t.rank);var n=rn(t.shape,e),r=n[0],o=y(n[1]),a=t.as2D(-1,o);return this.reduce(a,"any",a.dtype).reshape(r);},t.prototype.squaredDifference=function(t,e){var n=exports.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ta("return (a - b) * (a - b);",t.shape,e.shape):new Zo("return (a - b) * (a - b);",t.shape,e.shape);return this.compileAndRun(n,[t,e]);},t.prototype.realDivide=function(t,e){if(exports.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")){return this.packedBinaryOp(t,e,"\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 n=new Zo("\nif (b == 0.0) {\n  return NAN;\n} \nif (a == b) {\n  return 1.0;\n};\nreturn a / b;",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"float32");return this.compileAndRun(n,[t,e],r);},t.prototype.floorDiv=function(t,e){if(exports.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  ivec4 ia = round(a);\n  ivec4 ib = round(b);\n  bvec4 cond = notEqual(ib, ivec4(0));\n  ivec4 result = ivec4(0);\n  vec4 s = sign(a) * sign(b);\n\n  // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n  if (cond[0]) {\n    result[0] = idiv(ia[0], ib[0], s[0]);\n  }\n  if (cond[1]) {\n    result[1] = idiv(ia[1], ib[1], s[1]);\n  }\n  if (cond[2]) {\n    result[2] = idiv(ia[2], ib[2], s[2]);\n  }\n  if (cond[3]) {\n    result[3] = idiv(ia[3], ib[3], s[3]);\n  }\n  return vec4(result);\n","int32");var n=new Zo("\n  float s = sign(a) * sign(b);\n  int ia = round(a);\n  int ib = round(b);\n  if (ib != 0) {\n    // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n    return float(idiv(ia, ib, s));\n  } else {\n    return NAN;\n  }\n",t.shape,e.shape),r=this.makeOutputArray(n.outputShape,"int32");return this.compileAndRun(n,[t,e],r);},t.prototype.add=function(t,e){if("complex64"===t.dtype&&"complex64"===e.dtype)return this.complexSeparableBinaryOp(t,e,Yo);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.add(t,e);var n=Ct(t.dtype,e.dtype);if(exports.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,Yo,n);var r=new Zo(Yo,t.shape,e.shape),o=this.makeOutputArray(r.outputShape,n);return this.compileAndRun(r,[t,e],o);},t.prototype.packedBinaryOp=function(t,e,n,r,o){void 0===o&&(o=!1);var a=new ta(n,t.shape,e.shape,o),i=this.makePackedTensor(a.outputShape,r);return this.compileAndRun(a,[t,e],i);},t.prototype.complexSeparableBinaryOp=function(t,e,n){var r=this,o=this.texData.get(t.dataId),a=this.texData.get(e.dataId),i=[[o.complexTensors.real,a.complexTensors.real],[o.complexTensors.imag,a.complexTensors.imag]].map(function(o){var a=o[0],i=o[1],s=r.makeComplexComponentTensorHandle(t,a),u=r.makeComplexComponentTensorHandle(e,i),l=new Zo(n,t.shape,e.shape),c=r.makeOutputArray(l.outputShape,Ct(a.dtype,i.dtype));return r.compileAndRun(l,[s,u],c);}),s=i[0],u=i[1],l=this.complex(s,u);return s.dispose(),u.dispose(),l;},t.prototype.makeComplexComponentTensorHandle=function(t,e){return{dataId:e.dataId,dtype:e.dtype,shape:t.shape};},t.prototype.addN=function(t){if(1===t.length)return t[0];if(t.length>exports.ENV.get("WEBGL_MAX_TEXTURES_IN_SHADER")){var e=Math.floor(t.length/2),n=this.addN(t.slice(0,e)),r=this.addN(t.slice(e));return this.addN([n,r]);}var o=t.map(function(t){return t.dtype;}).reduce(function(t,e){return Ct(t,e);}),a=t.map(function(t){return t.shape;}),i=exports.ENV.getBool("WEBGL_PACK"),u=i?new Eo(t[0].shape,a):new Co(t[0].shape,a),l=i?this.makePackedTensor(u.outputShape,o):this.makeOutputArray(u.outputShape,o);return this.compileAndRun(u,t,l);},t.prototype.subtract=function(t,e){if("complex64"===t.dtype&&"complex64"===e.dtype)return this.complexSeparableBinaryOp(t,e,Qo);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.subtract(t,e);var n=Ct(t.dtype,e.dtype);if(exports.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,Qo,t.dtype);var r=new Zo(Qo,t.shape,e.shape),o=this.makeOutputArray(r.outputShape,n);return this.compileAndRun(r,[t,e],o);},t.prototype.pow=function(t,e){var n=exports.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS"),r=n?new ta("\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  vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));\n  \n  result.r = isNaN.r > 0. ? NAN : result.r;\n  result.g = isNaN.g > 0. ? NAN : result.g;\n  result.b = isNaN.b > 0. ? NAN : result.b;\n  result.a = isNaN.a > 0. ? NAN : result.a;\n\n  return result;\n",t.shape,e.shape):new Zo("\nif(a < 0.0 && floor(b) < b){\n  return NAN;\n}\nreturn (round(mod(b, 2.0)) != 1) ?\n    pow(abs(a), b) : sign(a) * pow(abs(a), b);\n",t.shape,e.shape),o=Ct(t.dtype,e.dtype),a=n?this.makePackedTensor(r.outputShape,o):this.makeOutputArray(r.outputShape,o);return this.compileAndRun(r,[t,e],a);},t.prototype.ceil=function(t){var e=new Vi(t.shape,"return ceil(x);");return this.compileAndRun(e,[t]);},t.prototype.floor=function(t){var e=new Vi(t.shape,"return floor(x);");return this.compileAndRun(e,[t]);},t.prototype.sign=function(t){var e=new Vi(t.shape,"\n  if (isnan(x)) { return 0.0; }\n  return sign(x);\n");return this.compileAndRun(e,[t]);},t.prototype.isNaN=function(t){var e=new Vi(t.shape,"return float(isnan(x));"),n=this.makeOutputArray(e.outputShape,"bool");return this.compileAndRun(e,[t],n);},t.prototype.isInf=function(t){var e=new Vi(t.shape,"return float(isinf(x));"),n=this.makeOutputArray(e.outputShape,"bool");return this.compileAndRun(e,[t],n);},t.prototype.isFinite=function(t){var e=new Vi(t.shape,"return float(!isnan(x) && !isinf(x));"),n=this.makeOutputArray(e.outputShape,"bool");return this.compileAndRun(e,[t],n);},t.prototype.round=function(t){var e=new Vi(t.shape,"\n  // OpenGL ES does not support round function.\n  // The algorithm is based on banker's rounding.\n  float base = floor(x);\n  if ((x - base) < 0.5) {\n    return floor(x);\n  } else if ((x - base) > 0.5) {\n    return ceil(x);\n  } else {\n    if (mod(base, 2.0) == 0.0) {\n      return base;\n    } else {\n      return base + 1.0;\n    }\n  }\n");return this.compileAndRun(e,[t]);},t.prototype.exp=function(t){var e;return e=exports.ENV.getBool("WEBGL_PACK")?new es(t.shape,ji):new Vi(t.shape,ji),this.compileAndRun(e,[t]);},t.prototype.expm1=function(t){var e=new Vi(t.shape,"return exp(x) - 1.0;");return this.compileAndRun(e,[t]);},t.prototype.log=function(t){var e;return e=exports.ENV.getBool("WEBGL_PACK")?new es(t.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 Vi(t.shape,"if (x < 0.0) return NAN;\n  return log(x);"),this.compileAndRun(e,[t]);},t.prototype.log1p=function(t){var e=new Vi(t.shape,"return log(1.0 + x);");return this.compileAndRun(e,[t]);},t.prototype.sqrt=function(t){var e=new Vi(t.shape,"return sqrt(x);");return this.compileAndRun(e,[t]);},t.prototype.rsqrt=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.rsqrt(t);var e=new Vi(t.shape,"return inversesqrt(x);");return this.compileAndRun(e,[t]);},t.prototype.square=function(t){var e=new Vi(t.shape,"return x * x;");return this.compileAndRun(e,[t]);},t.prototype.reciprocal=function(t){var e=new Vi(t.shape,"return 1.0 / x;");return this.compileAndRun(e,[t]);},t.prototype.relu=function(t){var e;return e=exports.ENV.getBool("WEBGL_PACK")?new es(t.shape,ts):new Vi(t.shape,Hi),this.compileAndRun(e,[t]);},t.prototype.prelu=function(t,e){var n=exports.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ta("\n  vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n  return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",t.shape,e.shape):new Zo("return (a < 0.) ? b * a : a;",t.shape,e.shape);return this.compileAndRun(n,[t,e]);},t.prototype.elu=function(t){var e=new Vi(t.shape,"return (x >= 0.0) ? x : (exp(x) - 1.0);");return this.compileAndRun(e,[t]);},t.prototype.eluDer=function(t,e){var n=exports.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ta("\n  vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n  return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n",t.shape,e.shape):new Zo("return (b >= 1.0) ? a : a * (b + 1.0);",t.shape,e.shape);return this.compileAndRun(n,[t,e]);},t.prototype.selu=function(t){var e=new Vi(t.shape,$i);return this.compileAndRun(e,[t]);},t.prototype.int=function(t){var e=new Vi(t.shape,"return float(int(x));"),n=this.makeOutputArray(e.outputShape,"int32");return this.compileAndRun(e,[t],n);},t.prototype.clip=function(t,e,n){var r,o=(r=exports.ENV.getBool("WEBGL_PACK_CLIP")?new na(t.shape):new ea(t.shape)).getCustomSetupFunc(e,n);return this.compileAndRun(r,[t],null,o);},t.prototype.abs=function(t){var e=new Vi(t.shape,"return abs(x);");return this.compileAndRun(e,[t]);},t.prototype.complexAbs=function(t){var e=this.texData.get(t.dataId),n=new ra(t.shape),r=[this.makeComplexComponentTensorHandle(t,e.complexTensors.real),this.makeComplexComponentTensorHandle(t,e.complexTensors.imag)];return this.compileAndRun(n,r);},t.prototype.sigmoid=function(t){var e=new Vi(t.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(e,[t]);},t.prototype.softplus=function(t){var e=new Vi(t.shape,"\n  float epsilon = 1.1920928955078125e-7;\n  float threshold = log(epsilon) + 2.0;\n\n  bool too_large = x > -threshold;\n  bool too_small = x < threshold;\n\n  float result;\n  float exp_x = exp(x);\n\n  if (too_large){\n    result = x;\n  }\n  else if (too_small){\n    result = exp_x;\n  }\n  else{\n    result = log(exp_x + 1.0);\n  }\n  return result;\n");return this.compileAndRun(e,[t]);},t.prototype.sin=function(t){var e=new Vi(t.shape,Ki);return this.compileAndRun(e,[t]);},t.prototype.cos=function(t){var e=new Vi(t.shape,Xi);return this.compileAndRun(e,[t]);},t.prototype.tan=function(t){var e=new Vi(t.shape,"return tan(x);");return this.compileAndRun(e,[t]);},t.prototype.asin=function(t){var e=new Vi(t.shape,"return asin(x);");return this.compileAndRun(e,[t]);},t.prototype.acos=function(t){var e=new Vi(t.shape,"return acos(x);");return this.compileAndRun(e,[t]);},t.prototype.atan=function(t){var e=new Vi(t.shape,Yi);return this.compileAndRun(e,[t]);},t.prototype.atan2=function(t,e){var n=exports.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")?new ta("\n  vec4 result = atan(a, b);\n  vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));\n  \n  result.r = isNaN.r > 0. ? NAN : result.r;\n  result.g = isNaN.g > 0. ? NAN : result.g;\n  result.b = isNaN.b > 0. ? NAN : result.b;\n  result.a = isNaN.a > 0. ? NAN : result.a;\n\n  return result;\n",t.shape,e.shape):new Zo("\n  if (isnan(a)) return a;\n  if (isnan(b)) return b;\n\n  return atan(a, b);\n",t.shape,e.shape);return this.compileAndRun(n,[t,e]);},t.prototype.sinh=function(t){var e=new Vi(t.shape,"\n  float e2x = exp(x);\n  return (e2x - 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t]);},t.prototype.cosh=function(t){var e=new Vi(t.shape,"\n  float e2x = exp(-x);\n  return (e2x + 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t]);},t.prototype.tanh=function(t){var e=new Vi(t.shape,"\n  float e2x = exp(-2.0 * abs(x));\n  return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n");return this.compileAndRun(e,[t]);},t.prototype.asinh=function(t){var e=new Vi(t.shape,"return log(x + sqrt(x * x + 1.0));");return this.compileAndRun(e,[t]);},t.prototype.acosh=function(t){var e=new Vi(t.shape,Qi);return this.compileAndRun(e,[t]);},t.prototype.atanh=function(t){var e=new Vi(t.shape,Ji);return this.compileAndRun(e,[t]);},t.prototype.erf=function(t){var e=new Vi(t.shape,'\n  // Error function is calculated approximately with elementary function.\n  // See "Handbook of Mathematical Functions with Formulas,\n  // Graphs, and Mathematical Tables", Abramowitz and Stegun.\n  float p = 0.3275911;\n  float a1 = 0.254829592;\n  float a2 = -0.284496736;\n  float a3 = 1.421413741;\n  float a4 = -1.453152027;\n  float a5 = 1.061405429;\n\n  float 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(e,[t]);},t.prototype.step=function(t,e){var n=new Vi(t.shape,function(t){return void 0===t&&(t=0),Gi+"\n    return x > 0.0 ? 1.0 : float("+t+");\n  ";}(e));return this.compileAndRun(n,[t]);},t.prototype.conv2dByMatMul=function(t,e,n){var r=t.shape,o=this.texData.get(t.dataId),a=n.inChannels,i=r[0]*r[1]*r[2],u=n.outChannels,l=(1===i||1===u)&&a>1e3,c=r[2]%2!=0&&!!o.isPacked;if(l||!exports.ENV.getBool("WEBGL_LAZILY_UNPACK")||!exports.ENV.getBool("WEBGL_PACK_BINARY_OPERATIONS")||!c){var h=this.reshape(t,[1,r[0]*r[1]*r[2],n.inChannels]),p=this.reshape(e,[1,n.inChannels,n.outChannels]);return this.reshape(this.batchMatMul(h,p,!1,!1),n.outShape);}var f=ft.make([1,r[0]*r[1]*(r[2]+1),n.inChannels],{dataId:t.dataId},t.dtype,this),v=o.shape;o.shape=o.shape.slice(),o.shape[o.shape.length-2]++,d(xe(o.shape,f.shape),function(){return"packed reshape "+o.shape+" to "+f.shape+" isn't free";});var m=this.reshape(e,[1,n.inChannels,n.outChannels]),g=this.batchMatMul(f,m,!1,!1),y=this.texData.get(g.dataId);return d(y.isPacked,function(){return"batchMatMul result is expected to be packed";}),o.shape=v,y.shape=n.outShape,ft.make(n.outShape,{dataId:g.dataId},g.dtype,this);},t.prototype.conv2dWithIm2Row=function(t,e,n){var r=n.filterWidth,o=n.filterHeight,a=n.inChannels,i=n.outWidth,s=n.outHeight,u=r*o*a,l=s*i,c=[u,l],h=t.squeeze([0]),p=e.reshape([1,u,-1]),f=new ii(c,h.shape,n),d=this.compileAndRun(f,[h]).reshape([1,c[0],c[1]]),v=new hi(d.shape,[1,l,n.outChannels],!0,!1);return this.compileAndRun(v,[d,p]).reshape([1,s,i,n.outChannels]);},t.prototype.conv2d=function(t,e,n){if(1===n.filterHeight&&1===n.filterWidth&&1===n.dilationHeight&&1===n.dilationWidth&&1===n.strideHeight&&1===n.strideWidth&&("SAME"===n.padInfo.type||"VALID"===n.padInfo.type))return this.conv2dByMatMul(t,e,n);if(exports.ENV.getBool("WEBGL_CONV_IM2COL")&&1===t.shape[0])return this.conv2dWithIm2Row(t,e,n);var r=new pa(n);return this.compileAndRun(r,[t,e]);},t.prototype.conv2dDerInput=function(t,e,n){var r=new sa(n);return this.compileAndRun(r,[t,e]);},t.prototype.conv2dDerFilter=function(t,e,n){var r=new ia(n);return this.compileAndRun(r,[t,e]);},t.prototype.depthwiseConv2D=function(t,e,n){var r;return exports.ENV.getBool("WEBGL_PACK_DEPTHWISECONV")&&n.strideWidth<=2&&n.outChannels/n.inChannels==1?(r=new va(n),this.compileAndRun(r,[t,e],this.makePackedTensor(n.outShape,t.dtype))):(r=new da(n),this.compileAndRun(r,[t,e]));},t.prototype.depthwiseConv2DDerInput=function(t,e,n){var r=new ha(n);return this.compileAndRun(r,[t,e]);},t.prototype.depthwiseConv2DDerFilter=function(t,e,n){var r=new ca(n);return this.compileAndRun(r,[t,e]);},t.prototype.conv3d=function(t,e,n){var r=new fa(n);return this.compileAndRun(r,[t,e]);},t.prototype.conv3dDerInput=function(t,e,n){var r=new la(n);return this.compileAndRun(r,[t,e]);},t.prototype.conv3dDerFilter=function(t,e,n){var r=new ua(n);return this.compileAndRun(r,[t,e]);},t.prototype.maxPool=function(t,e){var n=new gi(e,"max",!1),r=this.makeOutputArray(n.outputShape,t.dtype);return this.compileAndRun(n,[t],r);},t.prototype.avgPool=function(t,e){var n=new gi(e,"avg",!1),r=this.makeOutputArray(n.outputShape,"float32");return this.compileAndRun(n,[t],r);},t.prototype.maxPoolBackprop=function(t,e,n,r){var o=new gi(r,"max",!0),a=this.compileAndRun(o,[e]),i=new ci(r),s=this.makeOutputArray(i.outputShape,e.dtype),u=this.compileAndRun(i,[t,a],s);return a.dispose(),u;},t.prototype.avgPoolBackprop=function(t,e,n){var r=new qo(n),o=this.makeOutputArray(r.outputShape,e.dtype);return this.compileAndRun(r,[t],o);},t.prototype.cast=function(t,e){return so(t,e,this);},t.prototype.unstack=function(t,e){for(var n=t.shape[e],r=new Array(t.rank-1),o=0,a=0;a<t.rank;a++)a!==e&&(r[o++]=t.shape[a]);var i=new Array(t.rank).fill(0),s=t.shape.slice();s[e]=1;var u=new Array(n);for(a=0;a<u.length;a++)i[e]=a,u[a]=this.slice(t,i,s).reshape(r);return u;},t.prototype.reshape=function(t,e){var n=this.texData.get(t.dataId);return!n.isPacked||xe(t.shape,e)||null!==n.texture&&xe(n.shape,e)?uo(t,e):this.packedReshape(t,e);},t.prototype.resizeBilinear=function(t,e,n,r){var o=exports.ENV.getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new Ci(t.shape,e,n,r):new wi(t.shape,e,n,r);return this.compileAndRun(o,[t]);},t.prototype.resizeBilinearBackprop=function(t,e,n){var r=new bi(t,e,n);return this.compileAndRun(r,[t]);},t.prototype.resizeNearestNeighbor=function(t,e,n,r){var o=new Ri(t.shape,e,n,r);return this.compileAndRun(o,[t]);},t.prototype.resizeNearestNeighborBackprop=function(t,e,n){var r=new Ei(t,e,n);return this.compileAndRun(r,[t]);},t.prototype.multinomial=function(t,e,n,r){var o=e?t:qr(t),a=o.shape[0],i=o.shape[1],s=new pi(a,i,n),u=this.makeOutputArray(s.outputShape,"int32"),l=s.getCustomSetupFunc(r);return this.compileAndRun(s,[o],u,l);},t.prototype.oneHot=function(t,e,n,r){var o=new fi(t.size,e,n,r);return this.compileAndRun(o,[t]);},t.prototype.nonMaxSuppression=function(t,e,n,r,o){return Ye("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead"),mo(t.dataSync(),e.dataSync(),n,r,o);},t.prototype.cropAndResize=function(t,e,n,r,o,a){var i=new ma(t.shape,e.shape,r,o,a);return this.compileAndRun(i,[t,e,n]);},t.prototype.depthToSpace=function(t,e,n){d(e>1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+e;});var r=t.shape[0],o="NHWC"===n?t.shape[1]:t.shape[2],a="NHWC"===n?t.shape[2]:t.shape[3],i="NHWC"===n?t.shape[3]:t.shape[1],s=o*e,u=a*e,l=i/(e*e),c=new wa("NHWC"===n?[r,s,u,l]:[r,l,s,u],e,n);return this.compileAndRun(c,[t]);},t.prototype.split=function(t,e,n){return yo(t,e,n);},t.prototype.scatterND=function(t,e,n){var r=Dr(0,t,n),o=r.sliceRank,a=r.numUpdates,i=r.sliceSize,s=r.strides,u=r.outputSize,l=[u/i,i],c=t.reshape([a,o]),h=e.reshape([a,i]);if(0===u)return uo(mn([]),n);var p=yn(0),f=new Ni(a,o,c.rank,h.rank,s,l);return this.compileAndRun(f,[h,c,p]).reshape(n);},t.prototype.sparseToDense=function(t,e,n,r){var o=Dr(0,t,n),a=o.sliceRank,i=o.numUpdates,s=o.strides,u=o.outputSize,l=new Ni(i,a,t.rank,e.rank,s,[u,1],!1);return this.compileAndRun(l,[e,t,r]).reshape(n);},t.prototype.fft=function(t){return this.fftImpl(t,!1);},t.prototype.ifft=function(t){return this.fftImpl(t,!0);},t.prototype.fftImpl=function(t,e){var n=this.texData.get(t.dataId),r=new ka(Sa,t.shape,e),o=new ka(Na,t.shape,e),a=[this.makeComplexComponentTensorHandle(t,n.complexTensors.real),this.makeComplexComponentTensorHandle(t,n.complexTensors.imag)],i=this.compileAndRun(r,a),s=this.compileAndRun(o,a),u=this.complex(i,s).as2D(t.shape[0],t.shape[1]);return i.dispose(),s.dispose(),u;},t.prototype.gatherND=function(t,e){var n=e.shape,r=n[n.length-1],o=Nr(t,e),a=o[0],i=o[1],s=o[2],u=o[3],l=e.reshape([i,r]),c=t.reshape([t.size/s,s]),h=new Fa(r,u,[i,s]);return this.compileAndRun(h,[c,l]).reshape(a);},t.prototype.fill=function(t,e,n){if("string"===(n=n||U(e))){var r=A(n,y(t));return r.fill(e),ft.make(t,{values:r},n);}var o=new Aa(t,e),a=o.getCustomSetupFunc(e),i=this.makeOutputArray(t,n);return this.compileAndRun(o,[],i,a);},t.prototype.onesLike=function(t){if("string"===t.dtype)throw new Error("onesLike is not supported under string dtype");return this.fill(t.shape,1,t.dtype);},t.prototype.zerosLike=function(t){return this.fill(t.shape,"string"===t.dtype?"":0,t.dtype);},t.prototype.linspace=function(t,e,n){return lo(t,e,n);},t.prototype.makeOutputArray=function(t,e){return ft.make(t,{},e,this);},t.prototype.makePackedTensor=function(t,e){var n=ft.make(t,{},e,this);return this.texData.get(n.dataId).isPacked=!0,n;},t.prototype.unpackTensor=function(t){var e=new ns(t.shape);return this.compileAndRun(e,[t],ft.make(e.outputShape,{},t.dtype,this));},t.prototype.packTensor=function(t){var e=new di(t.shape);return this.compileAndRun(e,[t],this.makePackedTensor(t.shape,t.dtype),null,!0);},t.prototype.packedReshape=function(t,e){var n=t.reshape([de(t.shape)].concat(ve(t.shape))),r=[de(e)].concat(ve(e)),o=new xi(r,n.shape);return this.compileAndRun(o,[n]).reshape(e);},t.prototype.decode=function(t){var e,n=this.texData.get(t),r=n.isPacked,o=n.shape,a=n.dtype,i=me(o),s=Pa(o),u=this.makeTensorHandle(o,"float32");return this.texData.get(u.dataId).isPacked=!0,this.texData.get(u.dataId).dtype=a,this.texData.get(u.dataId).texShape=s.map(function(t){return 2*t;}),e=r?new ba(i,s):new xa(i,s),this.compileAndRun(e,[{shape:i,dtype:a,dataId:t}],u,null,!0),u;},t.prototype.compileAndRun=function(t,e,n,r,o){var a=this;if(void 0===o&&(o=!1),null==n&&(n=t.usesPackedTextures?this.makePackedTensor(t.outputShape,e[0].dtype):this.makeOutputArray(t.outputShape,e[0].dtype)),0===n.size)return this.texData.get(n.dataId).values=k(n.dtype,0),n;var i=e.map(function(e){if("complex64"===e.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");var n=a.texData.get(e.dataId);if(null==n.texture){if(!t.usesPackedTextures&&y(e.shape)<=exports.ENV.getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:e.shape,texData:null,isUniform:!0,uniformValues:n.values};t.usesPackedTextures&&(n.isPacked=!0,n.shape=e.shape);}else if(!!n.isPacked!=!!t.usesPackedTextures)e=n.isPacked?a.unpackTensor(e):a.packTensor(e),n=a.texData.get(e.dataId);else if(n.isPacked&&!xe(n.shape,e.shape)){var r=e,o=e.shape;e.shape=n.shape,e=a.packedReshape(e,o),n=a.texData.get(e.dataId),r.shape=o;}return a.uploadToGPU(e.dataId),{shape:e.shape,texData:n,isUniform:!1};});this.uploadToGPU(n.dataId);var u,l={shape:n.shape,texData:this.texData.get(n.dataId),isUniform:!1},c=function(t,e,n){var r="";e.concat(n).forEach(function(t){var e=null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0,n=t.isUniform?"uniform":t.texData.texShape;r+=t.shape+"_"+n+"_"+e;});var o=t.userCode,a=t.constructor.name;return a+="_"+r+"_"+o;}(t,i,l),h=this.getAndSaveBinary(c,function(){return function(t,e,n,r){var o=e.userCode,a=n.map(function(t,n){var r={logicalShape:t.shape,texShape:t.isUniform?null:t.texData.texShape,isUniform:t.isUniform,isPacked:!t.isUniform&&t.texData.isPacked,flatOffset:null};return null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0&&(r.flatOffset=t.texData.slice.flatOffset),{name:e.variableNames[n],shapeInfo:r};}),i=a.map(function(t){return t.shapeInfo;}),u={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},l=Do(a,u,o,e.usesPackedTextures),c=t.createProgram(l),h=null,p=t.getUniformLocation(c,"NAN",!1);1===exports.ENV.getNumber("WEBGL_VERSION")&&(h=t.getUniformLocation(c,"INFINITY",!1));for(var f={},d=0;d<e.variableNames.length;d++){var v=e.variableNames[d];f[v]=t.getUniformLocation(c,v,!1),f["offset"+v]=t.getUniformLocation(c,"offset"+v,!1);}return{program:e,source:l,webGLProgram:c,uniformLocations:f,inShapeInfos:i,outShapeInfo:u,infLoc:h,nanLoc:p};}(a.gpgpu,t,i,l);}),p=null!=this.activeTimers;return p&&(u=this.startTimer()),function(t,e,n,r,o){ai(e.inShapeInfos,n),ai([e.outShapeInfo],[r]);var a=r.texData.texture,i=r.texData.texShape;r.texData.isPacked?t.setOutputPackedMatrixTexture(a,i[0],i[1]):t.setOutputMatrixTexture(a,i[0],i[1]),t.setProgram(e.webGLProgram),1===exports.ENV.getNumber("WEBGL_VERSION")&&null!==e.infLoc&&t.gl.uniform1f(e.infLoc,1/0),null!==e.nanLoc&&t.gl.uniform1f(e.nanLoc,NaN),n.forEach(function(n,r){var o=e.program.variableNames[r],a=e.uniformLocations[o],i=e.uniformLocations["offset"+o];if(null!=a)if(n.isUniform){if(y(n.shape)<2)t.gl.uniform1f(a,n.uniformValues[0]);else{var s=n.uniformValues;s instanceof Float32Array||(s=new Float32Array(s)),t.gl.uniform1fv(a,s);}}else null!=n.texData.slice&&null!=i&&t.gl.uniform1i(i,n.texData.slice.flatOffset),t.setInputMatrixTexture(n.texData.texture,a,r);}),null!=o&&o(t,e.webGLProgram),t.executeProgram();}(this.gpgpu,h,i,l,r),p&&(u=this.endTimer(u),this.activeTimers.push({name:t.constructor.name,query:this.getQueryTime(u)})),!exports.ENV.getBool("WEBGL_LAZILY_UNPACK")&&this.texData.get(n.dataId).isPacked&&!1===o?this.unpackTensor(n):n;},t.prototype.getAndSaveBinary=function(t,e){return t in this.binaryCache||(this.binaryCache[t]=e()),this.binaryCache[t];},t.prototype.getTextureManager=function(){return this.textureManager;},t.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);},t.prototype.floatPrecision=function(){var t=this;return null==this.floatPrecisionValue&&(this.floatPrecisionValue=Pe(function(){var e=exports.ENV.getBool("DEBUG");exports.ENV.set("DEBUG",!1);var n=t.abs(yn(1e-8)).dataSync()[0];return exports.ENV.set("DEBUG",e),n>0?32:16;})),this.floatPrecisionValue;},t.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4;},t.prototype.uploadToGPU=function(t){var e,n=this.texData.get(t),r=n.shape,o=n.dtype,a=n.values,i=n.texture,s=n.usage,u=n.isPacked;if(null==i){var l,c=null!=this.activeTimers;c&&(l=K());var h=n.texShape;if(null==h&&(h=ge(r,u),n.texShape=h),null!=a){var p=me(r),f=void 0,d=h[1],v=h[0],m=a instanceof Uint8Array;u?(d=(e=La(h[0],h[1]))[0],v=e[1],f=new Ia(p,[v,d],m)):f=new Ra(p,[v,d],m);var g=this.makeTensorHandle([v,d],o);this.texData.get(g.dataId).usage=m?Oa.PIXELS:Oa.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(g.dataId),d,v,a);var x=this.makeTensorHandle(f.outputShape,g.dtype);x.size=y(f.outputShape),this.texData.get(x.dataId).isPacked=u,this.compileAndRun(f,[g],x);var b=this.texData.get(x.dataId);n.texture=b.texture,n.texShape=b.texShape,n.isPacked=b.isPacked,n.usage=b.usage,this.disposeData(g.dataId),this.texData.delete(x.dataId),n.values=null,c&&(this.uploadWaitMs+=K()-l);}else{var w=this.acquireTexture(h,s,o,u);n.texture=w;}}},t.prototype.convertAndCacheOnCPU=function(t,e){var n=this.texData.get(t),r=n.dtype;return this.releaseGPUData(t),null!=e&&(n.values=function(t,e){if("float32"===e||"complex64"===e)return t;if("int32"===e||"bool"===e){for(var n="int32"===e?new Int32Array(t.length):new Uint8Array(t.length),r=0;r<n.length;++r)n[r]=Math.round(t[r]);return n;}throw new Error("Unknown dtype "+e);}(e,r)),n.values;},t.prototype.acquireTexture=function(t,e,n,r){if(this.numBytesInGPU+=this.computeBytes(t,n),!this.warnedAboutMemory&&this.numBytesInGPU>1024*this.numMBBeforeWarning*1024){var o=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn("High memory usage in GPU: "+o+" MB, most likely due to a memory leak");}return this.textureManager.acquireTexture(t,e,r);},t.prototype.computeBytes=function(t,e){return t[0]*t[1]*F(e);},t;}();_t()&&Dt.registerBackend("webgl",function(){return new as();},2);var is=pn({abs_:function(t){var e=Ze(t,"x","abs");return"complex64"===e.dtype?Dt.runKernel(function(t){return t.complexAbs(e);},{$x:e}):Dt.runKernel(function(t,n){var r=t.abs(e);return n([e]),r;},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.toFloat().step(-1));}};});}}),ss=pn({acos_:function(t){var e=Ze(t,"x","acos");return Dt.runKernel(function(t,n){var r=t.acos(e);return n([e]),r;},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(yn(1).sub(n.toFloat().square()).sqrt()).neg();}};});}}),us=pn({acosh_:function(t){var e=Ze(t,"x","acosh");return Dt.runKernel(function(t,n){var r=t.acosh(e);return n([e]),r;},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(n.toFloat().square().sub(1).sqrt());}};});}}),ls=pn({asin_:function(t){var e=Ze(t,"x","asin");return Dt.runKernel(function(t,n){var r=t.asin(e);return n([e]),r;},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(yn(1).sub(n.toFloat().square()).sqrt());}};});}}),cs=pn({asinh_:function(t){var e=Ze(t,"x","asinh");return Dt.runKernel(function(t,n){var r=t.asinh(e);return n([e]),r;},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(yn(1).add(n.toFloat().square()).sqrt());}};});}}),hs=pn({atan_:function(t){var e=Ze(t,"x","atan");return Dt.runKernel(function(t,n){var r=t.atan(e);return n([e]),r;},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.toFloat().square().add(1));}};});}}),ps=pn({atanh_:function(t){var e=Ze(t,"x","atanh");return Dt.runKernel(function(t,n){var r=t.atanh(e);return n([e]),r;},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(yn(1).sub(n.toFloat().square()));}};});}}),fs=pn({ceil_:function(t){var e=Ze(t,"x","ceil");return Dt.runKernel(function(t){return t.ceil(e);},{$x:e},function(t){return{$x:function(){return Dn(t);}};});}}),ds=pn({clipByValue_:function(t,e,n){var r=Ze(t,"x","clipByValue");return d(e<=n,function(){return"Error in clip: min ("+e+") must be less than or equal to max ("+n+").";}),Dt.runKernel(function(t,o){var a=t.clip(r,e,n);return o([r]),a;},{$x:r},function(t,r){var o=r[0];return{$x:function(){return t.where(o.greaterEqual(e).logicalAnd(o.lessEqual(n)),Dn(t));}};});}}),vs=pn({cos_:function(t){var e=Ze(t,"x","cos");return Dt.runKernel(function(t,n){var r=t.cos(e);return n([e]),r;},{$x:e},function(t,e){var n=e[0];return{$x:function(){return n.toFloat().sin().neg().mul(t);}};});}}),ms=pn({cosh_:function(t){var e=Ze(t,"x","cosh");return Dt.runKernel(function(t,n){var r=t.cosh(e);return n([e]),r;},{$x:e},function(t,e){var n=e[0];return{$x:function(){return n.toFloat().sinh().mulStrict(t);}};});}}),gs=pn({erf_:function(t){var e=Ze(t,"x","erf");return d("int32"===e.dtype||"float32"===e.dtype,function(){return"Input dtype must be `int32` or `float32`.";}),"int32"===e.dtype&&(e=e.toFloat()),Dt.runKernel(function(t,n){var r=t.erf(e);return n([e]),r;},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.square().neg().exp().mul(2/Math.sqrt(Math.PI)));}};});}}),ys=pn({exp_:function(t){var e=Ze(t,"x","exp");return Dt.runKernel(function(t,n){var r=t.exp(e);return n([r]),r;},{$x:e},function(t,e){return{$x:function(){return t.mulStrict(e[0]);}};});}}),xs=pn({expm1_:function(t){var e=Ze(t,"x","expm1");return Dt.runKernel(function(t,n){var r=t.expm1(e);return n([e]),r;},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.exp());}};});}}),bs=pn({floor_:function(t){var e=Ze(t,"x","floor");return Dt.runKernel(function(t){return t.floor(e);},{$x:e},function(t){return{$x:function(){return Dn(t);}};});}}),ws=pn({log_:function(t){var e=Ze(t,"x","log");return Dt.runKernel(function(t,n){var r=t.log(e);return n([e]),r;},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.toFloat());}};});}}),Cs=pn({log1p_:function(t){var e=Ze(t,"x","log1p");return Dt.runKernel(function(t,n){var r=t.log1p(e);return n([e]),r;},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.add(1));}};});}}),Es=pn({logSigmoid_:function(t){var e=Ze(t,"x","logSigmoid");return Dt.runKernel(function(t,n){var r=t.softplus(e.neg()).neg();return n([e]),r;},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.neg().sigmoid());}};});}}),Rs=pn({neg_:function(t){var e=Ze(t,"x","neg");return Dt.runKernel(function(t){return t.neg(e);},{$x:e},function(t){return{$x:function(){return t.neg();}};});}}),Is=pn({reciprocal_:function(t){var e=Ze(t,"x","reciprocal");return Dt.runKernel(function(t,n){var r=t.reciprocal(e);return n([e]),r;},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.square().neg());}};});}}),Ss=pn({round_:function(t){var e=Ze(t,"x","round");return Dt.runKernel(function(t){return t.round(e);},{$x:e},function(t){return{$x:function(){return Dn(t);}};});}}),Ns=pn({rsqrt_:function(t){var e=Ze(t,"x","rsqrt");return Dt.runKernel(function(t,n){var r=t.rsqrt(e);return n([e]),r;},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.pow(1.5).mul(2)).neg();}};});}}),ks=pn({sigmoid_:function(t){var e=Ze(t,"x","sigmoid");return Dt.runKernel(function(t,n){var r=t.sigmoid(e);return n([r]),r;},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.mul(yn(1).sub(n)));}};});}}),As=pn({sign_:function(t){var e=Ze(t,"x","sign");return Dt.runKernel(function(t){return t.sign(e);},{$x:e},function(t){return{$x:function(){return Dn(t);}};});}}),Ts=pn({isNaN_:function(t){var e=Ze(t,"x","isNaN");return Dt.runKernel(function(t){return t.isNaN(e);},{$x:e},function(t){return{$x:function(){return Dn(t);}};});}}),Ds=pn({isInf_:function(t){var e=Ze(t,"x","isInf");return Dt.runKernel(function(t){return t.isInf(e);},{$x:e},function(t){return{$x:function(){return Dn(t);}};});}}),_s=pn({isFinite_:function(t){var e=Ze(t,"x","isFinite");return Dt.runKernel(function(t){return t.isFinite(e);},{$x:e},function(t){return{$x:function(){return Dn(t);}};});}}),Os=pn({sin_:function(t){var e=Ze(t,"x","sin");return Dt.runKernel(function(t,n){var r=t.sin(e);return n([e]),r;},{$x:e},function(t,e){var n=e[0];return{$x:function(){return n.toFloat().cos().mul(t);}};});}}),Ms=pn({sinh_:function(t){var e=Ze(t,"x","sinh");return Dt.runKernel(function(t,n){var r=t.sinh(e);return n([e]),r;},{$x:e},function(t,e){var n=e[0];return{$x:function(){return n.toFloat().cosh().mulStrict(t);}};});}}),Fs=pn({softplus_:function(t){var e=Ze(t,"x","softplus");return Dt.runKernel(function(t,n){var r=t.softplus(e);return n([e]),r;},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.sigmoid());}};});}}),Bs=pn({sqrt_:function(t){var e=Ze(t,"x","sqrt");return Dt.runKernel(function(t,n){var r=t.sqrt(e);return n([e]),r;},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.toFloat().sqrt().mul(2));}};});}}),Ps=pn({square_:function(t){var e=Ze(t,"x","square");return Dt.runKernel(function(t,n){return n([e]),t.square(e);},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.toFloat().mul(2));}};});}}),Ls=pn({step_:function(t,e){void 0===e&&(e=0);var n=Ze(t,"x","step");return Dt.runKernel(function(t){return t.step(n,e);},{$x:n},function(t){return{$x:function(){return Dn(t);}};});}}),Ws=pn({tan_:function(t){var e=Ze(t,"x","tan");return Dt.runKernel(function(t,n){var r=t.tan(e);return n([e]),r;},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.cos().square());}};});}}),Us=pn({tanh_:function(t){var e=Ze(t,"x","tanh");return Dt.runKernel(function(t,n){var r=t.tanh(e);return n([r]),r;},{$x:e},function(t,e){var n=e[0];return{$x:function(){return yn(1).sub(n.square()).mulStrict(t);}};});}});function zs(t,e,n,r,o,a){var i,s,u=Ze(t,"x","batchNorm"),l=Ze(e,"mean","batchNorm"),c=Ze(n,"variance","batchNorm");return null!=o&&(i=Ze(o,"scale","batchNorm")),null!=r&&(s=Ze(r,"offset","batchNorm")),d(2===u.rank,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+".";}),d(2===l.rank||1===l.rank,function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank "+l.rank+".";}),d(2===c.rank||1===c.rank,function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank "+c.rank+".";}),null!=i&&d(2===i.rank||1===i.rank,function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank "+i.rank+".";}),null!=s&&d(2===s.rank||1===s.rank,function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank "+s.rank+".";}),qs(u,l,c,s,i,a);}function Vs(t,e,n,r,o,a){var i,s,u=Ze(t,"x","batchNorm"),l=Ze(e,"mean","batchNorm"),c=Ze(n,"variance","batchNorm");return null!=o&&(i=Ze(o,"scale","batchNorm")),null!=r&&(s=Ze(r,"offset","batchNorm")),d(3===u.rank,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+".";}),d(3===l.rank||1===l.rank,function(){return"Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank "+l.rank+".";}),d(3===c.rank||1===c.rank,function(){return"Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank "+c.rank+".";}),null!=i&&d(3===i.rank||1===i.rank,function(){return"Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank "+i.rank+".";}),null!=s&&d(3===s.rank||1===s.rank,function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank "+s.rank+".";}),qs(u,l,c,s,i,a);}function Gs(t,e,n,r,o,a){var i,s,u=Ze(t,"x","batchNorm"),l=Ze(e,"mean","batchNorm"),c=Ze(n,"variance","batchNorm");return null!=o&&(i=Ze(o,"scale","batchNorm")),null!=r&&(s=Ze(r,"offset","batchNorm")),d(4===u.rank,function(){return"Error in batchNorm4D: x must be rank 4 but got rank "+u.rank+".";}),d(4===l.rank||1===l.rank,function(){return"Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank "+l.rank+".";}),d(4===c.rank||1===c.rank,function(){return"Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank "+c.rank+".";}),null!=i&&d(4===i.rank||1===i.rank,function(){return"Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank "+i.rank+".";}),null!=s&&d(4===s.rank||1===s.rank,function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank "+s.rank+".";}),qs(u,l,c,s,i,a);}function qs(t,e,n,r,o,a){null==a&&(a=.001);var i,s,u,l=Ze(t,"x","batchNorm"),c=Ze(e,"mean","batchNorm"),h=Ze(n,"variance","batchNorm");null!=o&&(i=Ze(o,"scale","batchNorm")),null!=r&&(s=Ze(r,"offset","batchNorm")),d(c.rank===h.rank,function(){return"Batch normalization gradient requires mean and variance to have equal ranks.";}),d(null==s||c.rank===s.rank,function(){return"Batch normalization gradient requires mean and offset to have equal ranks.";}),d(null==i||c.rank===i.rank,function(){return"Batch normalization gradient requires mean and scale to have equal ranks.";}),u=0===l.rank||1===l.rank?l.as4D(1,1,1,l.size):2===l.rank?l.as4D(1,1,l.shape[0],l.shape[1]):3===l.rank?l.as4D(1,l.shape[0],l.shape[1],l.shape[2]):l;return Dt.runKernel(function(t,e){var n=t.batchNormalization(u,Hs(c),Hs(h),a,Hs(i),Hs(s));return e([l,c,h,i]),n;},{$x:l,$mean:c,$variance:h,$scale:i,$offset:s},function(t,e){var n=e,r=n[0],o=n[1],i=n[2],s=n[3],l=null==s?yn(1):s,c=Xr(o.shape,u.shape),h=[];if(1===o.rank){for(var p=0;p<u.shape.length-1;++p)h.push(u.shape[p]);h.push(1);}var f=r.sub(o),d=t.mul(l),v=Ns(i.add(yn(a))),m=v.mul(v).mul(v).mul(yn(-.5));return{$x:function(){return 1===o.rank?t.mul(yr(v.as4D(1,1,1,o.shape[0]),h)).mul(l).reshape(r.shape):t.mul(v).mul(l).reshape(r.shape);},$mean:function(){var t=v.mul(yn(-1)).mul(d);return 1===o.rank&&(t=t.sum(c)),t.reshape(o.shape);},$variance:function(){var t=m.mul(f).mul(d);return 1===o.rank&&(t=t.sum(c)),t.reshape(o.shape);},$scale:function(){var e=f.mul(v),n=t.mul(e);return 1===o.rank&&(n=n.sum(c)),n.reshape(o.shape);},$offset:function(){var e=t;return 1===o.rank&&(e=e.sum(c)),e.reshape(o.shape);}};}).reshape(l.shape);}function Hs(t){return null==t?null:0===t.rank?t.as1D():1===t.rank?t:2===t.rank?t.as4D(1,1,t.shape[0],t.shape[1]):3===t.rank?t.as4D(1,t.shape[0],t.shape[1],t.shape[2]):t;}function $s(){Oe("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon");}var js=pn({batchNormalization2d_:function(t,e,n,r,o,a){return void 0===r&&(r=.001),$s(),zs(t,e,n,a,o,r);}}),Ks=pn({batchNormalization3d_:function(t,e,n,r,o,a){return void 0===r&&(r=.001),$s(),Vs(t,e,n,a,o,r);}}),Xs=pn({batchNormalization4d_:function(t,e,n,r,o,a){return void 0===r&&(r=.001),$s(),Gs(t,e,n,a,o,r);}}),Ys=pn({batchNormalization_:function(t,e,n,r,o,a){return void 0===r&&(r=.001),$s(),qs(t,e,n,a,o,r);}}),Qs=pn({batchNorm_:qs}),Js=pn({batchNorm2d_:zs}),Zs=pn({batchNorm3d_:Vs}),tu=pn({batchNorm4d_:Gs});function eu(t,e,n,r,o,a){d(t.length===e.rank,function(){return"Length of inShape ("+t.length+") and rank of dy ("+e.rank+") must match";});var i=t,s=e,u=!1;3===e.rank&&(u=!0,s=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]),i=[1,t[0],t[1],t[2]]);var l=i[3],c=s.shape[3];d(4===i.length,function(){return"Error in conv2dDerInput: inShape must be length 4, but got length "+i.length+".";}),d(4===s.rank,function(){return"Error in conv2dDerInput: dy must be rank 4, but got rank "+s.rank;}),d(4===n.rank,function(){return"Error in conv2dDerInput: filter must be rank 4, but got rank "+n.rank;}),d(l===n.shape[2],function(){return"Error in conv2dDerInput: depth of input ("+l+") must match input depth for filter "+n.shape[2]+".";}),d(c===n.shape[3],function(){return"Error in conv2dDerInput: depth of output ("+c+") must match output depth for filter "+n.shape[3]+".";}),null!=a&&d(b(o),function(){return"Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+o+".";});var h=Jr(i,n.shape,r,1,o,a),p=Dt.runKernel(function(t,e){var r=t.conv2dDerInput(s,n,h);return e([n,s]),r;},{dy4D:s,filter:n},function(t,e){var n=e[0],i=e[1];return{dy4D:function(){return au(t,n,r,o,"NHWC",1,a);},filter:function(){return su(t,i,n.shape,r,o,a);}};});return u?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p;}function nu(t,e,n,r,o,a){var i=t;3===t.rank&&(i=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var s=e;3===s.rank&&(s=e.as4D(1,e.shape[0],e.shape[1],e.shape[2])),d(4===i.rank,function(){return"Error in conv2dDerFilter: input must be rank 4, but got shape "+i.shape+".";}),d(4===s.rank,function(){return"Error in conv2dDerFilter: dy must be rank 4, but got shape "+s.shape+".";}),d(4===n.length,function(){return"Error in conv2dDerFilter: filterShape must be length 4, but got "+n+".";}),d(i.shape[3]===n[2],function(){return"Error in conv2dDerFilter: depth of input "+i.shape[3]+") must match input depth in filter ("+n[2]+".";}),d(s.shape[3]===n[3],function(){return"Error in conv2dDerFilter: depth of dy ("+s.shape[3]+") must match output depth for filter ("+n[3]+").";}),null!=a&&d(b(o),function(){return"Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+o+".";});var u=Jr(i.shape,n,r,1,o,a);return Dt.runKernel(function(t){return t.conv2dDerFilter(i,s,u);},{x4D:i,dy4D:s});}function ru(t){var e=function(t){return"number"==typeof t?[t,t,t]:2===t.length?[t[0],t[1],1]:t;}(t),n=e[0],r=e[1],o=e[2];return 1===n&&1===r&&1===o;}var ou=pn({conv1d_:function(t,e,n,r,o,a,i){void 0===o&&(o="NWC"),void 0===a&&(a=1);var s=Ze(t,"x","conv1d"),u=Ze(e,"filter","conv1d"),l=s,c=!1;2===s.rank&&(c=!0,l=s.as3D(1,s.shape[0],s.shape[1])),d(3===l.rank,function(){return"Error in conv1d: input must be rank 3, but got rank "+l.rank+".";}),d(3===u.rank,function(){return"Error in conv1d: filter must be rank 3, but got rank "+u.rank+".";}),null!=i&&d(b(r),function(){return"Error in conv1d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+r+".";}),d(l.shape[2]===u.shape[1],function(){return"Error in conv1d: depth of input ("+l.shape[2]+") must match input depth for filter "+u.shape[1]+".";}),d(io(n,a),function(){return"Error in conv1D: Either stride or dilation must be 1. Got stride "+n+" and dilation '"+a+"'";}),d("NWC"===o,function(){return"Error in conv1d: got dataFormat of "+o+" but only NWC is currently supported.";});var h=u.as4D(1,u.shape[0],u.shape[1],u.shape[2]),p=l.as4D(l.shape[0],1,l.shape[1],l.shape[2]),f=au(p,h,[1,n],r,"NHWC",[1,a],i);return c?f.as2D(f.shape[2],f.shape[3]):f.as3D(f.shape[0],f.shape[2],f.shape[3]);}}),au=pn({conv2d_:function(t,e,n,r,o,a,i){void 0===o&&(o="NHWC"),void 0===a&&(a=[1,1]);var s=Ze(t,"x","conv2d"),u=Ze(e,"filter","conv2d"),l=s,c=!1;3===s.rank&&(c=!0,l=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),d(4===l.rank,function(){return"Error in conv2d: input must be rank 4, but got rank "+l.rank+".";}),d(4===u.rank,function(){return"Error in conv2d: filter must be rank 4, but got rank "+u.rank+".";}),null!=i&&d(b(r),function(){return"Error in conv2d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+r+".";}),d(l.shape[3]===u.shape[2],function(){return"Error in conv2d: depth of input ("+l.shape[3]+") must match input depth for filter "+u.shape[2]+".";}),d(io(n,a),function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+a+"'";}),d("NHWC"===o,function(){return"Error in conv2d: got dataFormat of "+o+" but only NHWC is currently supported.";});var h=Jr(l.shape,u.shape,n,a,r,i),p=Dt.runKernel(function(t,e){var n=t.conv2d(l,u,h);return e([u,l]),n;},{x:l,$filter:u},function(t,e){var o=e,i=o[0],s=o[1];return d(ao(a),function(){return"Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+a+"'";}),{x:function(){return eu(s.shape,t,i,n,r);},$filter:function(){return nu(s,t,i.shape,n,r);}};});return c?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p;}}),iu=pn({conv3d_:function(t,e,n,r,o,a){void 0===o&&(o="NDHWC"),void 0===a&&(a=[1,1,1]);var i=Ze(t,"x","conv3d"),s=Ze(e,"filter","conv3d"),u=i,l=!1;4===i.rank&&(l=!0,u=i.as5D(1,i.shape[0],i.shape[1],i.shape[2],i.shape[3])),d(5===u.rank,function(){return"Error in conv3d: input must be rank 5, but got rank "+u.rank+".";}),d(5===s.rank,function(){return"Error in conv3d: filter must be rank 5, but got rank "+s.rank+".";}),d(u.shape[4]===s.shape[3],function(){return"Error in conv3d: depth of input ("+u.shape[4]+") must match input depth for filter "+s.shape[3]+".";}),d(function(t,e){return ru(t)||ru(e);}(n,a),function(){return"Error in conv3D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+a+"'";}),d("NDHWC"===o,function(){return"Error in conv3d: got dataFormat of "+o+" but only NDHWC is currently supported.";});var c=Zr(u.shape,s.shape,n,a,r),h=Dt.runKernel(function(t,e){var n=t.conv3d(u,s,c);return e([u,s]),n;},{x:u,$filter:s},function(t,e){d(ru(a),function(){return"Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+a+"'";});var o=e[0],i=e[1];return{x:function(){return function(t,e,n,r,o){d(t.length===e.rank,function(){return"Length of inShape ("+t.length+") and rank of dy ("+e.rank+") must match";});var a=t,i=e,s=!1;4===e.rank&&(s=!0,i=e.as5D(1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]),a=[1,t[0],t[1],t[2],t[3]]);var u=a[4],l=i.shape[4];d(5===a.length,function(){return"Error in conv3dDerInput: inShape must be length 5, but got length "+a.length+".";}),d(5===i.rank,function(){return"Error in conv3dDerInput: dy must be rank 5, but got rank "+i.rank;}),d(5===n.rank,function(){return"Error in conv3dDerInput: filter must be rank 5, but got rank "+n.rank;}),d(u===n.shape[3],function(){return"Error in conv3dDerInput: depth of input ("+u+") must match input depth for filter "+n.shape[3]+".";}),d(l===n.shape[4],function(){return"Error in conv3dDerInput: depth of output ("+l+") must match output depth for filter "+n.shape[4]+".";});var c=Zr(a,n.shape,r,1,o),h=Dt.runKernel(function(t){return t.conv3dDerInput(i,n,c);},{dy5D:i});return s?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h;}(o.shape,t,i,n,r);},$filter:function(){return function(t,e,n,r,o){var a=t;4===t.rank&&(a=t.as5D(1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]));var i=e;4===i.rank&&(i=e.as5D(1,e.shape[0],e.shape[1],e.shape[2],e.shape[3])),d(5===a.rank,function(){return"Error in conv3dDerFilter: input must be rank 5, but got shape "+a.shape+".";}),d(5===i.rank,function(){return"Error in conv3dDerFilter: dy must be rank 5, but got shape "+i.shape+".";}),d(5===n.length,function(){return"Error in conv3dDerFilter: filterShape must be length 5, but got "+n+".";}),d(a.shape[4]===n[3],function(){return"Error in conv3dDerFilter: depth of input "+a.shape[4]+") must match input depth in filter ("+n[3]+".";}),d(i.shape[4]===n[4],function(){return"Error in conv3dDerFilter: depth of dy ("+i.shape[4]+") must match output depth for filter ("+n[4]+").";});var s=Zr(a.shape,n,r,1,o);return Dt.runKernel(function(t){return t.conv3dDerFilter(a,i,s);},{x5D:a,dy5D:i});}(o,t,i.shape,n,r);}};});return l?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h;}}),su=pn({conv2dDerFilter_:nu}),uu=pn({depthwiseConv2d_:function(t,e,n,r,o,a,i){void 0===o&&(o="NHWC"),void 0===a&&(a=[1,1]);var s=Ze(t,"x","depthwiseConv2d"),u=Ze(e,"filter","depthwiseConv2d"),l=s,c=!1;3===s.rank&&(c=!0,l=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),d(4===l.rank,function(){return"Error in depthwiseConv2d: input must be rank 4, but got rank "+l.rank+".";}),d(4===u.rank,function(){return"Error in depthwiseConv2d: filter must be rank 4, but got rank "+u.rank+".";}),d(l.shape[3]===u.shape[2],function(){return"Error in depthwiseConv2d: number of input channels ("+l.shape[3]+") must match the inChannels dimension in filter "+u.shape[2]+".";}),null==a&&(a=[1,1]),d(io(n,a),function(){return"Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+a+"'";}),null!=i&&d(b(r),function(){return"Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+r+".";});var h=Jr(l.shape,u.shape,n,a,r,i,!0),p=Dt.runKernel(function(t,e){var n=t.depthwiseConv2D(l,u,h);return e([l,u]),n;},{x:l,$filter:u},function(t,e){d(ao(a),function(){return"Error in gradient of depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+a+"'";});var n=e[0],r=e[1];return{x:function(){return function(t,e,n,r){var o=e,a=!1;3===e.rank&&(a=!0,o=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var i=Dt.runKernel(function(t){return t.depthwiseConv2DDerInput(o,n,r);},{dy4D:o});return a?i.as3D(i.shape[1],i.shape[2],i.shape[3]):i;}(n.shape,t,r,h);},$filter:function(){return function(t,e,n,r){var o=t;3===t.rank&&(o=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var a=e;return 3===a.rank&&(a=e.as4D(1,e.shape[0],e.shape[1],e.shape[2])),Dt.runKernel(function(t){return t.depthwiseConv2DDerFilter(o,a,r);},{x4D:o,dy4D:a});}(n,t,r.shape,h);}};});return c?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p;}}),lu=pn({separableConv2d_:function(t,e,n,r,o,a,i){void 0===a&&(a=[1,1]),void 0===i&&(i="NHWC");var s=Ze(t,"x","separableConv2d"),u=Ze(e,"depthwiseFilter","separableConv2d"),l=Ze(n,"pointwiseFilter","separableConv2d"),c=s,h=!1;if(3===s.rank&&(h=!0,c=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),"NCHW"===i)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");d(4===c.rank,function(){return"Error in separableConv2d: input must be rank 4, but got rank "+c.rank+".";}),d(4===u.rank,function(){return"Error in separableConv2d: depthwise filter must be rank 4, but got rank "+u.rank+".";}),d(4===l.rank,function(){return"Error in separableConv2d: pointwise filter must be rank 4, but got rank "+u.rank+".";}),d(1===l.shape[0],function(){return"Error in separableConv2d: the first dimension of pointwise filter  must be 1, but got "+l.shape[0]+".";}),d(1===l.shape[1],function(){return"Error in separableConv2d: the second dimension of pointwise filter must be 1, but got "+l.shape[1]+".";});var p=u.shape[2],f=u.shape[3];d(l.shape[2]===p*f,function(){return"Error in separableConv2d: the third dimension of pointwise filter must be "+p*f+", but got "+l.shape[2]+".";});var v=uu(c,u,r,o,i,a),m=au(v,l,1,"valid",i);return h?m.as3D(m.shape[1],m.shape[2],m.shape[3]):m;}}),cu=pn({conv2dTranspose_:function(t,e,n,r,o,a){return eu(n,Ze(t,"x","conv2dTranspose"),Ze(e,"filter","conv2dTranspose"),r,o,a);}});var hu=pn({matMul_:function(t,e,n,r){var o;void 0===n&&(n=!1),void 0===r&&(r=!1);var a=Ze(t,"a","matMul"),i=Ze(e,"b","matMul");o=Rt(a,i),a=o[0],i=o[1];var s=n?a.shape[a.rank-2]:a.shape[a.rank-1],u=r?i.shape[i.rank-1]:i.shape[i.rank-2],l=n?a.shape[a.rank-1]:a.shape[a.rank-2],c=r?i.shape[i.rank-2]:i.shape[i.rank-1],h=a.shape.slice(0,-2),p=i.shape.slice(0,-2),f=y(h),v=y(p);d(a.rank>=2&&i.rank>=2&&a.rank===i.rank,function(){return"Error in matMul: inputs must have the same rank of at least 2, got ranks "+a.rank+" and "+i.rank+".";}),d(x(h,p),function(){return"Error in matMul: outer dimensions ("+h+") and ("+p+") of Tensors with shapes "+a.shape+" and "+i.shape+" must match.";}),d(s===u,function(){return"Error in matMul: inner shapes ("+s+") and ("+u+") of Tensors with shapes "+a.shape+" and "+i.shape+" and transposeA="+n+" and transposeB="+r+" must match.";});var m=a.shape.slice(0,-2).concat([l,c]),g=n?a.as3D(f,s,l):a.as3D(f,l,s),b=r?i.as3D(v,c,u):i.as3D(v,u,c);return Dt.runKernel(function(t,e){var o=t.batchMatMul(g,b,n,r);return e([g,b]),o;},{$a:g,$b:b},function(t,e){var o=e,a=o[0],i=o[1];return n||r?!n&&r?{$a:function(){return t.matMul(i,!1,!1);},$b:function(){return t.matMul(a,!0,!1);}}:n&&!r?{$a:function(){return i.matMul(t,!1,!0);},$b:function(){return a.matMul(t,!1,!1);}}:{$a:function(){return i.matMul(t,!0,!0);},$b:function(){return t.matMul(a,!0,!0);}}:{$a:function(){return t.matMul(i,!1,!0);},$b:function(){return a.matMul(t,!0,!1);}};}).reshape(m);}}),pu=pn({dot_:function(t,e){var n=Ze(t,"t1","dot"),r=Ze(e,"t2","dot");d(!(1!==n.rank&&2!==n.rank||1!==r.rank&&2!==r.rank),function(){return"Error in dot: inputs must all be rank 1 or 2, but got ranks "+n.rank+" and "+r.rank+".";});var o=1===n.rank?n.size:n.shape[1],a=1===r.rank?r.size:r.shape[0];return d(o===a,function(){return"Error in dot: inner dimensions of inputs must match, but got "+o+" and "+a+".";}),1===n.rank&&1===r.rank?n.as2D(1,-1).matMul(r.as2D(-1,1)).asScalar():1===n.rank&&2===r.rank?n.as2D(1,-1).matMul(r.as2D(r.shape[0],r.shape[1])).as1D():2===n.rank&&1===r.rank?n.matMul(r.as2D(-1,1)).as1D():n.matMul(r.as2D(r.shape[0],r.shape[1]));}}),fu=pn({outerProduct_:function(t,e){var n=Ze(t,"v1","outerProduct"),r=Ze(e,"v2","outerProduct");return d(1===n.rank&&1===r.rank,function(){return"Error in outerProduct: inputs must be rank 1, but got ranks "+n.rank+" and "+r.rank+".";}),n.as2D(-1,1).matMul(r.as2D(1,-1));}});var du=pn({reverse_:function(t,e){var n=Ze(t,"x","reverse");if(0===n.rank)return n.clone();var r=S(e,n.shape);return Dt.runKernel(function(t){return t.reverse(n,r);},{$x:n},function(t){return{$x:function(){return t.reverse(r);}};}).reshapeAs(n);}}),vu=pn({reverse1d_:function(t){var e=Ze(t,"x","reverse");return d(1===e.rank,function(){return"Error in reverse1D: x must be rank 1 but got rank "+e.rank+".";}),du(e,0);}}),mu=pn({reverse2d_:function(t,e){var n=Ze(t,"x","reverse");return d(2===n.rank,function(){return"Error in reverse2D: x must be rank 2 but got rank "+n.rank+".";}),du(n,e);}}),gu=pn({reverse3d_:function(t,e){var n=Ze(t,"x","reverse");return d(3===n.rank,function(){return"Error in reverse3D: x must be rank 3 but got rank "+n.rank+".";}),du(n,e);}}),yu=pn({reverse4d_:function(t,e){var n=Ze(t,"x","reverse");return d(4===n.rank,function(){return"Error in reverse4D: x must be rank 4 but got rank "+n.rank+".";}),du(n,e);}});function xu(t,e,n,r,o,a){var i=Ze(t,"x","maxPool"),s=i,u=!1;3===i.rank&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),null==r&&(r=[1,1]),d(4===s.rank,function(){return"Error in maxPool: input must be rank 4 but got rank "+s.rank+".";}),d(io(n,r),function(){return"Error in maxPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'";}),null!=a&&d(b(o),function(){return"Error in maxPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+o+".";});var l=Qr(s.shape,e,n,r,o,a),c=Dt.runKernel(function(t,e){var n=t.maxPool(s,l);return e([s,n]),n;},{x:s},function(t,a){var i=a[0],s=a[1];return{x:function(){return function(t,e,n,r,o,a,i,s){var u=Ze(t,"dy","maxPoolBackprop"),l=Ze(e,"input","maxPoolBackprop"),c=Ze(n,"output","maxPoolBackprop");d(l.rank===u.rank,function(){return"Rank of input ("+l.rank+") does not match rank of dy ("+u.rank+")";}),null==a&&(a=[1,1]),d(io(o,a),function(){return"Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+o+" and dilations '"+a+"'";}),d(4===u.rank,function(){return"Error in maxPoolBackprop: dy must be rank 4 but got rank "+u.rank+".";}),d(4===l.rank,function(){return"Error in maxPoolBackprop: input must be rank 4 but got rank "+l.rank+".";}),null!=s&&d(b(i),function(){return"Error in maxPoolBackprop: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+i+".";});var h=Qr(l.shape,r,o,a,i,s);return Dt.runKernel(function(t){return t.maxPoolBackprop(u,l,c,h);},{$dy:u,$input:l});}(t,i,s,e,n,r,o);}};});return u?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c;}function bu(t,e,n,r,o,a){var i=Ze(t,"x","avgPool","float32");null==r&&(r=[1,1]),d(io(n,r),function(){return"Error in avgPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'";});var s=i,u=!1;3===i.rank&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),d(4===s.rank,function(){return"Error in avgPool: x must be rank 4 but got rank "+s.rank+".";}),null!=a&&d(b(o),function(){return"Error in avgPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+o+".";});var l=Qr(s.shape,e,n,r,o,a),c=Dt.runKernel(function(t){return t.avgPool(s,l);},{x:s},function(t){return{x:function(){return function(t,e,n,r,o,a){var i=Ze(t,"dy","avgPoolBackprop"),s=Ze(e,"input","avgPoolBackprop");d(s.rank===i.rank,function(){return"Rank of input ("+s.rank+") does not match rank of dy ("+i.rank+")";}),null==o&&(o=[1,1]),d(io(r,o),function(){return"Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+o+"'";});var u=s,l=i,c=!1;3===s.rank&&(c=!0,u=s.as4D(1,s.shape[0],s.shape[1],s.shape[2]),l=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),d(4===l.rank,function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+l.rank+".";}),d(4===u.rank,function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+u.rank+".";});var h=Qr(u.shape,n,r,o,a),p=Dt.runKernel(function(t){return t.avgPoolBackprop(l,u,h);},{dy4D:l,input4D:u});return c?p.as3D(p.shape[1],p.shape[2],p.shape[3]):p;}(t,s,e,n,r,o);}};});return c=c.cast(i.dtype),u?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c;}var wu=pn({maxPool_:function(t,e,n,r,o){return xu(t,e,n,1,r,o);}}),Cu=pn({avgPool_:function(t,e,n,r,o){return bu(t,e,n,1,r,o);}}),Eu=pn({pool_:function(t,e,n,r,o,a){null==o&&(o=[1,1]),null==a&&(a=1),0===r&&(r="valid");var i=Ze(t,"x","maxPool"),s=i,u=!1;3===i.rank&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),d(io(a,o),function(){return"Error in pool: Either strides or dilations must be 1. Got strides "+a+" and dilations '"+o+"'";});var l,c=Qr(s.shape,e,a,o,r),h=[c.dilationHeight,c.dilationWidth];l="same"===r?function(t,e){var n=t.map(function(t,n){return t+(t-1)*(e[n]-1);}).map(function(t){return t-1;}),r=n.map(function(t){return Math.floor(t/2);}),o=n.map(function(t,e){return t-r[e];});return n.map(function(t,e){return[r[e],o[e]];});}([c.filterHeight,c.filterWidth],h):[[0,0],[0,0]];var p=1===h[0]&&1===h[1],f=function(t,e,n){var r=n.map(function(t){return t[0];}),o=n.map(function(t){return t[1];}),a=t.concat(r,o),i=e.map(function(t,e){return(t-a[e]%t)%t;}),s=o.map(function(t,e){return t+i[e];}),u=e.map(function(t,e){return[r[e],s[e]];}),l=e.map(function(t,e){return[0,i[e]];});return[u,l];}([c.inHeight,c.inWidth],h,l),v=f[0],m=f[1],g=p?r:"valid",y=p?s:vr(s,h,v),x=("avg"===n?function(){return bu(y,e,a,1,g);}:function(){return xu(y,e,a,1,g);})(),b=p?x:Qn(x,h,m);return u?b.as3D(b.shape[1],b.shape[2],b.shape[3]):b;}});var Ru=pn({slice_:function(t,e,n){var r,o,a=Ze(t,"x","slice");if(0===a.rank)throw new Error("Slicing scalar is not possible");r="number"==typeof e?[e].concat(new Array(a.rank-1).fill(0)):e.length<a.rank?e.concat(new Array(a.rank-e.length).fill(0)):e.slice(),o=(o=null==n?new Array(a.rank).fill(-1):"number"==typeof n?[n].concat(new Array(a.rank-1).fill(-1)):n.length<a.rank?n.concat(new Array(a.rank-n.length).fill(-1)):n).map(function(t,e){return t>=0?t:(d(-1===t,function(){return"Bad value in size";}),a.shape[e]-r[e]);}),function(t,e,n){d(t.rank===e.length,function(){return"Error in slice"+t.rank+"D: Length of begin "+e+" must match the rank of the array ("+t.rank+").";}),d(t.rank===n.length,function(){return"Error in slice"+t.rank+"D: Length of size "+n+" must match the rank of the array ("+t.rank+").";});for(var r=function(r){d(e[r]+n[r]<=t.shape[r],function(){return"Error in slice"+t.rank+"D: begin["+r+"] + size["+r+"] ("+(e[r]+n[r])+") would overflow input.shape["+r+"] ("+t.shape[r]+")";});},o=0;o<t.rank;++o)r(o);}(a,r,o);var i=a.shape;return Dt.runKernel(function(t){return t.slice(a,r,o);},{$x:a},function(t){for(var e=[],n=0;n<t.rank;n++)e.push([r[n],i[n]-r[n]-o[n]]);return{$x:function(){return t.pad(e);}};});}}),Iu=pn({slice1d_:function(t,e,n){var r=Ze(t,"x","slice1d");return d(1===r.rank,function(){return"slice1d expects a rank-1 tensor, but got a rank-"+r.rank+" tensor";}),Ru(r,[e],[n]);}}),Su=pn({slice2d_:function(t,e,n){var r=Ze(t,"x","slice2d");return d(2===r.rank,function(){return"slice2d expects a rank-2 tensor, but got a rank-"+r.rank+" tensor";}),Ru(r,e,n);}}),Nu=pn({slice3d_:function(t,e,n){var r=Ze(t,"x","slice3d");return d(3===r.rank,function(){return"slice3d expects a rank-3 tensor, but got a rank-"+r.rank+" tensor";}),Ru(r,e,n);}}),ku=pn({slice4d_:function(t,e,n){var r=Ze(t,"x","slice4d");return d(4===r.rank,function(){return"slice4d expects a rank-4 tensor, but got a rank-"+r.rank+" tensor";}),Ru(r,e,n);}});function Au(t,e,n,r,o){return e.rank<n.rank&&(e=e.reshape(on(e.shape,r))),t.rank<n.rank&&(t=t.reshape(on(t.shape,r))),{$x:function(){var r=t.mul(n.equal(e).cast(t.dtype));return null==o?r:r.transpose(o);}};}var Tu=pn({all_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=Ze(t,"x","all","bool"),o=S(e,r.shape),a=o,i=sn(a,r.rank);null!=i&&(r=r.transpose(i),a=ln(a.length,r.rank));var s=Dt.runKernel(function(t){return t.all(r,a);},{$x:r});if(n){var u=on(s.shape,o);return s.reshape(u);}return s;}}),Du=pn({any_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=Ze(t,"x","any","bool"),o=S(e,r.shape),a=o,i=sn(a,r.rank);null!=i&&(r=r.transpose(i),a=ln(a.length,r.rank));var s=Dt.runKernel(function(t){return t.any(r,a);},{$x:r});if(n){var u=on(s.shape,o);return s.reshape(u);}return s;}}),_u=pn({argMax_:function(t,e){void 0===e&&(e=0);var n=Ze(t,"x","argMax");null==e&&(e=0);var r=S(e,n.shape),o=sn(r,n.rank);return null!=o&&(n=n.transpose(o),r=ln(r.length,n.rank)),Dt.runKernel(function(t,e){var o=t.argMax(n,r[0]);return e([n]),o;},{$x:n},function(t,e){var n=e[0];return{$x:function(){return Dn(n);}};});}}),Ou=pn({argMin_:function(t,e){void 0===e&&(e=0);var n=Ze(t,"x","argMin");null==e&&(e=0);var r=S(e,n.shape),o=sn(r,n.rank);return null!=o&&(n=n.transpose(o),r=ln(r.length,n.rank)),Dt.runKernel(function(t,e){var o=t.argMin(n,r[0]);return e([n]),o;},{$x:n},function(t,e){var n=e[0];return{$x:function(){return Dn(n);}};});}}),Mu=pn({logSumExp_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=Ze(t,"x","logSumExp"),o=S(e,r.shape),a=r.max(o,!0),i=r.sub(a).exp().sum(o).log(),s=a.reshape(i.shape).add(i);if(n){var u=on(s.shape,o);return s.reshape(u);}return s;}}),Fu=pn({max_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=Ze(t,"x","max"),o=r,a=S(e,r.shape),i=a,s=sn(i,r.rank);null!=s&&(r=r.transpose(s),i=ln(i.length,r.rank));var u=Dt.runKernel(function(t,e){var n=t.max(r,i);return e([o,n]),n;},{$x:r},function(t,e){return Au(t,e[1],e[0],a,s);});if(n){var l=on(u.shape,a);u=u.reshape(l);}return u;}}),Bu=pn({mean_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=Ze(t,"x","mean"),o=S(e,r.shape),a=y(rn(r.shape,o)[1]);return Vr(function(t){var r=yn(a);return{value:(r.dtype===t.dtype?t:t.cast(r.dtype)).div(r).sum(e,n),gradFunc:function(e){var n=t.shape.slice();return o.forEach(function(t){n[t]=1;}),e.reshape(n).mul(In(t.shape,"float32")).div(a);}};})(r);}}),Pu=pn({min_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=Ze(t,"x","min"),o=r,a=S(e,r.shape),i=a,s=sn(i,r.rank);null!=s&&(r=r.transpose(s),i=ln(i.length,r.rank));var u=Dt.runKernel(function(t,e){var n=t.min(r,i);return e([o,n]),n;},{$x:r},function(t,e){return Au(t,e[1],e[0],a,s);});if(n){var l=on(u.shape,a);u=u.reshape(l);}return u;}}),Lu=pn({moments_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=S(e,(t=Ze(t,"x","moments")).shape),o=t.mean(r,n),a=o.shape;n||(a=on(o.shape,r));var i=t.toFloat().sub(o.reshape(a)).square();return{mean:o,variance:i.mean(r,n)};}}),Wu=pn({sum_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=Ze(t,"x","sum");"bool"===r.dtype&&(r=r.toInt());var o=S(e,r.shape);return Vr(function(t){var e=sn(o,t.rank),r=o,a=t;null!=e&&(a=t.transpose(e),r=ln(r.length,t.rank));var i=Dt.runKernel(function(t){return t.sum(a,r);},{permutedX:a});if(n){var s=on(i.shape,o);i=i.reshape(s);}return{value:i,gradFunc:function(e){var n=t.shape.slice();return o.forEach(function(t){n[t]=1;}),e.reshape(n).mul(In(t.shape,"float32"));}};})(r);}}),Uu=pn({prod_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=Ze(t,"x","prod");"bool"===r.dtype&&(r=r.toInt());var o=S(e,r.shape),a=sn(o,r.rank),i=o,s=r;null!=a&&(s=r.transpose(a),i=ln(i.length,r.rank));var u=Dt.runKernel(function(t){return t.prod(s,i);},{permutedX:s});if(n){var l=on(u.shape,o);u=u.reshape(l);}return u;}});var zu=pn({equal_:function(t,e){var n,r=Ze(t,"a","equal"),o=Ze(e,"b","equal");return n=Rt(r,o),r=n[0],o=n[1],Yr(r.shape,o.shape),Dt.runKernel(function(t){return t.equal(r,o);},{$a:r,$b:o});}}),Vu=pn({equalStrict_:function(t,e){var n=Ze(t,"a","equalStrict"),r=Ze(e,"b","equalStrict");return v(n.shape,r.shape,"Error in equalStrict: "),n.equal(r);}}),Gu=pn({greater_:function(t,e){var n,r=Ze(t,"a","greater"),o=Ze(e,"b","greater");return n=Rt(r,o),r=n[0],o=n[1],Yr(r.shape,o.shape),Dt.runKernel(function(t){return t.greater(r,o);},{$a:r,$b:o});}}),qu=pn({greaterEqual_:function(t,e){var n,r=Ze(t,"a","greaterEqual"),o=Ze(e,"b","greaterEqual");return n=Rt(r,o),r=n[0],o=n[1],Yr(r.shape,o.shape),Dt.runKernel(function(t,e){var n=t.greaterEqual(r,o);return e([r,o]),n;},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return{$a:function(){return Dn(n);},$b:function(){return Dn(r);}};});}}),Hu=pn({greaterEqualStrict_:function(t,e){var n=Ze(t,"a","greaterEqualStrict"),r=Ze(e,"b","greaterEqualStrict");return v(n.shape,r.shape,"Error in greaterEqualStrict: "),n.greaterEqual(r);}}),$u=pn({greaterStrict_:function(t,e){var n=Ze(t,"a","greaterStrict"),r=Ze(e,"b","greaterStrict");return v(n.shape,r.shape,"Error in greaterStrict: "),n.greater(r);}}),ju=pn({less_:function(t,e){var n,r=Ze(t,"a","less"),o=Ze(e,"b","less");return n=Rt(r,o),r=n[0],o=n[1],Yr(r.shape,o.shape),Dt.runKernel(function(t){return t.less(r,o);},{$a:r,$b:o});}}),Ku=pn({lessEqual_:function(t,e){var n,r=Ze(t,"a","lessEqual"),o=Ze(e,"b","lessEqual");return n=Rt(r,o),r=n[0],o=n[1],Yr(r.shape,o.shape),Dt.runKernel(function(t){return t.lessEqual(r,o);},{$a:r,$b:o});}}),Xu=pn({lessEqualStrict_:function(t,e){var n=Ze(t,"a","lessEqualStrict"),r=Ze(e,"b","lessEqualStrict");return v(n.shape,r.shape,"Error in lessEqualStrict: "),n.lessEqual(r);}}),Yu=pn({lessStrict_:function(t,e){var n=Ze(t,"a","lessStrict"),r=Ze(e,"b","lessStrict");return v(n.shape,r.shape,"Error in lessStrict: "),n.less(r);}}),Qu=pn({notEqual_:function(t,e){var n,r=Ze(t,"a","notEqual"),o=Ze(e,"b","notEqual");return n=Rt(r,o),r=n[0],o=n[1],Yr(r.shape,o.shape),Dt.runKernel(function(t){return t.notEqual(r,o);},{$a:r,$b:o});}}),Ju=pn({notEqualStrict_:function(t,e){var n=Ze(t,"a","notEqualStrict"),r=Ze(e,"b","notEqualStrict");return v(n.shape,r.shape,"Error in notEqualStrict: "),n.notEqual(r);}});var Zu=pn({add_:function(t,e){var n,r=Ze(t,"a","add"),o=Ze(e,"b","add");n=Rt(r,o),r=n[0],o=n[1];var a=Yr(r.shape,o.shape);return Dt.runKernel(function(t){return t.add(r,o);},{$a:r,$b:o},function(t){return{$a:function(){var e=t,n=Xr(r.shape,a);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape);},$b:function(){var e=t,n=Xr(o.shape,a);return n.length>0&&(e=e.sum(n)),e.reshape(o.shape);}};});}}),tl=pn({addN_:function(t){d(Array.isArray(t),function(){return"The argument passed to tf.addN() must be a list of tensors";}),d(t.length>=1,function(){return"Must pass at least one tensor to tf.addN(), but got "+t.length;});var e=t.map(function(t,e){return Ze(t,"tensors"+e,"addN");}),n=e[0];e.forEach(function(t){if(t.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype");}),e.forEach(function(t){if(!x(t.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape");});var r=e;return Dt.runKernel(function(t){return t.addN(e);},r,function(t){var n={};return e.forEach(function(e,r){n[r]=function(){return t.clone();};}),n;});}}),el=pn({addStrict_:function(t,e){var n=Ze(t,"a","addStrict"),r=Ze(e,"b","addStrict");return v(n.shape,r.shape,"Error in addStrict: "),n.add(r);}}),nl=pn({atan2_:function(t,e){var n,r=Ze(t,"a","atan2"),o=Ze(e,"b","atan2");n=Rt(r,o),r=n[0],o=n[1];var a=Yr(r.shape,o.shape);return Dt.runKernel(function(t,e){var n=t.atan2(r,o);return e([r,o]),n;},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=Zu(n.square(),r.square()),o=t.mul(r.div(e)),i=Xr(n.shape,a);return i.length>0&&(o=o.sum(i)),o.reshape(n.shape);},$b:function(){var e=Zu(n.square(),r.square()),o=Rs(t.mul(n.div(e))),i=Xr(r.shape,a);return i.length>0&&(o=o.sum(i)),o.reshape(r.shape);}};});}}),rl=pn({div_:function(t,e){var n,r=Ze(t,"a","div"),o=Ze(e,"b","div");if(n=Rt(r,o),r=n[0],o=n[1],"int32"===r.dtype&&"int32"===o.dtype)return al(r,o);var a=Yr(r.shape,o.shape);return Dt.runKernel(function(t,e){var n=t.realDivide(r,o);return e([r,o]),n;},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=t.div(r.toFloat()),o=Xr(n.shape,a);return o.length>0?e.sum(o).reshape(n.shape):e;},$b:function(){var e=t.mul(n.toFloat()),o=Xr(r.shape,a);o.length>0&&(e=e.sum(o).reshape(r.shape));var i=r.square();return e.div(i.toFloat()).neg();}};});}}),ol=pn({divStrict_:function(t,e){var n=Ze(t,"a","div"),r=Ze(e,"b","div");return v(n.shape,r.shape,"Error in divideStrict: "),n.div(r);}}),al=pn({floorDiv_:function(t,e){var n,r=Ze(t,"a","floorDiv"),o=Ze(e,"b","floorDiv");n=Rt(r,o),r=n[0],o=n[1];var a=Yr(r.shape,o.shape);return Dt.runKernel(function(t,e){var n=t.floorDiv(r,o);return e([r,o]),n;},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=t.div(r.toFloat()),o=Xr(n.shape,a);return o.length>0?e.sum(o).reshape(n.shape):e;},$b:function(){var e=t.mul(n.toFloat()),o=Xr(r.shape,a);o.length>0&&(e=e.sum(o).reshape(r.shape));var i=r.square();return e.div(i.toFloat()).neg();}};});}}),il=pn({maximum_:function(t,e){var n,r=Ze(t,"a","maximum"),o=Ze(e,"b","maximum");return n=Rt(r,o),r=n[0],o=n[1],"bool"===r.dtype&&(r=r.toInt(),o=o.toInt()),Yr(r.shape,o.shape),Dt.runKernel(function(t,e){var n=t.maximum(r,o);return e([r,o]),n;},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return{$a:function(){return t.mul(n.greaterEqual(r).toFloat());},$b:function(){return t.mul(n.less(r).toFloat());}};});}}),sl=pn({maximumStrict_:function(t,e){var n=Ze(t,"a","maximumStrict"),r=Ze(e,"b","maximumStrict");return v(n.shape,r.shape,"Error in maximumStrict: "),n.maximum(r);}}),ul=pn({minimum_:function(t,e){var n,r=Ze(t,"a","minimum"),o=Ze(e,"b","minimum");return n=Rt(r,o),r=n[0],o=n[1],"bool"===r.dtype&&(r=r.toInt(),o=o.toInt()),Yr(r.shape,o.shape),Dt.runKernel(function(t,e){var n=t.minimum(r,o);return e([r,o]),n;},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return{$a:function(){return t.mul(n.lessEqual(r).toFloat());},$b:function(){return t.mul(n.greater(r).toFloat());}};});}}),ll=pn({minimumStrict_:function(t,e){var n=Ze(t,"a","minimumStrict"),r=Ze(e,"b","minimumStrict");return v(n.shape,r.shape,"Error in minimumStrict: "),n.minimum(r);}}),cl=pn({mod_:function(t,e){var n,r=Ze(t,"a","mod"),o=Ze(e,"b","mod");n=Rt(r,o),r=n[0],o=n[1];var a=Yr(r.shape,o.shape);return Dt.runKernel(function(t,e){var n=t.mod(r,o);return e([r,o]),n;},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=Xr(n.shape,a);return e.length>0?t.sum(e).reshape(n.shape):t;},$b:function(){var e=t.mul(n.div(r).floor().neg()),o=Xr(r.shape,a);return o.length>0?e.sum(o).reshape(r.shape):e;}};});}}),hl=pn({modStrict_:function(t,e){var n=Ze(t,"a","modStrict"),r=Ze(e,"b","modStrict");return v(n.shape,r.shape,"Error in modStrict: "),n.mod(r);}}),pl=pn({mul_:function(t,e){var n,r=Ze(t,"a","mul"),o=Ze(e,"b","mul");n=Rt(r,o),r=n[0],o=n[1];var a=Yr(r.shape,o.shape);return Dt.runKernel(function(t,e){var n=t.multiply(r,o);return e([r,o]),n;},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=t.mul(r.toFloat()),o=Xr(n.shape,a);return o.length>0?e.sum(o).reshape(n.shape):e;},$b:function(){var e=t.mul(n.toFloat()),o=Xr(r.shape,a);return o.length>0?e.sum(o).reshape(r.shape):e;}};});}}),fl=pn({mulStrict_:function(t,e){var n=Ze(t,"a","mul"),r=Ze(e,"b","mul");return v(n.shape,r.shape,"Error in multiplyStrict: "),n.mul(r);}}),dl=pn({pow_:function(t,e){var n=Ze(t,"base","pow"),r=Ze(e,"exp","pow"),o=Yr(n.shape,r.shape);return t=n.cast(Ct(n.dtype,r.dtype)),e=r.cast(Ct(n.dtype,r.dtype)),Dt.runKernel(function(t,e){var o=t.pow(n,r);return e([n,r,o]),o;},{$base:n,$exp:r},function(t,e){var n=e[0],r=e[1],a=e[2];return{$base:function(){var e=r.toFloat(),a=t.mul(e.mul(n.pow(e.sub(yn(1))))),i=Xr(n.shape,o);return i.length>0&&(a=a.sum(i)),a.reshape(n.shape);},$exp:function(){var e=n.greater(0),i=n.log().where(e,Dn(n)),s=t.mul(a.mul(i)),u=Xr(r.shape,o);return u.length>0&&(s=s.sum(u)),s.reshape(r.shape);}};});}}),vl=pn({powStrict_:function(t,e){return v(t.shape,e.shape,"Error in powStrict: "),t.pow(e);}}),ml=pn({squaredDifference_:function(t,e){var n,r=Ze(t,"a","squaredDifference"),o=Ze(e,"b","squaredDifference");return n=Rt(r,o),r=n[0],o=n[1],Yr(r.shape,o.shape),Dt.runKernel(function(t,e){var n=t.squaredDifference(r,o);return e([r,o]),n;},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1],o=yn(2);return{$a:function(){return t.mul(n.sub(r).mul(o));},$b:function(){return t.mul(r.sub(n).mul(o));}};});}}),gl=pn({squaredDifferenceStrict_:function(t,e){var n=Ze(t,"a","squaredDifferenceStrict"),r=Ze(e,"b","squaredDifferenceStrict");return v(n.shape,r.shape,"Error in squaredDifferenceStrict: "),n.squaredDifference(r);}}),yl=pn({sub_:function(t,e){var n,r=Ze(t,"a","sub"),o=Ze(e,"b","sub");n=Rt(r,o),r=n[0],o=n[1];var a=Yr(r.shape,o.shape);return Dt.runKernel(function(t){return t.subtract(r,o);},{$a:r,$b:o},function(t){return{$a:function(){var e=t,n=Xr(r.shape,a);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape);},$b:function(){var e=t,n=Xr(o.shape,a);return n.length>0&&(e=e.sum(n)),e.neg().reshape(o.shape);}};});}}),xl=pn({subStrict_:function(t,e){var n=Ze(t,"a","subStrict"),r=Ze(e,"b","subStrict");return v(n.shape,r.shape,"Error in subStrict: "),n.sub(r);}});var bl=pn({logicalAnd_:function(t,e){var n=Ze(t,"a","logicalAnd","bool"),r=Ze(e,"b","logicalAnd","bool");return Yr(n.shape,r.shape),Dt.runKernel(function(t){return t.logicalAnd(n,r);},{$a:n,$b:r});}}),wl=pn({logicalNot_:function(t){var e=Ze(t,"x","logicalNot","bool");return Dt.runKernel(function(t){return t.logicalNot(e);},{$x:e});}}),Cl=pn({logicalOr_:function(t,e){var n=Ze(t,"a","logicalOr","bool"),r=Ze(e,"b","logicalOr","bool");return Yr(n.shape,r.shape),Dt.runKernel(function(t){return t.logicalOr(n,r);},{$a:n,$b:r});}}),El=pn({logicalXor_:function(t,e){var n=Ze(t,"a","logicalXor","bool"),r=Ze(e,"b","logicalXor","bool");return Yr(n.shape,r.shape),Cl(t,e).logicalAnd(bl(t,e).logicalNot());}}),Rl=pn({where_:function(t,e,n){var r=Ze(e,"a","where"),o=Ze(n,"b","where"),a=Ze(t,"condition","where","bool");return v(r.shape,o.shape,"Error in where: "),1===a.rank?d(a.shape[0]===r.shape[0],function(){return"The first dimension of `a` must match the size of `condition`.";}):v(a.shape,o.shape,"Error in where: "),Dt.runKernel(function(t,e){var n=t.select(a,r,o);return e([a]),n;},{$condition:a,$a:r,$b:o},function(t,e){var n=e[0];return{$condition:function(){return Dn(n).toFloat();},$a:function(){return t.mul(n.cast(t.dtype));},$b:function(){return t.mul(n.logicalNot().cast(t.dtype));}};});}}),Il=function(t){return r(this,void 0,void 0,function(){var e,n,r;return o(this,function(o){switch(o.label){case 0:return[4,(e=Ze(t,"condition","whereAsync","bool")).data()];case 1:return n=o.sent(),r=wo(e.shape,n),t!==e&&e.dispose(),[2,r];}});});};var Sl=pn({elu_:function(t){var e=Ze(t,"x","elu");return Dt.runKernel(function(t,n){var r=t.elu(e);return n([r]),r;},{$x:e},function(t,e){var n=e[0];return{$x:function(){return Dt.runKernel(function(e){return e.eluDer(t,n);},{dy:t,y:n});}};});}}),Nl=pn({leakyRelu_:function(t,e){void 0===e&&(e=.2);var n=Ze(t,"x","leakyRelu");return il(yn(e).mul(n),n);}}),kl=pn({prelu_:function(t,e){var n=Ze(t,"x","prelu"),r=Ze(e,"alpha","prelu");return Dt.runKernel(function(t,e){var o=t.prelu(n,r);return e([n,r]),o;},{$x:n,$alpha:r},function(t,e){var n=e[0],r=e[1],o=n.greater(0);return{$x:function(){return Rl(o,t,t.mul(r));},$alpha:function(){var e=Rl(o,Dn(t),t.mul(n)),a=Xr(r.shape,t.shape);return a.length>0&&(e=e.sum(a)),e.reshape(r.shape);}};});}}),Al=pn({relu_:function(t){var e=Ze(t,"x","relu");return"bool"===e.dtype?e.toInt():Dt.runKernel(function(t,n){var r=t.relu(e);return n([e]),r;},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mulStrict(n.step().toFloat());}};});}}),Tl=pn({selu_:function(t){var e=Ze(t,"x","selu");return Dt.runKernel(function(t,n){var r=t.selu(e);return n([e]),r;},{$x:e},function(t,e){var n=e[0];return{$x:function(){var e=n.greater(yn(0)),r=yn(Ui),o=yn(zi),a=t.mul(o),i=t.mul(r).mul(n.toFloat().exp());return Rl(e,a,i);}};});}});var Dl=pn({transpose_:function(t,e){var n=Ze(t,"x","transpose");return null==e&&(e=n.shape.map(function(t,e){return e;}).reverse()),d(n.rank===e.length,function(){return"Error in transpose: rank of input "+n.rank+" must match length of perm "+e+".";}),e.forEach(function(t){d(t>=0&&t<n.rank,function(){return"All entries in 'perm' must be between 0 and "+(n.rank-1)+" but got "+e;});}),n.rank<=1?n.clone():Dt.runKernel(function(t){return t.transpose(n,e);},{$x:n},function(t){var n=un(e);return{$x:function(){return t.transpose(n);}};});}});var _l=pn({localResponseNormalization_:function(t,e,n,r,o){void 0===e&&(e=5),void 0===n&&(n=1),void 0===r&&(r=1),void 0===o&&(o=.5);var a=Ze(t,"x","localResponseNormalization");d(4===a.rank||3===a.rank,function(){return"Error in localResponseNormalization: x must be rank 3 or 4 but got\n               rank "+a.rank+".";}),d(b(e),function(){return"Error in localResponseNormalization: depthRadius must be an integer but got depthRadius "+e+".";});var i=a,s=!1;3===a.rank&&(s=!0,i=a.as4D(1,a.shape[0],a.shape[1],a.shape[2]));var u=Dt.runKernel(function(t,a){var s=t.localResponseNormalization4D(i,e,n,r,o);return a([i,s]),s;},{x4D:i},function(t,a){var i=a[0],s=a[1];return{x4D:function(){return Dt.runKernel(function(a){return a.LRNGrad(t,i,s,e,n,r,o);},{});}};});return s?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u;}});var Ol=pn({norm_:function(t,e,n,r){void 0===e&&(e="euclidean"),void 0===n&&(n=null),void 0===r&&(r=!1);var o=function t(e,n,r){if(void 0===r&&(r=null),0===e.rank)return e.abs();if(1!==e.rank&&null===r)return t(e.reshape([-1]),n,r);if(1===e.rank||"number"==typeof r||Array.isArray(r)&&1===r.length){if(1===n)return e.abs().sum(r);if(n===1/0)return e.abs().max(r);if(n===-1/0)return e.abs().min(r);if("euclidean"===n||2===n)return e.abs().pow(yn(2,"int32")).sum(r).sqrt();throw new Error("Error in norm: invalid ord value: "+n);}if(Array.isArray(r)&&2===r.length){if(1===n)return e.abs().sum(r[0]).max(r[1]-1);if(n===1/0)return e.abs().sum(r[1]).max(r[0]);if(n===-1/0)return e.abs().sum(r[1]).min(r[0]);if("fro"===n||"euclidean"===n)return e.square().sum(r).sqrt();throw new Error("Error in norm: invalid ord value: "+n);}throw new Error("Error in norm: invalid axis: "+r);}(t=Ze(t,"x","norm"),e,n),a=o.shape;if(r){var i=S(n,t.shape);a=on(o.shape,i);}return o.reshape(a);}});function Ml(t,e){for(var n=[],r=t;r<e;++r)n.push(r);return n;}function Fl(t){for(var e=[],n=0;n<t.length;++n)for(var r=0;r<t[n].length;++r)e.push(t[n][r]);return e;}var Bl=pn({gather_:function(t,e,n){void 0===n&&(n=0);var r=Ze(t,"x","gather"),o=Ze(e,"indices","gather","int32");n=S(n,r.shape)[0];var a=function(t,e,n){for(var r=t.shape[n],o=[],a=1,i=1,s=0;s<n;s++)o.push(t.shape[s]),a*=t.shape[s];for(s=0;s<e.rank;s++)o.push(e.shape[s]);for(s=n+1;s<t.rank;s++)o.push(t.shape[s]),i*=t.shape[s];return{batchSize:a,sliceSize:i,dimSize:r,outputShape:o};}(r,o,n);return Dt.runKernel(function(t,e){var a=t.gather(r,o.flatten(),n);return e([o]),a;},{$x:r},function(t,e){var o=e[0];return{$x:function(){var e=r.shape,a=o.size,i=e.slice(0,n),s=i.length,u=e.slice(n,e.length).slice(1),l=u.length,c=Ml(0,s),h=Ml(s+1,s+1+l),p=Fl([i,[a],u]),f=t.reshape(p),d=o.reshape([a]),v=Fl([[s],c,h]),m=f.transpose(v),g=Pl(m,d,r.shape[n]),y=un(v);return g=g.transpose(y);}};}).reshape(a.outputShape);}}),Pl=pn({unsortedSegmentSum_:function(t,e,n){var r=Ze(t,"x","unsortedSegmentSum"),o=Ze(e,"segmentIds","unsortedSegmentSum","int32");return d(b(n),function(){return"numSegments must be of dtype int";}),Dt.runKernel(function(t,e){var a=t.unsortedSegmentSum(r,o,n);return e([o]),a;},{$x:r},function(t,e){var n=e[0];return{$x:function(){return function(t,e){for(var n=il(e,Dn(e)),r=Bl(t,n),o=qu(e,yn(0,"int32")),a=r.rank-o.rank,i=0;i<a;++i)o=nr(o,i+1);o=bl(o,In(r.shape,"bool"));var s=Dn(r);return Rl(o,r,s);}(t,n);}};});}});var Ll=pn({basicLSTMCell_:function(t,e,n,r,o,a){var i=Ze(t,"forgetBias","basicLSTMCell"),s=Ze(e,"lstmKernel","basicLSTMCell"),u=Ze(n,"lstmBias","basicLSTMCell"),l=Ze(r,"data","basicLSTMCell"),c=Ze(o,"c","basicLSTMCell"),h=Ze(a,"h","basicLSTMCell"),p=l.concat(h,1).matMul(s).add(u),f=p.shape[0],d=p.shape[1]/4,v=[f,d],m=p.slice([0,0],v),g=p.slice([0,d],v),y=p.slice([0,2*d],v),x=p.slice([0,3*d],v),b=m.sigmoid().mulStrict(g.tanh()).addStrict(c.mulStrict(i.add(y).sigmoid())),w=b.tanh().mulStrict(x.sigmoid());return[b,w];}}),Wl=pn({multiRNNCell_:function(t,e,n,r){for(var o=Ze(e,"data","multiRNNCell"),a=tn(n,"c","multiRNNCell"),i=tn(r,"h","multiRNNCell"),s=o,u=[],l=0;l<t.length;l++){var c=t[l](s,a[l],i[l]);u.push(c[0]),u.push(c[1]),s=c[1];}var h=[],p=[];for(l=0;l<u.length;l+=2)h.push(u[l]),p.push(u[l+1]);return[h,p];}});var Ul=pn({movingAverage_:function(t,e,n,r,o){void 0===o&&(o=!0);var a=Ze(t,"v","movingAverage"),i=Ze(e,"x","movingAverage"),s=Ze(n,"decay","movingAverage");It(a,i),d(x(a.shape,i.shape),function(){return"Shape mismatch in v and x";});var u=yn(1),l=u.sub(s),c=i.sub(a).mul(l);if(o){d(null!=r,function(){return"When using zeroDebias: true, step is required.";});var h=Ze(r,"step","movingAverage");c=c.div(u.sub(dl(s,h)));}return a.add(c);}});var zl=pn({stridedSlice_:function(t,e,n,r,o,a,i,s,u){if(void 0===o&&(o=0),void 0===a&&(a=0),void 0===i&&(i=0),void 0===s&&(s=0),void 0===u&&(u=0),0!==i)throw new Error("ellipsis mask is not yet supported");if(0!==s)throw new Error("new axis mask is not yet supported");var l=Ze(t,"x","stridedSlice");if(r.every(function(t){return 1===t;})){var c=_r(l.shape,e,n,r,o,a,i,s,u),h=c[0],p=c[1],f=c[2],d=p.filter(function(t,e){return-1===f.indexOf(e);});return Ru(l,h,p).reshape(d);}return Dt.runKernel(function(t){return t.stridedSlice(l,e,n,r,o,a,i,s,u);},{$x:l});}});var Vl=pn({topk_:function(t,e,n){void 0===e&&(e=1),void 0===n&&(n=!0);var r=Ze(t,"x","topk");if(0===r.rank)throw new Error("topk() expects the input to be of rank 1 or higher");var o=r.shape[r.shape.length-1];if(e>o)throw new Error("'k' passed to topk() must be <= the last dimension ("+o+") but got "+e);var a=Dt.runKernel(function(t){return t.topk(r,e,n);},{$x:r});return{values:a[0],indices:a[1]};}});var Gl=pn({scatterND_:function(t,e,n){var r=Ze(t,"indices","scatterND","int32"),o=Ze(e,"updates","scatterND");return Tr(o,r,n),Dt.runKernel(function(t){return t.scatterND(r,o,n);},{$indices:r,$updates:o});}});var ql=pn({fft_:function(t){d("complex64"===t.dtype,function(){return"The dtype for tf.spectral.fft() must be complex64 but got "+t.dtype+".";});var e=t.shape[t.shape.length-1],n=t.size/e,r=t.as2D(n,e);return Dt.runKernel(function(t){return t.fft(r);},{input:t}).reshape(t.shape);}}),Hl=pn({ifft_:function(t){d("complex64"===t.dtype,function(){return"The dtype for tf.spectral.ifft() must be complex64 but got "+t.dtype+".";});var e=t.shape[t.shape.length-1],n=t.size/e,r=t.as2D(n,e);return Dt.runKernel(function(t){return t.ifft(r);},{input:t}).reshape(t.shape);}}),$l=pn({rfft_:function(t,e){d("float32"===t.dtype,function(){return"The dtype for rfft() must be real value but got "+t.dtype;});var n,r=t.shape[t.shape.length-1],o=t.size/r;if(null!=e&&e<r){var a=t.shape.map(function(t){return 0;}),i=t.shape.map(function(t){return t;});i[t.shape.length-1]=e,n=t.slice(a,i),r=e;}else if(null!=e&&e>r){var s=t.shape.map(function(t){return t;});s[t.shape.length-1]=e-r,n=t.concat(Sn(s),t.shape.length-1),r=e;}else n=t;var u=n.zerosLike(),l=fn(n,u).as2D(o,r),c=ql(l),h=Math.floor(r/2)+1,p=dn(c),f=vn(c),v=p.split([h,r-h],p.shape.length-1),m=f.split([h,r-h],f.shape.length-1),g=n.shape.slice();return g[n.shape.length-1]=h,fn(v[0],m[0]).reshape(g);}}),jl=pn({irfft_:function(t){var e=t.shape[t.shape.length-1],n=t.size/e;if(e<=2){var r=t.as2D(n,e),o=Hl(r);return dn(o);}var a=[n,2*(e-1)],i=dn(t).as2D(n,e),s=vn(t).as2D(n,e),u=i.slice([0,1],[n,e-2]).reverse(1),l=s.slice([0,1],[n,e-2]).reverse(1).mul(yn(-1)),c=i.concat(u,1),h=s.concat(l,1);return r=fn(c,h).as2D(a[0],a[1]),o=Hl(r),dn(o);}}),Kl=Object.freeze({fft:ql,ifft:Hl,rfft:$l,irfft:jl});var Xl=pn({sparseToDense_:function(t,e,n,r){void 0===r&&(r=0);var o=Ze(t,"sparseIndices","sparseToDense","int32"),a=Ze(e,"sparseValues","sparseToDense"),i=Ze(r,"defaultValue","sparseToDense",a.dtype);return function(t,e,n,r){if("int32"!==t.dtype)throw new Error("tf.sparseToDense() expects the indices to be int32 type, but the dtype was "+t.dtype+".");if(t.rank>2)throw new Error("sparseIndices should be a scalar, vector, or matrix, but got shape "+t.shape+".");var o=t.rank>0?t.shape[0]:1,a=t.rank>1?t.shape[1]:1;if(n.length!==a)throw new Error("outputShape has incorrect number of elements:, "+n.length+", should be: "+a+".");var i=e.size;if(0!==e.rank&&(1!==e.rank||i!==o))throw new Error("sparseValues has incorrect shape "+e.shape+", should be [] or ["+o+"]");if(e.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype");}(o,a,n,i),Dt.runKernel(function(t){return t.sparseToDense(o,a,n,i);},{$sparseIndices:o,$sparseValues:a,$defaultValue:i});}});var Yl=pn({gatherND_:function(t,e){var n=Ze(e,"indices","gatherND","int32"),r=Ze(t,"x","gatherND");return Dt.runKernel(function(t){return t.gatherND(r,n);},{$x:r,$indices:n});}});var Ql=pn({dropout_:function(t,e,n,r){if(null!=n&&!x(t.shape,n))throw new Error("Non-default noise shape is not implemented yet: "+JSON.stringify(n));var o=fr(t.shape,0,1,"float32",r).greater(e);return o=o.div(yl(1,e)),t.mul(o);}});function Jl(t,e,n){for(var r=1-t%2,o=new Float32Array(t),a=0;a<t;++a){var i=2*Math.PI*a/(t+r-1);o[a]=e-n*Math.cos(i);}return xn(o,"float32");}var tc=pn({hannWindow_:function(t){return Jl(t,.5,.5);}}),ec=pn({hammingWindow_:function(t){return Jl(t,.54,.46);}}),nc=pn({frame_:function(t,e,n,r,o){void 0===r&&(r=!1),void 0===o&&(o=0);for(var a=0,i=[];a+e<=t.size;)i.push(Ru(t,a,e)),a+=n;if(r){var s=a+e-t.size,u=_n([Ru(t,a,e-s),Nn([s],o)]);i.push(u);}return 0===i.length?bn([],[0,e]):_n(i).as2D(i.length,e);}}),rc=Object.freeze({hannWindow:tc,hammingWindow:ec,frame:nc});!function(t){t[t.NONE=0]="NONE",t[t.MEAN=1]="MEAN",t[t.SUM=2]="SUM",t[t.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS";}(exports.Reduction||(exports.Reduction={}));var oc=pn({absoluteDifference_:function(t,e,n,r){void 0===r&&(r=exports.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=Ze(t,"labels","absoluteDifference"),a=Ze(e,"predictions","absoluteDifference"),i=null;null!=n&&(i=Ze(n,"weights","absoluteDifference")),v(o.shape,a.shape,"Error in absoluteDifference: ");var s=o.sub(a).abs();return ac(s,i,r);}}),ac=pn({computeWeightedLoss_:function(t,e,n){void 0===n&&(n=exports.Reduction.SUM_BY_NONZERO_WEIGHTS);var r=Ze(t,"losses","computeWeightedLoss"),o=null;null!=e&&(o=Ze(e,"weights","computeWeightedLoss"));var a=null==o?r:r.mul(o);if(n===exports.Reduction.NONE)return a;if(n===exports.Reduction.SUM)return a.sum();if(n===exports.Reduction.MEAN){if(null==o)return a.mean();var i=r.size/o.size,s=a.sum().div(o.sum());return i>1?s.div(yn(i)):s;}if(n===exports.Reduction.SUM_BY_NONZERO_WEIGHTS){if(null==o)return a.sum().div(yn(r.size));var u=o.mul(In(r.shape)).notEqual(yn(0)).sum().toFloat();return a.sum().div(u);}throw Error("Unknown reduction: "+n);}}),ic=pn({cosineDistance_:function(t,e,n,r,o){void 0===o&&(o=exports.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=Ze(t,"labels","cosineDistance"),i=Ze(e,"predictions","cosineDistance"),s=null;null!=r&&(s=Ze(r,"weights","cosineDistance")),v(a.shape,i.shape,"Error in cosineDistance: ");var u=yn(1).sub(a.mul(i).sum(n,!0));return ac(u,s,o);}}),sc=pn({hingeLoss_:function(t,e,n,r){void 0===r&&(r=exports.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=Ze(t,"labels","hingeLoss"),a=Ze(e,"predictions","hingeLoss"),i=null;null!=n&&(i=Ze(n,"weights","hingeLoss")),v(o.shape,a.shape,"Error in hingeLoss: ");var s=yn(1);o=yn(2).mul(o).sub(s);var u=s.sub(o.mul(a)).relu();return ac(u,i,r);}}),uc=pn({huberLoss_:function(t,e,n,r,o){void 0===r&&(r=1),void 0===o&&(o=exports.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=Ze(t,"labels","huberLoss"),i=Ze(e,"predictions","huberLoss"),s=null;null!=n&&(s=Ze(n,"weights","huberLoss")),v(a.shape,i.shape,"Error in huberLoss: ");var u=yn(r),l=i.sub(a).abs(),c=ul(l,u),h=l.sub(c),p=yn(.5).mul(c.square()).add(u.mul(h));return ac(p,s,o);}}),lc=pn({logLoss_:function(t,e,n,r,o){void 0===r&&(r=1e-7),void 0===o&&(o=exports.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=Ze(t,"labels","logLoss"),i=Ze(e,"predictions","logLoss"),s=null;null!=n&&(s=Ze(n,"weights","logLoss")),v(a.shape,i.shape,"Error in logLoss: ");var u=yn(1),l=yn(r),c=a.mul(i.add(l).log()).neg().sub(u.sub(a).mul(u.sub(i).add(l).log()));return ac(c,s,o);}}),cc=pn({meanSquaredError_:function(t,e,n,r){void 0===r&&(r=exports.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=Ze(t,"labels","meanSquaredError"),a=Ze(e,"predictions","meanSquaredError"),i=null;null!=n&&(i=Ze(n,"weights","meanSquaredError")),v(o.shape,a.shape,"Error in meanSquaredError: ");var s=o.squaredDifference(a);return ac(s,i,r);}}),hc=pn({sigmoidCrossEntropy_:function(t,e,n,r,o){void 0===r&&(r=0),void 0===o&&(o=exports.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=Ze(t,"multiClassLabels","sigmoidCrossEntropy"),i=Ze(e,"logits","sigmoidCrossEntropy"),s=null;if(null!=n&&(s=Ze(n,"weights","sigmoidCrossEntropy")),v(a.shape,i.shape,"Error in sigmoidCrossEntropy: "),r>0){var u=yn(r),l=yn(1),c=yn(.5);a=a.mul(l.sub(u)).add(c.mul(u));}var h=function(t,e){var n=Ze(t,"labels","sigmoidCrossEntropyWithLogits"),r=Ze(e,"logits","sigmoidCrossEntropyWithLogits");v(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");var o=r.relu(),a=r.mul(n),i=r.abs().neg().exp().log1p();return o.sub(a).add(i);}(a,i);return ac(h,s,o);}}),pc=pn({softmaxCrossEntropy_:function(t,e,n,r,o){void 0===r&&(r=0),void 0===o&&(o=exports.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=Ze(t,"onehotLabels","softmaxCrossEntropy"),i=Ze(e,"logits","softmaxCrossEntropy"),s=null;if(null!=n&&(s=Ze(n,"weights","softmaxCrossEntropy")),v(a.shape,i.shape,"Error in softmaxCrossEntropy: "),r>0){var u=yn(r),l=yn(1),c=yn(a.shape[1]);a=a.mul(l.sub(u)).add(u.div(c));}var h=function(t,e,n){if(void 0===n&&(n=-1),-1===n&&(n=e.rank-1),n!==e.rank-1)throw Error("Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank "+e.rank+" and dim was "+n);return Vr(function(t,e,r){var o=e.logSumExp([n],!0),a=e.toFloat().sub(o);return r([t,a]),{value:a.mul(t).neg().sum([n]),gradFunc:function(t,e){var r=e[0],o=e[1],a=on(t.shape,[n]);return[t.reshape(a).mul(r.toFloat().sub(o.exp())),t.reshape(a).mul(o.exp().sub(r.toFloat()))];}};})(t,e);}(a,i);return ac(h,s,o);}}),fc=Object.freeze({get Reduction(){return exports.Reduction;},absoluteDifference:oc,computeWeightedLoss:ac,cosineDistance:ic,hingeLoss:sc,huberLoss:uc,logLoss:lc,meanSquaredError:cc,sigmoidCrossEntropy:hc,softmaxCrossEntropy:pc});function dc(t,e){return void 0===e&&(e=!1),Dt.tidy(function(){if(2!==t.shape.length)throw new Error("qr2d() requires a 2D Tensor, but got a "+t.shape.length+"D Tensor.");for(var n=t.shape[0],r=t.shape[1],o=rr(n),a=t.clone(),i=bn([[1]],[1,1]),s=i.clone(),u=n>=r?r:n,l=function(t){var e,u=a,l=s,c=o;e=Dt.tidy(function(){var e=a.slice([t,t],[n-t,1]),u=e.norm(),l=a.slice([t,t],[1,1]),c=l.sign().neg(),h=l.sub(c.mul(u)),p=e.div(h);s=1===p.shape[0]?i.clone():i.concat(p.slice([1,0],[p.shape[0]-1,p.shape[1]]),0);var f=c.matMul(h).div(u).neg(),d=a.slice([t,0],[n-t,r]),v=f.mul(s);a=0===t?d.sub(v.matMul(s.transpose().matMul(d))):a.slice([0,0],[t,r]).concat(d.sub(v.matMul(s.transpose().matMul(d))),0);var m=o.slice([0,t],[n,o.shape[1]-t]);return o=0===t?m.sub(m.matMul(s).matMul(v.transpose())):o.slice([0,0],[n,t]).concat(m.sub(m.matMul(s).matMul(v.transpose())),1),[s,a,o];}),s=e[0],a=e[1],o=e[2],Le([u,l,c]);},c=0;c<u;++c)l(c);return!e&&n>r&&(o=o.slice([0,0],[n,r]),a=a.slice([0,0],[r,r])),[o,a];});}var vc=pn({gramSchmidt_:function(t){var e;if(Array.isArray(t)){e=!1,d(null!=t&&t.length>0,function(){return"Gram-Schmidt process: input must not be null, undefined, or empty";});for(var n=t[0].shape[0],r=function(e){d(t[e].shape[0]===n,function(){return"Gram-Schmidt: Non-unique lengths found in the input vectors: ("+t[e].shape[0]+" vs. "+n+")";});},o=1;o<t.length;++o)r(o);}else e=!0,t=Pn(t,t.shape[0],0).map(function(t){return mr(t,[0]);});d(t.length<=t[0].shape[0],function(){return"Gram-Schmidt: Number of vectors ("+t.length+") exceeds number of dimensions ("+t[0].shape[0]+").";});var a=[],i=t,s=function(t){a.push(Dt.tidy(function(){var e=i[t];if(t>0)for(var n=0;n<t;++n){var r=Wu(a[n].mulStrict(e)).mul(a[n]);e=e.sub(r);}return e.div(Ol(e,"euclidean"));}));};for(o=0;o<t.length;++o)s(o);return e?gr(a,0):a;}}),mc=pn({qr_:function(t,e){if(void 0===e&&(e=!1),t.rank<2)throw new Error("qr() requires input tensor to have a rank >= 2, but got rank "+t.rank);if(2===t.rank)return dc(t,e);var n=t.shape.slice(0,t.shape.length-2).reduce(function(t,e){return t*e;}),r=br(t.reshape([n,t.shape[t.shape.length-2],t.shape[t.shape.length-1]]),0),o=[],a=[];return r.forEach(function(t){var n=dc(t,e),r=n[0],i=n[1];o.push(r),a.push(i);}),[gr(o,0).reshape(t.shape),gr(a,0).reshape(t.shape)];}}),gc=Object.freeze({gramSchmidt:vc,qr:mc});function yc(t,e,n,r,o){null==r&&(r=.5),null==o&&(o=Number.NEGATIVE_INFINITY);var a=t.shape[0];return n=Math.min(n,a),d(0<=r&&r<=1,function(){return"iouThreshold must be in [0, 1], but was '"+r+"'";}),d(2===t.rank,function(){return"boxes must be a 2D tensor, but was of rank '"+t.rank+"'";}),d(4===t.shape[1],function(){return"boxes must have 4 columns, but 2nd dimension was "+t.shape[1];}),d(1===e.rank,function(){return"scores must be a 1D tensor";}),d(e.shape[0]===a,function(){return"scores has incompatible shape with boxes. Expected "+a+", but was "+e.shape[0];}),{maxOutputSize:n,iouThreshold:r,scoreThreshold:o};}var xc=pn({resizeBilinear_:function(t,e,n){void 0===n&&(n=!1);var r=Ze(t,"images","resizeBilinear");d(3===r.rank||4===r.rank,function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+r.rank+".";}),d(2===e.length,function(){return"Error in resizeBilinear: new shape must 2D, but got shape "+e+".";});var o=r,a=!1;3===r.rank&&(a=!0,o=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var i=e[0],s=e[1],u=Dt.runKernel(function(t,e){return e([o]),t.resizeBilinear(o,i,s,n);},{batchImages:o},function(t,e){return{batchImages:function(){return Dt.runKernel(function(r){return r.resizeBilinearBackprop(t,e[0],n);},{});}};});return a?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u;}}),bc=pn({resizeNearestNeighbor_:function(t,e,n){void 0===n&&(n=!1);var r=Ze(t,"images","resizeNearestNeighbor");d(3===r.rank||4===r.rank,function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+r.rank+".";}),d(2===e.length,function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+e+".";}),d("float32"===r.dtype||"int32"===r.dtype,function(){return"`images` must have `int32` or `float32` as dtype";});var o=r,a=!1;3===r.rank&&(a=!0,o=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var i=e[0],s=e[1],u=Dt.runKernel(function(t,e){return e([o]),t.resizeNearestNeighbor(o,i,s,n);},{batchImages:o},function(t,e){return{batchImages:function(){return Dt.runKernel(function(r){return r.resizeNearestNeighborBackprop(t,e[0],n);},{});}};});return a?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u;}}),wc=pn({nonMaxSuppression_:function(t,e,n,r,o){void 0===r&&(r=.5),void 0===o&&(o=Number.NEGATIVE_INFINITY);var a=Ze(t,"boxes","nonMaxSuppression"),i=Ze(e,"scores","nonMaxSuppression"),s=yc(a,i,n,r,o);return n=s.maxOutputSize,r=s.iouThreshold,o=s.scoreThreshold,Dt.runKernel(function(t){return t.nonMaxSuppression(a,i,n,r,o);},{$boxes:a});}}),Cc=function(t,e,n,a,i){return void 0===a&&(a=.5),void 0===i&&(i=Number.NEGATIVE_INFINITY),r(this,void 0,void 0,function(){var r,s,u,l,c,h;return o(this,function(o){switch(o.label){case 0:return r=Ze(t,"boxes","nonMaxSuppressionAsync"),s=Ze(e,"scores","nonMaxSuppressionAsync"),u=yc(r,s,n,a,i),n=u.maxOutputSize,a=u.iouThreshold,i=u.scoreThreshold,[4,r.data()];case 1:return l=o.sent(),[4,s.data()];case 2:return c=o.sent(),h=mo(l,c,n,a,i),r!==t&&r.dispose(),s!==e&&s.dispose(),[2,h];}});});},Ec=pn({cropAndResize_:function(t,e,n,r,o,a){var i=Ze(t,"image","cropAndResize","float32"),s=Ze(e,"boxes","cropAndResize","float32"),u=Ze(n,"boxInd","cropAndResize","int32");o=o||"bilinear",a=a||0;var l=s.shape[0];return d(4===i.rank,function(){return"Error in cropAndResize: image must be rank 4,but got rank "+i.rank+".";}),d(2===s.rank&&4===s.shape[1],function(){return"Error in cropAndResize: boxes must be have size ["+l+",4] but had shape "+s.shape+".";}),d(1===u.rank&&u.shape[0]===l,function(){return"Error in cropAndResize: boxInd must be have size ["+l+"] but had shape "+s.shape+".";}),d(2===r.length,function(){return"Error in cropAndResize: cropSize must be of length 2, but got length "+r.length+".";}),d(r[0]>=1&&r[1]>=1,function(){return"cropSize must be atleast [1,1], but was "+r;}),d("bilinear"===o||"nearest"===o,function(){return"method must be bilinear or nearest, but was "+o;}),Dt.runKernel(function(t,e){return t.cropAndResize(i,s,u,r,o,a);},{$image:i,$boxes:s});}}),Rc=Object.freeze({resizeBilinear:xc,resizeNearestNeighbor:bc,nonMaxSuppression:wc,nonMaxSuppressionAsync:Cc,cropAndResize:Ec});var Ic=pn({matMul_:function(t,e,n,r,o,a){var i;void 0===n&&(n=!1),void 0===r&&(r=!1),void 0===a&&(a="linear");var s=Ze(t,"a","fused matMul"),u=Ze(e,"b","fused matMul");i=Rt(s,u),s=i[0],u=i[1];var l=n?s.shape[s.rank-2]:s.shape[s.rank-1],c=r?u.shape[u.rank-1]:u.shape[u.rank-2],h=n?s.shape[s.rank-1]:s.shape[s.rank-2],p=r?u.shape[u.rank-2]:u.shape[u.rank-1],f=s.shape.slice(0,-2),v=u.shape.slice(0,-2),m=y(f),g=y(v);d(s.rank>=2&&u.rank>=2&&s.rank===u.rank,function(){return"Error in fused matMul: inputs must have the same rank of at least 2, got ranks "+s.rank+" and "+u.rank+".";}),d(x(f,v),function(){return"Error in fused matMul: outer dimensions ("+f+") and ("+v+") of Tensors with shapes "+s.shape+" and "+u.shape+" must match.";}),d(l===c,function(){return"Error in fused matMul: inner shapes ("+l+") and ("+c+") of Tensors with shapes "+s.shape+" and "+u.shape+" and transposeA="+n+" and transposeB="+r+" must match.";});var b,w=s.shape.slice(0,-2).concat([h,p]),C=n?s.as3D(m,l,h):s.as3D(m,h,l),E=r?u.as3D(g,p,c):u.as3D(g,c,p);null!=o&&Yr(w,(b=Rt(b=Ze(o,"bias","fused matMul"),s)[0]).shape);var R={$a:C,$b:E};return null!=o&&(R.$bias=b),Dt.runKernel(function(t,e){var o=t.fusedBatchMatMul(C,E,n,r,b,a);return e([C,E,o]),o;},R,function(t,e){var i,s=e[0],u=e[1],l=e[2];if(null==a||"linear"===a)i=t;else{if("relu"!==a)throw new Error("Gradient for activation "+a+" has not been implemented yet.");i=t.mul(l.step());}var c={};return null!=o&&(c={$bias:function(){var t=i,e=Xr(b.shape,i.shape);return e.length>0&&(t=t.sum(e)),t.reshape(b.shape);}}),n||r?!n&&r?Object.assign({$a:function(){return i.matMul(u,!1,!1);},$b:function(){return i.matMul(s,!0,!1);}},c):n&&!r?Object.assign({$a:function(){return u.matMul(i,!1,!0);},$b:function(){return s.matMul(i,!1,!1);}},c):Object.assign({$a:function(){return u.matMul(i,!0,!0);},$b:function(){return i.matMul(s,!0,!0);}},c):Object.assign({$a:function(){return i.matMul(u,!1,!0);},$b:function(){return s.matMul(i,!0,!1);}},c);}).reshape(w);}}),Sc=Object.freeze({matMul:Ic}),Nc=Object.freeze({image:Rc,linalg:gc,losses:fc,spectral:Kl,fused:Sc,signal:rc,op:pn,batchNormalization2d:js,batchNormalization3d:Ks,batchNormalization4d:Xs,batchNormalization:Ys,batchNorm:Qs,batchNorm2d:Js,batchNorm3d:Zs,batchNorm4d:tu,complex:fn,real:dn,imag:vn,concat:_n,concat1d:On,concat2d:Mn,concat3d:Fn,concat4d:Bn,split:Pn,conv1d:ou,conv2d:au,conv3d:iu,conv2dDerFilter:su,depthwiseConv2d:uu,separableConv2d:lu,conv2dTranspose:cu,matMul:hu,dot:pu,outerProduct:fu,reverse:du,reverse1d:vu,reverse2d:mu,reverse3d:gu,reverse4d:yu,maxPool:wu,avgPool:Cu,pool:Eu,slice:Ru,slice1d:Iu,slice2d:Su,slice3d:Nu,slice4d:ku,abs:is,acos:ss,acosh:us,asin:ls,asinh:cs,atan:hs,atanh:ps,ceil:fs,clipByValue:ds,cos:vs,cosh:ms,erf:gs,exp:ys,expm1:xs,floor:bs,log:ws,log1p:Cs,logSigmoid:Es,neg:Rs,reciprocal:Is,round:Ss,rsqrt:Ns,sigmoid:ks,sign:As,isNaN:Ts,isInf:Ds,isFinite:_s,sin:Os,sinh:Ms,softplus:Fs,sqrt:Bs,square:Ps,step:Ls,tan:Ws,tanh:Us,all:Tu,any:Du,argMax:_u,argMin:Ou,logSumExp:Mu,max:Fu,mean:Bu,min:Pu,moments:Lu,sum:Wu,prod:Uu,equal:zu,equalStrict:Vu,greater:Gu,greaterEqual:qu,greaterEqualStrict:Hu,greaterStrict:$u,less:ju,lessEqual:Ku,lessEqualStrict:Xu,lessStrict:Yu,notEqual:Qu,notEqualStrict:Ju,add:Zu,addN:tl,addStrict:el,atan2:nl,div:rl,divStrict:ol,floorDiv:al,maximum:il,maximumStrict:sl,minimum:ul,minimumStrict:ll,mod:cl,modStrict:hl,mul:pl,mulStrict:fl,pow:dl,powStrict:vl,squaredDifference:ml,squaredDifferenceStrict:gl,sub:yl,subStrict:xl,elu:Sl,leakyRelu:Nl,prelu:kl,relu:Al,selu:Tl,logicalAnd:bl,logicalNot:wl,logicalOr:Cl,logicalXor:El,where:Rl,whereAsync:Il,buffer:Xn,print:Yn,batchToSpaceND:Qn,cast:Jn,clone:Zn,cumsum:tr,depthToSpace:er,expandDims:nr,eye:rr,multinomial:or,oneHot:ar,pad:ir,pad1d:sr,pad2d:ur,pad3d:lr,pad4d:cr,rand:hr,randomNormal:pr,randomUniform:fr,reshape:dr,spaceToBatchND:vr,squeeze:mr,stack:gr,tile:yr,truncatedNormal:xr,unstack:br,setdiff1dAsync:wr,fill:Nn,linspace:kn,ones:In,range:An,scalar:yn,tensor:mn,tensor1d:xn,tensor2d:bn,tensor3d:wn,tensor4d:Cn,tensor5d:En,tensor6d:Rn,zeros:Sn,onesLike:Tn,zerosLike:Dn,transpose:Dl,softmax:qr,logSoftmax:Hr,localResponseNormalization:_l,norm:Ol,gather:Bl,unsortedSegmentSum:Pl,basicLSTMCell:Ll,multiRNNCell:Wl,movingAverage:Ul,stridedSlice:zl,topk:Vl,scatterND:Gl,fft:ql,ifft:Hl,rfft:$l,irfft:jl,sparseToDense:Xl,gatherND:Yl,dropout:Ql,hannWindow:tc,hammingWindow:ec,frame:nc});var kc=function(){function t(){if(this.blockSize=48,this.firstUse=!0,exports.ENV.get("IS_BROWSER")){var t="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(300,150):"undefined"!=typeof document?document.createElement("canvas"):null;null!==t&&(this.fromPixels2DContext=t.getContext("2d"));}this.data=new $r(this,Dt);}return t.prototype.register=function(t,e,n){if(this.firstUse&&(this.firstUse=!1,exports.ENV.get("IS_NODE")&&Ye("\n============================\nHi there 👋. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.\n============================\n")),this.data.has(t))throw new Error("Data buffer is already registered");this.data.set(t,{dtype:n});},t.prototype.write=function(t,e){if(null==e)throw new Error("MathBackendCPU.write(): values can not be null");this.data.get(t).values=e;},t.prototype.fromPixels=function(t,e){if(null==t)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var n,r,o=t.data instanceof Uint8Array,a="undefined"!=typeof ImageData&&t instanceof ImageData,i="undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement,u="undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement;if(exports.ENV.get("IS_NODE")&&null==t.getContext)throw new Error("When running in node, pixels must be an HTMLCanvasElement like the one returned by the `canvas` npm package");if(null!=t.getContext)n=t.getContext("2d").getImageData(0,0,t.width,t.height).data;else if(a||o)n=t.data;else{if(!u&&!i)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 "+t.constructor.name);if(null==this.fromPixels2DContext)throw new Error("Can't read pixels from HTMLImageElement outside the browser.");this.fromPixels2DContext.canvas.width=t.width,this.fromPixels2DContext.canvas.height=t.height,this.fromPixels2DContext.drawImage(t,0,0,t.width,t.height),n=this.fromPixels2DContext.getImageData(0,0,t.width,t.height).data;}if(4===e)r=new Int32Array(n);else{var l=t.width*t.height;r=new Int32Array(l*e);for(var c=0;c<l;c++)for(var h=0;h<e;++h)r[c*e+h]=n[4*c+h];}return wn(r,[t.height,t.width,e],"int32");},t.prototype.read=function(t){return r(this,void 0,void 0,function(){return o(this,function(e){return[2,this.readSync(t)];});});},t.prototype.readSync=function(t){var e=this.data.get(t),n=e.dtype,r=e.complexTensors;return"complex64"===n?ho(this.readSync(r.real.dataId),this.readSync(r.imag.dataId)):this.data.get(t).values;},t.prototype.bufferSync=function(t){var e=this.readSync(t.dataId),n=e;if("string"===t.dtype)try{n=e.map(function(t){return J(t);});}catch(t){throw new Error("Failed to decode encoded string bytes into utf-8");}return Xn(t.shape,t.dtype,n);},t.prototype.disposeData=function(t){if(this.data.has(t)){var e=this.data.get(t).complexTensors;null!=e&&(e.real.dispose(),e.imag.dispose()),this.data.delete(t);}},t.prototype.time=function(t){return r(this,void 0,void 0,function(){var e;return o(this,function(n){return e=K(),t(),[2,{kernelMs:K()-e}];});});},t.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."]};},t.prototype.complex=function(t,e){var n=ft.make(t.shape,{},"complex64");return this.data.get(n.dataId).complexTensors={real:Dt.keep(t.clone()),imag:Dt.keep(e.clone())},n;},t.prototype.real=function(t){return this.data.get(t.dataId).complexTensors.real.clone();},t.prototype.imag=function(t){return this.data.get(t.dataId).complexTensors.imag.clone();},t.prototype.assertNotComplex=function(t,e){Array.isArray(t)||(t=[t]),t.forEach(function(t){null!=t&&d("complex64"!==t.dtype,function(){return e+" does not support complex64 tensors.";});});},t.prototype.slice=function(t,e,n){if(this.assertNotComplex(t,"slice"),Fr(t.shape,e,n)){var r=Br(e,t.strides),o=y(n);return mn(this.readSync(t.dataId).subarray(r,r+o),n,t.dtype);}for(var a=Xn(n,t.dtype),i=this.bufferSync(t),s=0;s<a.size;++s){var u=a.indexToLoc(s).map(function(t,n){return t+e[n];});a.values[s]=i.get.apply(i,u);}return a.toTensor();},t.prototype.stridedSlice=function(t,e,n,r,o,a,i,s,u){this.assertNotComplex(t,"stridedSlice");var l=_r(t.shape,e,n,r,o,a,i,s,u),c=l[0],h=l[1],p=l[2],f=h.filter(function(t,e){return-1===p.indexOf(e);});if(f.some(function(t){return 0===t;}))return mn([],f);for(var d=Xn(h,t.dtype),v=this.bufferSync(t),m=0;m<d.size;m++){for(var g=d.indexToLoc(m),y=new Array(g.length),x=0;x<y.length;x++)y[x]=g[x]*r[x]+c[x];d.set.apply(d,[v.get.apply(v,y)].concat(g));}return d.toTensor().reshape(f);},t.prototype.unstack=function(t,e){for(var n=t.shape[e],r=new Array(t.rank-1),o=0,a=0;a<t.rank;a++)a!==e&&(r[o++]=t.shape[a]);var i=new Array(t.rank).fill(0),s=t.shape.slice();s[e]=1;var u=new Array(n);for(a=0;a<u.length;a++)i[e]=a,u[a]=this.slice(t,i,s).reshape(r);return u;},t.prototype.reverse=function(t,e){this.assertNotComplex(t,"reverse");for(var n=Xn(t.shape,t.dtype),r=this.bufferSync(t),o=function(o){var a=n.indexToLoc(o),i=a.slice();e.forEach(function(e){return i[e]=t.shape[e]-1-i[e];}),n.set.apply(n,[r.get.apply(r,i)].concat(a));},a=0;a<n.size;a++)o(a);return n.toTensor();},t.prototype.concat=function(t,e){var n=this;this.assertNotComplex(t,"concat");var r=t.map(function(t){var n=y(t.shape.slice(e));return t.as2D(-1,n);}),o=hn(r.map(function(t){return t.shape;}),1),a=Xn(o,t[0].dtype).values;if(1===r[0].shape[0]){var i=0;r.forEach(function(t){a.set(n.readSync(t.dataId),i),i+=t.size;});}else{var s=0;r.forEach(function(t){for(var e=n.readSync(t.dataId),r=0,i=0;i<t.shape[0];++i)for(var u=i*o[1]+s,l=0;l<t.shape[1];++l)a[u+l]=e[r++];s+=t.shape[1];});}var u=hn(t.map(function(t){return t.shape;}),e);return mn(a,u,t[0].dtype);},t.prototype.neg=function(t){return this.assertNotComplex(t,"neg"),this.multiply(yn(-1),t);},t.prototype.add=function(t,e){return"complex64"===t.dtype||"complex64"===e.dtype?this.broadcastedBinaryComplexOp(t.cast("complex64"),e.cast("complex64"),function(t,e,n,r){return{real:t+n,imag:e+r};}):this.broadcastedBinaryOp(t,e,Ct(t.dtype,e.dtype),function(t,e){return t+e;});},t.prototype.addN=function(t){var e=this;this.assertNotComplex(t,"addN");for(var n=t.map(function(t){return e.readSync(t.dataId);}),r=Xn(t[0].shape,t[0].dtype),o=r.values,a=0;a<t.length;a++)for(var i=n[a],s=0;s<o.length;s++)o[s]+=i[s];return r.toTensor();},t.prototype.subtract=function(t,e){return"complex64"===t.dtype||"complex64"===e.dtype?this.broadcastedBinaryComplexOp(t.cast("complex64"),e.cast("complex64"),function(t,e,n,r){return{real:t-n,imag:e-r};}):this.broadcastedBinaryOp(t,e,Ct(t.dtype,e.dtype),function(t,e){return t-e;});},t.prototype.pow=function(t,e){return this.assertNotComplex([t,e],"pow"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){return Math.pow(t,e);});},t.prototype.batchMatMul=function(t,e,n,r){this.assertNotComplex([t,e],"matMul");for(var o=n?t.shape[1]:t.shape[2],a=n?t.shape[2]:t.shape[1],i=r?e.shape[1]:e.shape[2],s=t.shape[0],u=this.readSync(t.dataId),l=this.readSync(e.dataId),c=n?[t.strides[0],1,t.strides[1]]:[t.strides[0],t.strides[1],1],h=c[0],p=c[1],f=c[2],d=r?[1,e.strides[1],e.strides[0]]:[e.strides[1],1,e.strides[0]],v=d[0],m=d[1],g=d[2],y=a*i,x=Xn([s,a,i],t.dtype),b=x.values,w=this.blockSize,C=0;C<s;C++)for(var E=0;E<a;E+=w)for(var R=0;R<i;R+=w)for(var I=0;I<o;I+=w)for(var S=Math.min(E+w,a),N=Math.min(R+w,i),k=Math.min(I+w,o),A=E;A<S;A++)for(var T=R;T<N;T++){for(var D=0,_=I;_<k;_++)D+=u[C*h+A*p+_*f]*l[_*v+T*m+C*g];b[C*y+(A*i+T)]+=D;}return x.toTensor();},t.prototype.fusedBatchMatMul=function(t,e,n,r,o,a){var i=this.batchMatMul(t,e,n,r);return o&&(i=this.add(i,o)),a&&(i=function(t,e,n){if("linear"===e)return t.linear(n);if("relu"===e)return t.relu(n);throw new Error("Activation "+e+" has not been implemented for the CPU backend.");}(this,a,i)),i;},t.prototype.multiply=function(t,e){return"complex64"===t.dtype||"complex64"===e.dtype?this.broadcastedBinaryComplexOp(t.cast("complex64"),e.cast("complex64"),function(t,e,n,r){return{real:t*n-e*r,imag:t*r+e*n};}):this.broadcastedBinaryOp(t,e,Ct(t.dtype,e.dtype),function(t,e){return t*e;});},t.prototype.realDivide=function(t,e){this.assertNotComplex([t,e],"realDivide");return this.broadcastedBinaryOp(t,e,"float32",function(t,e){return t/e;});},t.prototype.floorDiv=function(t,e){this.assertNotComplex([t,e],"floorDiv");return this.broadcastedBinaryOp(t,e,"int32",function(t,e){return Math.floor(t/e);});},t.prototype.sum=function(t,e){this.assertNotComplex(t,"sum"),an("sum",e,t.rank);for(var n=rn(t.shape,e),r=n[0],o=n[1],a=Sn(r,Ct(t.dtype,"int32")),i=y(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),l=0;l<s.length;++l){for(var c=l*i,h=0,p=0;p<i;++p)h+=u[c+p];s[l]=h;}return a;},t.prototype.prod=function(t,e){this.assertNotComplex(t,"sum");for(var n=rn(t.shape,e),r=n[0],o=n[1],a=Sn(r,Ct(t.dtype,"int32")),i=y(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),l=0;l<s.length;++l){for(var c=l*i,h=1,p=0;p<i;++p)h*=u[c+p];s[l]=h;}return a;},t.prototype.unsortedSegmentSum=function(t,e,n){this.assertNotComplex(t,"unsortedSegmentSum");for(var r=[],o=t.rank-e.rank,a=0;a<o;++a)e=e.expandDims(a+1);for(a=0;a<n;++a){var i=yn(a,"int32"),s=zu(i,e).asType("float32").mul(t).sum(0);r.push(s);}return gr(r);},t.prototype.argMin=function(t,e){this.assertNotComplex(t,"argMin");var n=[e];an("argMin",n,t.rank);for(var r=rn(t.shape,n),o=r[0],a=r[1],i=Sn(o,"int32"),s=y(a),u=this.readSync(i.dataId),l=this.readSync(t.dataId),c=0;c<u.length;++c){for(var h=c*s,p=l[h],f=0,d=0;d<s;++d){var v=l[h+d];v<p&&(p=v,f=d);}u[c]=f;}return i;},t.prototype.argMax=function(t,e){this.assertNotComplex(t,"argMax");var n=[e];an("argMax",n,t.rank);for(var r=rn(t.shape,n),o=r[0],a=r[1],i=Sn(o,"int32"),s=y(a),u=this.readSync(i.dataId),l=this.readSync(t.dataId),c=0;c<u.length;++c){for(var h=c*s,p=l[h],f=0,d=0;d<s;++d){var v=l[h+d];v>p&&(p=v,f=d);}u[c]=f;}return i;},t.prototype.cumsum=function(t,e,n,r){if(this.assertNotComplex(t,"cumsum"),e!==t.rank-1)throw new Error("backend.cumsum in CPU expects an inner-most axis="+(t.rank-1)+" but got axis="+e);for(var o=Ct(t.dtype,"int32"),a=Sn(t.shape,o),i=this.readSync(a.dataId),s=this.readSync(t.dataId),u=t.shape[t.rank-1],l=r?function(t,e){return t+u-e-1;}:function(t,e){return t+e;},c=0;c<s.length;c+=u)for(var h=0;h<u;h++){var p=l(c,h);if(0===h)i[p]=n?0:s[p];else{var f=l(c,h-1);i[p]=n?s[f]+i[f]:s[p]+i[f];}}return a;},t.prototype.equal=function(t,e){return this.assertNotComplex([t,e],"equal"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t===e?1:0;});},t.prototype.notEqual=function(t,e){return this.assertNotComplex([t,e],"notEqual"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t!==e?1:0;});},t.prototype.less=function(t,e){return this.assertNotComplex([t,e],"less"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t<e?1:0;});},t.prototype.lessEqual=function(t,e){return this.assertNotComplex([t,e],"lessEqual"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t<=e?1:0;});},t.prototype.greater=function(t,e){return this.assertNotComplex([t,e],"greater"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t>e?1:0;});},t.prototype.greaterEqual=function(t,e){return this.assertNotComplex([t,e],"greaterEqual"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t>=e?1:0;});},t.prototype.logicalNot=function(t){this.assertNotComplex(t,"logicalNot");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r<e.length;++r)n[r]=e[r]?0:1;return ft.make(t.shape,{values:n},"bool");},t.prototype.logicalAnd=function(t,e){return this.assertNotComplex([t,e],"logicalAnd"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t&&e;});},t.prototype.logicalOr=function(t,e){return this.assertNotComplex([t,e],"logicalOr"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t||e;});},t.prototype.select=function(t,e,n){this.assertNotComplex([t,e,n],"select");for(var r=this.readSync(t.dataId),o=this.readSync(e.dataId),a=this.readSync(n.dataId),i=Sn(e.shape,Ct(e.dtype,n.dtype)),s=this.readSync(i.dataId),u=0,l=0===t.rank||t.rank>1||1===e.rank?1:e.shape[1],c=0;c<r.length;c++)for(var h=0;h<l;h++)1===r[c]?s[u++]=o[c]:s[u++]=a[c];return i;},t.prototype.where=function(t){this.assertNotComplex([t],"where");var e=this.readSync(t.dataId);return wo(t.shape,e);},t.prototype.topk=function(t,e,n){return this.assertNotComplex(t,"topk"),bo(this.readSync(t.dataId),t.shape,t.dtype,e);},t.prototype.min=function(t,e){this.assertNotComplex(t,"min"),an("min",e,t.rank);for(var n=rn(t.shape,e),r=n[0],o=n[1],a=Sn(r,t.dtype),i=y(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),l=0;l<s.length;++l){for(var c=l*i,h=u[c],p=0;p<i;++p){var f=u[c+p];f<h&&(h=f);}s[l]=h;}return a;},t.prototype.minimum=function(t,e){return this.assertNotComplex([t,e],"minimum"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){return Math.min(t,e);});},t.prototype.mod=function(t,e){return this.assertNotComplex([t,e],"mod"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){var n=t%e;return t<0&&e<0||t>=0&&e>=0?n:(n+e)%e;});},t.prototype.max=function(t,e){this.assertNotComplex(t,"max"),an("max",e,t.rank);for(var n=rn(t.shape,e),r=n[0],o=n[1],a=Sn(r,t.dtype),i=y(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),l=0;l<s.length;++l){for(var c=l*i,h=u[c],p=0;p<i;++p){var f=u[c+p];f>h&&(h=f);}s[l]=h;}return a;},t.prototype.maximum=function(t,e){return this.assertNotComplex([t,e],"maximum"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){return Math.max(t,e);});},t.prototype.all=function(t,e){this.assertNotComplex(t,"all"),an("all",e,t.rank);for(var n=rn(t.shape,e),r=n[0],o=n[1],a=Sn(r,t.dtype),i=y(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),l=0;l<s.length;++l){for(var c=l*i,h=u[c],p=0;p<i;++p){var f=u[c+p];h=h&&f;}s[l]=h;}return a;},t.prototype.any=function(t,e){this.assertNotComplex(t,"any"),an("any",e,t.rank);for(var n=rn(t.shape,e),r=n[0],o=n[1],a=Sn(r,t.dtype),i=y(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),l=0;l<s.length;++l){for(var c=l*i,h=u[c],p=0;p<i;++p){var f=u[c+p];h=h||f;}s[l]=h;}return a;},t.prototype.squaredDifference=function(t,e){return this.assertNotComplex([t,e],"squaredDifference"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){var n=t-e;return n*n;});},t.prototype.ceil=function(t){this.assertNotComplex(t,"ceil");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.ceil(e[r]);return ft.make(t.shape,{values:n});},t.prototype.floor=function(t){this.assertNotComplex(t,"floor");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.floor(e[r]);return ft.make(t.shape,{values:n});},t.prototype.sign=function(t){this.assertNotComplex(t,"x");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)e[r]<0?n[r]=-1:e[r]>0?n[r]=1:n[r]=0;return ft.make(t.shape,{values:n});},t.prototype.isNaN=function(t){this.assertNotComplex(t,"x");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r<e.length;++r)Number.isNaN(e[r])&&(n[r]=1);return ft.make(t.shape,{values:n},"bool");},t.prototype.isInf=function(t){this.assertNotComplex(t,"x");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r<e.length;++r)Math.abs(e[r])===1/0&&(n[r]=1);return ft.make(t.shape,{values:n},"bool");},t.prototype.isFinite=function(t){this.assertNotComplex(t,"x");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r<e.length;++r)Number.isFinite(e[r])&&(n[r]=1);return ft.make(t.shape,{values:n},"bool");},t.prototype.round=function(t){this.assertNotComplex(t,"round");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var o=Math.floor(e[r]);e[r]-o<.5?n[r]=Math.floor(e[r]):e[r]-o>.5?n[r]=Math.ceil(e[r]):n[r]=o%2==0?o:o+1;}return ft.make(t.shape,{values:n});},t.prototype.exp=function(t){this.assertNotComplex(t,"exp");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.exp(e[r]);return ft.make(t.shape,{values:n});},t.prototype.expm1=function(t){this.assertNotComplex(t,"expm1");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.expm1(e[r]);return ft.make(t.shape,{values:n});},t.prototype.log=function(t){this.assertNotComplex(t,"log");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var o=e[r];n[r]=Math.log(o);}return ft.make(t.shape,{values:n});},t.prototype.log1p=function(t){this.assertNotComplex(t,"log1p");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var o=e[r];n[r]=Math.log1p(o);}return ft.make(t.shape,{values:n});},t.prototype.sqrt=function(t){this.assertNotComplex(t,"sqrt");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var o=e[r];n[r]=Math.sqrt(o);}return ft.make(t.shape,{values:n});},t.prototype.rsqrt=function(t){this.assertNotComplex(t,"rsqrt");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var o=e[r];n[r]=1/Math.sqrt(o);}return ft.make(t.shape,{values:n});},t.prototype.square=function(t){this.assertNotComplex(t,"square");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var o=e[r];n[r]=o*o;}return ft.make(t.shape,{values:n});},t.prototype.reciprocal=function(t){this.assertNotComplex(t,"reciprocal");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=1/e[r];return ft.make(t.shape,{values:n});},t.prototype.linear=function(t){return t;},t.prototype.relu=function(t){this.assertNotComplex(t,"relu");for(var e=Sn(t.shape,t.dtype),n=this.readSync(e.dataId),r=this.readSync(t.dataId),o=0;o<r.length;++o)n[o]=Math.max(0,r[o]);return e;},t.prototype.prelu=function(t,e){return this.assertNotComplex([t,e],"prelu"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){return t<0?e*t:t;});},t.prototype.elu=function(t){this.assertNotComplex(t,"elu");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r){var o=n[r];e[r]=o>=0?o:Math.exp(o)-1;}return ft.make(t.shape,{values:e});},t.prototype.eluDer=function(t,e){this.assertNotComplex([t,e],"eluDer");for(var n=new Float32Array(e.size),r=this.readSync(e.dataId),o=this.readSync(t.dataId),a=0;a<r.length;++a){var i=r[a];n[a]=i>=1?o[a]:o[a]*(i+1);}return ft.make(e.shape,{values:n});},t.prototype.selu=function(t){this.assertNotComplex(t,"selu");for(var e=Ui,n=zi,r=new Float32Array(t.size),o=this.readSync(t.dataId),a=0;a<o.length;++a){var i=o[a];r[a]=i>=0?n*i:e*(Math.exp(i)-1);}return ft.make(t.shape,{values:r});},t.prototype.clip=function(t,e,n){this.assertNotComplex(t,"clip");for(var r=new Float32Array(t.size),o=this.readSync(t.dataId),a=0;a<o.length;++a){var i=o[a];r[a]=i>n?n:i<e?e:i;}return ft.make(t.shape,{values:r});},t.prototype.abs=function(t){for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.abs(n[r]);return ft.make(t.shape,{values:e});},t.prototype.complexAbs=function(t){for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<t.size;++r){var o=n[2*r],a=n[2*r+1];e[r]=Math.hypot(o,a);}return ft.make(t.shape,{values:e});},t.prototype.int=function(t){this.assertNotComplex(t,"int");for(var e=new Int32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=n[r];return ft.make(t.shape,{values:e},"int32");},t.prototype.sigmoid=function(t){this.assertNotComplex(t,"sigmoid");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=1/(1+Math.exp(-n[r]));return ft.make(t.shape,{values:e});},t.prototype.softplus=function(t){this.assertNotComplex(t,"softplus");for(var e=Math.log(1.1920928955078125e-7)+2,n=new Float32Array(t.size),r=this.readSync(t.dataId),o=0;o<r.length;++o){var a=r[o]>-e,i=r[o]<e,s=Math.exp(r[o]),u=void 0;u=i?s:a?r[o]:Math.log(1+s),n[o]=u;}return ft.make(t.shape,{values:n});},t.prototype.sin=function(t){this.assertNotComplex(t,"sin");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.sin(n[r]);return ft.make(t.shape,{values:e});},t.prototype.cos=function(t){this.assertNotComplex(t,"cos");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.cos(n[r]);return ft.make(t.shape,{values:e});},t.prototype.tan=function(t){this.assertNotComplex(t,"tan");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.tan(n[r]);return ft.make(t.shape,{values:e});},t.prototype.asin=function(t){this.assertNotComplex(t,"asin");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.asin(n[r]);return ft.make(t.shape,{values:e});},t.prototype.acos=function(t){this.assertNotComplex(t,"acos");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.acos(n[r]);return ft.make(t.shape,{values:e});},t.prototype.atan=function(t){this.assertNotComplex(t,"atan");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.atan(n[r]);return ft.make(t.shape,{values:e});},t.prototype.atan2=function(t,e){return this.assertNotComplex([t,e],"atan2"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){return Math.atan2(t,e);});},t.prototype.sinh=function(t){this.assertNotComplex(t,"sinh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.sinh(n[r]);return ft.make(t.shape,{values:e});},t.prototype.cosh=function(t){this.assertNotComplex(t,"cosh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.cosh(n[r]);return ft.make(t.shape,{values:e});},t.prototype.tanh=function(t){this.assertNotComplex(t,"tanh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=w(n[r]);return ft.make(t.shape,{values:e});},t.prototype.asinh=function(t){this.assertNotComplex(t,"asinh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.asinh(n[r]);return ft.make(t.shape,{values:e});},t.prototype.acosh=function(t){this.assertNotComplex(t,"acosh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.acosh(n[r]);return ft.make(t.shape,{values:e});},t.prototype.atanh=function(t){this.assertNotComplex(t,"atanh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.atanh(n[r]);return ft.make(t.shape,{values:e});},t.prototype.erf=function(t){this.assertNotComplex(t,"erf");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r){var o=n[r],a=1/(1+.3275911*o);e[r]=1-((((1.061405429*a-1.453152027)*a+1.421413741)*a-.284496736)*a+.254829592)*a*Math.exp(-o*o);}return ft.make(t.shape,{values:e});},t.prototype.step=function(t,e){void 0===e&&(e=0),this.assertNotComplex(t,"step");for(var n=new Float32Array(t.size),r=this.readSync(t.dataId),o=0;o<r.length;++o){var a=r[o];isNaN(a)?n[o]=NaN:n[o]=a>0?1:e;}return ft.make(t.shape,{values:n});},t.prototype.conv2d=function(t,e,n){this.assertNotComplex([t,e],"conv2d");for(var r=n.filterHeight,o=n.filterWidth,a=n.dilationHeight,i=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,l=Xn(n.outShape,t.dtype),c=this.readSync(t.dataId),h=this.readSync(e.dataId),p=l.values,f=0;f<n.batchSize;++f)for(var d=f*t.strides[0],v=f*l.strides[0],m=0;m<n.outHeight;++m)for(var g=v+m*l.strides[1],y=m*n.strideHeight-u,x=0;x<r;x++){var b=y+x*a;if(!(b<0||b>=n.inHeight))for(var w=x*e.strides[0],C=d+b*t.strides[1],E=0;E<n.outWidth;++E)for(var R=g+E*n.outChannels,I=E*n.strideWidth-s,S=0;S<o;S++){var N=I+S*i;if(!(N<0||N>=n.inWidth))for(var k=w+S*e.strides[1],A=C+N*n.inChannels,T=k,D=0;D<n.inChannels;++D){for(var _=c[A+D],O=0;O<n.outChannels;++O)p[R+O]+=_*h[T+O];T+=n.outChannels;}}}return l.toTensor();},t.prototype.conv3d=function(t,e,n){for(var r=n.filterDepth,o=n.filterHeight,a=n.filterWidth,i=n.dilationDepth,s=n.dilationHeight,u=n.dilationWidth,l=n.padInfo.front,c=n.padInfo.left,h=n.padInfo.top,p=Xn(n.outShape,t.dtype),f=this.readSync(t.dataId),d=this.readSync(e.dataId),v=p.values,m=0;m<n.batchSize;++m)for(var g=m*t.strides[0],y=m*p.strides[0],x=0;x<n.outDepth;++x)for(var b=y+x*p.strides[1],w=x*n.strideDepth-l,C=0;C<r;C++){var E=w+C*i;if(!(E<0||E>=n.inDepth))for(var R=C*e.strides[0],I=g+E*t.strides[1],S=0;S<n.outHeight;++S)for(var N=b+S*p.strides[2],k=S*n.strideHeight-h,A=0;A<o;A++){var T=k+A*s;if(!(T<0||T>=n.inHeight))for(var D=R+A*e.strides[1],_=I+T*t.strides[2],O=0;O<n.outWidth;++O)for(var M=N+O*n.outChannels,F=O*n.strideWidth-c,B=0;B<a;B++){var P=F+B*u;if(!(P<0||P>=n.inWidth))for(var L=D+B*e.strides[2],W=_+P*n.inChannels,U=L,z=0;z<n.inChannels;++z){for(var V=f[W+z],G=0;G<n.outChannels;++G)v[M+G]+=V*d[U+G];U+=n.outChannels;}}}}return p.toTensor();},t.prototype.conv2dDerInput=function(t,e,n){this.assertNotComplex([t,e],"conv2dDerInput");for(var r=Xn(n.inShape,"float32"),o=r.values,a=r.strides,i=a[0],s=a[1],u=a[2],l=this.readSync(t.dataId),c=t.strides,h=c[0],p=c[1],f=c[2],d=this.readSync(e.dataId),v=e.strides,m=v[0],g=v[1],y=v[2],x=n.batchSize,b=n.filterHeight,w=n.filterWidth,C=n.inChannels,E=n.inHeight,R=n.inWidth,I=n.outChannels,S=n.outHeight,N=n.outWidth,k=n.strideHeight,A=n.strideWidth,T=b-1-n.padInfo.top,D=w-1-n.padInfo.left,_=0;_<x;++_)for(var O=0;O<C;++O)for(var M=0;M<E;++M)for(var F=M-T,B=Math.max(0,Math.ceil(F/k)),P=Math.min(S,(b+F)/k),L=0;L<R;++L){for(var W=L-D,U=Math.max(0,Math.ceil(W/A)),z=Math.min(N,(w+W)/A),V=0,G=B;G<P;++G)for(var q=G*k-F,H=U;H<z;++H)for(var $=h*_+p*G+f*H,j=m*(b-1-q)+g*(w-1-(H*A-W))+y*O,K=0;K<I;++K){V+=l[$+K]*d[j+K];}o[i*_+s*M+u*L+O]=V;}return r.toTensor();},t.prototype.conv3dDerInput=function(t,e,n){for(var r=Xn(n.inShape,"float32"),o=r.values,a=r.strides,i=a[0],s=a[1],u=a[2],l=a[3],c=this.readSync(t.dataId),h=t.strides,p=h[0],f=h[1],d=h[2],v=h[3],m=this.readSync(e.dataId),g=e.strides,y=g[0],x=g[1],b=g[2],w=g[3],C=n.batchSize,E=n.filterDepth,R=n.filterHeight,I=n.filterWidth,S=n.inChannels,N=n.inDepth,k=n.inHeight,A=n.inWidth,T=n.outChannels,D=n.outDepth,_=n.outHeight,O=n.outWidth,M=n.strideDepth,F=n.strideHeight,B=n.strideWidth,P=E-1-n.padInfo.front,L=R-1-n.padInfo.top,W=I-1-n.padInfo.left,U=0;U<C;++U)for(var z=0;z<S;++z)for(var V=0;V<N;++V)for(var G=V-P,q=Math.max(0,Math.ceil(G/M)),H=Math.min(D,(E+G)/M),$=0;$<k;++$)for(var j=$-L,K=Math.max(0,Math.ceil(j/F)),X=Math.min(_,(R+j)/F),Y=0;Y<A;++Y){for(var Q=Y-W,J=Math.max(0,Math.ceil(Q/B)),Z=Math.min(O,(I+Q)/B),tt=0,et=q;et<H;++et)for(var nt=et*M-G,rt=K;rt<X;++rt)for(var ot=rt*F-j,at=J;at<Z;++at)for(var it=p*U+f*et+d*rt+v*at,st=y*(E-1-nt)+x*(R-1-ot)+b*(I-1-(at*B-Q))+w*z,ut=0;ut<T;++ut){tt+=c[it+ut]*m[st+ut];}o[i*U+s*V+u*$+l*Y+z]=tt;}return r.toTensor();},t.prototype.conv2dDerFilter=function(t,e,n){this.assertNotComplex([t,e],"conv2dDerFilter");for(var r=n.strideHeight,o=n.strideWidth,a=n.filterHeight,i=n.filterWidth,s=Xn(n.filterShape,"float32"),u=n.padInfo.left,l=n.padInfo.top,c=this.bufferSync(t),h=this.bufferSync(e),p=0;p<a;++p)for(var f=Math.max(0,Math.ceil((l-p)/r)),d=Math.min(n.outHeight,(n.inHeight+l-p)/r),v=0;v<i;++v)for(var m=Math.max(0,Math.ceil((u-v)/o)),g=Math.min(n.outWidth,(n.inWidth+u-v)/o),y=0;y<n.inChannels;++y)for(var x=0;x<n.outChannels;++x){for(var b=0,w=0;w<n.batchSize;++w)for(var C=f;C<d;++C)for(var E=p+C*r-l,R=m;R<g;++R){var I=v+R*o-u;b+=c.get(w,E,I,y)*h.get(w,C,R,x);}s.set(b,p,v,y,x);}return s.toTensor();},t.prototype.conv3dDerFilter=function(t,e,n){for(var r=n.strideDepth,o=n.strideHeight,a=n.strideWidth,i=n.filterDepth,s=n.filterHeight,u=n.filterWidth,l=Xn(n.filterShape,"float32"),c=l.values,h=l.strides,p=h[0],f=h[1],d=h[2],v=h[3],m=this.readSync(e.dataId),g=e.strides,y=g[0],x=g[1],b=g[2],w=g[3],C=this.readSync(t.dataId),E=t.strides,R=E[0],I=E[1],S=E[2],N=E[3],k=n.padInfo.front,A=n.padInfo.left,T=n.padInfo.top,D=0;D<i;++D)for(var _=Math.max(0,Math.ceil((k-D)/r)),O=Math.min(n.outDepth,(n.inDepth+k-D)/r),M=D*p,F=0;F<s;++F)for(var B=Math.max(0,Math.ceil((T-F)/o)),P=Math.min(n.outHeight,(n.inHeight+T-F)/o),L=F*f+M,W=0;W<u;++W)for(var U=Math.max(0,Math.ceil((A-W)/a)),z=Math.min(n.outWidth,(n.inWidth+A-W)/a),V=W*d+L,G=0;G<n.inChannels;++G)for(var q=G*v+V,H=0;H<n.outChannels;++H){for(var $=0,j=0;j<n.batchSize;++j)for(var K=j*R,X=j*y,Y=_;Y<O;++Y)for(var Q=(D+Y*r-k)*I+K,J=Y*x+X,Z=B;Z<P;++Z)for(var tt=(F+Z*o-T)*S+Q,et=Z*b+J,nt=U;nt<z;++nt){var rt=nt*w+et;$+=C[(W+nt*a-A)*N+tt+G]*m[rt+H];}c[q+H]=$;}return l.toTensor();},t.prototype.depthwiseConv2D=function(t,e,n){this.assertNotComplex([t,e],"depthwiseConv2D");for(var r=n.filterHeight,o=n.filterWidth,a=n.dilationHeight,i=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,l=n.outChannels/n.inChannels,c=Xn(n.outShape,t.dtype),h=this.readSync(t.dataId),p=this.readSync(e.dataId),f=c.values,d=0;d<n.batchSize;++d)for(var v=d*t.strides[0],m=d*c.strides[0],g=0;g<n.outHeight;++g)for(var y=m+g*c.strides[1],x=g*n.strideHeight-s,b=0;b<r;++b){var w=x+b*a;if(!(w<0||w>=n.inHeight))for(var C=b*e.strides[0],E=v+w*t.strides[1],R=0;R<n.outWidth;++R)for(var I=y+R*c.strides[2],S=R*n.strideWidth-u,N=0;N<o;++N){var k=S+N*i;if(!(k<0||k>=n.inWidth))for(var A=C+N*e.strides[1],T=E+k*n.inChannels,D=I,_=A,O=0;O<n.inChannels;++O){for(var M=h[T+O],F=0;F<l;++F)f[D+F]+=M*p[_+F];D+=l,_+=l;}}}return c.toTensor();},t.prototype.depthwiseConv2DDerInput=function(t,e,n){this.assertNotComplex([t,e],"depthwiseConv2DDerInput");for(var r=Xn(n.inShape,"float32"),o=r.values,a=r.strides,i=a[0],s=a[1],u=a[2],l=this.readSync(t.dataId),c=t.strides,h=c[0],p=c[1],f=c[2],d=this.readSync(e.dataId),v=e.strides,m=v[0],g=v[1],y=v[2],x=n.batchSize,b=n.filterHeight,w=n.filterWidth,C=n.inChannels,E=n.inHeight,R=n.inWidth,I=n.outChannels,S=n.outHeight,N=n.outWidth,k=n.strideHeight,A=n.strideWidth,T=b-1-n.padInfo.top,D=w-1-n.padInfo.left,_=I/C,O=0;O<x;++O)for(var M=0;M<C;++M)for(var F=0;F<E;++F)for(var B=F-T,P=Math.max(0,Math.ceil(B/k)),L=Math.min(S,(b+B)/k),W=0;W<R;++W){for(var U=W-D,z=Math.max(0,Math.ceil(U/A)),V=Math.min(N,(w+U)/A),G=0,q=P;q<L;++q)for(var H=q*k-B,$=z;$<V;++$)for(var j=h*O+p*q+f*$,K=m*(b-1-H)+g*(w-1-($*A-U))+y*M,X=0;X<_;++X){G+=l[j+(M*_+X)]*d[K+X];}o[i*O+s*F+u*W+M]=G;}return r.toTensor();},t.prototype.depthwiseConv2DDerFilter=function(t,e,n){this.assertNotComplex([t,e],"depthwiseConv2DDerFilter");for(var r=n.strideHeight,o=n.strideWidth,a=n.filterHeight,i=n.filterWidth,s=Xn(n.filterShape,"float32"),u=n.padInfo.left,l=n.padInfo.top,c=n.outChannels/n.inChannels,h=this.bufferSync(t),p=this.bufferSync(e),f=0;f<a;++f)for(var d=Math.max(0,Math.ceil((l-f)/r)),v=Math.min(n.outHeight,(n.inHeight+l-f)/r),m=0;m<i;++m)for(var g=Math.max(0,Math.ceil((u-m)/o)),y=Math.min(n.outWidth,(n.inWidth+u-m)/o),x=0;x<n.outChannels;++x){for(var b=Math.trunc(x/c),w=x%c,C=0,E=0;E<n.batchSize;++E)for(var R=d;R<v;++R)for(var I=f+R*r-l,S=g;S<y;++S){var N=m+S*o-u;C+=h.get(E,I,N,b)*p.get(E,R,S,x);}s.set(C,f,m,b,w);}return s.toTensor();},t.prototype.tile=function(t,e){return this.assertNotComplex(t,"tile"),xo(this.bufferSync(t),e);},t.prototype.pad=function(t,e,n){this.assertNotComplex(t,"pad");var r=e.map(function(e,n){return e[0]+t.shape[n]+e[1];}),o=e.map(function(t){return t[0];}),a=this.bufferSync(t),i=Xn(r,t.dtype);0!==n&&i.values.fill(n);for(var s=0;s<t.size;s++){var u=a.indexToLoc(s),l=u.map(function(t,e){return t+o[e];});i.set.apply(i,[a.get.apply(a,u)].concat(l));}return i.toTensor();},t.prototype.transpose=function(t,e){this.assertNotComplex(t,"transpose");for(var n=new Array(t.rank),r=0;r<n.length;r++)n[r]=t.shape[e[r]];var o=this.readSync(t.dataId),a=Xn(n,t.dtype),i=this.bufferSync(t);for(r=0;r<t.size;++r){for(var s=i.indexToLoc(r),u=new Array(s.length),l=0;l<u.length;l++)u[l]=s[e[l]];var c=a.locToIndex(u);a.values[c]=o[r];}return a.toTensor();},t.prototype.gather=function(t,e,n){this.assertNotComplex([t,e],"gather");var r=t.shape.slice(),o=this.readSync(e.dataId);r[n]=o.length;for(var a=Xn(r,t.dtype),i=this.bufferSync(t),s=0;s<a.size;++s){var u=a.indexToLoc(s),l=u.slice();l[n]=o[u[n]];var c=i.locToIndex(l);a.values[s]=i.values[c];}return a.toTensor();},t.prototype.batchToSpaceND=function(t,e,n){this.assertNotComplex([t],"batchToSpaceND");var r=e.reduce(function(t,e){return t*e;}),o=Cr(t.shape,e,r),a=Er(o.length,e.length),i=Rr(t.shape,e,r),s=Ir(n,e.length),u=Sr(i,n,e.length);return t.reshape(o).transpose(a).reshape(i).slice(s,u);},t.prototype.spaceToBatchND=function(t,e,n){this.assertNotComplex([t],"spaceToBatchND");var r=e.reduce(function(t,e){return t*e;}),o=[[0,0]];o.push.apply(o,n);for(var a=1+e.length;a<t.shape.length;++a)o.push([0,0]);var i=t.pad(o),s=Cr(i.shape,e,r,!1),u=Er(s.length,e.length,!1),l=Rr(i.shape,e,r,!1);return i.reshape(s).transpose(u).reshape(l);},t.prototype.pool=function(t,e,n){this.assertNotComplex(t,"pool");for(var r=e.strideHeight,o=e.strideWidth,a=e.dilationHeight,i=e.dilationWidth,s=e.effectiveFilterHeight,u=e.effectiveFilterWidth,l=e.padInfo.top,c=e.padInfo.left,h="max"===n?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,p=this.readSync(t.dataId),f=Xn(e.outShape,t.dtype),d=f.values,v=e.outShape[1]*e.outShape[2]*e.outShape[3],m=e.outShape[2]*e.outShape[3],g=e.outShape[3],y=0;y<e.batchSize;++y)for(var x=y*v,b=y*t.strides[0],w=0;w<e.inChannels;++w)for(var C=0;C<e.outHeight;++C)for(var E=C*r-l,R=Math.max(0,E),I=Math.min(e.inHeight,s+E),S=x+C*m,N=0;N<e.outWidth;++N){for(var k=N*o-c,A=Math.max(0,k),T=Math.min(e.inWidth,u+k),D=h,_=0,O=0,M=R;M<I;M+=a){for(var F=b+M*t.strides[1],B=A;B<T;B+=i){var P=p[F+B*t.strides[2]+w];"max"===n&&P>D?D=P:"avg"===n&&(_+=P,O++);}if(isNaN(D))break;}d[S+N*g+w]="avg"===n?_/O:D;}return f.toTensor();},t.prototype.maxPool=function(t,e){return this.pool(t,e,"max");},t.prototype.maxPoolPositions=function(t,e){for(var n=Xn(e.outShape,"int32"),r=e.strideHeight,o=e.strideWidth,a=e.dilationHeight,i=e.dilationWidth,s=e.effectiveFilterHeight,u=e.effectiveFilterWidth,l=e.padInfo.top,c=e.padInfo.left,h=this.bufferSync(t),p=0;p<e.batchSize;++p)for(var f=0;f<e.inChannels;++f)for(var d=0;d<e.outHeight;++d){for(var v=d*r-l,m=v;m<0;)m+=a;for(var g=Math.min(e.inHeight,s+v),y=0;y<e.outWidth;++y){for(var x=y*o-c,b=x;b<0;)b+=i;for(var w=Math.min(e.inWidth,u+x),C=Number.NEGATIVE_INFINITY,E=-1,R=m;R<g;R+=a)for(var I=R-v,S=b;S<w;S+=i){var N=S-x,k=h.get(p,R,S,f);k>C&&(C=k,E=I*u+N);}n.set(E,p,d,y,f);}}return n.toTensor();},t.prototype.maxPoolBackprop=function(t,e,n,r){this.assertNotComplex([e,n],"maxPoolBackprop");for(var o=this.maxPoolPositions(e,r),a=r.strideHeight,i=r.strideWidth,s=r.dilationHeight,u=r.dilationWidth,l=r.effectiveFilterHeight,c=r.effectiveFilterWidth,h=c-1-r.padInfo.left,p=l-1-r.padInfo.top,f=Xn(e.shape,"float32"),d=this.bufferSync(o),v=this.bufferSync(t),m=0;m<r.batchSize;++m)for(var g=0;g<r.inChannels;++g)for(var y=0;y<r.inHeight;++y)for(var x=0;x<r.inWidth;++x){for(var b=y-p,w=x-h,C=0,E=0;E<l;E+=s){var R=(b+E)/a;if(!(R<0||R>=r.outHeight||Math.floor(R)!==R))for(var I=0;I<c;I+=u){var S=(w+I)/i;if(!(S<0||S>=r.outWidth||Math.floor(S)!==S)){var N=l*c-1-d.get(m,R,S,g)===E*c+I?1:0;if(0!==N)C+=v.get(m,R,S,g)*N;}}}f.set(C,m,y,x,g);}return f.toTensor();},t.prototype.avgPoolBackprop=function(t,e,n){this.assertNotComplex([t,e],"avgPoolBackprop");for(var r=n.strideHeight,o=n.strideWidth,a=n.filterHeight,i=n.filterWidth,s=n.dilationHeight,u=n.dilationWidth,l=n.effectiveFilterHeight,c=n.effectiveFilterWidth,h=c-1-n.padInfo.left,p=l-1-n.padInfo.top,f=Xn(e.shape,"float32"),d=1/(a*i),v=this.bufferSync(t),m=0;m<n.batchSize;++m)for(var g=0;g<n.inChannels;++g)for(var y=0;y<n.inHeight;++y)for(var x=0;x<n.inWidth;++x){for(var b=y-p,w=x-h,C=0,E=0;E<l;E+=s){var R=(b+E)/r;if(!(R<0||R>=n.outHeight||Math.floor(R)!==R))for(var I=0;I<c;I+=u){var S=(w+I)/o;if(!(S<0||S>=n.outWidth||Math.floor(S)!==S))C+=v.get(m,R,S,g);}}f.set(C*d,m,y,x,g);}return f.toTensor();},t.prototype.cast=function(t,e){return so(t,e,this);},t.prototype.reshape=function(t,e){return uo(t,e);},t.prototype.avgPool=function(t,e){return this.assertNotComplex(t,"avgPool"),this.pool(t,e,"avg").toFloat();},t.prototype.resizeBilinear=function(t,e,n,r){this.assertNotComplex(t,"resizeBilinear");for(var o=t.shape,a=o[0],i=o[1],s=o[2],u=o[3],l=this.readSync(t.dataId),c=new Float32Array(y([a,e,n,u])),h=[r&&e>1?i-1:i,r&&n>1?s-1:s],p=[r&&e>1?e-1:e,r&&n>1?n-1:n],f=0,d=h[0]/p[0],v=h[1]/p[1],m=0;m<a;m++)for(var g=0;g<e;g++)for(var x=d*g,b=Math.floor(x),w=x-b,C=Math.min(i-1,Math.ceil(x)),E=m*t.strides[0]+b*t.strides[1],R=m*t.strides[0]+C*t.strides[1],I=0;I<n;I++)for(var S=v*I,N=Math.floor(S),k=S-N,A=Math.min(s-1,Math.ceil(S)),T=E+N*t.strides[2],D=R+N*t.strides[2],_=E+ +A*t.strides[2],O=R+A*t.strides[2],M=0;M<u;M++){var F=l[T+M],B=l[D+M],P=F+(l[_+M]-F)*k,L=P+(B+(l[O+M]-B)*k-P)*w;c[f++]=L;}return mn(c,[a,e,n,u]);},t.prototype.resizeBilinearBackprop=function(t,e,n){this.assertNotComplex([t,e],"resizeBilinearBackprop");for(var r=e.shape,o=r[0],a=r[1],i=r[2],s=r[3],u=t.shape,l=u[1],c=u[2],h=new Float32Array(o*a*i*s),p=[n&&l>1?a-1:a,n&&c>1?i-1:i],f=[n&&l>1?l-1:l,n&&c>1?c-1:c],d=p[0]/f[0],v=p[1]/f[1],m=this.readSync(t.dataId),g=0,y=0;y<o;y++)for(var x=y*e.strides[0],b=0;b<l;b++)for(var w=b*d,C=Math.floor(w),E=Math.min(Math.ceil(w),a-1),R=x+C*e.strides[1],I=x+E*e.strides[1],S=w-C,N=1-S,k=0;k<c;k++)for(var A=k*v,T=Math.floor(A),D=Math.min(Math.ceil(A),i-1),_=A-T,O=1-_,M=R+T*e.strides[2],F=R+D*e.strides[2],B=I+T*e.strides[2],P=I+D*e.strides[2],L=N*O,W=N*_,U=S*O,z=S*_,V=0;V<s;V++){var G=m[g++];h[M+V]+=G*L,h[F+V]+=G*W,h[B+V]+=G*U,h[P+V]+=G*z;}return Cn(h,[o,i,a,s],e.dtype);},t.prototype.resizeNearestNeighbor=function(t,e,n,r){this.assertNotComplex(t,"resizeNearestNeighbor");for(var o=t.shape,a=o[0],i=o[1],s=o[2],u=o[3],l=this.readSync(t.dataId),c=new Float32Array(a*e*n*u),h=[r&&e>1?i-1:i,r&&n>1?s-1:s],p=[r&&e>1?e-1:e,r&&n>1?n-1:n],f=h[0]/p[0],d=h[1]/p[1],v=0,m=0;m<a;m++)for(var g=m*t.strides[0],y=0;y<e;y++)for(var x=f*y,b=g+Math.min(i-1,r?Math.round(x):Math.floor(x))*t.strides[1],w=0;w<n;w++)for(var C=d*w,E=b+Math.min(s-1,r?Math.round(C):Math.floor(C))*t.strides[2],R=0;R<u;R++){var I=l[E+R];c[v++]=I;}return mn(c,[a,e,n,u],t.dtype);},t.prototype.resizeNearestNeighborBackprop=function(t,e,n){this.assertNotComplex([t,e],"resizeNearestNeighborBackprop");for(var r=e.shape,o=r[0],a=r[1],i=r[2],s=r[3],u=t.shape,l=u[1],c=u[2],h=new Float32Array(o*a*i*s),p=this.readSync(t.dataId),f=[n&&l>1?a-1:a,n&&c>1?i-1:i],d=[n&&l>1?l-1:l,n&&c>1?c-1:c],v=f[0]/d[0],m=f[1]/d[1],g=1/v,y=1/m,x=2*Math.ceil(g)+2,b=2*Math.ceil(y)+2,w=0;w<o;w++)for(var C=w*e.strides[0],E=0;E<a;E++)for(var R=C+E*e.strides[1],I=Math.floor(E*g),S=Math.floor(I-x/2),N=0;N<i;N++)for(var k=R+N*e.strides[2],A=Math.floor(N*y),T=Math.floor(A-b/2),D=0;D<s;D++){for(var _=0,O=0;O<x;O++){var M=O+S;if(!(M<0||M>=l)){var F=C+M*t.strides[1],B=M*v;if(E===Math.min(a-1,n?Math.round(B):Math.floor(B)))for(var P=0;P<b;P++){var L=P+T;if(!(L<0||L>=c)){var W=F+L*t.strides[2],U=L*m;N===Math.min(i-1,n?Math.round(U):Math.floor(U))&&(_+=p[W+D]);}}}}h[k+D]=_;}return Cn(h,e.shape,e.dtype);},t.prototype.batchNormalization=function(t,e,n,r,o,a){this.assertNotComplex([t,e,n,o,a],"batchNorm");for(var i=this.readSync(t.dataId),s=this.readSync(e.dataId),u=this.readSync(n.dataId),l=o?this.readSync(o.dataId):new Float32Array([1]),c=a?this.readSync(a.dataId):new Float32Array([0]),h=new Float32Array(i.length),p=c.length,f=l.length,d=u.length,v=s.length,m=0,g=0,y=0,x=0,b=0;b<i.length;++b)h[b]=c[m++]+(i[b]-s[g++])*l[y++]/Math.sqrt(u[x++]+r),m>=p&&(m=0),g>=v&&(g=0),y>=f&&(y=0),x>=d&&(x=0);return Cn(h,t.shape);},t.prototype.localResponseNormalization4D=function(t,e,n,r,o){this.assertNotComplex(t,"localResponseNormalization4D");var a=t.shape[3],i=a-1,s=this.readSync(t.dataId),u=t.size,l=new Float32Array(u);function c(t){for(var n=t%a,r=t-n+Math.max(0,n-e),o=t-n+Math.min(n+e,i),u=0;r<=o;r++){var l=s[r];u+=l*l;}return u;}for(var h=0;h<u;h++){var p=c(h),f=s[h]*Math.pow(n+r*p,-o);l[h]=f;}return Cn(l,t.shape);},t.prototype.LRNGrad=function(t,e,n,r,o,a,i){this.assertNotComplex(t,"LRNGrad");for(var s=t.shape[3],u=this.readSync(t.dataId),l=this.readSync(e.dataId),c=this.readSync(n.dataId),h=new Float32Array(t.size),p=t.size,f=0;f<p;f++){for(var d=f%s,v=f-d+Math.max(0,d-r),m=f-d+Math.min(s,d+r+1),g=0,y=v;y<m;y++)g+=Math.pow(l[y],2);g=a*g+o;for(y=v;y<m;y++){var x=-2*a*i*l[y]*c[f]/g;f===y&&(x+=Math.pow(g,-i)),x*=u[f],h[y]+=x;}}return Cn(h,t.shape);},t.prototype.multinomial=function(t,e,n,r){this.assertNotComplex(t,"multinomial");for(var o=e?t:qr(t),a=o.shape[0],i=o.shape[1],s=Sn([a,n],"int32"),u=this.readSync(s.dataId),l=this.readSync(o.dataId),c=0;c<a;++c){var h=c*i,p=new Float32Array(i-1);p[0]=l[h];for(var f=1;f<p.length;++f)p[f]=p[f-1]+l[h+f];for(var d=$n(r.toString()),v=c*n,m=0;m<n;++m){var g=d();u[v+m]=p.length;for(var y=0;y<p.length;y++)if(g<p[y]){u[v+m]=y;break;}}}return s;},t.prototype.oneHot=function(t,e,n,r){this.assertNotComplex(t,"oneHot");var o=new Float32Array(t.size*e);o.fill(r);for(var a=this.readSync(t.dataId),i=0;i<t.size;++i)a[i]>=0&&a[i]<e&&(o[i*e+a[i]]=n);return bn(o,[t.size,e],"int32");},t.prototype.nonMaxSuppression=function(t,e,n,r,o){return this.assertNotComplex(t,"nonMaxSuppression"),mo(this.readSync(t.dataId),this.readSync(e.dataId),n,r,o);},t.prototype.fft=function(t){return this.fftBatch(t,!1);},t.prototype.ifft=function(t){return this.fftBatch(t,!0);},t.prototype.fftBatch=function(t,e){for(var n=t.shape[0],r=t.shape[1],o=Xn(t.shape,"float32"),a=Xn(t.shape,"float32"),i=dn(t).as2D(n,r),s=vn(t).as2D(n,r),u=0;u<n;u++)for(var l=i.slice([u,0],[1,r]),c=s.slice([u,0],[1,r]),h=fn(l,c),p=this.readSync(this.fftImpl(h,e).dataId),f=0;f<r;f++){var d=po(p,f);o.values[u*r+f]=d.real,a.values[u*r+f]=d.imag;}return fn(o.toTensor(),a.toTensor()).as2D(n,r);},t.prototype.fftImpl=function(t,e){var n=t.as1D(),r=n.size;if(this.isExponentOf2(r)){var o=this.fftRadix2(n,r,e).as2D(t.shape[0],t.shape[1]);return e&&(o=fn(dn(o).div(yn(r)),vn(o).div(yn(r)))),o;}var a=this.readSync(t.dataId),i=function(t){for(var e=new Float32Array(t.length/2),n=new Float32Array(t.length/2),r=0;r<t.length;r+=2)e[r/2]=t[r],n[r/2]=t[r+1];return{real:e,imag:n};}(this.fourierTransformByMatmul(a,r,e));return fn(i.real,i.imag).as2D(t.shape[0],t.shape[1]);},t.prototype.isExponentOf2=function(t){return 0==(t&t-1);},t.prototype.fftRadix2=function(t,e,n){if(1===e)return t;var r=this.readSync(t.dataId),o=e/2,a=function(t){for(var e=Math.ceil(t.length/4),n=new Float32Array(e),r=new Float32Array(e),o=0;o<t.length;o+=4)n[Math.floor(o/4)]=t[o],r[Math.floor(o/4)]=t[o+1];return{real:n,imag:r};}(r),i=fn(a.real,a.imag).as1D(),s=function(t){for(var e=Math.floor(t.length/4),n=new Float32Array(e),r=new Float32Array(e),o=2;o<t.length;o+=4)n[Math.floor(o/4)]=t[o],r[Math.floor(o/4)]=t[o+1];return{real:n,imag:r};}(r),u=fn(s.real,s.imag).as1D();i=this.fftRadix2(i,o,n),u=this.fftRadix2(u,o,n);var l=function(t,e){for(var n=new Float32Array(t/2),r=new Float32Array(t/2),o=0;o<Math.ceil(t/2);o++){var a=(e?2:-2)*Math.PI*(o/t);n[o]=Math.cos(a),r[o]=Math.sin(a);}return{real:n,imag:r};}(e,n),c=fn(l.real,l.imag).mul(u),h=i.add(c),p=i.sub(c),f=dn(h).concat(dn(p)),d=vn(h).concat(vn(p));return fn(f,d).as1D();},t.prototype.fourierTransformByMatmul=function(t,e,n){for(var r=new Float32Array(2*e),o=0;o<e;o++){for(var a=0,i=0,s=0;s<e;s++){var u=vo(o*s,e,n),l=po(t,s);a+=l.real*u.real-l.imag*u.imag,i+=l.real*u.imag+l.imag*u.real;}n&&(a/=e,i/=e),fo(r,a,i,o);}return r;},t.prototype.depthToSpace=function(t,e,n){d("NHWC"===n,function(){return"Only NHWC dataFormat supported on CPU for depthToSpace. Got "+n;}),d(e>1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+e;});for(var r=t.shape[0],o=t.shape[1],a=t.shape[2],i=t.shape[3],s=o*e,u=a*e,l=i/(e*e),c=this.readSync(t.dataId),h=new Float32Array(r*s*u*l),p=0,f=0;f<r;++f)for(var v=0;v<s;++v)for(var m=Math.floor(v/e),g=v%e,y=0;y<u;++y)for(var x=Math.floor(y/e),b=(g*e+y%e)*l,w=0;w<l;++w){var C=w+b+i*(x+a*(m+o*f));h[p++]=c[C];}return Cn(h,[r,s,u,l]);},t.prototype.broadcastedBinaryOp=function(t,e,n,r){var o=Yr(t.shape,e.shape),a=Xn(o,n),i=this.readSync(t.dataId),s=this.readSync(e.dataId),u=Kr(t.shape,o),l=Kr(e.shape,o),c=a.values;if(u.length+l.length===0)for(var h=0;h<c.length;++h)c[h]=r(i[h%i.length],s[h%s.length]);else{var p=this.bufferSync(t),f=this.bufferSync(e),d=function(n){var o=a.indexToLoc(n),h=o.slice(-t.rank);u.forEach(function(t){return h[t]=0;});var d=p.locToIndex(h),v=o.slice(-e.rank);l.forEach(function(t){return v[t]=0;});var m=f.locToIndex(v);c[n]=r(i[d],s[m]);};for(h=0;h<c.length;++h)d(h);}return a.toTensor();},t.prototype.broadcastedBinaryComplexOp=function(t,e,n){var r=Yr(t.shape,e.shape),o=Xn(r,"float32"),a=Xn(r,"float32"),i=this.readSync(t.dataId),s=this.readSync(e.dataId),u=Kr(t.shape,r),l=Kr(e.shape,r),c=o.values,h=a.values;if(u.length+l.length===0)for(var p=0;p<c.length;p++){var f=p%i.length,d=p%s.length,v=n(i[2*f],i[2*f+1],s[2*d],s[2*d+1]);c[p]=v.real,h[p]=v.imag;}else{var m=this.bufferSync(this.data.get(t.dataId).complexTensors.real),g=this.bufferSync(this.data.get(e.dataId).complexTensors.real),y=function(r){var a=o.indexToLoc(r),p=a.slice(-t.rank);u.forEach(function(t){return p[t]=0;});var f=m.locToIndex(p),d=a.slice(-e.rank);l.forEach(function(t){return d[t]=0;});var v=g.locToIndex(d),y=n(i[2*f],i[2*f+1],s[2*v],s[2*v+1]);c[r]=y.real,h[r]=y.imag;};for(p=0;p<c.length;p++)y(p);}return this.complex(o.toTensor(),a.toTensor());},t.prototype.split=function(t,e,n){return yo(t,e,n);},t.prototype.dispose=function(){},t.prototype.floatPrecision=function(){return 32;},t.prototype.epsilon=function(){return 1e-7;},t.prototype.cropAndResize=function(t,e,n,r,o,a){for(var i=t.shape,s=i[0],u=i[1],l=i[2],c=i[3],h=e.shape[0],p=r[0],f=r[1],d=Xn([h,p,f,c],t.dtype),v=this.readSync(e.dataId),m=this.readSync(n.dataId),g=this.readSync(t.dataId),y=t.strides,x=d.strides,b=0;b<h;b++){var w=4*b,C=v[w],E=v[w+1],R=v[w+2],I=v[w+3],S=m[b];if(!(S>=s))for(var N=p>1?(R-C)*(u-1)/(p-1):0,k=f>1?(I-E)*(l-1)/(f-1):0,A=0;A<p;A++){var T=p>1?C*(u-1)+A*N:.5*(C+R)*(u-1);if(T<0||T>u-1)for(var D=0;D<f;D++)for(var _=0;_<c;_++){var O=_+D*x[2]+A*x[1]+b*x[0];d.values[O]=a;}else if("bilinear"===o){var M=Math.floor(T),F=Math.ceil(T),B=T-M;for(D=0;D<f;D++){if((H=f>1?E*(l-1)+D*k:.5*(E+I)*(l-1))<0||H>l-1)for(_=0;_<c;_++){O=_+D*x[2]+A*x[1]+b*x[0];d.values[O]=a;}else{var P=Math.floor(H),L=Math.ceil(H),W=H-P;for(_=0;_<c;_++){var U=g[O=_+P*y[2]+M*y[1]+S*y[0]],z=g[O=_+L*y[2]+M*y[1]+S*y[0]],V=g[O=_+P*y[2]+F*y[1]+S*y[0]],G=U+(z-U)*W,q=V+(g[O=_+L*y[2]+F*y[1]+S*y[0]]-V)*W;O=_+D*x[2]+A*x[1]+b*x[0],d.values[O]=G+(q-G)*B;}}}}else for(D=0;D<f;++D){var H;if((H=f>1?E*(l-1)+D*k:.5*(E+I)*(l-1))<0||H>l-1)for(_=0;_<c;_++){O=_+D*x[2]+A*x[1]+b*x[0];d.values[O]=a;}else{var $=Math.round(H),j=Math.round(T);for(_=0;_<c;_++){var K=_+$*y[2]+j*y[1]+S*y[0],X=_+D*x[2]+A*x[1]+b*x[0];d.values[X]=g[K];}}}}}return d.toTensor();},t.prototype.sparseToDense=function(t,e,n,r){var o=Dr(0,t,n),a=o.sliceRank,i=o.numUpdates,s=o.sliceSize,u=o.strides,l=o.outputSize;return this.scatter(t,e,n,l,s,i,a,u,r,!1);},t.prototype.gatherND=function(t,e){var n=e.shape,r=n[n.length-1],o=Nr(t,e),a=o[0],i=o[1],s=o[2],u=o[3];if(0===i)return mn([],a,t.dtype);for(var l=new lt([i,s],t.dtype),c=this.readSync(e.dataId),h=this.readSync(t.dataId),p=0;p<i;p++){for(var f=[],d=0,v=0;v<r;v++){var m=c[p*r+v];d+=m*u[v],f.push(m);}if(d<0||d>=t.size/s)throw new Error("Invalid indices: "+f+" does not index into "+t.shape);for(var g=0;g<s;g++)l.values[p*s+g]=h[d*s+g];}return l.toTensor().reshape(a);},t.prototype.scatterND=function(t,e,n){var r=Dr(0,t,n),o=r.sliceRank,a=r.numUpdates,i=r.sliceSize,s=r.strides,u=r.outputSize,l=yn(0);return this.scatter(t,e,n,u,i,a,o,s,l,!0);},t.prototype.fill=function(t,e,n){var r=A(n=n||U(e),y(t));return r.fill(e),ft.make(t,{values:r},n);},t.prototype.onesLike=function(t){if("string"===t.dtype)throw new Error("onesLike is not supported for string tensors");return this.fill(t.shape,1,t.dtype);},t.prototype.zerosLike=function(t){var e=A(t.dtype,y(t.shape));return ft.make(t.shape,{values:e},t.dtype);},t.prototype.linspace=function(t,e,n){return lo(t,e,n);},t.prototype.scatter=function(t,e,n,r,o,a,i,s,u,l){var c=[r/o,o],h=this.readSync(t.dataId),p=this.readSync(e.dataId);if(0===r)return mn([],n,e.dtype);var f=new lt(c,e.dtype);f.values.fill(this.readSync(u.dataId)[0]);for(var d=0;d<a;d++){for(var v=[],m=0,g=0;g<i;g++){var y=h[d*i+g];v.push(y),m+=y*s[g];}if(m<0||m>=r/o)throw new Error("Invalid indices: "+v+" does not index into "+n);for(var x=0;x<o;x++)l?f.values[m*o+x]+=p[d*o+x]:f.values[m*o+x]=0===e.rank?p[0]:p[d*o+x];}return f.toTensor().reshape(n);},t;}();Dt.registerBackend("cpu",function(){return new kc();},1);var Ac=function(){function t(){this.textEncoder=new TextEncoder();}return t.prototype.fetch=function(t,e){return fetch(t,e);},t.prototype.now=function(){return performance.now();},t.prototype.encode=function(t,e){if("utf-8"!==e&&"utf8"!==e)throw new Error("Browser's encoder only supports utf-8, but got "+e);return this.textEncoder.encode(t);},t.prototype.decode=function(t,e){return new TextDecoder(e).decode(t);},t;}();exports.ENV.get("IS_BROWSER")&&exports.ENV.setPlatform("browser",new Ac());var Tc,Dc=function(){return require("node-fetch");},_c=function(){function t(){this.util=require("util"),this.textEncoder=new this.util.TextEncoder();}return t.prototype.fetch=function(t,e){return null!=exports.ENV.global.fetch?exports.ENV.global.fetch(t,e):(null==Tc&&(Tc=Dc()),Tc(t,e));},t.prototype.now=function(){var t=process.hrtime();return 1e3*t[0]+t[1]/1e6;},t.prototype.encode=function(t,e){if("utf-8"!==e&&"utf8"!==e)throw new Error("Node built-in encoder only supports utf-8, but got "+e);return this.textEncoder.encode(t);},t.prototype.decode=function(t,e){return 0===t.length?"":new this.util.TextDecoder(e).decode(t);},t;}();exports.ENV.get("IS_NODE")&&exports.ENV.setPlatform("node",new _c());var Oc={float32:4,int32:4,uint16:2,uint8:1,bool:1},Mc=4;function Fc(t,e){for(var n={},r=0,o=function(e){var o=e.name,a=e.dtype,i=e.shape,s=y(i),u=void 0;if(("quantization"in e)){var l=e.quantization;if("uint8"!==l.dtype&&"uint16"!==l.dtype)throw new Error("Weight "+e.name+" has unknown quantization dtype "+l.dtype+". Supported quantization dtypes are: 'uint8' and 'uint16'.");var c=Oc[l.dtype],h=t.slice(r,r+s*c),p="uint8"===l.dtype?new Uint8Array(h):new Uint16Array(h);if("float32"===a)u=Float32Array.from(p,function(t){return t*l.scale+l.min;});else{if("int32"!==a)throw new Error("Unsupported dtype in weight '"+o+"': "+a);u=Int32Array.from(p,function(t){return Math.round(t*l.scale+l.min);});}r+=s*c;}else if("string"===a){var f=y(e.shape);u=[];for(var d=0;d<f;d++){var v=new Uint32Array(t.slice(r,r+Mc))[0];r+=Mc;var m=new Uint8Array(t.slice(r,r+v));u.push(m),r+=v;}}else{var g=Oc[a];h=t.slice(r,r+s*g);if("float32"===a)u=new Float32Array(h);else if("int32"===a)u=new Int32Array(h);else{if("bool"!==a)throw new Error("Unsupported dtype in weight '"+o+"': "+a);u=new Uint8Array(h);}r+=s*g;}n[o]=mn(u,i,a);},a=0,i=e;a<i.length;a++){o(i[a]);}return n;}function Bc(t){if(null===t)throw new Error("Invalid input value: "+JSON.stringify(t));var e=0,n=[];t.forEach(function(t){if(e+=t.byteLength,n.push(t.byteLength===t.buffer.byteLength?t:new t.constructor(t)),!(t instanceof Float32Array||t instanceof Int32Array||t instanceof Uint8Array))throw new Error("Unsupported TypedArray subtype: "+t.constructor.name);});var r=new Uint8Array(e),o=0;return n.forEach(function(t){r.set(new Uint8Array(t.buffer),o),o+=t.byteLength;}),r.buffer;}var Pc="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function Lc(t){return Pc?Buffer.byteLength(t):new Blob([t]).size;}function Wc(t){var e=0;t.forEach(function(t){e+=t.byteLength;});var n=new Uint8Array(e),r=0;return t.forEach(function(t){n.set(new Uint8Array(t),r),r+=t.byteLength;}),n.buffer;}function Uc(t){for(t=t.trim();t.endsWith("/");)t=t.slice(0,t.length-1);var e=t.split("/");return e[e.length-1];}function zc(t){if(t.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date(),modelTopologyType:"JSON",modelTopologyBytes:null==t.modelTopology?0:Lc(JSON.stringify(t.modelTopology)),weightSpecsBytes:null==t.weightSpecs?0:Lc(JSON.stringify(t.weightSpecs)),weightDataBytes:null==t.weightData?0:t.weightData.byteLength};}var Vc=function(){function t(){this.saveRouters=[],this.loadRouters=[];}return t.getInstance=function(){return null==t.instance&&(t.instance=new t()),t.instance;},t.registerSaveRouter=function(e){t.getInstance().saveRouters.push(e);},t.registerLoadRouter=function(e){t.getInstance().loadRouters.push(e);},t.getSaveHandlers=function(e){return t.getHandlers(e,"save");},t.getLoadHandlers=function(e,n){return t.getHandlers(e,"load",n);},t.getHandlers=function(e,n,r){var o=[];return("load"===n?t.getInstance().loadRouters:t.getInstance().saveRouters).forEach(function(t){var n=t(e,r);null!==n&&o.push(n);}),o;},t;}(),Gc="://",qc=function(){function t(){this.managers={};}return t.getInstance=function(){return null==t.instance&&(t.instance=new t()),t.instance;},t.registerManager=function(e,n){d(null!=e,function(){return"scheme must not be undefined or null.";}),e.endsWith(Gc)&&(e=e.slice(0,e.indexOf(Gc))),d(e.length>0,function(){return"scheme must not be an empty string.";});var r=t.getInstance();d(null==r.managers[e],function(){return"A model store manager is already registered for scheme '"+e+"'.";}),r.managers[e]=n;},t.getManager=function(t){var e=this.getInstance().managers[t];if(null==e)throw new Error("Cannot find model manager for scheme '"+t+"'");return e;},t.getSchemes=function(){return Object.keys(this.getInstance().managers);},t;}();function Hc(t){if(-1===t.indexOf(Gc))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+qc.getSchemes().join(","));return{scheme:t.split(Gc)[0],path:t.split(Gc)[1]};}function $c(t,e,n){return void 0===n&&(n=!1),r(this,void 0,void 0,function(){var r,a,i,s,u,l,c,h,p;return o(this,function(o){switch(o.label){case 0:return d(t!==e,function(){return"Old path and new path are the same: '"+t+"'";}),d((r=Vc.getLoadHandlers(t)).length>0,function(){return"Copying failed because no load handler is found for source URL "+t+".";}),d(r.length<2,function(){return"Copying failed because more than one ("+r.length+") load handlers for source URL "+t+".";}),a=r[0],d((i=Vc.getSaveHandlers(e)).length>0,function(){return"Copying failed because no save handler is found for destination URL "+e+".";}),d(i.length<2,function(){return"Copying failed because more than one ("+r.length+") save handlers for destination URL "+e+".";}),s=i[0],u=Hc(t).scheme,l=Hc(t).path,c=u===Hc(t).scheme,[4,a.load()];case 1:return h=o.sent(),n&&c?[4,qc.getManager(u).removeModel(l)]:[3,3];case 2:o.sent(),o.label=3;case 3:return[4,s.save(h)];case 4:return p=o.sent(),!n||c?[3,6]:[4,qc.getManager(u).removeModel(l)];case 5:o.sent(),o.label=6;case 6:return[2,p.modelArtifactsInfo];}});});}var jc="models_store",Kc="model_info_store";function Xc(){if(!exports.ENV.getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");var t=window,e=t.indexedDB||t.mozIndexedDB||t.webkitIndexedDB||t.msIndexedDB||t.shimIndexedDB;if(null==e)throw new Error("The current browser does not appear to support IndexedDB.");return e;}function Yc(t){var e=t.result;e.createObjectStore(jc,{keyPath:"modelPath"}),e.createObjectStore(Kc,{keyPath:"modelPath"});}var Qc=function(){function t(t){if(this.indexedDB=Xc(),null==t||!t)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=t;}return t.prototype.save=function(t){return r(this,void 0,void 0,function(){return o(this,function(e){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return[2,this.databaseAction(this.modelPath,t)];});});},t.prototype.load=function(){return r(this,void 0,void 0,function(){return o(this,function(t){return[2,this.databaseAction(this.modelPath)];});});},t.prototype.databaseAction=function(t,e){var n=this;return new Promise(function(t,r){var o=n.indexedDB.open("tensorflowjs",1);o.onupgradeneeded=function(){return Yc(o);},o.onsuccess=function(){var a=o.result;if(null==e){var i=a.transaction(jc,"readonly"),s=i.objectStore(jc).get(n.modelPath);s.onsuccess=function(){if(null==s.result)return a.close(),r(new Error("Cannot find model with path '"+n.modelPath+"' in IndexedDB."));t(s.result.modelArtifacts);},s.onerror=function(t){return a.close(),r(s.error);},i.oncomplete=function(){return a.close();};}else{var u,l=zc(e),c=a.transaction(Kc,"readwrite"),h=c.objectStore(Kc),p=h.put({modelPath:n.modelPath,modelArtifactsInfo:l});p.onsuccess=function(){var o=(u=a.transaction(jc,"readwrite")).objectStore(jc).put({modelPath:n.modelPath,modelArtifacts:e,modelArtifactsInfo:l});o.onsuccess=function(){return t({modelArtifactsInfo:l});},o.onerror=function(t){var e=(h=c.objectStore(Kc)).delete(n.modelPath);e.onsuccess=function(){return a.close(),r(o.error);},e.onerror=function(t){return a.close(),r(o.error);};};},p.onerror=function(t){return a.close(),r(p.error);},c.oncomplete=function(){null==u?a.close():u.oncomplete=function(){return a.close();};};}},o.onerror=function(t){return r(o.error);};});},t.URL_SCHEME="indexeddb://",t;}(),Jc=function(t){return exports.ENV.getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(Qc.URL_SCHEME)?(e=t.slice(Qc.URL_SCHEME.length),new Qc(e)):null;var e;};Vc.registerSaveRouter(Jc),Vc.registerLoadRouter(Jc);var Zc=function(){function t(){this.indexedDB=Xc();}return t.prototype.listModels=function(){return r(this,void 0,void 0,function(){var t=this;return o(this,function(e){return[2,new Promise(function(e,n){var r=t.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=function(){return Yc(r);},r.onsuccess=function(){var t=r.result,o=t.transaction(Kc,"readonly"),a=o.objectStore(Kc).getAll();a.onsuccess=function(){for(var t={},n=0,r=a.result;n<r.length;n++){var o=r[n];t[o.modelPath]=o.modelArtifactsInfo;}e(t);},a.onerror=function(e){return t.close(),n(a.error);},o.oncomplete=function(){return t.close();};},r.onerror=function(t){return n(r.error);};})];});});},t.prototype.removeModel=function(t){return r(this,void 0,void 0,function(){var e=this;return o(this,function(n){var r;return t=(r=t).startsWith(Qc.URL_SCHEME)?r.slice(Qc.URL_SCHEME.length):r,[2,new Promise(function(n,r){var o=e.indexedDB.open("tensorflowjs",1);o.onupgradeneeded=function(){return Yc(o);},o.onsuccess=function(){var e,a=o.result,i=a.transaction(Kc,"readwrite"),s=i.objectStore(Kc),u=s.get(t);u.onsuccess=function(){if(null==u.result)return a.close(),r(new Error("Cannot find model with path '"+t+"' in IndexedDB."));var o=s.delete(t),i=function(){var o=(e=a.transaction(jc,"readwrite")).objectStore(jc).delete(t);o.onsuccess=function(){return n(u.result.modelArtifactsInfo);},o.onerror=function(t){return r(u.error);};};o.onsuccess=i,o.onerror=function(t){return i(),a.close(),r(u.error);};},u.onerror=function(t){return a.close(),r(u.error);},i.oncomplete=function(){null==e?a.close():e.oncomplete=function(){return a.close();};};},o.onerror=function(t){return r(o.error);};})];});});},t;}();if(exports.ENV.getBool("IS_BROWSER"))try{qc.registerManager(Qc.URL_SCHEME,new Zc());}catch(t){}var th="/",eh="tensorflowjs_models",nh="info",rh="model_topology",oh="weight_specs",ah="weight_data",ih="model_metadata";function sh(t){return{info:[eh,t,nh].join(th),topology:[eh,t,rh].join(th),weightSpecs:[eh,t,oh].join(th),weightData:[eh,t,ah].join(th),modelMetadata:[eh,t,ih].join(th)};}function uh(t){var e=t.split(th);if(e.length<3)throw new Error("Invalid key format: "+t);return e.slice(1,e.length-1).join(th);}var lh=function(){function t(t){if(!exports.ENV.getBool("IS_BROWSER")||void 0===window.localStorage)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,null==t||!t)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=t,this.keys=sh(this.modelPath);}return t.prototype.save=function(t){return r(this,void 0,void 0,function(){var e,n,r;return o(this,function(o){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");e=JSON.stringify(t.modelTopology),n=JSON.stringify(t.weightSpecs),r=zc(t);try{return this.LS.setItem(this.keys.info,JSON.stringify(r)),this.LS.setItem(this.keys.topology,e),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,(a=t.weightData,Pc?Buffer.from(a).toString("base64"):btoa(String.fromCharCode.apply(null,new Uint8Array(a))))),this.LS.setItem(this.keys.modelMetadata,JSON.stringify({format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy})),[2,{modelArtifactsInfo:r}];}catch(t){throw this.LS.removeItem(this.keys.info),this.LS.removeItem(this.keys.topology),this.LS.removeItem(this.keys.weightSpecs),this.LS.removeItem(this.keys.weightData),this.LS.removeItem(this.keys.modelMetadata),new Error("Failed to save model '"+this.modelPath+"' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes="+r.modelTopologyBytes+", weightSpecsBytes="+r.weightSpecsBytes+", weightDataBytes="+r.weightDataBytes+".");}var a;return[2];});});},t.prototype.load=function(){return r(this,void 0,void 0,function(){var t,e,n,r,a,i,s;return o(this,function(o){if(null==(t=JSON.parse(this.LS.getItem(this.keys.info))))throw new Error("In local storage, there is no model with name '"+this.modelPath+"'");if("JSON"!==t.modelTopologyType)throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");if(e={},null==(n=JSON.parse(this.LS.getItem(this.keys.topology))))throw new Error("In local storage, the topology of model '"+this.modelPath+"' is missing.");if(e.modelTopology=n,null==(r=JSON.parse(this.LS.getItem(this.keys.weightSpecs))))throw new Error("In local storage, the weight specs of model '"+this.modelPath+"' are missing.");if(e.weightSpecs=r,null!=(a=this.LS.getItem(this.keys.modelMetadata))&&(i=JSON.parse(a),e.format=i.format,e.generatedBy=i.generatedBy,e.convertedBy=i.convertedBy),null==(s=this.LS.getItem(this.keys.weightData)))throw new Error("In local storage, the binary weight values of model '"+this.modelPath+"' are missing.");return e.weightData=function(t){if(Pc){var e=Buffer.from(t,"base64");return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength);}for(var n=atob(t),r=new Uint8Array(n.length),o=0;o<n.length;++o)r.set([n.charCodeAt(o)],o);return r.buffer;}(s),[2,e];});});},t.URL_SCHEME="localstorage://",t;}(),ch=function(t){return exports.ENV.getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(lh.URL_SCHEME)?(e=t.slice(lh.URL_SCHEME.length),new lh(e)):null;var e;};Vc.registerSaveRouter(ch),Vc.registerLoadRouter(ch);var hh=function(){function t(){d(exports.ENV.getBool("IS_BROWSER"),function(){return"Current environment is not a web browser";}),d(void 0!==window.localStorage,function(){return"Current browser does not appear to support localStorage";}),this.LS=window.localStorage;}return t.prototype.listModels=function(){return r(this,void 0,void 0,function(){var t,e,n,r,a,i;return o(this,function(o){for(t={},e=eh+th,n=th+nh,r=0;r<this.LS.length;++r)(a=this.LS.key(r)).startsWith(e)&&a.endsWith(n)&&(i=uh(a),t[i]=JSON.parse(this.LS.getItem(a)));return[2,t];});});},t.prototype.removeModel=function(t){return r(this,void 0,void 0,function(){var e,n;return o(this,function(r){var o;if(t=(o=t).startsWith(lh.URL_SCHEME)?o.slice(lh.URL_SCHEME.length):o,e=sh(t),null==this.LS.getItem(e.info))throw new Error("Cannot find model at path '"+t+"'");return n=JSON.parse(this.LS.getItem(e.info)),this.LS.removeItem(e.info),this.LS.removeItem(e.topology),this.LS.removeItem(e.weightSpecs),this.LS.removeItem(e.weightData),[2,n];});});},t;}();if(exports.ENV.getBool("IS_BROWSER"))try{qc.registerManager(lh.URL_SCHEME,new hh());}catch(t){}var ph="model",fh=".json",dh=".weights.bin";function vh(t){return new Promise(function(t){return setTimeout(t);}).then(t);}var mh=function(){function t(e){if(!exports.ENV.getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(t.URL_SCHEME)&&(e=e.slice(t.URL_SCHEME.length)),null!=e&&0!==e.length||(e=ph),this.modelTopologyFileName=e+fh,this.weightDataFileName=e+dh;}return t.prototype.save=function(t){return r(this,void 0,void 0,function(){var e,n,r,a,i,s;return o(this,function(o){switch(o.label){case 0:if("undefined"==typeof document)throw new Error("Browser downloads are not supported in this environment since `document` is not present");if(e=window.URL.createObjectURL(new Blob([t.weightData],{type:"application/octet-stream"})),!(t.modelTopology instanceof ArrayBuffer))return[3,1];throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");case 1:return n=[{paths:["./"+this.weightDataFileName],weights:t.weightSpecs}],r={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,weightsManifest:n},a=window.URL.createObjectURL(new Blob([JSON.stringify(r)],{type:"application/json"})),(i=null==this.jsonAnchor?document.createElement("a"):this.jsonAnchor).download=this.modelTopologyFileName,i.href=a,[4,vh(function(){return i.dispatchEvent(new MouseEvent("click"));})];case 2:return o.sent(),null==t.weightData?[3,4]:((s=null==this.weightDataAnchor?document.createElement("a"):this.weightDataAnchor).download=this.weightDataFileName,s.href=e,[4,vh(function(){return s.dispatchEvent(new MouseEvent("click"));})]);case 3:o.sent(),o.label=4;case 4:return[2,{modelArtifactsInfo:zc(t)}];}});});},t.URL_SCHEME="downloads://",t;}(),gh=function(){function t(t){if(null==t||t.length<1)throw new Error("When calling browserFiles, at least 1 file is required, but received "+t);this.files=t;}return t.prototype.load=function(){return r(this,void 0,void 0,function(){var t,e,n=this;return o(this,function(r){return t=this.files[0],e=this.files.slice(1),[2,new Promise(function(r,o){var a=new FileReader();a.onload=function(a){var i=JSON.parse(a.target.result),s=i.modelTopology;if(null!=s){0===e.length&&r({modelTopology:s});var u=i.weightsManifest;if(null!=u){var l;try{l=n.checkManifestAndWeightFiles(u,e);}catch(t){return void o(t);}var c=[],h=[],p=[];u.forEach(function(t){t.paths.forEach(function(t){h.push(t),p.push(null);}),c.push.apply(c,t.weights);}),u.forEach(function(t){t.paths.forEach(function(t){var e=new FileReader();e.onload=function(e){var n=e.target.result,o=h.indexOf(t);p[o]=n,-1===p.indexOf(null)&&r({modelTopology:s,weightSpecs:c,weightData:Wc(p)});},e.onerror=function(e){return o("Failed to weights data from file of path '"+t+"'.");},e.readAsArrayBuffer(l[t]);});});}else o(new Error("weightManifest field is missing from file "+t.name));}else o(new Error("modelTopology field is missing from file "+t.name));},a.onerror=function(e){return o("Failed to read model topology and weights manifest JSON from file '"+t.name+"'. BrowserFiles supports loading Keras-style tf.Model artifacts only.");},a.readAsText(t);})];});});},t.prototype.checkManifestAndWeightFiles=function(t,e){for(var n=[],r=e.map(function(t){return Uc(t.name);}),o={},a=0,i=t;a<i.length;a++){i[a].paths.forEach(function(t){var a=Uc(t);if(-1!==n.indexOf(a))throw new Error("Duplicate file basename found in weights manifest: '"+a+"'");if(n.push(a),-1===r.indexOf(a))throw new Error("Weight file with basename '"+a+"' is not provided.");o[t]=e[r.indexOf(a)];});}if(n.length!==e.length)throw new Error("Mismatch in the number of files in weights manifest ("+n.length+") and the number of weight files provided ("+e.length+").");return o;},t;}();function yh(t,e,n,r){!function(t){d(null!=t&&Array.isArray(t)&&t.length>0,function(){return"promises must be a none empty array";});}(t),function(t,e){d(t>=0&&t<=1,function(){return"Progress fraction must be in range [0, 1], but got startFraction "+t;}),d(e>=0&&e<=1,function(){return"Progress fraction must be in range [0, 1], but got endFraction "+e;}),d(e>=t,function(){return"startFraction must be no more than endFraction, but got startFraction "+t+" and endFraction "+e;});}(n=null==n?0:n,r=null==r?1:r);var o=0;return Promise.all(t.map(function(a){return a.then(function(a){var i=n+ ++o/t.length*(r-n);return e(i),a;}),a;}));}function xh(t,e){return r(this,void 0,void 0,function(){var n,r,a,i,s,u,l,c,h,p;return o(this,function(o){switch(o.label){case 0:return null==e&&(e={}),n=null==e.fetchFunc?Y:e.fetchFunc,(r=Object.assign({},e.requestInit)).headers=Object.assign({},r.headers,{responseType:"arraybuffer"}),a=t.map(function(t){return n(t,r);}),i=0,s=.5,null!=e.onProgress?[3,2]:[4,Promise.all(a)];case 1:return u=o.sent(),[3,4];case 2:return[4,yh(a,e.onProgress,i,s)];case 3:u=o.sent(),o.label=4;case 4:return l=u.map(function(t){return t.arrayBuffer();}),c=.5,h=1,null!=e.onProgress?[3,6]:[4,Promise.all(l)];case 5:return p=o.sent(),[3,8];case 6:return[4,yh(l,e.onProgress,c,h)];case 7:p=o.sent(),o.label=8;case 8:return[2,p];}});});}function bh(t){var e=this;return function(n,a,i){return void 0===a&&(a=""),r(e,void 0,void 0,function(){var e,r,s,u,l,c,h,p,f,d;return o(this,function(o){switch(o.label){case 0:if(e=n.map(function(){return!1;}),r={},s=null!=i?i.map(function(){return!1;}):[],u=[],n.forEach(function(t,n){var o=0;t.weights.forEach(function(t){var a="quantization"in t?t.quantization.dtype:t.dtype,l=Oc[a]*y(t.shape),c=function(){e[n]=!0,null==r[n]&&(r[n]=[]),r[n].push({manifestEntry:t,groupOffset:o,sizeBytes:l});};null!=i?i.forEach(function(e,n){e===t.name&&(c(),s[n]=!0);}):c(),u.push(t.name),o+=l;});}),!s.every(function(t){return t;}))throw l=i.filter(function(t,e){return!s[e];}),new Error("Could not find weights in manifest with names: "+l.join(", ")+". \nManifest JSON has weights with names: "+u.join(", ")+".");return c=e.reduce(function(t,e,n){return e&&t.push(n),t;},[]),h=[],c.forEach(function(t){n[t].paths.forEach(function(t){var e=a+(a.endsWith("/")?"":"/")+t;h.push(e);});}),[4,t(h)];case 1:return p=o.sent(),f={},d=0,c.forEach(function(t){for(var e=n[t].paths.length,o=0,a=0;a<e;a++)o+=p[d+a].byteLength;for(var i=new ArrayBuffer(o),s=new Uint8Array(i),u=0,l=0;l<e;l++){var c=new Uint8Array(p[d+l]);s.set(c,u),u+=c.byteLength;}r[t].forEach(function(t){var e=Fc(i.slice(t.groupOffset,t.groupOffset+t.sizeBytes),[t.manifestEntry]);for(var n in e)f[n]=e[n];}),d+=e;}),[2,f];}});});};}Vc.registerSaveRouter(function(t){return exports.ENV.getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(mh.URL_SCHEME)?(e=t.slice(mh.URL_SCHEME.length),void 0===e&&(e="model"),new mh(e)):null;var e;});var wh=function(){function t(t,e){if(this.DEFAULT_METHOD="POST",null==e&&(e={}),this.weightPathPrefix=e.weightPathPrefix,this.onProgress=e.onProgress,null!=e.fetchFunc?(d("function"==typeof e.fetchFunc,function(){return"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)";}),this.fetch=e.fetchFunc):this.fetch=Y,d(null!=t&&t.length>0,function(){return"URL path for http must not be null, undefined or empty.";}),Array.isArray(t)&&d(2===t.length,function(){return"URL paths for http must have a length of 2, (actual length is "+t.length+").";}),this.path=t,null!=e.requestInit&&null!=e.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=e.requestInit||{};}return t.prototype.save=function(t){return r(this,void 0,void 0,function(){var e,n,r,a;return o(this,function(o){switch(o.label){case 0:if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return(e=Object.assign({method:this.DEFAULT_METHOD},this.requestInit)).body=new FormData(),n=[{paths:["./model.weights.bin"],weights:t.weightSpecs}],r={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,weightsManifest:n},e.body.append("model.json",new Blob([JSON.stringify(r)],{type:"application/json"}),"model.json"),null!=t.weightData&&e.body.append("model.weights.bin",new Blob([t.weightData],{type:"application/octet-stream"}),"model.weights.bin"),[4,this.fetch(this.path,e)];case 1:if((a=o.sent()).ok)return[2,{modelArtifactsInfo:zc(t),responses:[a]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+a.status+".");}});});},t.prototype.load=function(){return r(this,void 0,void 0,function(){var t,e,n,r,a,i,s,u;return o(this,function(o){switch(o.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(!(t=o.sent()).ok)throw new Error("Request to "+this.path+" failed with status code "+t.status+". Please verify this URL points to the model JSON of the model to load.");o.label=2;case 2:return o.trys.push([2,4,,5]),[4,t.json()];case 3:return e=o.sent(),[3,5];case 4:throw o.sent(),n="Failed to parse model JSON of response from "+this.path+".",this.path.endsWith(".pb")?n+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":n+=" Please make sure the server is serving valid JSON for this request.",new Error(n);case 5:if(r=e.modelTopology,a=e.weightsManifest,null==r&&null==a)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return null==a?[3,7]:[4,this.loadWeights(a)];case 6:u=o.sent(),i=u[0],s=u[1],o.label=7;case 7:return[2,{modelTopology:r,weightSpecs:i,weightData:s}];}});});},t.prototype.loadWeights=function(t){return r(this,void 0,void 0,function(){var e,n,r,a,i,s,u,l,c,h,p;return o(this,function(o){switch(o.label){case 0:for(e=Array.isArray(this.path)?this.path[1]:this.path,n=function(t){var e=t.lastIndexOf("/"),n=t.lastIndexOf("?"),r=t.substring(0,e),o=n>e?t.substring(n):"";return[r+"/",o];}(e),r=n[0],a=n[1],i=this.weightPathPrefix||r,s=[],u=0,l=t;u<l.length;u++)c=l[u],s.push.apply(s,c.weights);return h=[],t.forEach(function(t){t.paths.forEach(function(t){h.push(i+t+a);});}),[4,xh(h,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress})];case 1:return p=o.sent(),[2,[s,Wc(p)]];}});});},t.URL_SCHEME_REGEX=/^https?:\/\//,t;}();function Ch(t){return null!=t.match(wh.URL_SCHEME_REGEX);}var Eh=function(t,e){return(Array.isArray(t)?t.every(function(t){return Ch(t);}):Ch(t))?Rh(t,{onProgress:e}):null;};function Rh(t,e){return new wh(t,e);}Vc.registerSaveRouter(Eh),Vc.registerLoadRouter(Eh);var Ih=function(){function t(t,e,n,r){this.modelTopology=t,this.weightSpecs=e,this.weightData=n,this.trainingConfig=r;}return t.prototype.load=function(){return r(this,void 0,void 0,function(){var t;return o(this,function(e){return t={},null!=this.modelTopology&&(t=n({modelTopology:this.modelTopology},t)),null!=this.weightSpecs&&this.weightSpecs.length>0&&(t=n({weightSpecs:this.weightSpecs},t)),null!=this.weightData&&this.weightData.byteLength>0&&(t=n({weightData:this.weightData},t)),null!=this.trainingConfig&&(t=n({trainingConfig:this.trainingConfig},t)),[2,t];});});},t;}(),Sh=function(){function t(t){this.saveHandler=t;}return t.prototype.save=function(t){return r(this,void 0,void 0,function(){return o(this,function(e){return[2,this.saveHandler(t)];});});},t;}();var Nh=Object.freeze({browserFiles:function(t){return new gh(t);},browserHTTPRequest:function(t,e){return Rh(t,e);},concatenateArrayBuffers:Wc,decodeWeights:Fc,encodeWeights:function(t,e){return r(this,void 0,void 0,function(){var n,a,i,s,u,l=this;return o(this,function(c){switch(c.label){case 0:for(n=[],a=[],i=Array.isArray(t)?t.map(function(t){return t.name;}):Object.keys(t),s=function(s){var u=i[s],c=Array.isArray(t)?t[s].tensor:t[u];if("float32"!==c.dtype&&"int32"!==c.dtype&&"bool"!==c.dtype&&"string"!==c.dtype)throw new Error("Unsupported dtype in weight '"+u+"': "+c.dtype);var h={name:u,shape:c.shape,dtype:c.dtype};if("string"===c.dtype){var p=new Promise(function(t){return r(l,void 0,void 0,function(){var e,n,r,a,i,s,u;return o(this,function(o){switch(o.label){case 0:return[4,c.bytes()];case 1:for(e=o.sent(),n=e.reduce(function(t,e){return t+e.length;},0)+Mc*e.length,r=new Uint8Array(n),a=0,i=0;i<e.length;i++)s=e[i],u=new Uint8Array(new Uint32Array([s.length]).buffer),r.set(u,a),a+=Mc,r.set(s,a),a+=s.length;return t(r),[2];}});});});a.push(p);}else a.push(c.data());null!=e&&(h.group=e),n.push(h);},u=0;u<i.length;++u)s(u);return[4,Promise.all(a)];case 1:return[2,{data:Bc(c.sent()),specs:n}];}});});},fromMemory:function(t,e,n,r){return new Ih(t,e,n,r);},getLoadHandlers:function(t,e){return Vc.getLoadHandlers(t,e);},getModelArtifactsInfoForJSON:zc,getSaveHandlers:function(t){return Vc.getSaveHandlers(t);},http:Rh,isHTTPScheme:Ch,loadWeights:function(t,e,n,a){return void 0===e&&(e=""),r(this,void 0,void 0,function(){return o(this,function(r){return[2,bh(function(t){return xh(t,{requestInit:a});})(t,e,n)];});});},registerLoadRouter:function(t){return Vc.registerLoadRouter(t);},registerSaveRouter:function(t){return Vc.registerSaveRouter(t);},weightsLoaderFactory:bh,withSaveHandler:function(t){return new Sh(t);},copyModel:function(t,e){return r(this,void 0,void 0,function(){return o(this,function(n){return[2,$c(t,e,!1)];});});},listModels:function(){return r(this,void 0,void 0,function(){var t,e,n,r,a,i,s;return o(this,function(o){switch(o.label){case 0:t=qc.getSchemes(),e={},n=0,r=t,o.label=1;case 1:return n<r.length?(a=r[n],[4,qc.getManager(a).listModels()]):[3,4];case 2:for(s in i=o.sent())e[a+Gc+s]=i[s];o.label=3;case 3:return n++,[3,1];case 4:return[2,e];}});});},moveModel:function(t,e){return r(this,void 0,void 0,function(){return o(this,function(n){return[2,$c(t,e,!0)];});});},removeModel:function(t){return r(this,void 0,void 0,function(){var e;return o(this,function(n){return e=Hc(t),[2,qc.getManager(e.scheme).removeModel(e.path)];});});}});var kh=pn({confusionMatrix_:function(t,e,n){var r=Ze(t,"labels","confusionMatrix"),o=Ze(e,"predictions","confusionMatrix");d(null==n||n>0&&Number.isInteger(n),function(){return"If provided, numClasses must be a positive integer, but got "+n;}),d(1===r.rank,function(){return"Expected the rank of labels to be 1, but got "+r.rank;}),d(1===o.rank,function(){return"Expected the rank of predictions to be 1, but got "+o.rank;}),d(r.shape[0]===o.shape[0],function(){return"Mismatch in the number of examples: "+r.shape[0]+" vs. "+o.shape[0]+". Labels and predictions should have the same number of elements.";}),d(n>0&&Number.isInteger(n),function(){return"numClasses is required to be a positive integer, but got "+n;});var a=ar(r.asType("int32"),n),i=ar(o.asType("int32"),n);return a.transpose().matMul(i).asType("int32");}}),Ah=Object.freeze({confusionMatrix:kh});var Th=pn({fromPixels_:function(t,e){if(void 0===e&&(e=3),e>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");return Dt.fromPixels(t,e);}}),Dh=Object.freeze({toPixels:function(t,e){return r(this,void 0,void 0,function(){var n,r,a,i,s,u,l,c,h,p,f,d,v,m,g,y,x,b,w,C,E,R,I;return o(this,function(o){switch(o.label){case 0:if(n=Ze(t,"img","toPixels"),t instanceof ft||(n=n.toInt()),2!==n.rank&&3!==n.rank)throw new Error("toPixels only supports rank 2 or 3 tensors, got rank "+n.rank+".");if(r=n.shape.slice(0,2),a=r[0],i=r[1],(s=2===n.rank?1:n.shape[2])>4||2===s)throw new Error("toPixels only supports depth of size 1, 3 or 4 but got "+s);return[4,n.data()];case 1:return u=o.sent(),l=n.min(),c=n.max(),[4,Promise.all([l.data(),c.data()])];case 2:if(h=o.sent(),p=h[0],f=h[1],d=p[0],v=f[0],l.dispose(),c.dispose(),"float32"===n.dtype){if(d<0||v>1)throw new Error("Tensor values for a float32 Tensor must be in the range [0 - 1] but got range ["+d+" - "+v+"].");}else{if("int32"!==n.dtype)throw new Error("Unsupported type for toPixels: "+n.dtype+". Please use float32 or int32 tensors.");if(d<0||v>255)throw new Error("Tensor values for a int32 Tensor must be in the range [0 - 255] but got range ["+d+" - "+v+"].");}for(m="float32"===n.dtype?255:1,g=new Uint8ClampedArray(i*a*4),y=0;y<a*i;++y)x=void 0,b=void 0,w=void 0,C=void 0,1===s?(x=u[y]*m,b=u[y]*m,w=u[y]*m,C=255):3===s?(x=u[3*y]*m,b=u[3*y+1]*m,w=u[3*y+2]*m,C=255):4===s&&(x=u[4*y]*m,b=u[4*y+1]*m,w=u[4*y+2]*m,C=u[4*y+3]*m),g[0+(E=4*y)]=Math.round(x),g[E+1]=Math.round(b),g[E+2]=Math.round(w),g[E+3]=Math.round(C);return null!=e&&(e.width=i,e.height=a,R=e.getContext("2d"),I=new ImageData(g,i,a),R.putImageData(I,0,0)),n!==t&&n.dispose(),[2,g];}});});},fromPixels:Th}),_h=function(){function t(){}return t.prototype.getClassName=function(){return this.constructor.className;},t.fromConfig=function(t,e){return new t(e);},t;}(),Oh=function(){function t(){this.classNameMap={};}return t.getMap=function(){return null==t.instance&&(t.instance=new t()),t.instance;},t.register=function(e){t.getMap().classNameMap[e.className]=[e,e.fromConfig];},t;}();function Mh(t){d(null!=t.className,function(){return"Class being registered does not have the static className property defined.";}),d("string"==typeof t.className,function(){return"className is required to be a string, but got type "+typeof t.className;}),d(t.className.length>0,function(){return"Class being registered has an empty-string as its className, which is disallowed.";}),Oh.register(t);}var Fh=Object.freeze({Serializable:_h,SerializationMap:Oh,registerClass:Mh}),Bh=.001,Ph=.1;function Lh(){return 32===Dt.backend.floatPrecision()?Bh:Ph;}function Wh(t,e,n){var r=!0;if((M(t)||M(e))&&(r=!1),M(t)&&M(e)&&(r=!0),r){var o=t.constructor.name,a=e.constructor.name;if(o!==a)throw new Error("Arrays are of different type. Actual: "+o+". Expected: "+a);}if(Array.isArray(t)&&Array.isArray(e)){var i=Qe(t),s=Qe(e);if(!x(i,s))throw new Error("Arrays have different shapes. Actual: ["+i+"]. Expected: ["+s+"]");}var u=M(t)?t:g(t),l=M(e)?e:g(e);if(u.length!==l.length)throw new Error("Arrays have different lengths actual: "+u.length+" vs expected: "+l.length+".\nActual:   "+u+".\nExpected: "+l+".");for(var c=0;c<l.length;++c){var h=u[c],p=l[c];if(!n(h,p))throw new Error("Arrays differ: actual["+c+"] = "+h+", expected["+c+"] = "+p+".\nActual:   "+u+".\nExpected: "+l+".");}}function Uh(t,e,n){return!isFinite(t)&&!isFinite(e)||!(isNaN(t)||isNaN(e)||Math.abs(t-e)>n);}var zh=Object.freeze({TEST_EPSILON_FLOAT16:Ph,expectArraysClose:function(t,e,n){return null==n&&(n=Lh()),Wh(t,e,function(t,e){return Uh(t,e,n);});},testEpsilon:Lh,expectPromiseToFail:function(t,e){t().then(function(){return e.fail();},function(){return e();});},expectArraysEqual:function(t,e){var n="string"==typeof e||"number"==typeof e||"boolean"==typeof e?[e]:e;return P(t)||P(t[0])||P(e)||P(e[0])?Wh(t,n,function(t,e){return t==e;}):Wh(t,e,function(t,e){return Uh(t,e,0);});},expectNumbersClose:function(t,e,n){if(null==n&&(n=Lh()),!Uh(t,e,n))throw new Error("Numbers differ: actual === "+t+", expected === "+e);},expectValuesInRange:function(t,e,n){for(var r=0;r<t.length;r++)if(t[r]<e||t[r]>n)throw new Error("Value out of range:"+t[r]+" low: "+e+", high: "+n);},expectArrayBuffersEqual:function(t,e){expect(new Float32Array(t)).toEqual(new Float32Array(e));}}),Vh="1.2.3",Gh=Object.freeze({gpgpu_util:ri,webgl_util:Ae,MathBackendWebGL:as,setWebGLContext:Ft,GPGPUContext:oi}),qh=function(t){function n(){return null!==t&&t.apply(this,arguments)||this;}return e(n,t),n.prototype.minimize=function(t,e,n){void 0===e&&(e=!1);var r=this.computeGradients(t,n),o=r.value,a=r.grads;if(null!=n){var i=n.map(function(t){return{name:t.name,tensor:a[t.name]};});this.applyGradients(i);}else this.applyGradients(a);return Le(a),e?o:(o.dispose(),null);},Object.defineProperty(n.prototype,"iterations",{get:function(){return null==this.iterations_&&(this.iterations_=0),this.iterations_;},enumerable:!0,configurable:!0}),n.prototype.incrementIterations=function(){this.iterations_=this.iterations+1;},n.prototype.computeGradients=function(t,e){return zr(t,e);},n.prototype.dispose=function(){null!=this.iterations_&&Le(this.iterations_);},n.prototype.saveIterations=function(){return r(this,void 0,void 0,function(){return o(this,function(t){return null==this.iterations_&&(this.iterations_=0),[2,{name:"iter",tensor:yn(this.iterations_,"int32")}];});});},n.prototype.getWeights=function(){return r(this,void 0,void 0,function(){return o(this,function(t){throw new Error("getWeights() is not implemented for this optimizer yet.");});});},n.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){return o(this,function(t){throw new Error("setWeights() is not implemented for this optimizer class "+this.getClassName());});});},n.prototype.extractIterations=function(t){return r(this,void 0,void 0,function(){var e;return o(this,function(n){switch(n.label){case 0:return e=this,[4,t[0].tensor.data()];case 1:return e.iterations_=n.sent()[0],[2,t.slice(1)];}});});},n;}(_h);Object.defineProperty(qh,Symbol.hasInstance,{value:function(t){return null!=t.minimize&&null!=t.computeGradients&&null!=t.applyGradients;}});var Hh=function(t){function n(e,n,r){void 0===r&&(r=null);var o=t.call(this)||this;return o.learningRate=e,o.rho=n,o.epsilon=r,o.accumulatedGrads=[],o.accumulatedUpdates=[],null==r&&(o.epsilon=Dt.backend.epsilon()),o;}return e(n,t),n.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map(function(t){return t.name;}):Object.keys(t)).forEach(function(n,r){var o=Dt.registeredVariables[n];null==e.accumulatedGrads[r]&&(e.accumulatedGrads[r]={originalName:n+"/accum_grad",variable:Pe(function(){return Dn(o).variable(!1);})}),null==e.accumulatedUpdates[r]&&(e.accumulatedUpdates[r]={originalName:n+"/accum_var",variable:Pe(function(){return Dn(o).variable(!1);})});var a=Array.isArray(t)?t[r].tensor:t[n];if(null!=a){var i=e.accumulatedGrads[r].variable,s=e.accumulatedUpdates[r].variable;Pe(function(){var t=i.mul(e.rho).add(a.square().mul(1-e.rho)),n=s.add(e.epsilon).sqrt().div(i.add(e.epsilon).sqrt()).mul(a),r=s.mul(e.rho).add(n.square().mul(1-e.rho));i.assign(t),s.assign(r);var u=n.mul(-e.learningRate).add(o);o.assign(u);});}}),this.incrementIterations();},n.prototype.dispose=function(){null!=this.accumulatedUpdates&&(Le(this.accumulatedGrads.map(function(t){return t.variable;})),Le(this.accumulatedUpdates.map(function(t){return t.variable;})));},n.prototype.getWeights=function(){return r(this,void 0,void 0,function(){var t;return o(this,function(e){switch(e.label){case 0:return t=this.accumulatedGrads.concat(this.accumulatedUpdates),[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(t.map(function(t){return{name:t.originalName,tensor:t.variable};}))];}});});},n.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){var e;return o(this,function(n){switch(n.label){case 0:return[4,this.extractIterations(t)];case 1:return t=n.sent(),e=t.length/2,this.accumulatedGrads=t.slice(0,e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)};}),this.accumulatedUpdates=t.slice(e,2*e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)};}),[2];}});});},n.prototype.getConfig=function(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon};},n.fromConfig=function(t,e){return new t(e.learningRate,e.rho,e.epsilon);},n.className="AdadeltaOptimizer",n;}(qh);Mh(Hh);var $h=function(t){function n(e,n){void 0===n&&(n=.1);var r=t.call(this)||this;return r.learningRate=e,r.initialAccumulatorValue=n,r.accumulatedGrads=[],r;}return e(n,t),n.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map(function(t){return t.name;}):Object.keys(t)).forEach(function(n,r){var o=Dt.registeredVariables[n];if(null==e.accumulatedGrads[r]){e.accumulatedGrads[r]={originalName:n+"/accumulator",variable:Pe(function(){return Nn(o.shape,e.initialAccumulatorValue).variable(!1);})};}var a=Array.isArray(t)?t[r].tensor:t[n];if(null!=a){var i=e.accumulatedGrads[r].variable;Pe(function(){var t=i.add(a.square());i.assign(t);var n=a.div(t.add(Dt.backend.epsilon()).sqrt()).mul(-e.learningRate).add(o);o.assign(n);});}}),this.incrementIterations();},n.prototype.dispose=function(){null!=this.accumulatedGrads&&Le(this.accumulatedGrads.map(function(t){return t.variable;}));},n.prototype.getWeights=function(){return r(this,void 0,void 0,function(){return o(this,function(t){switch(t.label){case 0:return[4,this.saveIterations()];case 1:return[2,[t.sent()].concat(this.accumulatedGrads.map(function(t){return{name:t.originalName,tensor:t.variable};}))];}});});},n.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){return o(this,function(e){switch(e.label){case 0:return[4,this.extractIterations(t)];case 1:return t=e.sent(),this.accumulatedGrads=t.map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)};}),[2];}});});},n.prototype.getConfig=function(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue};},n.fromConfig=function(t,e){return new t(e.learningRate,e.initialAccumulatorValue);},n.className="Adagrad",n;}(qh);Mh($h);var jh=function(t){function n(e,n,r,o){void 0===o&&(o=null);var a=t.call(this)||this;return a.learningRate=e,a.beta1=n,a.beta2=r,a.epsilon=o,a.accumulatedFirstMoment=[],a.accumulatedSecondMoment=[],Pe(function(){a.accBeta1=yn(n).variable(),a.accBeta2=yn(r).variable();}),null==o&&(a.epsilon=Dt.backend.epsilon()),a;}return e(n,t),n.prototype.applyGradients=function(t){var e=this,n=Array.isArray(t)?t.map(function(t){return t.name;}):Object.keys(t);Pe(function(){var r=yl(1,e.accBeta1),o=yl(1,e.accBeta2);n.forEach(function(n,a){var i=Dt.registeredVariables[n];null==e.accumulatedFirstMoment[a]&&(e.accumulatedFirstMoment[a]={originalName:n+"/m",variable:Pe(function(){return Dn(i).variable(!1);})}),null==e.accumulatedSecondMoment[a]&&(e.accumulatedSecondMoment[a]={originalName:n+"/v",variable:Pe(function(){return Dn(i).variable(!1);})});var s=Array.isArray(t)?t[a].tensor:t[n];if(null!=s){var u=e.accumulatedFirstMoment[a].variable,l=e.accumulatedSecondMoment[a].variable,c=u.mul(e.beta1).add(s.mul(1-e.beta1)),h=l.mul(e.beta2).add(s.square().mul(1-e.beta2)),p=c.div(r),f=h.div(o);u.assign(c),l.assign(h);var d=p.div(f.sqrt().add(e.epsilon)).mul(-e.learningRate).add(i);i.assign(d);}}),e.accBeta1.assign(e.accBeta1.mul(e.beta1)),e.accBeta2.assign(e.accBeta2.mul(e.beta2));}),this.incrementIterations();},n.prototype.dispose=function(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&Le(this.accumulatedFirstMoment.map(function(t){return t.variable;})),null!=this.accumulatedSecondMoment&&Le(this.accumulatedSecondMoment.map(function(t){return t.variable;}));},n.prototype.getWeights=function(){return r(this,void 0,void 0,function(){var t;return o(this,function(e){switch(e.label){case 0:return t=this.accumulatedFirstMoment.concat(this.accumulatedSecondMoment),[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(t.map(function(t){return{name:t.originalName,tensor:t.variable};}))];}});});},n.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){var e,n=this;return o(this,function(r){switch(r.label){case 0:return[4,this.extractIterations(t)];case 1:return t=r.sent(),Pe(function(){n.accBeta1.assign(dl(n.beta1,n.iterations_+1)),n.accBeta2.assign(dl(n.beta2,n.iterations_+1));}),e=t.length/2,this.accumulatedFirstMoment=t.slice(0,e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)};}),this.accumulatedSecondMoment=t.slice(e,2*e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)};}),[2];}});});},n.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon};},n.fromConfig=function(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon);},n.className="Adam",n;}(qh);Mh(jh);var Kh=function(t){function n(e,n,r,o,a){void 0===o&&(o=null),void 0===a&&(a=0);var i=t.call(this)||this;return i.learningRate=e,i.beta1=n,i.beta2=r,i.epsilon=o,i.decay=a,i.accumulatedFirstMoment=[],i.accumulatedWeightedInfNorm=[],Pe(function(){i.iteration=yn(0).variable(),i.accBeta1=yn(n).variable();}),null==o&&(i.epsilon=Dt.backend.epsilon()),i;}return e(n,t),n.prototype.applyGradients=function(t){var e=this,n=Array.isArray(t)?t.map(function(t){return t.name;}):Object.keys(t);Pe(function(){var r=yl(1,e.accBeta1),o=rl(-e.learningRate,e.iteration.mul(e.decay).add(1));n.forEach(function(n,a){var i=Dt.registeredVariables[n];null==e.accumulatedFirstMoment[a]&&(e.accumulatedFirstMoment[a]={originalName:n+"/m",variable:Dn(i).variable(!1)}),null==e.accumulatedWeightedInfNorm[a]&&(e.accumulatedWeightedInfNorm[a]={originalName:n+"/v",variable:Dn(i).variable(!1)});var s=Array.isArray(t)?t[a].tensor:t[n];if(null!=s){var u=e.accumulatedFirstMoment[a].variable,l=e.accumulatedWeightedInfNorm[a].variable,c=u.mul(e.beta1).add(s.mul(1-e.beta1)),h=l.mul(e.beta2),p=s.abs(),f=h.maximum(p);u.assign(c),l.assign(f);var d=o.div(r).mul(c.div(f.add(e.epsilon))).add(i);i.assign(d);}}),e.iteration.assign(e.iteration.add(1)),e.accBeta1.assign(e.accBeta1.mul(e.beta1));}),this.incrementIterations();},n.prototype.dispose=function(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&Le(this.accumulatedFirstMoment.map(function(t){return t.variable;})),null!=this.accumulatedWeightedInfNorm&&Le(this.accumulatedWeightedInfNorm.map(function(t){return t.variable;}));},n.prototype.getWeights=function(){return r(this,void 0,void 0,function(){return o(this,function(t){throw new Error("getWeights() is not implemented for Adamax yet.");});});},n.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){return o(this,function(t){throw new Error("setWeights() is not implemented for Adamax yet.");});});},n.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay};},n.fromConfig=function(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon,e.decay);},n.className="Adamax",n;}(qh);Mh(Kh);var Xh=function(t){function n(e){var n=t.call(this)||this;return n.learningRate=e,n.setLearningRate(e),n;}return e(n,t),n.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map(function(t){return t.name;}):Object.keys(t)).forEach(function(n,r){var o=Array.isArray(t)?t[r].tensor:t[n];if(null!=o){var a=Dt.registeredVariables[n];Pe(function(){var t=e.c.mul(o).add(a);a.assign(t);});}}),this.incrementIterations();},n.prototype.setLearningRate=function(t){this.learningRate=t,null!=this.c&&this.c.dispose(),this.c=We(yn(-t));},n.prototype.dispose=function(){this.c.dispose();},n.prototype.getWeights=function(){return r(this,void 0,void 0,function(){return o(this,function(t){switch(t.label){case 0:return[4,this.saveIterations()];case 1:return[2,[t.sent()]];}});});},n.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){return o(this,function(e){switch(e.label){case 0:return[4,this.extractIterations(t)];case 1:if(0!==(t=e.sent()).length)throw new Error("SGD optimizer does not have settable weights.");return[2];}});});},n.prototype.getConfig=function(){return{learningRate:this.learningRate};},n.fromConfig=function(t,e){return new t(e.learningRate);},n.className="SGD",n;}(qh);Mh(Xh);var Yh=function(t){function n(e,n,r){void 0===r&&(r=!1);var o=t.call(this,e)||this;return o.learningRate=e,o.momentum=n,o.useNesterov=r,o.accumulations=[],o.m=yn(o.momentum),o;}return e(n,t),n.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map(function(t){return t.name;}):Object.keys(t)).forEach(function(n,r){var o=Dt.registeredVariables[n];if(null==e.accumulations[r]){e.accumulations[r]={originalName:n+"/momentum",variable:Pe(function(){return Dn(o).variable(!1);})};}var a=e.accumulations[r].variable,i=Array.isArray(t)?t[r].tensor:t[n];null!=i&&Pe(function(){var t,n=e.m.mul(a).add(i);t=e.useNesterov?e.c.mul(i.add(n.mul(e.m))).add(o):e.c.mul(n).add(o),a.assign(n),o.assign(t);});}),this.incrementIterations();},n.prototype.dispose=function(){this.m.dispose(),null!=this.accumulations&&Le(this.accumulations.map(function(t){return t.variable;}));},n.prototype.setMomentum=function(t){this.momentum=t;},n.prototype.getWeights=function(){return r(this,void 0,void 0,function(){return o(this,function(t){switch(t.label){case 0:return[4,this.saveIterations()];case 1:return[2,[t.sent()].concat(this.accumulations.map(function(t){return{name:t.originalName,tensor:t.variable};}))];}});});},n.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){return o(this,function(e){switch(e.label){case 0:return[4,this.extractIterations(t)];case 1:return t=e.sent(),this.accumulations=t.map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)};}),[2];}});});},n.prototype.getConfig=function(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov};},n.fromConfig=function(t,e){return new t(e.learningRate,e.momentum,e.useNesterov);},n.className="MomentumOptimizer",n;}(Xh);Mh(Yh);var Qh=function(t){function n(e,n,r,o,a){void 0===n&&(n=.9),void 0===r&&(r=0),void 0===o&&(o=null),void 0===a&&(a=!1);var i=t.call(this)||this;return i.learningRate=e,i.decay=n,i.momentum=r,i.epsilon=o,i.accumulatedMeanSquares=[],i.accumulatedMoments=[],i.accumulatedMeanGrads=[],i.centered=a,null==o&&(i.epsilon=Dt.backend.epsilon()),i;}return e(n,t),n.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map(function(t){return t.name;}):Object.keys(t)).forEach(function(n,r){var o=Dt.registeredVariables[n];null==e.accumulatedMeanSquares[r]&&(e.accumulatedMeanSquares[r]={originalName:n+"/rms",variable:Pe(function(){return Dn(o).variable(!1);})}),null==e.accumulatedMoments[r]&&(e.accumulatedMoments[r]={originalName:n+"/momentum",variable:Pe(function(){return Dn(o).variable(!1);})}),null==e.accumulatedMeanGrads[r]&&e.centered&&(e.accumulatedMeanGrads[r]={originalName:n+"/mg",variable:Pe(function(){return Dn(o).variable(!1);})});var a=Array.isArray(t)?t[r].tensor:t[n];if(null!=a){var i=e.accumulatedMeanSquares[r].variable,s=e.accumulatedMoments[r].variable;Pe(function(){var t=i.mul(e.decay).add(a.square().mul(1-e.decay));if(e.centered){var n=e.accumulatedMeanGrads[r].variable,u=n.mul(e.decay).add(a.mul(1-e.decay)),l=s.mul(e.momentum).add(a.mul(e.learningRate).div(t.sub(u.square().add(e.epsilon)).sqrt()));i.assign(t),n.assign(u),s.assign(l);var c=o.sub(l);o.assign(c);}else{var h=i.mul(e.decay).add(a.square().mul(1-e.decay));l=s.mul(e.momentum).add(a.mul(e.learningRate).div(h.add(e.epsilon).sqrt()));i.assign(h),s.assign(l);c=o.sub(l);o.assign(c);}});}}),this.incrementIterations();},n.prototype.dispose=function(){null!=this.accumulatedMeanSquares&&Le(this.accumulatedMeanSquares.map(function(t){return t.variable;})),null!=this.accumulatedMeanGrads&&this.centered&&Le(this.accumulatedMeanGrads.map(function(t){return t.variable;})),null!=this.accumulatedMoments&&Le(this.accumulatedMoments.map(function(t){return t.variable;}));},n.prototype.getWeights=function(){return r(this,void 0,void 0,function(){var t;return o(this,function(e){switch(e.label){case 0:return t=this.accumulatedMeanSquares.concat(this.accumulatedMoments),this.centered&&t.push.apply(t,this.accumulatedMeanGrads),[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(t.map(function(t){return{name:t.originalName,tensor:t.variable};}))];}});});},n.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){var e;return o(this,function(n){switch(n.label){case 0:return[4,this.extractIterations(t)];case 1:return t=n.sent(),e=this.centered?t.length/3:t.length/2,this.accumulatedMeanSquares=t.slice(0,e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)};}),this.accumulatedMoments=t.slice(e,2*e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)};}),this.centered&&(this.accumulatedMeanGrads=t.slice(2*e,3*e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)};})),[2];}});});},n.prototype.getConfig=function(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered};},n.fromConfig=function(t,e){return new t(e.learningRate,e.decay,e.momentum,e.epsilon,e.centered);},n.className="RMSProp",n;}(qh);Mh(Qh);var Jh=function(){function t(){}return t.sgd=function(t){return new Xh(t);},t.momentum=function(t,e,n){return void 0===n&&(n=!1),new Yh(t,e,n);},t.rmsprop=function(t,e,n,r,o){return void 0===e&&(e=.9),void 0===n&&(n=0),void 0===r&&(r=null),void 0===o&&(o=!1),new Qh(t,e,n,r,o);},t.adam=function(t,e,n,r){return void 0===t&&(t=.001),void 0===e&&(e=.9),void 0===n&&(n=.999),void 0===r&&(r=null),new jh(t,e,n,r);},t.adadelta=function(t,e,n){return void 0===t&&(t=.001),void 0===e&&(e=.95),void 0===n&&(n=null),new Hh(t,e,n);},t.adamax=function(t,e,n,r,o){return void 0===t&&(t=.002),void 0===e&&(e=.9),void 0===n&&(n=.999),void 0===r&&(r=null),void 0===o&&(o=0),new Kh(t,e,n,r,o);},t.adagrad=function(t,e){return void 0===e&&(e=.1),new $h(t,e);},t;}(),Zh={sgd:Jh.sgd,momentum:Jh.momentum,adadelta:Jh.adadelta,adagrad:Jh.adagrad,rmsprop:Jh.rmsprop,adamax:Jh.adamax,adam:Jh.adam},tp="undefined"!=typeof requestAnimationFrame?requestAnimationFrame:"undefined"!=typeof setImmediate?setImmediate:function(t){return t();};function ep(){return new Promise(function(t){return tp(function(){return t();});});}ht=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 extendStatics = function (e, t) {
      return (extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (e, t) {
        e.__proto__ = t;
      } || function (e, t) {
        for (var n in t) t.hasOwnProperty(n) && (e[n] = t[n]);
      })(e, t);
    };function __extends(e, t) {
      function n() {
        this.constructor = e;
      }extendStatics(e, t), e.prototype = null === t ? Object.create(t) : (n.prototype = t.prototype, new n());
    }var _epsilon,
        __assign = function () {
      return (__assign = Object.assign || function (e) {
        for (var t, n = 1, r = arguments.length; n < r; n++) for (var i in t = arguments[n]) Object.prototype.hasOwnProperty.call(t, i) && (e[i] = t[i]);return e;
      }).apply(this, arguments);
    };function __awaiter(e, t, n, r) {
      return new (n || (n = Promise))(function (i, a$$1) {
        function o(e) {
          try {
            l$$1(r.next(e));
          } catch (e) {
            a$$1(e);
          }
        }function s(e) {
          try {
            l$$1(r.throw(e));
          } catch (e) {
            a$$1(e);
          }
        }function l$$1(e) {
          e.done ? i(e.value) : new n(function (t) {
            t(e.value);
          }).then(o, s);
        }l$$1((r = r.apply(e, t || [])).next());
      });
    }function __generator(e, t) {
      var n,
          r,
          i,
          a$$1,
          o = { label: 0, sent: function () {
          if (1 & i[0]) throw i[1];return i[1];
        }, trys: [], ops: [] };return a$$1 = { next: s(0), throw: s(1), return: s(2) }, "function" == typeof Symbol && (a$$1[Symbol.iterator] = function () {
        return this;
      }), a$$1;function s(a$$1) {
        return function (s) {
          return function (a$$1) {
            if (n) throw new TypeError("Generator is already executing.");for (; o;) try {
              if (n = 1, r && (i = 2 & a$$1[0] ? r.return : a$$1[0] ? r.throw || ((i = r.return) && i.call(r), 0) : r.next) && !(i = i.call(r, a$$1[1])).done) return i;switch (r = 0, i && (a$$1 = [2 & a$$1[0], i.value]), a$$1[0]) {case 0:case 1:
                  i = a$$1;break;case 4:
                  return o.label++, { value: a$$1[1], done: !1 };case 5:
                  o.label++, r = a$$1[1], a$$1 = [0];continue;case 7:
                  a$$1 = o.ops.pop(), o.trys.pop();continue;default:
                  if (!(i = (i = o.trys).length > 0 && i[i.length - 1]) && (6 === a$$1[0] || 2 === a$$1[0])) {
                    o = 0;continue;
                  }if (3 === a$$1[0] && (!i || a$$1[1] > i[0] && a$$1[1] < i[3])) {
                    o.label = a$$1[1];break;
                  }if (6 === a$$1[0] && o.label < i[1]) {
                    o.label = i[1], i = a$$1;break;
                  }if (i && o.label < i[2]) {
                    o.label = i[2], o.ops.push(a$$1);break;
                  }i[2] && o.ops.pop(), o.trys.pop();continue;}a$$1 = t.call(e, o);
            } catch (e) {
              a$$1 = [6, e], r = 0;
            } finally {
              n = i = 0;
            }if (5 & a$$1[0]) throw a$$1[1];return { value: a$$1[0] ? a$$1[1] : void 0, done: !0 };
          }([a$$1, s]);
        };
      }
    }function epsilon() {
      return null == _epsilon && (_epsilon = Ke().epsilon()), _epsilon;
    }function imageDataFormat() {
      return "channelsLast";
    }var AttributeError = function (e) {
      function t(n) {
        var r = e.call(this, n) || this;return Object.setPrototypeOf(r, t.prototype), r;
      }return __extends(t, e), t;
    }(Error),
        RuntimeError = function (e) {
      function t(n) {
        var r = e.call(this, n) || this;return Object.setPrototypeOf(r, t.prototype), r;
      }return __extends(t, e), t;
    }(Error),
        ValueError = function (e) {
      function t(n) {
        var r = e.call(this, n) || this;return Object.setPrototypeOf(r, t.prototype), r;
      }return __extends(t, e), t;
    }(Error),
        NotImplementedError = function (e) {
      function t(n) {
        var r = e.call(this, n) || this;return Object.setPrototypeOf(r, t.prototype), r;
      }return __extends(t, e), t;
    }(Error),
        AssertionError = function (e) {
      function t(n) {
        var r = e.call(this, n) || this;return Object.setPrototypeOf(r, t.prototype), r;
      }return __extends(t, e), t;
    }(Error),
        IndexError = function (e) {
      function t(n) {
        var r = e.call(this, n) || this;return Object.setPrototypeOf(r, t.prototype), r;
      }return __extends(t, e), t;
    }(Error);function pyListRepeat(e, t) {
      if (Array.isArray(e)) {
        for (var n = [], r = 0; r < t; r++) n = n.concat(e);return n;
      }return (n = new Array(t)).fill(e), n;
    }function assert(e, t) {
      if (!e) throw new AssertionError(t);
    }function count(e, t) {
      for (var n = 0, r = 0, i = e; r < i.length; r++) {
        i[r] === t && n++;
      }return n;
    }function singletonOrArray(e) {
      return 1 === e.length ? e[0] : e;
    }function toList(e) {
      return Array.isArray(e) ? e : [e];
    }function toSnakeCase(e) {
      var t = e.replace(/(.)([A-Z][a-z0-9]+)/g, "$1_$2").replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase();return "_" !== t[0] ? t : "private" + t;
    }function toCamelCase(e) {
      return e.length <= 1 ? e : -1 === e.indexOf("_") ? e : e.replace(/[_]+(\w|$)/g, function (e, t) {
        return t.toUpperCase();
      });
    }var _GLOBAL_CUSTOM_OBJECTS = {};function serializeKerasObject(e) {
      if (null === e || void 0 === e) return null;var t = {};return t.className = e.getClassName(), t.config = e.getConfig(), t;
    }function convertNDArrayScalarsInConfig(e) {
      if (null != e && "object" == typeof e) if (Array.isArray(e)) e.forEach(function (e) {
        return convertNDArrayScalarsInConfig(e);
      });else for (var t = 0, n = Object.keys(e); t < n.length; t++) {
        var r = n[t],
            i = e[r];null != i && "object" == typeof i && (Array.isArray(i) || "ndarray" !== i.type || "number" != typeof i.value ? convertNDArrayScalarsInConfig(i) : e[r] = i.value);
      }
    }function deserializeKerasObject(e, t, n, r, i) {
      var a$$1, o, s;if (void 0 === t && (t = {}), void 0 === n && (n = {}), void 0 === r && (r = "object"), void 0 === i && (i = !1), "string" == typeof e) {
        var l$$1 = e,
            u = void 0;if (l$$1 in n) u = n[l$$1];else if (l$$1 in _GLOBAL_CUSTOM_OBJECTS) u = _GLOBAL_CUSTOM_OBJECTS[l$$1];else if (null == (u = t[l$$1])) throw new ValueError("Unknown " + r + ": " + e + ". This may be due to one of the following reasons:\n1. The " + r + " is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom " + r + " is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().");return u;
      }var c = e;if (null == c.className || null == c.config) throw new ValueError(r + ": Improper config format: " + JSON.stringify(c) + ".\n'className' and 'config' must set.");var p = c.className,
          h = void 0,
          d = void 0;if (p in n ? (h = (a$$1 = n[p])[0], d = a$$1[1]) : p in _GLOBAL_CUSTOM_OBJECTS ? (h = (o = _GLOBAL_CUSTOM_OBJECTS.className)[0], d = o[1]) : p in t && (h = (s = t[p])[0], d = s[1]), null == h) throw new ValueError("Unknown " + r + ": " + p + ". This may be due to one of the following reasons:\n1. The " + r + " is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom " + r + " is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().");if (null != d) {
        for (var f = {}, g = 0, m = Object.keys(_GLOBAL_CUSTOM_OBJECTS); g < m.length; g++) {
          f[S = m[g]] = _GLOBAL_CUSTOM_OBJECTS[S];
        }for (var y = 0, v = Object.keys(n); y < v.length; y++) {
          f[S = v[y]] = n[S];
        }c.config.customObjects = f;for (var b = __assign({}, _GLOBAL_CUSTOM_OBJECTS), w = 0, z = Object.keys(n); w < z.length; w++) {
          var S = z[w];_GLOBAL_CUSTOM_OBJECTS[S] = n[S];
        }convertNDArrayScalarsInConfig(c.config);var A = d(h, c.config, n, i);return _GLOBAL_CUSTOM_OBJECTS = __assign({}, b), A;
      }b = __assign({}, _GLOBAL_CUSTOM_OBJECTS);for (var _ = 0, C = Object.keys(n); _ < C.length; _++) {
        S = C[_];_GLOBAL_CUSTOM_OBJECTS[S] = n[S];
      }A = new h(c.config);return _GLOBAL_CUSTOM_OBJECTS = __assign({}, b), A;
    }function numberCompare(e, t) {
      return e < t ? -1 : e > t ? 1 : 0;
    }function reverseNumberCompare(e, t) {
      return -1 * numberCompare(e, t);
    }function unique(e) {
      if (null == e) return e;for (var t = [], n = 0, r = e; n < r.length; n++) {
        var i = r[n];-1 === t.indexOf(i) && t.push(i);
      }return t;
    }function isObjectEmpty(e) {
      if (null == e) throw new ValueError("Invalid value in obj: " + JSON.stringify(e));for (var t in e) if (e.hasOwnProperty(t)) return !1;return !0;
    }function checkStringTypeUnionValue(e, t, n) {
      if (null != n && e.indexOf(n) < 0) throw new ValueError(n + " is not a valid " + t + ".  Valid values are " + e + " or null/undefined.");
    }function checkArrayTypeAndLength(e, t, n, r) {
      return void 0 === n && (n = 0), void 0 === r && (r = 1 / 0), assert(n >= 0), assert(r >= n), Array.isArray(e) && e.length >= n && e.length <= r && e.every(function (e) {
        return typeof e === t;
      });
    }function assertPositiveInteger(e, t) {
      Array.isArray(e) ? (Z.assert(e.length > 0, function () {
        return t + " is unexpectedly an empty array.";
      }), e.forEach(function (e, n) {
        return assertPositiveInteger(e, "element " + (n + 1) + " of " + t);
      })) : Z.assert(Number.isInteger(e) && e > 0, function () {
        return "Expected " + t + " to be a positive integer, but got " + formatAsFriendlyString(e) + ".";
      });
    }function formatAsFriendlyString(e) {
      return null === e ? "null" : Array.isArray(e) ? "[" + e.map(function (e) {
        return formatAsFriendlyString(e);
      }).join(",") + "]" : "string" == typeof e ? '"' + e + '"' : "" + e;
    }function debounce(e, t) {
      var n,
          r = Z.now();return function () {
        for (var i = [], a$$1 = 0; a$$1 < arguments.length; a$$1++) i[a$$1] = arguments[a$$1];var o = Z.now();return o - r < t ? n : (r = o, n = e.apply(void 0, i));
      };
    }function calcL2Norms(e, t) {
      return Pe(function () {
        return Bs(Wu(fl(e, e), t, !0));
      });
    }var Constraint = function (e) {
      function t() {
        return null !== e && e.apply(this, arguments) || this;
      }return __extends(t, e), t.prototype.getConfig = function () {
        return {};
      }, t;
    }(Fh.Serializable),
        MaxNorm = function (e) {
      function t(t) {
        var n = e.call(this) || this;return n.defaultMaxValue = 2, n.defaultAxis = 0, n.maxValue = null != t.maxValue ? t.maxValue : n.defaultMaxValue, n.axis = null != t.axis ? t.axis : n.defaultAxis, n;
      }return __extends(t, e), t.prototype.apply = function (e) {
        var t = this;return Pe(function () {
          var n = calcL2Norms(e, t.axis),
              r = ds(n, 0, t.maxValue);return pl(e, rl(r, Zu(epsilon(), n)));
        });
      }, t.prototype.getConfig = function () {
        return { maxValue: this.maxValue, axis: this.axis };
      }, t.className = "MaxNorm", t;
    }(Constraint);Fh.registerClass(MaxNorm);var UnitNorm = function (e) {
      function t(t) {
        var n = e.call(this) || this;return n.defaultAxis = 0, n.axis = null != t.axis ? t.axis : n.defaultAxis, n;
      }return __extends(t, e), t.prototype.apply = function (e) {
        var t = this;return Pe(function () {
          return rl(e, Zu(epsilon(), calcL2Norms(e, t.axis)));
        });
      }, t.prototype.getConfig = function () {
        return { axis: this.axis };
      }, t.className = "UnitNorm", t;
    }(Constraint);Fh.registerClass(UnitNorm);var NonNeg = function (e) {
      function t() {
        return null !== e && e.apply(this, arguments) || this;
      }return __extends(t, e), t.prototype.apply = function (e) {
        return Al(e);
      }, t.className = "NonNeg", t;
    }(Constraint);Fh.registerClass(NonNeg);var MinMaxNorm = function (e) {
      function t(t) {
        var n = e.call(this) || this;return n.defaultMinValue = 0, n.defaultMaxValue = 1, n.defaultRate = 1, n.defaultAxis = 0, n.minValue = null != t.minValue ? t.minValue : n.defaultMinValue, n.maxValue = null != t.maxValue ? t.maxValue : n.defaultMaxValue, n.rate = null != t.rate ? t.rate : n.defaultRate, n.axis = null != t.axis ? t.axis : n.defaultAxis, n;
      }return __extends(t, e), t.prototype.apply = function (e) {
        var t = this;return Pe(function () {
          var n = calcL2Norms(e, t.axis),
              r = Zu(pl(t.rate, ds(n, t.minValue, t.maxValue)), pl(1 - t.rate, n));return pl(e, rl(r, Zu(epsilon(), n)));
        });
      }, t.prototype.getConfig = function () {
        return { minValue: this.minValue, maxValue: this.maxValue, rate: this.rate, axis: this.axis };
      }, t.className = "MinMaxNorm", t;
    }(Constraint);Fh.registerClass(MinMaxNorm);var CONSTRAINT_IDENTIFIER_REGISTRY_SYMBOL_MAP = { maxNorm: "MaxNorm", minMaxNorm: "MinMaxNorm", nonNeg: "NonNeg", unitNorm: "UnitNorm" };function serializeConstraint(e) {
      return serializeKerasObject(e);
    }function deserializeConstraint(e, t) {
      return void 0 === t && (t = {}), deserializeKerasObject(e, Fh.SerializationMap.getMap().classNameMap, t, "constraint");
    }function getConstraint(e) {
      return null == e ? null : "string" == typeof e ? deserializeConstraint({ className: e in CONSTRAINT_IDENTIFIER_REGISTRY_SYMBOL_MAP ? CONSTRAINT_IDENTIFIER_REGISTRY_SYMBOL_MAP[e] : e, config: {} }) : e instanceof Constraint ? e : deserializeConstraint(e);
    }function maxNorm(e) {
      return new MaxNorm(e);
    }function unitNorm(e) {
      return new UnitNorm(e);
    }function nonNeg() {
      return new NonNeg();
    }function minMaxNorm(e) {
      return new MinMaxNorm(e);
    }var exports_constraints = Object.freeze({ maxNorm: maxNorm, unitNorm: unitNorm, nonNeg: nonNeg, minMaxNorm: minMaxNorm }),
        VALID_DATA_FORMAT_VALUES = ["channelsFirst", "channelsLast"],
        VALID_PADDING_MODE_VALUES = ["valid", "same", "causal"],
        VALID_POOL_MODE_VALUES = ["max", "avg"],
        VALID_BIDIRECTIONAL_MERGE_MODES = ["sum", "mul", "concat", "ave"],
        nameMap = new Map();function checkDataFormat(e) {
      checkStringTypeUnionValue(VALID_DATA_FORMAT_VALUES, "DataFormat", e);
    }function checkPaddingMode(e) {
      checkStringTypeUnionValue(VALID_PADDING_MODE_VALUES, "PaddingMode", e);
    }function checkPoolMode(e) {
      checkStringTypeUnionValue(VALID_POOL_MODE_VALUES, "PoolMode", e);
    }var _nameScopeStack = [],
        _nameScopeDivider = "/";function nameScope(e, t) {
      _nameScopeStack.push(e);try {
        var n = t();return _nameScopeStack.pop(), n;
      } catch (e) {
        throw _nameScopeStack.pop(), e;
      }
    }function currentNameScopePrefix() {
      return 0 === _nameScopeStack.length ? "" : _nameScopeStack.join(_nameScopeDivider) + _nameScopeDivider;
    }function getScopedTensorName(e) {
      if (!isValidTensorName(e)) throw new Error("Not a valid tensor name: '" + e + "'");return currentNameScopePrefix() + e;
    }function getUniqueTensorName(e) {
      if (!isValidTensorName(e)) throw new Error("Not a valid tensor name: '" + e + "'");nameMap.has(e) || nameMap.set(e, 0);var t = nameMap.get(e);if (nameMap.set(e, nameMap.get(e) + 1), t > 0) {
        var n = e + "_" + t;return nameMap.set(n, 1), n;
      }return e;
    }var tensorNameRegex = new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function isValidTensorName(e) {
      return !!e.match(tensorNameRegex);
    }function isInteger(e) {
      return e === parseInt(e.toString(), 10);
    }function arrayProd(e, t, n) {
      null == t && (t = 0), null == n && (n = e.length);for (var r = 1, i = t; i < n; ++i) r *= e[i];return r;
    }function toArray1D(e) {
      return e = Array.isArray(e) ? new Float32Array(e) : e, xn(e);
    }function min$1(e) {
      return Pu(toArray1D(e)).dataSync()[0];
    }function max$1(e) {
      return Fu(toArray1D(e)).dataSync()[0];
    }function range(e, t) {
      if (t < e) throw new ValueError("end (" + t + ") < begin (" + e + ") is forbidden.");for (var n = [], r = e; r < t; ++r) n.push(r);return n;
    }function cast$1(e, t) {
      return e.asType(t);
    }function expandDims$1(e, t) {
      void 0 === t && (t = -1);var n = e.shape.slice();return t < 0 && (t = n.length + t + 1), n.splice(t, 0, 1), e.reshape(n);
    }function repeat(e, t) {
      return Pe(function () {
        if (2 !== e.shape.length) throw new ValueError("repeat() expects a rank-2 tensor, but received a rank-" + e.shape.length + " tensor.");return tile$1(expandDims$1(e, 1), [1, t, 1]);
      });
    }function flatten(e) {
      var t = [arrayProd(e.shape)];return e.reshape(t);
    }function batchFlatten(e) {
      if (e.rank <= 1) throw new ValueError("batchFlatten requires a minimum rank of 2. Got rank: " + e.rank + ".");var t = [e.shape[0], arrayProd(e.shape, 1)];return e.reshape(t);
    }function sliceAlongFirstAxis(e, t, n) {
      return Pe(function () {
        switch (e.rank) {case 1:
            return Iu(e, t, n);case 2:
            return Su(e, [t, 0], [n, e.shape[1]]);case 3:
            return Nu(e, [t, 0, 0], [n, e.shape[1], e.shape[2]]);case 4:
            return ku(e, [t, 0, 0, 0], [n, e.shape[1], e.shape[2], e.shape[3]]);default:
            throw new ValueError("sliceAlongFirstAxis() received an unsupported tensor rank: " + e.rank);}
      });
    }function sliceAlongLastAxis(e, t, n) {
      return Pe(function () {
        switch (e.rank) {case 1:
            return Iu(e, t, n);case 2:
            return Su(e, [0, t], [e.shape[0], n]);case 3:
            return Nu(e, [0, 0, t], [e.shape[0], e.shape[1], n]);case 4:
            return ku(e, [0, 0, 0, t], [e.shape[0], e.shape[1], e.shape[2], n]);default:
            throw new ValueError("sliceAlongLastAxis() received an unsupported tensor rank: " + e.rank);}
      });
    }function sliceAlongAxis(e, t, n, r) {
      return Pe(function () {
        switch (e.rank) {case 1:
            return Iu(e, t, n);case 2:
            switch (r) {case 1:
                return sliceAlongFirstAxis(e, t, n);case 2:
                return sliceAlongLastAxis(e, t, n);default:
                throw new ValueError("The axis is not within the rank of the tensor " + r);}case 3:
            switch (r) {case 1:
                return sliceAlongFirstAxis(e, t, n);case 2:
                return Nu(e, [0, t, 0], [e.shape[0], n, e.shape[2]]);case 3:
                return sliceAlongLastAxis(e, t, n);default:
                throw new ValueError("The axis is not within the rank of the tensor " + r);}case 4:
            switch (r) {case 1:
                return sliceAlongFirstAxis(e, t, n);case 2:
                return ku(e, [0, t, 0, 0], [e.shape[0], n, e.shape[2], e.shape[3]]);case 3:
                return ku(e, [0, 0, t, 0], [e.shape[0], e.shape[1], n, e.shape[3]]);case 4:
                return sliceAlongLastAxis(e, t, n);default:
                throw new ValueError("The axis is not within the rank of the tensor " + r);}default:
            throw new ValueError("sliceAlongLastAxis() received an unsupported tensor rank: " + e.rank);}
      });
    }function concatenate(e, t) {
      var n;return void 0 === t && (t = -1), t < 0 && (t = 0 !== (n = e[0].rank) ? n : 0), t === e[0].rank && (t = -1), _n(e, t);
    }function concatAlongFirstAxis(e, t) {
      switch (e.rank) {case 1:
          return On([e, t]);case 2:
          return Mn([e, t], 0);case 3:
          return Fn([e, t], 0);case 4:
          return Bn([e, t], 0);default:
          throw new ValueError("concatAlongFirstAxis() received an unsupported tensor rank: " + e.rank);}
    }function tile$1(e, t) {
      if (Array.isArray(t) || (t = [t]), e.rank !== t.length) throw new ValueError("The length of input n (" + t.length + ") does not match the number of dimensions in input x (" + e.rank + ")");return yr(e, t);
    }function randomNormal$1(e, t, n, r, i) {
      return void 0 === t && (t = 0), void 0 === n && (n = 1), pr(e, t, n, r, i);
    }function dot(e, t, n, r) {
      if (e.rank < 2 || t.rank < 2) throw new NotImplementedError("dot requires both inputs to be rank >= 2 but got x shape = " + e.shape + " and y shape = " + t.shape);if (t.rank >= 3 && (s = e.shape.slice(-1)[0]) !== (c = t.shape.slice(-2)[0])) throw new NotImplementedError("If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = " + e.shape + " and  y shape = " + t.shape);if (2 === e.rank && 2 === t.rank) {
        var i = !1,
            a$$1 = !1;return Sc.matMul(e, t, i, a$$1, r ? reshapeBias(e.rank, r, imageDataFormat()) : null, n);
      }var o = e.shape.slice(),
          s = o.pop();e = e.reshape([-1, s]);var l$$1 = t.shape.slice(),
          u = l$$1.pop(),
          c = l$$1.pop(),
          p = l$$1.concat([u]),
          h = Array.from({ length: t.rank }, function (e, n) {
        return 0 === n ? t.rank - 2 : n <= t.rank - 2 ? n - 1 : n;
      });t = t.transpose(h).reshape([c, -1]);var d = o.concat(p);i = !1, a$$1 = !1;return Sc.matMul(e, t, i, a$$1, r ? reshapeBias(e.rank, r, imageDataFormat()) : null, n).reshape(d);
    }function gather$1(e, t, n) {
      return Pe(function () {
        return t = Array.isArray(t) ? xn(t, "int32") : t.toInt(), Bl(e, t, n);
      });
    }function square(e) {
      return fl(e, e);
    }function reshapeBias(e, t, n) {
      var r = t.shape;if (1 !== t.rank && t.rank !== e) throw new ValueError("Unexpected bias dimensions: " + t.rank + "; expected it to be 1 or " + e);if (5 === e) {
        if ("channelsFirst" === n) return 1 === r.length ? t.reshape([1, r[0], 1, 1, 1]) : t.reshape([1, r[3], r[0], r[1], r[2]]);if ("channelsLast" === n) return 1 === r.length ? t.reshape([1, 1, 1, 1, r[0]]) : t.reshape([1].concat(r));
      } else if (4 === e) {
        if ("channelsFirst" === n) return 1 === r.length ? t.reshape([1, r[0], 1, 1]) : t.reshape([1, r[2], r[0], r[1]]);if ("channelsLast" === n) return 1 === r.length ? t.reshape([1, 1, 1, r[0]]) : t.reshape([1].concat(r));
      } else if (3 === e) {
        if ("channelsFirst" === n) return 1 === r.length ? t.reshape([1, r[0], 1]) : t.reshape([1, r[1], r[0]]);if ("channelsLast" === n) return 1 === r.length ? t.reshape([1, 1, r[0]]) : t.reshape([1].concat(r));
      } else if (e < 3) return t;throw new ValueError("Unsupported input rank by biasAdd: " + t.rank);
    }function biasAdd(e, t, n) {
      return Pe(function () {
        return null == n && (n = imageDataFormat()), checkDataFormat(n), e.add(reshapeBias(e.rank, t, n));
      });
    }function elu$1(e, t) {
      if (void 0 === t && (t = 1), 1 !== t) throw new NotImplementedError("Support for alpha values other than 1 (" + t + ") is not implemented yet.");return Sl(e);
    }function softsign(e) {
      return Pe(function () {
        return rl(e, is(e).add(1));
      });
    }function dropout$1(e, t, n, r) {
      return Pe(function () {
        return Ql(e, t, n, r);
      });
    }function hardSigmoid(e) {
      return Pe(function () {
        var t = Zu(.5, pl(.2, e));return ds(t, 0, 1);
      });
    }function inTrainPhase(e, t, n) {
      return void 0 === n && (n = !1), n ? e() : t();
    }var VALID_FAN_MODE_VALUES = ["fanIn", "fanOut", "fanAvg"],
        VALID_DISTRIBUTION_VALUES = ["normal", "uniform", "truncatedNormal"];function checkFanMode(e) {
      checkStringTypeUnionValue(VALID_FAN_MODE_VALUES, "FanMode", e);
    }function checkDistribution(e) {
      checkStringTypeUnionValue(VALID_DISTRIBUTION_VALUES, "Distribution", e);
    }var Initializer = function (e) {
      function t() {
        return null !== e && e.apply(this, arguments) || this;
      }return __extends(t, e), t.prototype.fromConfigUsesCustomObjects = function () {
        return !1;
      }, t.prototype.getConfig = function () {
        return {};
      }, t;
    }(Fh.Serializable),
        Zeros = function (e) {
      function t() {
        return null !== e && e.apply(this, arguments) || this;
      }return __extends(t, e), t.prototype.apply = function (e, t) {
        return Sn(e, t);
      }, t.className = "Zeros", t;
    }(Initializer);Fh.registerClass(Zeros);var Ones = function (e) {
      function t() {
        return null !== e && e.apply(this, arguments) || this;
      }return __extends(t, e), t.prototype.apply = function (e, t) {
        return In(e, t);
      }, t.className = "Ones", t;
    }(Initializer);Fh.registerClass(Ones);var Constant = function (e) {
      function t(t) {
        var n = e.call(this) || this;if ("object" != typeof t) throw new ValueError("Expected argument of type ConstantConfig but got " + t);if (void 0 === t.value) throw new ValueError("config must have value set but got " + t);return n.value = t.value, n;
      }return __extends(t, e), t.prototype.apply = function (e, t) {
        var n = this;return Pe(function () {
          return pl(yn(n.value), In(e, t));
        });
      }, t.prototype.getConfig = function () {
        return { value: this.value };
      }, t.className = "Constant", t;
    }(Initializer);Fh.registerClass(Constant);var RandomUniform = function (e) {
      function t(t) {
        var n = e.call(this) || this;return n.DEFAULT_MINVAL = -.05, n.DEFAULT_MAXVAL = .05, n.minval = t.minval || n.DEFAULT_MINVAL, n.maxval = t.maxval || n.DEFAULT_MAXVAL, n.seed = t.seed, n;
      }return __extends(t, e), t.prototype.apply = function (e, t) {
        return fr(e, this.minval, this.maxval, t);
      }, t.prototype.getConfig = function () {
        return { minval: this.minval, maxval: this.maxval, seed: this.seed };
      }, t.className = "RandomUniform", t;
    }(Initializer);Fh.registerClass(RandomUniform);var RandomNormal = function (e) {
      function t(t) {
        var n = e.call(this) || this;return n.DEFAULT_MEAN = 0, n.DEFAULT_STDDEV = .05, n.mean = t.mean || n.DEFAULT_MEAN, n.stddev = t.stddev || n.DEFAULT_STDDEV, n.seed = t.seed, n;
      }return __extends(t, e), t.prototype.apply = function (e, t) {
        if ("float32" !== (t = t || "float32") && "int32" !== t) throw new NotImplementedError("randomNormal does not support dType " + t + ".");return randomNormal$1(e, this.mean, this.stddev, t, this.seed);
      }, t.prototype.getConfig = function () {
        return { mean: this.mean, stddev: this.stddev, seed: this.seed };
      }, t.className = "RandomNormal", t;
    }(Initializer);Fh.registerClass(RandomNormal);var TruncatedNormal = function (e) {
      function t(t) {
        var n = e.call(this) || this;return n.DEFAULT_MEAN = 0, n.DEFAULT_STDDEV = .05, n.mean = t.mean || n.DEFAULT_MEAN, n.stddev = t.stddev || n.DEFAULT_STDDEV, n.seed = t.seed, n;
      }return __extends(t, e), t.prototype.apply = function (e, t) {
        if ("float32" !== (t = t || "float32") && "int32" !== t) throw new NotImplementedError("truncatedNormal does not support dType " + t + ".");return xr(e, this.mean, this.stddev, t, this.seed);
      }, t.prototype.getConfig = function () {
        return { mean: this.mean, stddev: this.stddev, seed: this.seed };
      }, t.className = "TruncatedNormal", t;
    }(Initializer);Fh.registerClass(TruncatedNormal);var Identity = function (e) {
      function t(t) {
        var n = e.call(this) || this;return n.gain = null != t.gain ? t.gain : 1, n;
      }return __extends(t, e), t.prototype.apply = function (e, t) {
        var n = this;return Pe(function () {
          if (2 !== e.length || e[0] !== e[1]) throw new ValueError("Identity matrix initializer can only be used for 2D square matrices.");return pl(n.gain, rr(e[0]));
        });
      }, t.prototype.getConfig = function () {
        return { gain: this.gain };
      }, t.className = "Identity", t;
    }(Initializer);function computeFans(e, t) {
      var n, r;if (void 0 === t && (t = "channelsLast"), checkDataFormat(t), 2 === e.length) n = e[0], r = e[1];else if (-1 !== [3, 4, 5].indexOf(e.length)) {
        if ("channelsFirst" === t) {
          var i = arrayProd(e, 2);n = e[1] * i, r = e[0] * i;
        } else if ("channelsLast" === t) {
          i = arrayProd(e, 0, e.length - 2);n = e[e.length - 2] * i, r = e[e.length - 1] * i;
        }
      } else {
        var a$$1 = arrayProd(e);n = Math.sqrt(a$$1), r = Math.sqrt(a$$1);
      }return [n, r];
    }Fh.registerClass(Identity);var VarianceScaling = function (e) {
      function t(t) {
        var n = e.call(this) || this;if (t.scale < 0) throw new ValueError("scale must be a positive float. Got: " + t.scale);return n.scale = null == t.scale ? 1 : t.scale, n.mode = null == t.mode ? "fanIn" : t.mode, checkFanMode(n.mode), n.distribution = null == t.distribution ? "normal" : t.distribution, checkDistribution(n.distribution), n.seed = t.seed, n;
      }return __extends(t, e), t.prototype.apply = function (e, t) {
        var n = computeFans(e),
            r = n[0],
            i = n[1],
            a$$1 = this.scale;if ("fanIn" === this.mode ? a$$1 /= Math.max(1, r) : "fanOut" === this.mode ? a$$1 /= Math.max(1, i) : a$$1 /= Math.max(1, (r + i) / 2), "normal" === this.distribution) {
          var o = Math.sqrt(a$$1);if ("float32" !== (t = t || "float32") && "int32" !== t) throw new NotImplementedError(this.getClassName() + " does not support dType " + t + ".");return xr(e, 0, o, t, this.seed);
        }var s = Math.sqrt(3 * a$$1);return fr(e, -s, s, t);
      }, t.prototype.getConfig = function () {
        return { scale: this.scale, mode: this.mode, distribution: this.distribution, seed: this.seed };
      }, t.className = "VarianceScaling", t;
    }(Initializer);Fh.registerClass(VarianceScaling);var GlorotUniform = function (e) {
      function t(t) {
        return e.call(this, { scale: 1, mode: "fanAvg", distribution: "uniform", seed: null == t ? null : t.seed }) || this;
      }return __extends(t, e), t.prototype.getClassName = function () {
        return VarianceScaling.className;
      }, t.className = "GlorotUniform", t;
    }(VarianceScaling);Fh.registerClass(GlorotUniform);var GlorotNormal = function (e) {
      function t(t) {
        return e.call(this, { scale: 1, mode: "fanAvg", distribution: "normal", seed: null == t ? null : t.seed }) || this;
      }return __extends(t, e), t.prototype.getClassName = function () {
        return VarianceScaling.className;
      }, t.className = "GlorotNormal", t;
    }(VarianceScaling);Fh.registerClass(GlorotNormal);var HeNormal = function (e) {
      function t(t) {
        return e.call(this, { scale: 2, mode: "fanIn", distribution: "normal", seed: null == t ? null : t.seed }) || this;
      }return __extends(t, e), t.prototype.getClassName = function () {
        return VarianceScaling.className;
      }, t.className = "HeNormal", t;
    }(VarianceScaling);Fh.registerClass(HeNormal);var HeUniform = function (e) {
      function t(t) {
        return e.call(this, { scale: 2, mode: "fanIn", distribution: "uniform", seed: null == t ? null : t.seed }) || this;
      }return __extends(t, e), t.prototype.getClassName = function () {
        return VarianceScaling.className;
      }, t.className = "HeUniform", t;
    }(VarianceScaling);Fh.registerClass(HeUniform);var LeCunNormal = function (e) {
      function t(t) {
        return e.call(this, { scale: 1, mode: "fanIn", distribution: "normal", seed: null == t ? null : t.seed }) || this;
      }return __extends(t, e), t.prototype.getClassName = function () {
        return VarianceScaling.className;
      }, t.className = "LeCunNormal", t;
    }(VarianceScaling);Fh.registerClass(LeCunNormal);var LeCunUniform = function (e) {
      function t(t) {
        return e.call(this, { scale: 1, mode: "fanIn", distribution: "uniform", seed: null == t ? null : t.seed }) || this;
      }return __extends(t, e), t.prototype.getClassName = function () {
        return VarianceScaling.className;
      }, t.className = "LeCunNormal", t;
    }(VarianceScaling);Fh.registerClass(LeCunUniform);var Orthogonal = function (e) {
      function t(t) {
        var n = e.call(this) || this;if (n.DEFAULT_GAIN = 1, n.gain = null == t.gain ? n.DEFAULT_GAIN : t.gain, n.seed = t.seed, null != n.seed) throw new NotImplementedError("Random seed is not implemented for Orthogonal Initializer yet.");return n;
      }return __extends(t, e), t.prototype.apply = function (e, t) {
        var n = this;return Pe(function () {
          if (2 !== e.length) throw new NotImplementedError("The Orthogonal Initializer does not support non-2D shapes yet.");e[0] * e[1] > 2e3 && console.warn("Orthogonal initializer is being called on a matrix with more than 2000 (" + e[0] * e[1] + ") elements: Slowness may result.");var t = randomNormal$1(e[0] > e[1] ? [e[1], e[0]] : e, 0, 1, "float32"),
              r = gc.gramSchmidt(t);return e[0] > e[1] && (r = r.transpose()), pl(n.gain, r);
        });
      }, t.prototype.getConfig = function () {
        return { gain: this.gain, seed: this.seed };
      }, t.className = "Orthogonal", t;
    }(Initializer);Fh.registerClass(Orthogonal);var INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP = { constant: "Constant", glorotNormal: "GlorotNormal", glorotUniform: "GlorotUniform", heNormal: "HeNormal", heUniform: "HeUniform", identity: "Identity", leCunNormal: "LeCunNormal", leCunUniform: "LeCunUniform", ones: "Ones", orthogonal: "Orthogonal", randomNormal: "RandomNormal", randomUniform: "RandomUniform", truncatedNormal: "TruncatedNormal", varianceScaling: "VarianceScaling", zeros: "Zeros" };function deserializeInitializer(e, t) {
      return void 0 === t && (t = {}), deserializeKerasObject(e, Fh.SerializationMap.getMap().classNameMap, t, "initializer");
    }function serializeInitializer(e) {
      return serializeKerasObject(e);
    }function getInitializer(e) {
      if ("string" == typeof e) {
        var t = e in INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP ? INITIALIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP[e] : e;if ("GlorotNormal" === t) return new GlorotNormal();if ("GlorotUniform" === t) return new GlorotUniform();if ("HeNormal" === t) return new HeNormal();if ("HeUniform" === t) return new HeUniform();if ("LeCunNormal" === t) return new LeCunNormal();if ("LeCunUniform" === t) return new LeCunUniform();var n = {};return n.className = t, n.config = {}, deserializeInitializer(n);
      }return e instanceof Initializer ? e : deserializeInitializer(e);
    }function zeros$1() {
      return new Zeros();
    }function ones$1() {
      return new Ones();
    }function constant(e) {
      return new Constant(e);
    }function randomUniform$1(e) {
      return new RandomUniform(e);
    }function randomNormal$2(e) {
      return new RandomNormal(e);
    }function truncatedNormal$1(e) {
      return new TruncatedNormal(e);
    }function identity(e) {
      return new Identity(e);
    }function varianceScaling(e) {
      return new VarianceScaling(e);
    }function glorotUniform(e) {
      return new GlorotUniform(e);
    }function glorotNormal(e) {
      return new GlorotNormal(e);
    }function heNormal(e) {
      return new HeNormal(e);
    }function heUniform(e) {
      return new HeUniform(e);
    }function leCunNormal(e) {
      return new LeCunNormal(e);
    }function leCunUniform(e) {
      return new LeCunUniform(e);
    }function orthogonal(e) {
      return new Orthogonal(e);
    }var exports_initializers = Object.freeze({ zeros: zeros$1, ones: ones$1, constant: constant, randomUniform: randomUniform$1, randomNormal: randomNormal$2, truncatedNormal: truncatedNormal$1, identity: identity, varianceScaling: varianceScaling, glorotUniform: glorotUniform, glorotNormal: glorotNormal, heNormal: heNormal, heUniform: heUniform, leCunNormal: leCunNormal, leCunUniform: leCunUniform, orthogonal: orthogonal }),
        _nextUniqueTensorId = 0;function getNextUniqueTensorId() {
      return _nextUniqueTensorId++;
    }var _uidPrefixes = {};function getUid(e) {
      return void 0 === e && (e = ""), e in _uidPrefixes || (_uidPrefixes[e] = 0), _uidPrefixes[e] += 1, e + _uidPrefixes[e].toString();
    }function isArrayOfShapes(e) {
      return Array.isArray(e) && Array.isArray(e[0]);
    }function normalizeShapeList(e) {
      return 0 === e.length ? [] : Array.isArray(e[0]) ? e : [e];
    }function getExactlyOneTensor(e) {
      var t;if (Array.isArray(e)) {
        if (1 !== e.length) throw new ValueError("Expected Tensor length to be 1; got " + e.length);t = e[0];
      } else t = e;return t;
    }function getExactlyOneShape(e) {
      if (Array.isArray(e) && Array.isArray(e[0])) {
        if (1 === e.length) return (e = e)[0];throw new ValueError("Expected exactly 1 Shape; got " + e.length);
      }return e;
    }function countParamsInWeights(e) {
      for (var t = 0, n = 0, r = e; n < r.length; n++) {
        var i = r[n];0 === i.shape.length ? t += 1 : t += i.shape.reduce(function (e, t) {
          return e * t;
        });
      }return t;
    }var DEFAULT_VARIABLE_NAME_PREFIX = "Variable",
        LayerVariable = function () {
      function e(e, t, n, r, i) {
        void 0 === t && (t = "float32"), void 0 === n && (n = DEFAULT_VARIABLE_NAME_PREFIX), void 0 === r && (r = !0), void 0 === i && (i = null), this.dtype = null == t ? "float32" : t, this.shape = e.shape, this.id = getNextUniqueTensorId(), n = null == n ? DEFAULT_VARIABLE_NAME_PREFIX : n, this.originalName = getScopedTensorName(n), this.name = getUniqueTensorName(this.originalName), this.trainable_ = r, this.constraint = i, this.val = bt(e, this.trainable_, this.name, this.dtype);
      }return e.prototype.read = function () {
        return this.assertNotDisposed(), this.val;
      }, e.prototype.write = function (e) {
        return this.assertNotDisposed(), checkShapesMatch(this.val, e), this.val.id !== e.id && (this.val.assign(e), null != this.constraint && this.val.assign(this.constraint.apply(this.val))), this;
      }, e.prototype.dispose = function () {
        this.assertNotDisposed(), this.val.dispose();
      }, e.prototype.assertNotDisposed = function () {
        if (this.val.isDisposed) throw new Error("LayersVariable " + this.name + " is already disposed.");
      }, Object.defineProperty(e.prototype, "trainable", { get: function () {
          return this.trainable_;
        }, set: function (e) {
          this.trainable_ = e, this.val.trainable = e;
        }, enumerable: !0, configurable: !0 }), e;
    }();function checkShapesMatch(e, t) {
      if (e.shape.toString() !== t.shape.toString()) throw new Error("Shape mismatch: " + JSON.stringify(e.shape) + " vs. " + JSON.stringify(t.shape));
    }function batchGetValue(e) {
      return e.map(function (e) {
        return e.read();
      });
    }function batchSetValue(e) {
      e.forEach(function (e) {
        e[0].write(e[1]);
      });
    }var InputSpec = function () {
      return function (e) {
        this.dtype = e.dtype, this.shape = e.shape, null != e.shape ? this.ndim = e.shape.length : this.ndim = e.ndim, this.maxNDim = e.maxNDim, this.minNDim = e.minNDim, this.axes = e.axes || {};
      };
    }(),
        SymbolicTensor = function () {
      return function (e, t, n, r, i, a$$1, o) {
        this.dtype = e, this.shape = t, this.sourceLayer = n, this.inputs = r, this.callArgs = i, this.outputTensorIndex = o, this.id = getNextUniqueTensorId(), null != a$$1 && (this.originalName = getScopedTensorName(a$$1), this.name = getUniqueTensorName(this.originalName)), this.rank = t.length;
      };
    }(),
        _nextNodeID = 0,
        Node = function () {
      function e(e, t) {
        this.callArgs = t, this.id = _nextNodeID++, this.outboundLayer = e.outboundLayer, this.inboundLayers = e.inboundLayers, this.nodeIndices = e.nodeIndices, this.tensorIndices = e.tensorIndices, this.inputTensors = e.inputTensors, this.outputTensors = e.outputTensors, this.inputMasks = e.inputMasks, this.outputMasks = e.outputMasks, this.inputShapes = e.inputShapes, this.outputShapes = e.outputShapes;for (var n = 0, r = e.inboundLayers; n < r.length; n++) {
          var i = r[n];null != i && i.outboundNodes.push(this);
        }e.outboundLayer.inboundNodes.push(this);
      }return e.prototype.getConfig = function () {
        for (var e = [], t = 0, n = this.inboundLayers; t < n.length; t++) {
          var r = n[t];null != r ? e.push(r.name) : e.push(null);
        }return { outboundLayer: this.outboundLayer ? this.outboundLayer.name : null, inboundLayers: e, nodeIndices: this.nodeIndices, tensorIndices: this.tensorIndices };
      }, e;
    }(),
        _nextLayerID = 0,
        Layer = function (e) {
      function t(t) {
        var n = e.call(this) || this;n._callHook = null, n._addedWeightNames = [], n._stateful = !1, n.id = _nextLayerID++, n.activityRegularizer = null, n.inputSpec = null, n.supportsMasking = !1, n._trainableWeights = [], n._nonTrainableWeights = [], n._losses = [], n._updates = [], n._built = !1, n.inboundNodes = [], n.outboundNodes = [];var r = t.name;if (!r) {
          var i = n.getClassName();r = toSnakeCase(i) + "_" + getUid(i);
        }if (n.name = r, n.trainable_ = null == t.trainable || t.trainable, null != t.inputShape || null != t.batchInputShape) {
          var a$$1 = void 0;if (null != t.batchInputShape) a$$1 = t.batchInputShape;else if (null != t.inputShape) {
            var o = null;null != t.batchSize && (o = t.batchSize), a$$1 = [o].concat(t.inputShape);
          }n.batchInputShape = a$$1;var s = t.dtype;null == s && (s = t.inputDType), null == s && (s = "float32"), n.dtype = s;
        }return null != t.weights ? n.initialWeights = t.weights : n.initialWeights = null, n._refCount = null, n.fastWeightInitDuringBuild = !1, n;
      }return __extends(t, e), t.nodeKey = function (e, t) {
        return e.name + "_ib-" + t.toString();
      }, t.prototype.getNodeAtIndex = function (e, t) {
        if (0 === this.inboundNodes.length) throw new RuntimeError("The layer has never been called and thus has no defined " + t + ".");if (this.inboundNodes.length <= e) throw new ValueError("Asked to get " + t + " at node " + e + ", but the layer has only " + this.inboundNodes.length + " inbound nodes.");return this.inboundNodes[e];
      }, t.prototype.getInputAt = function (e) {
        return singletonOrArray(this.getNodeAtIndex(e, "input").inputTensors);
      }, t.prototype.getOutputAt = function (e) {
        return singletonOrArray(this.getNodeAtIndex(e, "output").outputTensors);
      }, Object.defineProperty(t.prototype, "input", { get: function () {
          if (this.inboundNodes.length > 1) throw new AttributeError("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 AttributeError("Layer " + this.name + " is not connected, no input to return.");return singletonOrArray(this.getNodeAtIndex(0, "input").inputTensors);
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "output", { get: function () {
          if (0 === this.inboundNodes.length) throw new AttributeError("Layer " + this.name + " has no inbound nodes.");if (this.inboundNodes.length > 1) throw new AttributeError("Layer " + this.name + ' has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use `getOutputAt(nodeIndex)` instead.');return singletonOrArray(this.getNodeAtIndex(0, "output").outputTensors);
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "losses", { get: function () {
          return this._losses;
        }, enumerable: !0, configurable: !0 }), t.prototype.calculateLosses = function () {
        return this.losses.map(function (e) {
          return e();
        });
      }, Object.defineProperty(t.prototype, "updates", { get: function () {
          return this._updates;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "built", { get: function () {
          return this._built;
        }, set: function (e) {
          this._built = e;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "trainable", { get: function () {
          return this.trainable_;
        }, set: function (e) {
          this._trainableWeights.forEach(function (t) {
            return t.trainable = e;
          }), this.trainable_ = e;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "trainableWeights", { get: function () {
          return this.trainable_ ? this._trainableWeights.filter(function (e) {
            return e.trainable;
          }) : [];
        }, set: function (e) {
          this._trainableWeights = e;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "nonTrainableWeights", { get: function () {
          return this.trainable ? this._trainableWeights.filter(function (e) {
            return !e.trainable;
          }).concat(this._nonTrainableWeights) : this._trainableWeights.concat(this._nonTrainableWeights);
        }, set: function (e) {
          this._nonTrainableWeights = e;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "weights", { get: function () {
          return this.trainableWeights.concat(this.nonTrainableWeights);
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "stateful", { get: function () {
          return this._stateful;
        }, enumerable: !0, configurable: !0 }), t.prototype.resetStates = function () {
        if (!this.stateful) throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.");
      }, t.prototype.assertInputCompatibility = function (e) {
        if (e = toList(e), null != this.inputSpec && 0 !== this.inputSpec.length) {
          var t = toList(this.inputSpec);if (e.length !== t.length) throw new ValueError("Layer " + this.name + " expects " + t.length + " inputs, but it received " + e.length + " input tensors. Input received: " + e);for (var n = 0; n < e.length; n++) {
            var r = e[n],
                i = t[n];if (null != i) {
              var a$$1 = r.rank;if (null != i.ndim && a$$1 !== i.ndim) throw new ValueError("Input " + n + " is incompatible with layer " + this.name + ": expected ndim=" + i.ndim + ", found ndim=" + a$$1);if (null != i.maxNDim && a$$1 > i.maxNDim) throw new ValueError("Input " + n + " is incompatible with layer " + this.name + ": expected max_ndim=" + i.maxNDim + ", found ndim=" + a$$1);if (null != i.minNDim && a$$1 < i.minNDim) throw new ValueError("Input " + n + " is incompatible with layer " + this.name + ": expected min_ndim=" + i.minNDim + ", found ndim=" + a$$1 + ".");if (null != i.dtype && r.dtype !== i.dtype) throw new ValueError("Input " + n + " is incompatible with layer " + this.name + " : expected dtype=" + i.dtype + ", found dtype=" + r.dtype + ".");if (i.axes) {
                var o = r.shape;for (var s in i.axes) {
                  var l$$1 = Number(s),
                      u = i.axes[s],
                      c = l$$1 >= 0 ? o[l$$1] : o[o.length + l$$1];if (null != u && -1 === [u, null].indexOf(c)) throw new ValueError("Input " + n + " is incompatible with layer " + this.name + ": expected axis " + l$$1 + " of input shape to have value " + u + " but got shape " + o + ".");
                }
              }if (null != i.shape) for (var p = 0; p < i.shape.length; ++p) {
                var h = i.shape[p],
                    d = r.shape[p];if (null != h && null != d && h !== d) throw new ValueError("Input " + n + " is incompatible with layer " + this.name + ": expected shape=" + i.shape + ", found shape=" + r.shape + ".");
              }
            }
          }
        }
      }, t.prototype.call = function (e, t) {
        return e;
      }, t.prototype.invokeCallHook = function (e, t) {
        null != this._callHook && this._callHook(e, t);
      }, t.prototype.setCallHook = function (e) {
        this._callHook = e;
      }, t.prototype.clearCallHook = function () {
        this._callHook = null;
      }, t.prototype.apply = function (e, t) {
        var n = this;t = t || {}, this.assertNotDisposed();for (var r = toList(e), i = !0, a$$1 = 0, o = r; a$$1 < o.length; a$$1++) {
          if (!(o[a$$1] instanceof SymbolicTensor)) {
            i = !1;break;
          }
        }for (var s = !0, l$$1 = 0, u = r; l$$1 < u.length; l$$1++) {
          if (u[l$$1] instanceof SymbolicTensor) {
            s = !1;break;
          }
        }if (i === s) throw new ValueError("Arguments to apply() must be all SymbolicTensors or all Tensors");return nameScope(this.name, function () {
          if (!n.built) {
            n.assertInputCompatibility(e);for (var i = [], a$$1 = 0, o = toList(e); a$$1 < o.length; a$$1++) {
              var l$$1 = o[a$$1];i.push(l$$1.shape);
            }n.build(singletonOrArray(i)), n.built = !0, n.initialWeights && n.setWeights(n.initialWeights), null === n._refCount && s && (n._refCount = 1);
          }if (n.assertInputCompatibility(e), s) {
            for (var u = [], c = 0, p = toList(g = n.call(e, t)); c < p.length; c++) {
              var h = p[c];-1 !== r.indexOf(h) && (h = h.clone()), u.push(h);
            }if (g = singletonOrArray(u), null != n.activityRegularizer) throw new NotImplementedError("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return g;
          }var d = collectInputShape(e),
              f = n.computeOutputShape(d),
              g = void 0,
              m = guessOutputDType(e);if (n.warnOnIncompatibleInputShape(Array.isArray(e) ? d[0] : d), g = null != f && f.length > 0 && Array.isArray(f[0]) ? f.map(function (r, i) {
            return new SymbolicTensor(m, r, n, toList(e), t, n.name, i);
          }) : new SymbolicTensor(m, f, n, toList(e), t, n.name), n.addInboundNode(e, g, null, null, d, f, t), n._refCount++, null != n.activityRegularizer) throw new NotImplementedError("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return g;
        });
      }, t.prototype.warnOnIncompatibleInputShape = function (e) {
        if (null != this.batchInputShape) if (e.length !== this.batchInputShape.length) console.warn("The rank of the input tensor provided (shape: " + JSON.stringify(e) + ") does not match that of the batchInputShape (" + JSON.stringify(this.batchInputShape) + ") of the layer " + this.name);else {
          var t = !1;this.batchInputShape.forEach(function (n, r) {
            null != n && null != e[r] && e[r] !== n && (t = !0);
          }), t && console.warn("The shape of the input tensor (" + JSON.stringify(e) + ") does not match the expectation of layer " + this.name + ": " + JSON.stringify(this.batchInputShape));
        }
      }, Object.defineProperty(t.prototype, "outputShape", { get: function () {
          if (null == this.inboundNodes || 0 === this.inboundNodes.length) throw new AttributeError("The layer " + this.name + " has never been called and thus has no defined output shape.");for (var e = [], t = 0, n = this.inboundNodes; t < n.length; t++) {
            var r = n[t],
                i = JSON.stringify(r.outputShapes);-1 === e.indexOf(i) && e.push(i);
          }if (1 === e.length) {
            var a$$1 = this.inboundNodes[0].outputShapes;return Array.isArray(a$$1) && Array.isArray(a$$1[0]) && 1 === a$$1.length ? a$$1[0] : a$$1;
          }throw new AttributeError("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 }), t.prototype.countParams = function () {
        if (!this.built) throw new RuntimeError("You tried to call countParams() on " + this.name + ", but the layer is not built yet. Build it first by calling build(batchInputShape).");return countParamsInWeights(this.weights);
      }, t.prototype.build = function (e) {
        this.built = !0;
      }, t.prototype.getWeights = function (e) {
        return void 0 === e && (e = !1), batchGetValue(e ? this.trainableWeights : this.weights);
      }, t.prototype.setWeights = function (e) {
        var t = this;Pe(function () {
          var n = t.weights;if (n.length !== e.length) throw new ValueError('You called setWeights(weights) on layer "' + t.name + '" with a weight list of length ' + e.length + ", but the layer was expecting " + n.length + " weights. Provided weights: " + e + "...");if (0 !== n.length) {
            for (var r = [], i = batchGetValue(n), a$$1 = 0; a$$1 < i.length; ++a$$1) {
              var o = i[a$$1],
                  s = n[a$$1],
                  l$$1 = e[a$$1];if (!Z.arraysEqual(o.shape, l$$1.shape)) throw new ValueError("Layer weight shape " + o.shape + " not compatible with provided weight shape " + l$$1.shape);r.push([s, l$$1]);
            }batchSetValue(r);
          }
        });
      }, t.prototype.addWeight = function (e, t, n, r, i, a$$1, o) {
        if (-1 !== this._addedWeightNames.indexOf(e)) throw new ValueError("Duplicate weight name " + e + " for layer " + this.name);this._addedWeightNames.push(e), null == n && (n = "float32"), this.fastWeightInitDuringBuild && (r = getInitializer("zeros"));var s = r.apply(t, n),
            l$$1 = new LayerVariable(s, n, e, a$$1, o);return s.dispose(), null != i && this.addLoss(function () {
          return i.apply(l$$1.read());
        }), null == a$$1 && (a$$1 = !0), a$$1 ? this._trainableWeights.push(l$$1) : this._nonTrainableWeights.push(l$$1), l$$1;
      }, t.prototype.setFastWeightInitDuringBuild = function (e) {
        this.fastWeightInitDuringBuild = e;
      }, t.prototype.addLoss = function (e) {
        var t;null == e || Array.isArray(e) && 0 === e.length || (e = toList(e), void 0 !== this._losses && null !== this._losses && (t = this.losses).push.apply(t, e));
      }, t.prototype.computeOutputShape = function (e) {
        return e;
      }, t.prototype.computeMask = function (e, t) {
        var n = this;if (!this.supportsMasking) {
          if (null != t) {
            if (!Array.isArray(t)) throw new TypeError("Layer " + this.name + " does not support masking, but was passed an inputMask.");t.forEach(function (e) {
              if (null != e) throw new TypeError("Layer " + n.name + " does not support masking, but was passed an inputMask.");
            });
          }return null;
        }return t;
      }, t.prototype.addInboundNode = function (e, t, n, r, i, a$$1, o) {
        void 0 === o && (o = null);var s = toList(e);t = toList(t), n = toList(n), r = toList(r), i = normalizeShapeList(i), a$$1 = normalizeShapeList(a$$1);for (var l$$1 = [], u = [], c = [], p = 0, h = s; p < h.length; p++) {
          var d = h[p];l$$1.push(d.sourceLayer), u.push(d.nodeIndex), c.push(d.tensorIndex);
        }new Node({ outboundLayer: this, inboundLayers: l$$1, nodeIndices: u, tensorIndices: c, inputTensors: s, outputTensors: t, inputMasks: n, outputMasks: r, inputShapes: i, outputShapes: a$$1 }, o);for (var f = 0; f < t.length; f++) t[f].sourceLayer = this, t[f].nodeIndex = this.inboundNodes.length - 1, t[f].tensorIndex = f;
      }, t.prototype.getConfig = function () {
        var e = { name: this.name, trainable: this.trainable };return null != this.batchInputShape && (e.batchInputShape = this.batchInputShape), null != this.dtype && (e.dtype = this.dtype), e;
      }, t.prototype.disposeWeights = function () {
        return this.weights.forEach(function (e) {
          return e.dispose();
        }), this.weights.length;
      }, t.prototype.assertNotDisposed = function () {
        if (0 === this._refCount) throw new Error("Layer '" + this.name + "' is already disposed.");
      }, t.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 e = 0;return 0 == --this._refCount && (e = this.disposeWeights()), { refCountAfterDispose: this._refCount, numDisposedVariables: e };
      }, t;
    }(Fh.Serializable);function collectInputShape(e) {
      for (var t = [], n = 0, r = e = toList(e); n < r.length; n++) {
        var i = r[n];t.push(i.shape);
      }return singletonOrArray(t);
    }function guessOutputDType(e) {
      return "float32";
    }function getSourceInputs(e, t, n) {
      if ((null == t || null != n && n > 0) && (t = e.sourceLayer, n = e.nodeIndex), 0 === t.inboundNodes.length) return [e];var r = t.inboundNodes[n];if (0 === r.inboundLayers.length) return r.inputTensors;for (var i = [], a$$1 = 0; a$$1 < r.inboundLayers.length; a$$1++) for (var o = 0, s = getSourceInputs(r.inputTensors[a$$1], r.inboundLayers[a$$1], r.nodeIndices[a$$1]); o < s.length; o++) {
        var l$$1 = s[o];-1 === i.indexOf(l$$1) && i.push(l$$1);
      }return i;
    }var ModelLoggingVerbosity,
        InputLayer = function (e) {
      function t(t) {
        var n = e.call(this, { dtype: t.dtype, name: null != t.name ? t.name : getUid("input").toString() }) || this;if (null == t.batchSize && (t.batchSize = null), null == t.sparse && (t.sparse = !1), n.trainable = !1, n.built = !0, n.sparse = t.sparse, null != t.inputShape && null != t.batchInputShape) throw new ValueError("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");var r = t.batchInputShape;if (null == r) {
          if (null == t.inputShape) throw new ValueError("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");r = [t.batchSize].concat(t.inputShape);
        } else if (null != t.batchSize) throw new ValueError("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");var i = t.dtype || "float32";n.batchInputShape = r, n.dtype = i, n.inputSpec = [{ shape: r }];var a$$1 = new SymbolicTensor(n.dtype, n.batchInputShape, n, [], {}, n.name);return a$$1.nodeIndex = 0, a$$1.tensorIndex = 0, new Node({ outboundLayer: n, inboundLayers: [], nodeIndices: [], tensorIndices: [], inputTensors: [a$$1], outputTensors: [a$$1], inputMasks: [null], outputMasks: [null], inputShapes: [r], outputShapes: [r] }), n;
      }return __extends(t, e), t.prototype.apply = function (e, t) {
        throw new ValueError("Cannot pass any input to an InputLayer's apply() method. InputLayer name: " + this.name);
      }, t.prototype.dispose = function () {
        return { refCountAfterDispose: this._refCount, numDisposedVariables: 0 };
      }, t.prototype.getConfig = function () {
        return { batchInputShape: this.batchInputShape, dtype: this.dtype, sparse: this.sparse, name: this.name };
      }, t.className = "InputLayer", t;
    }(Layer);function Input(e) {
      if (null == e.batchShape && null == e.shape) throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");if (null != e.batchShape && null != e.shape) throw new ValueError("Please provide either a `shape` or `batchShape` argument to Input, but not both.");var t = e.batchShape;null != e.shape && null == t && (t = [null].concat(e.shape));var n = e.dtype;return null == n && (n = "float32"), new InputLayer({ batchInputShape: t, name: e.name, dtype: n, sparse: e.sparse }).inboundNodes[0].outputTensors[0];
    }function resolveScalarsInLogs(e) {
      return __awaiter(this, void 0, void 0, function () {
        var t, n, r, i, a$$1, o, s, l$$1;return __generator(this, function (u) {
          switch (u.label) {case 0:
              if (null == e) return [2];for (i in t = [], n = [], r = [], e) "number" != typeof (a$$1 = e[i]) && (o = a$$1, t.push(o.data()), n.push(i), r.push(o));return t.length > 0 ? [4, Promise.all(t)] : [3, 2];case 1:
              for (s = u.sent(), l$$1 = 0; l$$1 < s.length; ++l$$1) e[n[l$$1]] = s[l$$1][0];Le(r), u.label = 2;case 2:
              return [2];}
        });
      });
    }function disposeTensorsInLogs(e) {
      if (null != e) for (var t in e) {
        var n = e[t];"number" != typeof n && n.dispose();
      }
    }Fh.registerClass(InputLayer), function (e) {
      e[e.SILENT = 0] = "SILENT", e[e.VERBOSE = 1] = "VERBOSE";
    }(ModelLoggingVerbosity || (ModelLoggingVerbosity = {}));var DEFAULT_YIELD_EVERY_MS = 125,
        BaseCallback = function () {
      function e() {
        this.validationData = null;
      }return e.prototype.setParams = function (e) {
        this.params = e;
      }, e.prototype.onEpochBegin = function (e, t) {
        return __awaiter(this, void 0, void 0, function () {
          return __generator(this, function (e) {
            return [2];
          });
        });
      }, e.prototype.onEpochEnd = function (e, t) {
        return __awaiter(this, void 0, void 0, function () {
          return __generator(this, function (e) {
            return [2];
          });
        });
      }, e.prototype.onBatchBegin = function (e, t) {
        return __awaiter(this, void 0, void 0, function () {
          return __generator(this, function (e) {
            return [2];
          });
        });
      }, e.prototype.onBatchEnd = function (e, t) {
        return __awaiter(this, void 0, void 0, function () {
          return __generator(this, function (e) {
            return [2];
          });
        });
      }, e.prototype.onTrainBegin = function (e) {
        return __awaiter(this, void 0, void 0, function () {
          return __generator(this, function (e) {
            return [2];
          });
        });
      }, e.prototype.onTrainEnd = function (e) {
        return __awaiter(this, void 0, void 0, function () {
          return __generator(this, function (e) {
            return [2];
          });
        });
      }, e.prototype.setModel = function (e) {}, e;
    }(),
        CallbackList = function () {
      function e(e, t) {
        void 0 === t && (t = 10), null == e && (e = []), this.callbacks = e, this.queueLength = t;
      }return e.prototype.append = function (e) {
        this.callbacks.push(e);
      }, e.prototype.setParams = function (e) {
        for (var t = 0, n = this.callbacks; t < n.length; t++) {
          n[t].setParams(e);
        }
      }, e.prototype.setModel = function (e) {
        for (var t = 0, n = this.callbacks; t < n.length; t++) {
          n[t].setModel(e);
        }
      }, e.prototype.onEpochBegin = function (e, t) {
        return __awaiter(this, void 0, void 0, function () {
          var n, r;return __generator(this, function (i) {
            switch (i.label) {case 0:
                null == t && (t = {}), n = 0, r = this.callbacks, i.label = 1;case 1:
                return n < r.length ? [4, r[n].onEpochBegin(e, t)] : [3, 4];case 2:
                i.sent(), i.label = 3;case 3:
                return n++, [3, 1];case 4:
                return [2];}
          });
        });
      }, e.prototype.onEpochEnd = function (e, t) {
        return __awaiter(this, void 0, void 0, function () {
          var n, r;return __generator(this, function (i) {
            switch (i.label) {case 0:
                null == t && (t = {}), n = 0, r = this.callbacks, i.label = 1;case 1:
                return n < r.length ? [4, r[n].onEpochEnd(e, t)] : [3, 4];case 2:
                i.sent(), i.label = 3;case 3:
                return n++, [3, 1];case 4:
                return [2];}
          });
        });
      }, e.prototype.onBatchBegin = function (e, t) {
        return __awaiter(this, void 0, void 0, function () {
          var n, r;return __generator(this, function (i) {
            switch (i.label) {case 0:
                null == t && (t = {}), n = 0, r = this.callbacks, i.label = 1;case 1:
                return n < r.length ? [4, r[n].onBatchBegin(e, t)] : [3, 4];case 2:
                i.sent(), i.label = 3;case 3:
                return n++, [3, 1];case 4:
                return [2];}
          });
        });
      }, e.prototype.onBatchEnd = function (e, t) {
        return __awaiter(this, void 0, void 0, function () {
          var n, r;return __generator(this, function (i) {
            switch (i.label) {case 0:
                null == t && (t = {}), n = 0, r = this.callbacks, i.label = 1;case 1:
                return n < r.length ? [4, r[n].onBatchEnd(e, t)] : [3, 4];case 2:
                i.sent(), i.label = 3;case 3:
                return n++, [3, 1];case 4:
                return [2];}
          });
        });
      }, e.prototype.onTrainBegin = function (e) {
        return __awaiter(this, void 0, void 0, function () {
          var t, n;return __generator(this, function (r) {
            switch (r.label) {case 0:
                null == e && (e = {}), t = 0, n = this.callbacks, r.label = 1;case 1:
                return t < n.length ? [4, n[t].onTrainBegin(e)] : [3, 4];case 2:
                r.sent(), r.label = 3;case 3:
                return t++, [3, 1];case 4:
                return [2];}
          });
        });
      }, e.prototype.onTrainEnd = function (e) {
        return __awaiter(this, void 0, void 0, function () {
          var t, n;return __generator(this, function (r) {
            switch (r.label) {case 0:
                null == e && (e = {}), t = 0, n = this.callbacks, r.label = 1;case 1:
                return t < n.length ? [4, n[t].onTrainEnd(e)] : [3, 4];case 2:
                r.sent(), r.label = 3;case 3:
                return t++, [3, 1];case 4:
                return [2];}
          });
        });
      }, e;
    }(),
        BaseLogger = function (e) {
      function t() {
        return e.call(this) || this;
      }return __extends(t, e), t.prototype.onEpochBegin = function (e) {
        return __awaiter(this, void 0, void 0, function () {
          return __generator(this, function (e) {
            return this.seen = 0, this.totals = {}, [2];
          });
        });
      }, t.prototype.onBatchEnd = function (e, t) {
        return __awaiter(this, void 0, void 0, function () {
          var e,
              n,
              r,
              i,
              a$$1 = this;return __generator(this, function (o) {
            for (i in null == t && (t = {}), e = null == t.size ? 0 : t.size, this.seen += e, n = function (n) {
              var i = t[n];if ("number" == typeof i) r.totals.hasOwnProperty(n) || (r.totals[n] = 0), r.totals[n] = r.totals[n] + i * e;else {
                var o = void 0;n in r.totals ? o = r.totals[n] : r.totals[n] = 0, r.totals[n] = Pe(function () {
                  return Zu(a$$1.totals[n], pl(i, e));
                }), null != o && o.dispose();
              }
            }, r = this, t) n(i);return [2];
          });
        });
      }, t.prototype.onEpochEnd = function (e, t) {
        return __awaiter(this, void 0, void 0, function () {
          var e,
              n,
              r,
              i,
              a$$1,
              o = this;return __generator(this, function (s) {
            if (null != t) for (e = function (e) {
              if (null == n.totals[e]) return "continue";"number" == typeof n.totals[e] ? t[e] = n.totals[e] / n.seen : Pe(function () {
                t[e] = pl(rl(1, o.seen), o.totals[e]), o.totals[e].dispose(), We(t[e]);
              });
            }, n = this, r = 0, i = this.params.metrics; r < i.length; r++) a$$1 = i[r], e(a$$1);return [2];
          });
        });
      }, t;
    }(BaseCallback),
        History = function (e) {
      function t() {
        return null !== e && e.apply(this, arguments) || this;
      }return __extends(t, e), t.prototype.onTrainBegin = function (e) {
        return __awaiter(this, void 0, void 0, function () {
          return __generator(this, function (e) {
            return this.epoch = [], this.history = {}, [2];
          });
        });
      }, t.prototype.onEpochEnd = function (e, t) {
        return __awaiter(this, void 0, void 0, function () {
          var n;return __generator(this, function (r) {
            for (n in null == t && (t = {}), this.epoch.push(e), t) null == this.history[n] && (this.history[n] = []), this.history[n].push(t[n]);return [2];
          });
        });
      }, t.prototype.syncData = function () {
        return __awaiter(this, void 0, void 0, function () {
          var e, t, n, r, i, a$$1, o, s, l$$1;return __generator(this, function (u) {
            switch (u.label) {case 0:
                for (r in e = [], t = [], n = [], this.history) for (i = this.history[r], a$$1 = 0; a$$1 < i.length; ++a$$1) "number" != typeof i[a$$1] && (o = i[a$$1], e.push(o.data()), t.push(r), n.push(a$$1));return [4, Promise.all(e)];case 1:
                for (s = u.sent(), l$$1 = 0; l$$1 < s.length; ++l$$1) this.history[t[l$$1]][n[l$$1]].dispose(), this.history[t[l$$1]][n[l$$1]] = s[l$$1][0];return [2];}
          });
        });
      }, t;
    }(BaseCallback),
        CustomCallback = function (e) {
      function t(t, n) {
        var r = e.call(this) || this;if (r.currentEpoch = 0, r.yieldEvery = n || "auto", "auto" === r.yieldEvery && (r.yieldEvery = DEFAULT_YIELD_EVERY_MS), "never" === r.yieldEvery && null != t.onYield) throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");return Z.isNumber(r.yieldEvery) && (r.maybeWait = debounce(r.maybeWait.bind(r), r.yieldEvery)), r.trainBegin = t.onTrainBegin, r.trainEnd = t.onTrainEnd, r.epochBegin = t.onEpochBegin, r.epochEnd = t.onEpochEnd, r.batchBegin = t.onBatchBegin, r.batchEnd = t.onBatchEnd, r.yield = t.onYield, r;
      }return __extends(t, e), t.prototype.maybeWait = function (e, t, n) {
        return __awaiter(this, void 0, void 0, function () {
          var r;return __generator(this, function (i) {
            switch (i.label) {case 0:
                return r = [], null == this.yield ? [3, 2] : [4, resolveScalarsInLogs(n)];case 1:
                i.sent(), r.push(this.yield(e, t, n)), i.label = 2;case 2:
                return r.push(ep()), [4, Promise.all(r)];case 3:
                return i.sent(), [2];}
          });
        });
      }, t.prototype.onEpochBegin = function (e, t) {
        return __awaiter(this, void 0, void 0, function () {
          return __generator(this, function (n) {
            switch (n.label) {case 0:
                return this.currentEpoch = e, null == this.epochBegin ? [3, 3] : [4, resolveScalarsInLogs(t)];case 1:
                return n.sent(), [4, this.epochBegin(e, t)];case 2:
                n.sent(), n.label = 3;case 3:
                return [2];}
          });
        });
      }, t.prototype.onEpochEnd = function (e, t) {
        return __awaiter(this, void 0, void 0, function () {
          var n;return __generator(this, function (r) {
            switch (r.label) {case 0:
                return n = [], null == this.epochEnd ? [3, 2] : [4, resolveScalarsInLogs(t)];case 1:
                r.sent(), n.push(this.epochEnd(e, t)), r.label = 2;case 2:
                return "epoch" === this.yieldEvery && n.push(ep()), [4, Promise.all(n)];case 3:
                return r.sent(), [2];}
          });
        });
      }, t.prototype.onBatchBegin = function (e, t) {
        return __awaiter(this, void 0, void 0, function () {
          return __generator(this, function (n) {
            switch (n.label) {case 0:
                return null == this.batchBegin ? [3, 3] : [4, resolveScalarsInLogs(t)];case 1:
                return n.sent(), [4, this.batchBegin(e, t)];case 2:
                n.sent(), n.label = 3;case 3:
                return [2];}
          });
        });
      }, t.prototype.onBatchEnd = function (e, t) {
        return __awaiter(this, void 0, void 0, function () {
          var n;return __generator(this, function (r) {
            switch (r.label) {case 0:
                return n = [], null == this.batchEnd ? [3, 2] : [4, resolveScalarsInLogs(t)];case 1:
                r.sent(), n.push(this.batchEnd(e, t)), r.label = 2;case 2:
                return "batch" === this.yieldEvery ? n.push(ep()) : Z.isNumber(this.yieldEvery) && n.push(this.maybeWait(this.currentEpoch, e, t)), [4, Promise.all(n)];case 3:
                return r.sent(), [2];}
          });
        });
      }, t.prototype.onTrainBegin = function (e) {
        return __awaiter(this, void 0, void 0, function () {
          return __generator(this, function (t) {
            switch (t.label) {case 0:
                return null == this.trainBegin ? [3, 3] : [4, resolveScalarsInLogs(e)];case 1:
                return t.sent(), [4, this.trainBegin(e)];case 2:
                t.sent(), t.label = 3;case 3:
                return [2];}
          });
        });
      }, t.prototype.onTrainEnd = function (e) {
        return __awaiter(this, void 0, void 0, function () {
          return __generator(this, function (t) {
            switch (t.label) {case 0:
                return null == this.trainEnd ? [3, 3] : [4, resolveScalarsInLogs(e)];case 1:
                return t.sent(), [4, this.trainEnd(e)];case 2:
                t.sent(), t.label = 3;case 3:
                return [2];}
          });
        });
      }, t;
    }(BaseCallback);function standardizeCallbacks(e, t) {
      return null == e && (e = {}), e instanceof BaseCallback ? [e] : Array.isArray(e) && e[0] instanceof BaseCallback ? e : toList(e).map(function (e) {
        return new CustomCallback(e, t);
      });
    }var CallbackConstructorRegistry = function () {
      function e() {}return e.registerCallbackConstructor = function (t, n) {
        Z.assert(t >= 0 && Number.isInteger(t), function () {
          return "Verbosity level is expected to be an integer >= 0, but got " + t;
        }), e.checkForDuplicate(n), null == e.constructors[t] && (e.constructors[t] = []), e.constructors[t].push(n);
      }, e.checkForDuplicate = function (t) {
        for (var n in e.constructors) {
          e.constructors[+n].forEach(function (e) {
            if (e === t) throw new ValueError("Duplicate callback constructor.");
          });
        }
      }, e.clear = function () {
        e.constructors = {};
      }, e.createCallbacks = function (t) {
        var n = [];for (var r in e.constructors) {
          var i = +r;t >= i && n.push.apply(n, e.constructors[i]);
        }return n.map(function (e) {
          return new e();
        });
      }, e.constructors = {}, e;
    }();function configureCallbacks(e, t, n, r, i, a$$1, o, s, l$$1) {
      var u = new History(),
          c = [new BaseLogger()].concat(CallbackConstructorRegistry.createCallbacks(t));null != e && c.push.apply(c, e), c.push(u);var p = new CallbackList(c);return p.setParams({ epochs: n, initialEpoch: r, samples: i, steps: a$$1, batchSize: o, verbose: t, doValidation: s, metrics: l$$1 }), { callbackList: p, history: u };
    }function deserialize(e, t, n) {
      return void 0 === t && (t = {}), void 0 === n && (n = !1), deserializeKerasObject(e, Fh.SerializationMap.getMap().classNameMap, t, "layer", n);
    }function l2Normalize(e, t) {
      return Pe(function () {
        "float32" !== e.dtype && (e = e.asType("float32"));var n = Wu(square(e), t, !0),
            r = Nn(n.shape, epsilon()),
            i = Bs(il(n, r));return rl(e, i);
      });
    }function meanSquaredError(e, t) {
      return Pe(function () {
        return Bu(square(yl(t, e)), -1);
      });
    }function meanAbsoluteError(e, t) {
      return Pe(function () {
        return Bu(is(yl(t, e)), -1);
      });
    }function meanAbsolutePercentageError(e, t) {
      return Pe(function () {
        var n = yl(e, t),
            r = ds(is(e), epsilon(), Number.MAX_VALUE),
            i = is(rl(n, r));return pl(100, Bu(i, -1));
      });
    }function meanSquaredLogarithmicError(e, t) {
      return Pe(function () {
        var n = ds(t, epsilon(), Number.MAX_VALUE),
            r = ws(Zu(1, n)),
            i = ds(e, epsilon(), Number.MAX_VALUE),
            a$$1 = ws(Zu(1, i));return Bu(square(yl(r, a$$1)), -1);
      });
    }function squaredHinge(e, t) {
      return Pe(function () {
        var n = il(0, yl(1, pl(e, t)));return Bu(square(n), -1);
      });
    }function hinge(e, t) {
      return Pe(function () {
        var n = il(0, yl(1, pl(e, t)));return Bu(n, -1);
      });
    }function categoricalHinge(e, t) {
      return Pe(function () {
        var n = Wu(pl(e, t), -1),
            r = Fu(pl(yl(1, e), t), -1);return il(0, Zu(1, yl(r, n)));
      });
    }function logcosh(e, t) {
      return Pe(function () {
        var n = Math.log(2),
            r = yl(t, e),
            i = yl(Zu(r, Fs(pl(-2, r))), n);return Bu(i, -1);
      });
    }function categoricalCrossentropy(e, t, n) {
      return void 0 === n && (n = !1), Pe(function () {
        if (n) t = qr(t);else {
          var r = Wu(t, t.shape.length - 1, !0);t = rl(t, r);
        }return t = ds(t, epsilon(), 1 - epsilon()), Rs(Wu(pl(e.toFloat(), ws(t)), t.shape.length - 1));
      });
    }function sparseCategoricalCrossentropy(e, t) {
      return Pe(function () {
        var n = bs(flatten(e)).toInt(),
            r = (t = ds(t, epsilon(), 1 - epsilon())).shape;return categoricalCrossentropy(ar(n, r[r.length - 1]).reshape(r), t, !1);
      });
    }function sigmoidCrossEntropyWithLogits(e, t) {
      if (!Z.arraysEqual(e.shape, t.shape)) throw new ValueError("logits and labels must have the same shape, but got shapes " + JSON.stringify(e.shape) + " and " + JSON.stringify(t.shape));return Pe(function () {
        var n = t.relu(),
            r = t.abs().neg();return n.sub(t.mul(e)).add(r.exp().log1p());
      });
    }function binaryCrossentropy(e, t) {
      return Pe(function () {
        var n;return n = ds(t, epsilon(), 1 - epsilon()), n = ws(rl(n, yl(1, n))), Bu(sigmoidCrossEntropyWithLogits(e, n), -1);
      });
    }function kullbackLeiblerDivergence(e, t) {
      return Pe(function () {
        var n = ds(e, epsilon(), 1),
            r = ds(t, epsilon(), 1);return Wu(pl(e, ws(rl(n, r))), -1);
      });
    }function poisson(e, t) {
      return Pe(function () {
        var n = ws(Zu(epsilon(), t));return Bu(yl(t, pl(e, n)), -1);
      });
    }function cosineProximity(e, t) {
      return Pe(function () {
        var n = l2Normalize(e, -1),
            r = l2Normalize(t, -1),
            i = pl(n, r);return Rs(Wu(i, -1));
      });
    }var lossesMap = { meanSquaredError: meanSquaredError, meanAbsoluteError: meanAbsoluteError, meanAbsolutePercentageError: meanAbsolutePercentageError, meanSquaredLogarithmicError: meanSquaredLogarithmicError, squaredHinge: squaredHinge, hinge: hinge, categoricalHinge: categoricalHinge, logcosh: logcosh, categoricalCrossentropy: categoricalCrossentropy, sparseCategoricalCrossentropy: sparseCategoricalCrossentropy, binaryCrossentropy: binaryCrossentropy, kullbackLeiblerDivergence: kullbackLeiblerDivergence, poisson: poisson, cosineProximity: cosineProximity };function get(e) {
      if ("string" == typeof e) {
        if (e in lossesMap) return lossesMap[e];var t = "Unknown loss " + e;throw e.toLowerCase().includes("softmaxcrossentropy") && (t = "Unknown loss " + e + '. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy'), new ValueError(t);
      }return e;
    }function binaryAccuracy(e, t) {
      return Pe(function () {
        var n = pl(.5, Tn(t)),
            r = cast$1(Gu(t, n), e.dtype);return Bu(zu(e, r), -1);
      });
    }function categoricalAccuracy(e, t) {
      return Pe(function () {
        return cast$1(zu(_u(e, -1), _u(t, -1)), "float32");
      });
    }function truePositives(e, t) {
      return Pe(function () {
        return bl(e.equal(1), t.equal(1)).sum().cast("float32");
      });
    }function falseNegatives(e, t) {
      return Pe(function () {
        return bl(e.equal(1), t.equal(0)).sum().cast("float32");
      });
    }function falsePositives(e, t) {
      return Pe(function () {
        return bl(e.equal(0), t.equal(1)).sum().cast("float32");
      });
    }function precision(e, t) {
      return Pe(function () {
        var n = truePositives(e, t),
            r = falsePositives(e, t),
            i = n.add(r);return Rl(Gu(i, 0), n.div(i), 0).cast("float32");
      });
    }function recall(e, t) {
      return Pe(function () {
        var n = truePositives(e, t),
            r = falseNegatives(e, t),
            i = n.add(r);return Rl(Gu(i, 0), n.div(i), 0).cast("float32");
      });
    }function binaryCrossentropy$1(e, t) {
      return binaryCrossentropy(e, t);
    }function sparseCategoricalAccuracy(e, t) {
      return e.rank === t.rank && (e = e.squeeze([e.rank - 1])), (t = t.argMax(-1)).dtype !== e.dtype && (t = t.asType(e.dtype)), zu(e, t).asType("float32");
    }var mse$1 = meanSquaredError,
        MSE$1 = meanSquaredError,
        mae$1 = meanAbsoluteError,
        MAE$1 = meanAbsoluteError,
        mape$1 = meanAbsolutePercentageError,
        MAPE$1 = meanAbsolutePercentageError,
        categoricalCrossentropy$1 = categoricalCrossentropy,
        cosine$1 = cosineProximity,
        sparseCategoricalCrossentropy$1 = sparseCategoricalCrossentropy,
        metricsMap = { binaryAccuracy: binaryAccuracy, categoricalAccuracy: categoricalAccuracy, precision: precision, categoricalCrossentropy: categoricalCrossentropy$1, sparseCategoricalCrossentropy: sparseCategoricalCrossentropy$1, mse: mse$1, MSE: MSE$1, mae: mae$1, MAE: MAE$1, mape: mape$1, MAPE: MAPE$1, cosine: cosine$1 };function get$1(e) {
      if ("string" == typeof e && e in metricsMap) return metricsMap[e];if ("string" != typeof e && null != e) return e;throw new ValueError("Unknown metric " + e);
    }function getLossOrMetricName(e) {
      if (assert(null !== e, "Unknown LossOrMetricFn " + e), "string" == typeof e) return e;for (var t = void 0, n = 0, r = Object.keys(lossesMap); n < r.length; n++) {
        var i = r[n];if (lossesMap[i] === e) {
          t = i;break;
        }
      }if (void 0 !== t) return t;for (var a$$1 = 0, o = Object.keys(metricsMap); a$$1 < o.length; a$$1++) {
        i = o[a$$1];if (metricsMap[i] === e) {
          t = i;break;
        }
      }return void 0 !== t ? t : e.name;
    }function getOptimizer(e) {
      var t = { Adagrad: function () {
          return Zh.adagrad(.01);
        }, Adadelta: function () {
          return Zh.adadelta(1, .95, epsilon());
        }, Adam: function () {
          return Zh.adam(.001, .9, .999, epsilon());
        }, Adamax: function () {
          return Zh.adamax(.002, .9, .999, epsilon(), 0);
        }, RMSProp: function () {
          return Zh.rmsprop(.001, .9, 0, epsilon());
        }, SGD: function () {
          return Zh.sgd(.01);
        } };if (t.adagrad = t.Adagrad, t.adadelta = t.Adadelta, t.adam = t.Adam, t.adamax = t.Adamax, t.rmsprop = t.RMSProp, t.sgd = t.SGD, e in t) return t[e]();throw new ValueError("Unknown Optimizer " + e);
    }function printSummary(e, t, n, r) {
      void 0 === r && (r = console.log);var i,
          a$$1 = isModelSequentialLike(e),
          o = ["Layer (type)", "Output shape", "Param #"];if (a$$1 ? (t = t || 65, n = n || [.45, .85, 1]) : (t = t || 98, n = n || [.33, .55, .67, 1]), n[n.length - 1] <= 1 && (n = n.map(function (e) {
        return Math.floor(t * e);
      })), !a$$1) for (var s in o.push("Receives inputs"), i = [], e.nodesByDepth) i.push.apply(i, e.nodesByDepth[s]);r("_".repeat(t)), printRow(o, n, r), r("=".repeat(t));for (var l$$1 = e.layers, u = 0; u < l$$1.length; ++u) a$$1 ? printLayerSummary(l$$1[u], n, r) : printLayerSummaryWithConnections(l$$1[u], n, i, r), r((u === l$$1.length - 1 ? "=" : "_").repeat(t));e.checkTrainableWeightsConsistency();var c = countTrainableParams(e),
          p = countParamsInWeights(e.nonTrainableWeights);r("Total params: " + (c + p)), r("Trainable params: " + c), r("Non-trainable params: " + p), r("_".repeat(t));
    }function countTrainableParams(e) {
      return null != e.collectedTrainableWeights ? countParamsInWeights(e.collectedTrainableWeights) : countParamsInWeights(e.trainableWeights);
    }function isModelSequentialLike(e) {
      var t = !0,
          n = [],
          r = [];for (var i in e.nodesByDepth) n.push(e.nodesByDepth[i]);for (var a$$1 = 0, o = n; a$$1 < o.length; a$$1++) {
        var s = o[a$$1];if (s.length > 1 || 1 === s.length && s[0].inboundLayers.length > 1) {
          t = !1;break;
        }r.push.apply(r, s);
      }if (t) for (var l$$1 = 0, u = e.layers; l$$1 < u.length; l$$1++) {
        for (var c = !1, p = 0, h = u[l$$1].inboundNodes; p < h.length; p++) {
          var d = h[p];if (-1 !== r.indexOf(d)) {
            if (c) {
              t = !1;break;
            }c = !0;
          }
        }if (!t) break;
      }return t;
    }function printRow(e, t, n) {
      void 0 === n && (n = console.log);for (var r = "", i = 0; i < e.length; ++i) i > 0 && (r = r.slice(0, r.length - 1) + " "), r = (r += e[i]).slice(0, t[i]), r += " ".repeat(t[i] - r.length);n(r);
    }function printLayerSummary(e, t, n) {
      var r;try {
        r = JSON.stringify(e.outputShape);
      } catch (e) {
        r = "multiple";
      }printRow([e.name + " (" + e.getClassName() + ")", r, e.countParams().toString()], t, n);
    }function printLayerSummaryWithConnections(e, t, n, r) {
      var i;try {
        i = JSON.stringify(e.outputShape);
      } catch (e) {
        i = "multiple";
      }for (var a$$1 = [], o = 0, s = e.inboundNodes; o < s.length; o++) {
        var l$$1 = s[o];if (!(null != n && n.length > 0 && -1 === n.indexOf(l$$1))) for (var u = 0; u < l$$1.inboundLayers.length; ++u) {
          var c = l$$1.inboundLayers[u].name,
              p = l$$1.nodeIndices[u],
              h = l$$1.tensorIndices[u];a$$1.push(c + "[" + p + "][" + h + "]");
        }
      }var d = e.name,
          f = e.getClassName(),
          g = 0 === a$$1.length ? "" : a$$1[0];printRow([d + " (" + f + ")", i, e.countParams().toString(), g], t, r);for (u = 1; u < a$$1.length; ++u) printRow(["", "", "", a$$1[u]], t, r);
    }function isArrayItemInputOrOutputName(e, t, n) {
      return ("inboundNodes" === e || "outputLayers" === e || "inputLayers" === e) && 0 === t && "string" == typeof n;
    }function convertPythonicToTs(e, t) {
      if (null === e) return null;if ("string" == typeof e) return toCamelCase(e);if ("number" == typeof e || "boolean" == typeof e) return e;if (e instanceof Array) {
        for (var n = [], r = e.length, i = 0; i < r; ++i) {
          var a$$1 = e[i];isArrayItemInputOrOutputName(t, i, a$$1) ? n.push(a$$1) : n.push(convertPythonicToTs(a$$1, t));
        }return n;
      }for (var o = {}, s = 0, l$$1 = Object.keys(e); s < l$$1.length; s++) {
        var u = l$$1[s],
            c = e[u];if ("name" === u && "string" == typeof c) o[u] = c;else {
          var p = toCamelCase(u);o[p] = convertPythonicToTs(c, p);
        }
      }return o;
    }function convertTsToPythonic(e, t) {
      if (null === e || void 0 === e) return null;if ("string" == typeof e) return toSnakeCase(e);if ("number" == typeof e || "boolean" == typeof e) return e;if (e instanceof Array) {
        for (var n = [], r = e.length, i = 0; i < r; ++i) {
          var a$$1 = e[i];isArrayItemInputOrOutputName(t, i, a$$1) ? n.push(a$$1) : n.push(convertTsToPythonic(a$$1, t));
        }return n;
      }for (var o = {}, s = 0, l$$1 = Object.keys(e); s < l$$1.length; s++) {
        var u = l$$1[s],
            c = e[u],
            p = toSnakeCase(u);o[p] = "name" !== u && "className" !== u || "string" != typeof c ? convertTsToPythonic(c, u) : c;
      }return o;
    }var version = "1.2.3";function assertFeedCompatibility(e, t) {
      if (null == e.dtype || e.dtype === t.dtype) return t;try {
        return Jn(t, e.dtype);
      } catch (n) {
        throw new ValueError("The dtype of the feed (" + t.dtype + ") can not be cast to the dtype of the key '" + e.name + "' (" + e.dtype + ").");
      }
    }var FeedDict = function () {
      function e(t) {
        if (this.id2Value = {}, this.id2Mask = {}, this.name2Id = {}, t instanceof e) for (var n in t.id2Value) this.id2Value[n] = t.id2Value[n], n in t.id2Mask && (this.id2Mask[n] = t.id2Mask[n]);else {
          if (null == t) return;for (var r = 0, i = t; r < i.length; r++) {
            var a$$1 = i[r];this.add(a$$1.key, a$$1.value);
          }
        }
      }return e.prototype.add = function (e, t, n) {
        if (null != this.id2Value[e.id]) throw new ValueError("Duplicate key: name=" + e.name + ", id=" + e.id);return this.id2Value[e.id] = assertFeedCompatibility(e, t), this.name2Id[e.name] = e.id, null != n && (this.id2Mask[e.id] = n), this;
      }, e.prototype.addFeed = function (e) {
        this.add(e.key, e.value);
      }, e.prototype.hasKey = function (e) {
        return null != this.id2Value[e.id];
      }, e.prototype.names = function () {
        return Object.keys(this.name2Id);
      }, e.prototype.getValue = function (e) {
        if (e instanceof SymbolicTensor) {
          if (null == this.id2Value[e.id]) throw new ValueError("Nonexistent key: " + e.name);return this.id2Value[e.id];
        }var t = this.name2Id[e];if (null == t) throw new ValueError("Feed dict has no SymbolicTensor name: " + e);return this.id2Value[t];
      }, e.prototype.getMask = function (e) {
        if (e instanceof SymbolicTensor) {
          if (null == this.id2Value[e.id]) throw new ValueError("Nonexistent key: " + e.name);return this.id2Mask[e.id];
        }var t = this.name2Id[e];if (null == t) throw new ValueError("Feed dict has no SymbolicTensor name: " + e);return this.id2Mask[t];
      }, e.prototype.disposeMasks = function () {
        null != this.id2Mask && Le(this.id2Mask);
      }, e;
    }(),
        cachedSorted = {},
        cachedRecipientCounts = {};function execute(e, t, n, r) {
      for (var i = null != n && n.training, a$$1 = Array.isArray(e), o = a$$1 ? e : [e], s = o.map(function (e) {
        return e.name;
      }), l$$1 = [], u = t.names(), c = 0, p = s; c < p.length; c++) {
        var h = p[c];-1 !== u.indexOf(h) ? l$$1.push(t.getValue(h)) : l$$1.push(null);
      }null != r && (r.maxNumTensors = -1 / 0, r.minNumTensors = 1 / 0);var d,
          f,
          g = s.join(",") + "|" + t.names().join(",");if (null == cachedSorted[g]) {
        var m = getTopologicalSortAndRecipientCounts(o, t);d = m.sorted, f = m.recipientCounts, cachedSorted[g] = d, cachedRecipientCounts[g] = f;
      }d = cachedSorted[g], f = {}, i || Object.assign(f, cachedRecipientCounts[g]);for (var y = new FeedDict(t), v = 0; v < d.length; ++v) {
        if (null != r) {
          var b = Fe().numTensors;b > r.maxNumTensors && (r.maxNumTensors = b), b < r.minNumTensors && (r.minNumTensors = b);
        }var w = d[v],
            z = w.sourceLayer;if (!(z instanceof InputLayer)) {
          for (var S = [], A = [], _ = [], C = !1, I = 0, E = w.inputs; I < E.length; I++) {
            var N = E[I],
                k = y.getValue(N),
                L = y.getMask(N);S.push(k), A.push(L), null != L && (C = !0), i || (f[N.name]--, 0 !== f[N.name] || t.hasKey(N) || -1 !== s.indexOf(N.name) || k.isDisposed || !0 === N.sourceLayer.stateful || _.push(k));
          }C && ((n = n || {}).mask = A[0]);var x = toList(z.apply(S, n)),
              T = null;z.supportsMasking && (T = z.computeMask(S, A));for (var D = getNodeOutputs(w), O = Array.isArray(D) ? D : [D], R = 0; R < O.length; ++R) {
            y.hasKey(O[R]) || y.add(O[R], x[R], Array.isArray(T) ? T[0] : T);var M = s.indexOf(O[R].name);-1 !== M && (l$$1[M] = x[R]);
          }i || Le(_);
        }
      }return y.disposeMasks(), a$$1 ? l$$1 : l$$1[0];
    }function getTopologicalSortAndRecipientCounts(e, t) {
      Z.assert(null != e && e.length > 0, function () {
        return "Expected at least one fetch, got none";
      });var n = [],
          r = {};if (1 === e.length) {
        var i = getTopologicalSortAndRecipientCountsForOneFetch(e[0], t);n = i.sorted, r = i.recipientMap;
      } else for (var a$$1 = new Set(), o = 0, s = e; o < s.length; o++) {
        for (var l$$1 = getTopologicalSortAndRecipientCountsForOneFetch(s[o], t), u = l$$1.sorted, c = l$$1.recipientMap, p = 0, h = u; p < h.length; p++) {
          var d = h[p];a$$1.has(d.name) || (n.push(d), a$$1.add(d.name));
        }var f = function (e) {
          null == r[e] && (r[e] = new Set()), c[e].forEach(function (t) {
            return r[e].add(t);
          });
        };for (var g in c) f(g);
      }return { sorted: n, recipientCounts: recipientMap2Counts(r) };
    }function recipientMap2Counts(e) {
      var t = {};for (var n in e) t[n] = e[n].size;return t;
    }function getTopologicalSortAndRecipientCountsForOneFetch(e, t) {
      for (var n = new Set(), r = [], i = {}, a$$1 = 0, o = t.names(); a$$1 < o.length; a$$1++) {
        var s = o[a$$1];n.add(s);
      }var l$$1 = [],
          u = [];for (l$$1.push(e); l$$1.length > 0;) {
        var c = l$$1[l$$1.length - 1];if (n.has(c.name)) l$$1.pop();else {
          var p = u[u.length - 1] === l$$1.length - 1;if (0 === c.inputs.length || p) l$$1.pop(), r.push(c), n.add(c.name), p && u.pop();else {
            u.push(l$$1.length - 1);for (var h = 0, d = c.inputs; h < d.length; h++) {
              var f = d[h];null == i[f.name] && (i[f.name] = new Set()), i[f.name].add(c.name), n.has(f.name) || l$$1.push(f);
            }
          }
        }
      }return { sorted: r, recipientMap: i };
    }function getNodeOutputs(e) {
      var t;if (1 === e.sourceLayer.inboundNodes.length) t = e.sourceLayer.output;else {
        for (var n = null, r = 0; r < e.sourceLayer.inboundNodes.length; ++r) for (var i = 0, a$$1 = e.sourceLayer.inboundNodes[r].outputTensors; i < a$$1.length; i++) {
          if (a$$1[i].id === e.id) {
            n = r;break;
          }
        }t = e.sourceLayer.getOutputAt(n);
      }return t;
    }var Container = function (e) {
      function t(n) {
        var r = e.call(this, {}) || this;if (r.containerNodes = new Set(), r.name = n.name, null == r.name) {
          var i = r.getClassName().toLowerCase();r.name = getUid(i);
        }if (r.supportsMasking = !1, r.trainable_ = !0, Array.isArray(n.inputs) ? r.inputs = n.inputs.slice() : r.inputs = [n.inputs], Array.isArray(n.outputs) ? r.outputs = n.outputs.slice() : r.outputs = [n.outputs], unique(r.inputs).length !== r.inputs.length) throw new ValueError("The list of inputs passed to the model is redundant. All inputs should only appear once. Found: " + r.inputs.map(function (e) {
          return e.name;
        }));unique(r.outputs).length !== r.outputs.length && console.warn("The list of outputs passed to the model is redundant. All outputs should only appear once. Found: " + r.outputs.map(function (e) {
          return e.name;
        })), r.inputLayers = [], r.inputLayersNodeIndices = [], r.inputLayersTensorIndices = [], r.outputLayers = [], r.outputLayersNodeIndices = [], r.outputLayersTensorIndices = [], r.layers = [];for (var a$$1 = 0, o = r.outputs; a$$1 < o.length; a$$1++) {
          var s = (I = o[a$$1]).sourceLayer,
              l$$1 = I.nodeIndex,
              u = I.tensorIndex;r.outputLayers.push(s), r.outputLayersNodeIndices.push(l$$1), r.outputLayersTensorIndices.push(u);
        }for (var c = 0, p = r.inputs; c < p.length; c++) {
          s = (I = p[c]).sourceLayer, l$$1 = I.nodeIndex, u = I.tensorIndex;assert(0 === l$$1, "input layer has >1 nodes"), assert(0 === u, "input layer has >1 tensors"), r.inputLayers.push(s), r.inputLayersNodeIndices.push(l$$1), r.inputLayersTensorIndices.push(u);
        }r.inputNames = [], r.outputNames = [], r.feedInputShapes = [], r.feedInputNames = [], r.feedOutputNames = [];for (var h = 0; h < r.inputLayers.length; h++) {
          if (!((s = r.inputLayers[h]) instanceof InputLayer)) throw new TypeError("Input layers to a LayersModel must be InputLayer objects. Received inputs: " + n.inputs + ". Input " + h + " (0-based) originates from layer type " + s.getClassName() + ".");r.inputNames.push(s.name), r.feedInputShapes.push(s.batchInputShape), r.feedInputNames.push(s.name);
        }for (var d = 0, f = r.outputLayers; d < f.length; d++) {
          s = f[d];r.outputNames.push(s.name);
        }r.internalInputShapes = r.inputs.map(function (e) {
          return e.shape;
        }), r.internalOutputShapes = r.outputs.map(function (e) {
          return e.shape;
        });for (var g = {}, m = {}, y = {}, v = {}, b = {}, w = [], z = function (e, n, i, a$$1, o, s) {
          null != a$$1 && null != o && null != s || (a$$1 = e.sourceLayer, o = e.nodeIndex, s = e.tensorIndex);var l$$1 = a$$1.inboundNodes[o];if (-1 !== i.indexOf(l$$1)) throw new RuntimeError("The tensor " + e.name + ' at layer "' + a$$1.name + '" is part of a cycle.');if (-1 === n.indexOf(l$$1)) {
            r.containerNodes.add(t.nodeKey(a$$1, o)), (a$$1.id in b) || (b[a$$1.id] = Object.keys(b).length), -1 === i.indexOf(l$$1) && i.push(l$$1);for (var u = l$$1.inboundLayers.length, c = 0; c < u; c++) {
              var p = l$$1.inputTensors[c],
                  h = l$$1.inboundLayers[c],
                  d = l$$1.nodeIndices[c],
                  f = l$$1.tensorIndices[c];z(p, n, i, h, d, f);
            }for (n.push(l$$1); i.indexOf(l$$1) >= 0;) i.splice(i.indexOf(l$$1), 1);w.push(l$$1);
          }
        }, S = [], A = [], _ = 0, C = r.outputs; _ < C.length; _++) {
          var I = C[_];z(I, S, A);
        }for (var E = 0, N = w.slice().reverse(); E < N.length; E++) {
          m[(K = N[E]).id] = K, K.id in g || (g[K.id] = 0);var k = g[K.id],
              L = null == y[K.outboundLayer.id] ? 0 : y[K.outboundLayer.id];k = Math.max(k, L), y[K.outboundLayer.id] = k, v[K.outboundLayer.id] = K.outboundLayer, g[K.id] = k;for (h = 0; h < K.inboundLayers.length; h++) {
            var x = K.inboundLayers[h],
                T = (l$$1 = K.nodeIndices[h], x.inboundNodes[l$$1]),
                D = null == g[T.id] ? 0 : g[T.id];g[T.id] = Math.max(k + 1, D), m[T.id] = T;
          }
        }var O = {};for (var R in g) {
          (k = g[R]) in O || (O[k] = []), O[k].push(m[R]);
        }var M = {};for (var P in y) {
          (k = y[P]) in M || (M[k] = []), M[k].push(v[P]);
        }var F = Object.keys(M).map(function (e) {
          return parseInt(e, 10);
        }).sort(reverseNumberCompare);r.layers = [];for (var V = 0, B = F; V < B.length; V++) {
          var U = M[k = B[V]];U.sort(function (e, t) {
            var n = b[e.id],
                r = b[t.id];return n < r ? -1 : n > r ? 1 : 0;
          });for (var W = 0, j = U; W < j.length; W++) {
            s = j[W];r.layers.push(s);
          }
        }r.layersByDepth = M, F = Object.keys(O).map(function (e) {
          return parseInt(e, 10);
        }).sort(reverseNumberCompare);for (var $ = r.inputs.slice(), q = [], G = 0, H = F; G < H.length; G++) for (var J = 0, Z$$1 = O[k = H[G]]; J < Z$$1.length; J++) {
          var K;if (null != (s = (K = Z$$1[J]).outboundLayer)) {
            for (var Y = 0, X = K.inputTensors; Y < X.length; Y++) {
              I = X[Y];if (-1 === $.indexOf(I)) throw new RuntimeError("Graph disconnected: cannot obtain value for tensor " + I + ' at layer "' + s.name + '". The following previous layers were accessed without issue: ' + q);
            }for (var Q = 0, ee = K.outputTensors; Q < ee.length; Q++) {
              I = ee[Q];$.push(I);
            }q.push(s.name);
          }
        }r.nodesByDepth = O;for (var te = r.layers.map(function (e) {
          return e.name;
        }), ne = function (e) {
          var t = te.filter(function (t) {
            return t === e;
          }).length;if (1 !== t) throw new RuntimeError('The name "' + e + '" is used ' + t + " times in the model. All layer names should be unique. Layer names: " + JSON.stringify(te));
        }, re = 0, ie = te; re < ie.length; re++) {
          ne(ie[re]);
        }return r.outboundNodes = [], r.inboundNodes = [], new Node({ outboundLayer: r, inboundLayers: [], nodeIndices: [], tensorIndices: [], inputTensors: r.inputs, outputTensors: r.outputs, inputMasks: r.inputs.map(function (e) {
            return null;
          }), outputMasks: r.outputs.map(function (e) {
            return null;
          }), inputShapes: r.inputs.map(function (e) {
            return e.shape;
          }), outputShapes: r.outputs.map(function (e) {
            return e.shape;
          }) }), r.built = !0, r._refCount = 1, r;
      }return __extends(t, e), t.prototype.assertNotDisposed = function () {
        if (0 === this._refCount) throw new Error("Container '" + this.name + "' is already disposed.");
      }, t.prototype.dispose = function () {
        this.assertNotDisposed();var e = { refCountAfterDispose: null, numDisposedVariables: 0 };if (0 == --this._refCount) for (var t = 0, n = this.layers; t < n.length; t++) {
          var r = n[t];e.numDisposedVariables += r.dispose().numDisposedVariables;
        }return e.refCountAfterDispose = this._refCount, e;
      }, Object.defineProperty(t.prototype, "trainable", { get: function () {
          return this.trainable_;
        }, set: function (e) {
          this.layers.forEach(function (t) {
            t._trainableWeights.forEach(function (t) {
              return t.trainable = e;
            });
          }), this.trainable_ = e;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "trainableWeights", { get: function () {
          if (this._trainableWeights.length > 0) throw new ValueError("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if (!this.trainable) return [];for (var e = [], t = 0, n = this.layers; t < n.length; t++) {
            var r = n[t];e = e.concat(r.trainableWeights);
          }return e;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "nonTrainableWeights", { get: function () {
          for (var e = [], t = 0, n = this.layers; t < n.length; t++) {
            var r = n[t];e.push.apply(e, r.nonTrainableWeights);
          }if (!this.trainable) {
            for (var i = [], a$$1 = 0, o = this.layers; a$$1 < o.length; a$$1++) {
              r = o[a$$1];i.push.apply(i, r.trainableWeights);
            }return i.concat(e);
          }return e;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "weights", { get: function () {
          return this.trainableWeights.concat(this.nonTrainableWeights);
        }, enumerable: !0, configurable: !0 }), t.prototype.loadWeights = function (e, t) {
        void 0 === t && (t = !0);for (var n = {}, r = 0, i = 0, a$$1 = this.layers; i < a$$1.length; i++) for (var o = 0, s = a$$1[i].weights; o < s.length; o++) {
          var l$$1 = s[o];if (null != n[l$$1.originalName]) throw new ValueError("Duplicate weight name: " + l$$1.originalName);n[l$$1.originalName] = l$$1, r++;
        }var u = [];for (var c in e) {
          if (null != n[c]) u.push([n[c], e[c]]);else if (t) throw new ValueError("Provided weight data has no target variable: " + c);delete n[c];
        }if (t) {
          var p = [];for (var h in n) p.push(h);if (p.length > 0) throw new ValueError(p.length + " of " + r + " weights are not set: " + p);
        }batchSetValue(u);
      }, t.prototype.updatedConfig = function () {
        var e = this.getConfig(),
            t = {};return t.className = this.getClassName(), t.config = e, t.kerasVersion = "tfjs-layers " + version, t.backend = "TensorFlow.js", t;
      }, t.prototype.toJSON = function (e, t) {
        void 0 === t && (t = !0);var n = convertTsToPythonic(this.updatedConfig());return t ? JSON.stringify(n) : n;
      }, t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          e = toList(e);for (var r = new FeedDict(), i = 0; i < n.inputs.length; ++i) r.add(n.inputs[i], e[i]);return execute(n.outputs, r, t);
        });
      }, t.prototype.computeMask = function (e, t) {
        var n = this;return Pe(function () {
          var r;return e = toList(e), r = null == t ? pyListRepeat(null, e.length) : toList(t), n.runInternalGraph(e, r)[1];
        });
      }, t.prototype.computeOutputShape = function (e) {
        var t = normalizeShapeList(e);if (t.length !== this.inputLayers.length) throw new ValueError("Invalid inputShape argument " + e + ": model has " + this.inputLayers.length + " tensor inputs.");for (var n = {}, r = 0; r < t.length; r++) {
          var i = this.inputLayers[r],
              a$$1 = t[r];n[A = i.name + "_0_0"] = a$$1;
        }var o = Object.keys(this.nodesByDepth).map(function (e) {
          return parseInt(e, 10);
        }).sort(reverseNumberCompare);if (o.length > 1) for (var s = 0, l$$1 = o; s < l$$1.length; s++) for (var u = l$$1[s], c = 0, p = this.nodesByDepth[u]; c < p.length; c++) {
          var h = p[c];i = h.outboundLayer;if (-1 === this.inputLayers.map(function (e) {
            return e.id;
          }).indexOf(i.id)) {
            for (var d = [], f = 0; f < h.inboundLayers.length; f++) {
              var g = h.inboundLayers[f],
                  m = h.nodeIndices[f],
                  y = h.tensorIndices[f],
                  v = n[A = g.name + "_" + m + "_" + y];d.push(v);
            }var b = normalizeShapeList(i.computeOutputShape(singletonOrArray(d))),
                w = i.inboundNodes.indexOf(h);for (f = 0; f < b.length; f++) {
              n[A = i.name + "_" + w + "_" + f] = b[f];
            }
          }
        }var z = [],
            S = [];for (r = 0; r < this.outputLayers.length; r++) {
          i = this.outputLayers[r], w = this.outputLayersNodeIndices[r], y = this.outputLayersTensorIndices[r];var A = i.name + "_" + w + "_" + y;S.push(A);
        }for (r = 0; r < S.length; r++) {
          var _ = S[r];assert(_ in n), z.push(n[_]);
        }return singletonOrArray(z);
      }, t.prototype.runInternalGraph = function (e, t) {
        null == t && (t = pyListRepeat(null, e.length));for (var n = {}, r = 0; r < this.inputs.length; ++r) {
          var i = this.inputs[r],
              a$$1 = e[r],
              o = t[r];n[i.id] = [a$$1, o];
        }for (var s = 0, l$$1 = Object.keys(this.nodesByDepth).map(function (e) {
          return parseInt(e, 10);
        }).sort(reverseNumberCompare); s < l$$1.length; s++) for (var u = l$$1[s], c = 0, p = this.nodesByDepth[u]; c < p.length; c++) {
          for (var h = p[c], d = h.outboundLayer, f = h.inputTensors, g = h.outputTensors, m = new Array(), y = 0, v = f; y < v.length; y++) {
            (i = v[y]).id in n && m.push(n[i.id]);
          }if (m.length === f.length) {
            var b = {},
                w = void 0,
                z = void 0,
                S = void 0,
                A = void 0;if (null != h.callArgs && (b = h.callArgs), 1 === m.length) {
              var _ = m[0],
                  C = _[0],
                  I = _[1];null == b.mask && (b.mask = I), S = toList(d.call(C, b)), A = toList(d.computeMask(C, I)), w = [C], z = [I];
            } else w = m.map(function (e) {
              return e[0];
            }), z = m.map(function (e) {
              return e[1];
            }), null == b.mask && (b.mask = z), S = toList(d.call(w, b)), A = toList(d.computeMask(w, z));if (d.activityRegularizer) throw new NotImplementedError("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for (r = 0; r < g.length; ++r) {
              i = g[r], a$$1 = S[r], o = A[r];n[i.id] = [a$$1, o];
            }
          }
        }for (var E = [], N = [], k = [], L = 0, x = this.outputs; L < x.length; L++) {
          assert((i = x[L]).id in n, "Could not compute output " + i.name + " : " + i.id);var T = n[i.id],
              D = T[0];o = T[1];k.push(D.shape), E.push(D), N.push(o);
        }return [E, N, k];
      }, t.prototype.buildNodeConversionMap = function (e) {
        for (var n, r = {}, i = 0, a$$1 = this.layers; i < a$$1.length; i++) {
          var o = a$$1[i];n = o instanceof t ? 1 : 0;for (var s = 0; s < o.inboundNodes.length; s++) {
            var l$$1 = t.nodeKey(o, s);this.containerNodes.has(l$$1) && (r[l$$1] = n, n += 1);
          }
        }return r;
      }, t.prototype.getLayer = function (e, t) {
        if (null != t) {
          if (this.layers.length <= t) throw new ValueError("Was asked to retrieve layer at index " + t + ", but model only has " + this.layers.length + " layer(s).");return this.layers[t];
        }if (null == e) throw new ValueError("Provide either a layer name or layer index");for (var n = 0, r = this.layers; n < r.length; n++) {
          var i = r[n];if (i.name === e) return i;
        }throw new ValueError("No such layer: " + e);
      }, t.prototype.calculateLosses = function () {
        var e = this;return Pe(function () {
          for (var n = [], r = 0, i = e.layers; r < i.length; r++) for (var a$$1 = i[r], o = 0; o < a$$1.inboundNodes.length; ++o) {
            var s = t.nodeKey(a$$1, o);e.containerNodes.has(s) && n.push.apply(n, a$$1.calculateLosses());
          }return n;
        });
      }, t.prototype.getConfig = function () {
        for (var e = { name: this.name }, n = this.buildNodeConversionMap(this.layers), r = [], i = 0, a$$1 = this.layers; i < a$$1.length; i++) {
          for (var o = (w = a$$1[i]).getClassName(), s = w.getConfig(), l$$1 = [], u = 0; u < w.inboundNodes.length; u++) {
            var c = w.inboundNodes[u],
                p = t.nodeKey(w, u),
                h = {};if (this.containerNodes.has(p)) {
              if (c.callArgs) try {
                JSON.stringify(c.callArgs), h = c.callArgs;
              } catch (e) {
                console.warn("Layer " + w.name + " was passed non-serializable keyword arguments: " + c.callArgs + ". They will not be included in the serialized model (and thus will be missing at deserialization time)."), h = {};
              }if (c.inboundLayers.length > 0) {
                for (var d = [], f = 0; f < c.inboundLayers.length; f++) {
                  var g = c.inboundLayers[f],
                      m = c.nodeIndices[f],
                      y = c.tensorIndices[f];null == (S = n[t.nodeKey(g, m)]) && (S = 0), d.push([g.name, S, y, h]);
                }l$$1.push(d);
              }
            }
          }var v = {};v.name = w.name, v.className = o, v.config = s, v.inboundNodes = l$$1, r.push(v);
        }e.layers = r;var b = [];for (f = 0; f < this.inputLayers.length; f++) {
          var w = this.inputLayers[f];m = this.inputLayersNodeIndices[f], p = t.nodeKey(w, m);if (this.containerNodes.has(p)) {
            null !== (S = n[p]) && void 0 !== S || (S = 0);y = this.inputLayersTensorIndices[f];b.push([w.name, S, y]);
          }
        }e.inputLayers = b;var z = [];for (f = 0; f < this.outputLayers.length; f++) {
          w = this.outputLayers[f], m = this.outputLayersNodeIndices[f], p = t.nodeKey(w, m);if (this.containerNodes.has(p)) {
            var S;null !== (S = n[p]) && void 0 !== S || (S = 0);y = this.outputLayersTensorIndices[f];z.push([w.name, S, y]);
          }
        }return e.outputLayers = z, e;
      }, t.fromConfig = function (e, t, n, r) {
        void 0 === n && (n = {}), void 0 === r && (r = !1);var i = {},
            a$$1 = {};function o(e, t) {
          e.name in a$$1 ? a$$1[e.name].push(t) : a$$1[e.name] = [t];
        }function s(e, t) {
          for (var n, r = [], a$$1 = 0, s = t; a$$1 < s.length; a$$1++) {
            var l$$1 = s[a$$1],
                u = l$$1[0],
                c = l$$1[1],
                p = l$$1[2];if (n = null == l$$1[3] ? {} : l$$1[3], !(u in i)) return void o(e, t);var h = i[u];if (h.inboundNodes.length <= c) return void o(e, t);var d = h.inboundNodes[c];r.push(d.outputTensors[p]);
          }r.length > 0 && e.apply(singletonOrArray(r), n);
        }function l$$1(e) {
          var n = e.name,
              a$$1 = deserialize(e, null != t.customObjects ? t.customObjects : {});a$$1.setFastWeightInitDuringBuild(r), i[n] = a$$1, e.inboundNodes.forEach(function (e) {
            if (!(e instanceof Array)) throw new ValueError("Corrupted configuration, expected array for nodeData: " + e);o(a$$1, e);
          });
        }for (var u = t.name, c = t.layers, p = 0, h = c; p < h.length; p++) {
          l$$1(g = h[p]);
        }for (; !isObjectEmpty(a$$1);) for (var d = 0, f = c; d < f.length; d++) {
          var g = f[d];if ((k = i[g.name]).name in a$$1) {
            var m = a$$1[k.name];delete a$$1[k.name];for (var y = 0, v = m; y < v.length; y++) {
              s(k, v[y]);
            }
          }
        }for (var b = [], w = [], z = 0, S = t.inputLayers; z < S.length; z++) {
          var A = (g = S[z])[0],
              _ = g[1],
              C = g[2];assert(A in i);var I = (k = i[A]).inboundNodes[_].outputTensors;b.push(I[C]);
        }for (var E = 0, N = t.outputLayers; E < N.length; E++) {
          A = (g = N[E])[0], _ = g[1], C = g[2];assert(A in i);var k;I = (k = i[A]).inboundNodes[_].outputTensors;w.push(I[C]);
        }return new e({ inputs: b, outputs: w, name: u });
      }, Object.defineProperty(t.prototype, "stateful", { get: function () {
          if (this._stateful) throw new ValueError("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 e = 0, t = this.layers; e < t.length; e++) {
            if (t[e].stateful) return !0;
          }return !1;
        }, enumerable: !0, configurable: !0 }), t.prototype.resetStates = function () {
        var e = this;Pe(function () {
          e.layers.forEach(function (e) {
            e.stateful && e.resetStates();
          });
        });
      }, t;
    }(Layer);function standardizeSampleOrClassWeights(e, t, n) {
      var r = t.length;if (null == e || Array.isArray(e) && 0 === e.length) return t.map(function (e) {
        return null;
      });if (1 === r) return Array.isArray(e) && 1 === e.length ? e : "object" == typeof e && t[0] in e ? [e[t[0]]] : [e];if (Array.isArray(e)) {
        if (e.length !== r) throw new Error("Provided " + n + " is an array of " + e.length + " element(s), but the model has " + r + " outputs. Make sure a set of weights is provided for each model output.");return e;
      }if ("object" == typeof e && Object.keys(e).length > 0 && "object" == typeof e[Object.keys(e)[0]]) {
        var i = [];return t.forEach(function (t) {
          t in e ? i.push(e[t]) : i.push(null);
        }), i;
      }throw new Error("The model has multiple (" + r + ") outputs, so " + n + " must be either an array with " + r + " elements or an object with " + t + " keys. Provided " + n + " not understood: " + JSON.stringify(e));
    }function standardizeClassWeights(e, t) {
      return standardizeSampleOrClassWeights(e, t, "classWeight");
    }function standardizeWeights(e, t, n, r) {
      return __awaiter(this, void 0, void 0, function () {
        var i, a$$1, o, s, l$$1;return __generator(this, function (u) {
          switch (u.label) {case 0:
              if (null != t || null != r) throw new Error("Support sampleWeight is not implemented yet");return null == n ? [3, 2] : (i = Pe(function () {
                if (1 === e.shape.length) return e.clone();if (2 === e.shape.length) {
                  if (e.shape[1] > 1) {
                    return e.argMax(1);
                  }if (1 === e.shape[1]) return e.reshape([e.shape[0]]);throw new Error("Encountered unexpected last-dimension size (" + e.shape[1] + ") during handling of class weights. The size is expected to be >= 1.");
                }throw new Error("Unexpected rank of target (y) tensor (" + e.rank + ") during handling of class weights. The rank is expected to be 1 or 2.");
              }), s = (o = Array).from, [4, i.data()]);case 1:
              return a$$1 = s.apply(o, [u.sent()]), Le(i), l$$1 = [], a$$1.forEach(function (e) {
                if (null == n[e]) throw new Error("classWeight must contain all classes in the training data. The class " + e + " exists in the data but not in classWeight");l$$1.push(n[e]);
              }), [2, xn(l$$1, "float32")];case 2:
              return [2, null];}
        });
      });
    }function computeWeightedLoss(e, t) {
      return pl(e, t);
    }var DEFAULT_VALIDATION_BATCH_SIZE = 32;function standardizeDataIteratorOutput(e, t) {
      var n,
          r,
          i = t;n = i.xs, r = i.ys, Z.assert(null != n && null != r, function () {
        return "A Dataset iterator for fitDataset() is expected to generate objects of the form `{xs: xVal, ys: yVal}`, where the two values may be `tf.Tensor`, an array of Tensors, or a map of string to Tensor.  The provided Dataset instead generates " + t;
      });var a$$1 = flattenTensorOrArrayOrMap("input", e.inputNames, n),
          o = flattenTensorOrArrayOrMap("output", e.outputNames, r),
          s = a$$1[0].shape[0];Z.assert(a$$1.length === e.inputs.length, function () {
        return "LayersModel has " + e.inputs.length + " inputs, but the dataset provides " + a$$1.length + " inputs.  (Expected input keys: " + JSON.stringify(e.inputNames) + ")";
      }), Z.assert(o.length === e.outputs.length, function () {
        return "LayersModel has " + e.outputs.length + " outputs, but the dataset provides " + o.length + " outputs.  (Expected output keys: " + JSON.stringify(e.outputNames) + ")";
      });var l$$1 = function (t) {
        Z.assert(a$$1[t].shape[0] === s, function () {
          return "Batch size mismatch: input " + e.inputNames[t] + " has " + a$$1[t].shape[0] + "; expected  " + s + " based on input " + e.inputNames[0] + ".";
        });
      };for (var u in a$$1) l$$1(u);var c = function (t) {
        Z.assert(o[t].shape[0] === s, function () {
          return "Batch size mismatch: output " + e.outputNames[t] + " has " + o[t].shape[0] + "; expected  " + s + " based on input " + e.inputNames[0] + ".";
        });
      };for (var p in o) c(p);return { xs: a$$1, ys: o };
    }function flattenTensorOrArrayOrMap(e, t, n) {
      if (n instanceof ft) return [n];if (Array.isArray(n)) return Z.assert(n.length === t.length, function () {
        return "Received an array of " + n.length + " Tensors, but expected " + t.length + " to match the " + e + " keys " + t + ".";
      }), n;for (var r = [], i = 0, a$$1 = t; i < a$$1.length; i++) {
        var o = a$$1[i];if (null == n[o]) throw new ValueError("The feature data generated by the dataset lacks the required " + e + " key '" + o + "'.");r.push(n[o]);
      }return r;
    }function standardizeTensorValidationData(e) {
      if (3 === e.length) throw new NotImplementedError("Validation with sample weights is not implemented yet.");return { xs: e[0], ys: e[1] };
    }function fitDataset(e, t, n) {
      return __awaiter(this, void 0, void 0, function () {
        var r, i, a$$1, o, s, l$$1, u, c, p, h, d, f, g, m, y, v, b, w, z, S, A, _, C, I, E, N, k, L, x, T, D, O, R, M;return __generator(this, function (P) {
          switch (P.label) {case 0:
              if (r = null != n.batchesPerEpoch, Z.assert(null != e.optimizer, function () {
                return "You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig).";
              }), Z.assert(null != n, function () {
                return "For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call.";
              }), Z.assert(null != n.epochs && n.epochs > 0 && Number.isInteger(n.epochs), function () {
                return "For fitDataset(), config.epochs is expected to be a positive integer, but got " + n.epochs;
              }), Z.assert(!r || n.batchesPerEpoch > 0 && Number.isInteger(n.batchesPerEpoch), function () {
                return "For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got " + n.batchesPerEpoch;
              }), Z.assert(null == n.validationSplit, function () {
                return "`validationSplit` is not supported by `fitDataset()`. Use validationData instead.";
              }), e.isTraining) throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining = !0, P.label = 1;case 1:
              return P.trys.push([1,, 26, 27]), i = null != n.validationData, a$$1 = void 0, o = void 0, i && (isDatasetObject(n.validationData) ? Z.assert(null == n.validationBatches || n.validationBatches > 0 && Number.isInteger(n.validationBatches), function () {
                return "For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got " + n.validationBatches;
              }) : (s = standardizeTensorValidationData(n.validationData), a$$1 = s.xs, o = s.ys)), l$$1 = e.makeTrainFunction(), u = e.getDedupedMetricsNames(), c = void 0, c = i ? u.slice().concat(u.map(function (e) {
                return "val_" + e;
              })) : u.slice(), p = standardizeCallbacks(n.callbacks, n.yieldEvery), h = null == n.verbose ? 1 : n.verbose, d = configureCallbacks(p, h, n.epochs, null, null, getStepsPerEpoch(t, n), null, i, c), f = d.callbackList, g = d.history, f.setModel(e), e.history = g, [4, f.onTrainBegin()];case 2:
              return P.sent(), e.stopTraining_ = !1, m = null == n.initialEpoch ? 0 : n.initialEpoch, [4, t.iterator()];case 3:
              y = P.sent(), P.label = 4;case 4:
              return m < n.epochs ? (v = {}, [4, f.onEpochBegin(m)]) : [3, 23];case 5:
              return P.sent(), b = 0, w = 0, r ? [3, 7] : [4, t.iterator()];case 6:
              y = P.sent(), P.label = 7;case 7:
              return !r || b < n.batchesPerEpoch ? [4, y.next()] : [3, 21];case 8:
              return z = P.sent(), r && z.done ? (console.warn("You provided `batchesPerEpoch` as " + n.batchesPerEpoch + ", but your dataset iterator ran out of data after " + b + " batches; interrupting training. Make sure that your dataset can generate at least `batchesPerEpoch * epochs` batches (in this case, " + n.batchesPerEpoch * n.epochs + " batches). You may need to use the repeat() function when building your dataset."), [3, 21]) : null == z.value ? [3, 15] : (S = standardizeDataIteratorOutput(e, z.value), A = S.xs, _ = S.ys, (C = {}).batch = w, C.size = A[0].shape[0], [4, f.onBatchBegin(w, C)]);case 9:
              if (P.sent(), I = [], null == n.classWeight) return [3, 13];E = standardizeClassWeights(n.classWeight, e.outputNames), M = 0, P.label = 10;case 10:
              return M < E.length ? (k = (N = I).push, [4, standardizeWeights(_[M], null, E[M])]) : [3, 13];case 11:
              k.apply(N, [P.sent()]), P.label = 12;case 12:
              return ++M, [3, 10];case 13:
              for (L = A.concat(_).concat(I), x = l$$1(L), Le(L), M = 0; M < u.length; ++M) T = u[M], D = x[M], C[T] = D, We(D);return [4, f.onBatchEnd(w, C)];case 14:
              P.sent(), disposeTensorsInLogs(C), w++, b++, P.label = 15;case 15:
              return (r ? b >= n.batchesPerEpoch : z.done) ? i ? (O = void 0, isDatasetObject(n.validationData) ? (R = toList, [4, e.evaluateDataset(n.validationData, { batches: n.validationBatches })]) : [3, 17]) : [3, 19] : [3, 20];case 16:
              return O = R.apply(void 0, [P.sent()]), [3, 18];case 17:
              O = toList(e.evaluate(a$$1, o, { batchSize: null == n.validationBatchSize ? DEFAULT_VALIDATION_BATCH_SIZE : n.validationBatchSize, verbose: 0 })), P.label = 18;case 18:
              for (M = 0; M < e.metricsNames.length; ++M) v["val_" + e.metricsNames[M]] = O[M];P.label = 19;case 19:
              return [3, 21];case 20:
              return e.stopTraining_ ? [3, 21] : [3, 7];case 21:
              return [4, f.onEpochEnd(m, v)];case 22:
              return P.sent(), m++, e.stopTraining_ ? [3, 23] : [3, 4];case 23:
              return [4, f.onTrainEnd()];case 24:
              return P.sent(), [4, e.history.syncData()];case 25:
              return P.sent(), [2, e.history];case 26:
              return e.isTraining = !1, [7];case 27:
              return [2];}
        });
      });
    }function getStepsPerEpoch(e, t) {
      var n = null;return null != t.batchesPerEpoch ? n = t.batchesPerEpoch : Number.isFinite(e.size) && (n = e.size), n;
    }function isDatasetObject(e) {
      return "function" == typeof e.iterator;
    }function isLazyIteratorObject(e) {
      return "function" == typeof e.next;
    }function evaluateDataset(e, t, n) {
      return __awaiter(this, void 0, void 0, function () {
        var r, i, a$$1, o, s, l$$1, u, c, p, h;return __generator(this, function (d) {
          switch (d.label) {case 0:
              if (r = null != (n = n || {}).batches, i = e.testFunction, a$$1 = [], n.verbose > 0) throw new NotImplementedError("Verbose mode is not implemented yet.");return Z.assert(!r || n.batches > 0 && Number.isInteger(n.batches), function () {
                return "Test loop expects `batches` to be a positive integer, but received " + JSON.stringify(n.batches);
              }), isLazyIteratorObject(t) ? (s = t, [3, 3]) : [3, 1];case 1:
              return [4, t.iterator()];case 2:
              s = d.sent(), d.label = 3;case 3:
              o = s, l$$1 = 0, u = 0, c = function () {
                var t;return __generator(this, function (s) {
                  switch (s.label) {case 0:
                      return [4, o.next()];case 1:
                      return t = s.sent(), a$$1 = Pe(function () {
                        if (t.value) {
                          var n = standardizeDataIteratorOutput(e, t.value),
                              r = n.xs,
                              o = n.ys,
                              s = r.concat(o),
                              c = Pe(function () {
                            return i(s);
                          });if (Le(s), 0 === u) for (var p = 0; p < c.length; ++p) a$$1.push(yn(0));var h = s[0].shape[0],
                              d = function (e) {
                            var t = c[e],
                                n = a$$1[e];a$$1[e] = Pe(function () {
                              return Zu(a$$1[e], pl(h, t));
                            }), u > 0 && Le(n);
                          };for (p = 0; p < c.length; ++p) d(p);Le(c), l$$1 += h, ++u;
                        }return a$$1;
                      }), t.done ? (r && console.warn("Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least `batches` batches (in this case, " + n.batches + " batches). You may need to use the repeat() function when building your dataset."), [2, "break"]) : [2];}
                });
              }, d.label = 4;case 4:
              return !r || u < n.batches ? [5, c()] : [3, 6];case 5:
              return "break" === d.sent() ? [3, 6] : [3, 4];case 6:
              for (p = 0; p < a$$1.length; ++p) h = a$$1[p], a$$1[p] = rl(a$$1[p], l$$1), Le(h);return [2, singletonOrArray(a$$1)];}
        });
      });
    }function checkBatchSize(e) {
      Z.assert(e > 0 && Number.isInteger(e), function () {
        return "batchSize is required to be a positive integer, but got " + e;
      });
    }function sliceArrays(e, t, n) {
      return null == e ? [null] : Array.isArray(e) ? e.map(function (e) {
        return sliceAlongFirstAxis(e, t, n - t);
      }) : sliceAlongFirstAxis(e, t, n - t);
    }function sliceArraysByIndices(e, t) {
      return Pe(function () {
        return null == e ? null : Array.isArray(e) ? e.map(function (e) {
          return sliceArraysByIndices(e, t);
        }) : gather$1(e, "int32" === t.dtype ? t : t.toInt());
      });
    }function makeBatches(e, t) {
      for (var n = [], r = 0, i = null; r < e;) (i = r + t) >= e && (i = e), n.push([r, i]), r = i;return n;
    }function fitLoop(e, t, n, r, i, a$$1, o, s, l$$1, u, c, p, h, d, f) {
      return __awaiter(this, void 0, void 0, function () {
        var g, m, y, v, b, w, z, S;return __generator(this, function (A) {
          switch (A.label) {case 0:
              if (null == i && (i = 32), null == a$$1 && (a$$1 = 1), null == c && (c = !0), null == h && (h = 0), g = !1, null != l$$1 && null != u && (g = !0), null != f && (g = !0, null == d)) throw new ValueError("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");return null != (m = e.checkNumSamples(n, i, d, "steps_per_epoch")) && (y = range(0, m)), null == o && (o = 1), v = configureCallbacks(s, o, a$$1, h, m, d, i, g, p), b = v.callbackList, w = v.history, b.setModel(e), e.history = w, [4, b.onTrainBegin()];case 1:
              A.sent(), e.stopTraining_ = !1, z = function (a$$1) {
                var o, s, p, h, f;return __generator(this, function (v) {
                  switch (v.label) {case 0:
                      return [4, b.onEpochBegin(a$$1)];case 1:
                      if (v.sent(), o = {}, null == d) return [3, 2];throw new NotImplementedError("stepsPerEpoch mode is not implemented yet.");case 2:
                      if ("batch" === c) throw new NotImplementedError("batch shuffling is not implemneted yet");c && Z.shuffle(y), s = xn(y), p = makeBatches(m, i), h = function (a$$1) {
                        var c;return __generator(this, function (h) {
                          switch (h.label) {case 0:
                              return c = {}, [4, b.onBatchBegin(a$$1, c)];case 1:
                              return h.sent(), Pe(function () {
                                var h = p[a$$1][0],
                                    d = p[a$$1][1],
                                    f = sliceAlongFirstAxis(s, h, d - h);c.batch = a$$1, c.size = d - h;for (var m = sliceArraysByIndices(n, f), y = t(m), v = 0; v < r.length; ++v) {
                                  var b = r[v],
                                      w = y[v];c[b] = w, We(w);
                                }if (a$$1 === p.length - 1 && g) {
                                  var z = e.testLoop(l$$1, u, i);for (v = 0; v < r.length; ++v) {
                                    b = r[v], w = z[v];We(w), o["val_" + b] = w;
                                  }
                                }
                              }), [4, b.onBatchEnd(a$$1, c)];case 2:
                              return h.sent(), disposeTensorsInLogs(c), e.stopTraining_ ? [2, "break"] : [2];}
                        });
                      }, f = 0, v.label = 3;case 3:
                      return f < p.length ? [5, h(f)] : [3, 6];case 4:
                      if ("break" === v.sent()) return [3, 6];v.label = 5;case 5:
                      return ++f, [3, 3];case 6:
                      s.dispose(), v.label = 7;case 7:
                      return [4, b.onEpochEnd(a$$1, o)];case 8:
                      return v.sent(), e.stopTraining_ ? [2, "break"] : [2];}
                });
              }, S = h, A.label = 2;case 2:
              return S < a$$1 ? [5, z(S)] : [3, 5];case 3:
              if ("break" === A.sent()) return [3, 5];A.label = 4;case 4:
              return ++S, [3, 2];case 5:
              return [4, b.onTrainEnd()];case 6:
              return A.sent(), [4, e.history.syncData()];case 7:
              return A.sent(), [2, e.history];}
        });
      });
    }function fitTensors(e, t, n, r) {
      return void 0 === r && (r = {}), __awaiter(this, void 0, void 0, function () {
        var i, a$$1, o, s, l$$1, u, c, p, h, d, f, g, m, y, v, b, w, z, S, A, _, C;return __generator(this, function (I) {
          switch (I.label) {case 0:
              if (e.isTraining) throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining = !0, I.label = 1;case 1:
              return I.trys.push([1,, 7, 8]), checkBatchSize(p = null == r.batchSize ? 32 : r.batchSize), h = !1, [4, e.standardizeUserData(t, n, r.sampleWeight, r.classWeight, h, p)];case 2:
              if (d = I.sent(), i = d[0], a$$1 = d[1], c = d[2], f = !1, g = void 0, !(null != r.validationData && r.validationData.length > 0)) return [3, 4];if (f = !0, 2 !== r.validationData.length) throw 3 === r.validationData.length ? new NotImplementedError("validationData including sample weights is not supported yet.") : new ValueError("When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; " + r.validationData + " is invalid.");return o = r.validationData[0], s = r.validationData[1], m = !0, [4, e.standardizeUserData(o, s, null, null, m, p)];case 3:
              return y = I.sent(), l$$1 = y[0], u = y[1], g = l$$1.concat(u), [3, 5];case 4:
              null != r.validationSplit && r.validationSplit > 0 && r.validationSplit < 1 ? (f = !0, v = Math.floor(i[0].shape[0] * (1 - r.validationSplit)), b = i[0].shape[0], l$$1 = sliceArrays(i, v, b), i = sliceArrays(i, 0, v), u = sliceArrays(a$$1, v, b), a$$1 = sliceArrays(a$$1, 0, v), g = l$$1.concat(u)) : null != r.validationSteps && (f = !0), I.label = 5;case 5:
              return w = i.concat(a$$1).concat(c), e.checkTrainableWeightsConsistency(), z = e.makeTrainFunction(), S = e.getDedupedMetricsNames(), A = void 0, _ = void 0, f ? (e.makeTestFunction(), A = e.testFunction, _ = S.slice().concat(S.map(function (e) {
                return "val_" + e;
              }))) : (A = null, g = [], _ = S.slice()), C = standardizeCallbacks(r.callbacks, r.yieldEvery), [4, fitLoop(e, z, w, S, p, r.epochs, r.verbose, C, A, g, r.shuffle, _, r.initialEpoch, null, null)];case 6:
              return [2, I.sent()];case 7:
              return e.isTraining = !1, disposeNewTensors(i, t), disposeNewTensors(a$$1, n), disposeNewTensors(l$$1, o), disposeNewTensors(u, s), null != c && Le(c), [7];case 8:
              return [2];}
        });
      });
    }function ensureTensorsRank2OrHigher(e) {
      var t = [];e instanceof ft && (e = [e]);for (var n = 0; n < e.length; ++n) {
        var r = e[n];if (1 === r.rank) t.push(expandDims$1(r, 1));else {
          if (0 === r.rank) throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");t.push(r);
        }
      }return t;
    }function disposeNewTensors(e, t) {
      if (null != e) {
        var n = [];if (t instanceof ft) n.push(t.id);else if (Array.isArray(t)) t.forEach(function (e) {
          return n.push(e.id);
        });else if (null != t) for (var r in t) {
          var i = t[r];n.push(i.id);
        }var a$$1 = [];if (e instanceof ft) -1 === n.indexOf(e.id) && a$$1.push(e);else if (Array.isArray(e)) e.forEach(function (e) {
          -1 === n.indexOf(e.id) && a$$1.push(e);
        });else if (null != e) for (var o in e) {
          var s = e[o];-1 === n.indexOf(s.id) && a$$1.push(s);
        }a$$1.forEach(function (e) {
          e.isDisposed || e.dispose();
        });
      }
    }function isDataTensor(e) {
      return e instanceof ft;
    }function isDataArray(e) {
      return Array.isArray(e);
    }function isDataDict(e) {
      return !isDataTensor(e) && !isDataArray(e);
    }function standardizeInputData(e, t, n, r, i) {
      if (void 0 === r && (r = !0), void 0 === i && (i = ""), null == t || 0 === t.length) {
        if (null != e) {
          var a$$1 = !1;if (isDataArray(e) && e.length > 0) a$$1 = !0;else if (isDataDict(e)) {
            for (var o in e) if (e.hasOwnProperty(o)) {
              a$$1 = !0;break;
            }
          } else a$$1 = !0;if (a$$1) throw new ValueError("Error when checking model " + i + " expected no data, but got " + e);
        }return [];
      }if (null == e) return t.map(function (e) {
        return null;
      });var s;if (isDataDict(e)) {
        e = e, s = [];for (var l$$1 = 0, u = t; l$$1 < u.length; l$$1++) {
          var c = u[l$$1];if (null == e[c]) throw new ValueError('No data provided for "' + c + '". Need data for each key in: ' + t);s.push(e[c]);
        }
      } else if (isDataArray(e)) {
        if ((e = e).length !== t.length) throw new ValueError("Error when checking model " + i + ": the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see " + t.length + " Tensor(s), but instead got the following list of Tensor(s): " + e);s = e;
      } else {
        if (e = e, t.length > 1) throw new ValueError("The model " + i + " expects " + t.length + " Tensor(s), but only received one Tensor. Found: Tensor with shape " + e.shape);s = [e];
      }if (s = ensureTensorsRank2OrHigher(s), null != n) for (var p = 0; p < t.length; ++p) if (null != n[p]) {
        var h = s[p];if (h.shape.length !== n[p].length) throw new ValueError("Error when checking " + i + ": expected " + t[p] + " to have " + n[p].length + " dimension(s). but got array with shape " + h.shape);for (var d = 0; d < n[p].length; ++d) if (0 !== d || r) {
          var f = h.shape[d],
              g = n[p][d];if (null != g && g >= 0 && f !== g) throw new ValueError("Error when checking " + i + ": expected " + t[p] + " to have shape [" + n[p] + "], but got array with shape [" + h.shape + "].");
        }
      }return s;
    }function checkArrayLengths(e, t, n) {
      var r = unique(e.map(function (e) {
        return e.shape[0];
      }));r.sort();var i = unique(t.map(function (e) {
        return e.shape[0];
      }));if (i.sort(), r.length > 1) throw new ValueError("All input Tensors (x) should have the same number of samples. Got array shapes: " + JSON.stringify(e.map(function (e) {
        return e.shape;
      })));if (i.length > 1) throw new ValueError("All target Tensors (y) should have the same number of samples. Got array shapes: " + JSON.stringify(t.map(function (e) {
        return e.shape;
      })));if (r.length > 0 && i.length > 0 && !Z.arraysEqual(r, i)) throw new ValueError("Input Tensors should have the same number of samples as target Tensors. Found " + r[0] + " input sample(s) and " + i[0] + " target sample(s).");
    }function checkLossAndTargetCompatibility(e, t, n) {
      for (var r = [meanSquaredError, binaryCrossentropy, categoricalCrossentropy], i = 0; i < e.length; ++i) {
        var a$$1 = e[i],
            o = t[i],
            s = n[i];if (null != o) {
          if (o === categoricalCrossentropy && 1 === a$$1.shape[a$$1.shape.length - 1]) throw new ValueError("You are passing a target array of shape " + a$$1.shape + " while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].");if (-1 !== r.indexOf(o)) for (var l$$1 = a$$1.shape.slice(1), u = s.slice(1), c = 0; c < l$$1.length; ++c) {
            var p = l$$1[c],
                h = u[c];if (null != h && p !== h) throw new ValueError("A target Tensor with shape " + a$$1.shape + " was passed for an output of shape " + s + ", while using a loss function that expects targets to have the same shape as the output.");
          }
        }
      }
    }function checkInputData(e, t, n, r, i) {
      var a$$1;if (void 0 === r && (r = !0), void 0 === i && (i = ""), Array.isArray(e)) {
        if (e.length !== t.length) throw new ValueError("Error when checking model " + i + ": the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see " + t.length + " Tensor(s), but instead got " + e.length + " Tensors(s).");a$$1 = e;
      } else {
        if (t.length > 1) throw new ValueError("The model expects " + t.length + " " + i + " Tensors, but only received one Tensor. Found: array with shape " + JSON.stringify(e.shape) + ".");a$$1 = [e];
      }if (null != n) for (var o = 0; o < t.length; ++o) if (null != n[o]) {
        var s = a$$1[o];if (s.shape.length !== n[o].length) throw new ValueError("Error when checking " + i + ": expected " + t[o] + " to have " + n[o].length + " dimension(s), but got array with shape " + JSON.stringify(s.shape));for (var l$$1 = 0; l$$1 < n[o].length; ++l$$1) if (0 !== l$$1 || r) {
          var u = s.shape[l$$1],
              c = n[o][l$$1];if (null != c && c !== u) throw new ValueError("Error when checking " + i + ": expected " + t[o] + " to have shape " + JSON.stringify(n[o]) + " but got array with shape " + JSON.stringify(s.shape) + ".");
        }
      }
    }function collectMetrics(e, t) {
      if (null == e || Array.isArray(e) && 0 === e.length) return t.map(function (e) {
        return [];
      });var n;if ("string" == typeof e || "function" == typeof e) n = [e];else {
        if (!Array.isArray(e) && "object" != typeof e) throw new TypeError("Type of metrics argument not understood. Expected an string,function, Array, or Object, found: " + e);n = e;
      }if (Array.isArray(n)) return t.map(function (e) {
        return n;
      });for (var r = [], i = 0, a$$1 = t; i < a$$1.length; i++) {
        var o = a$$1[i],
            s = n.hasOwnProperty(o) ? n[o] : [];Array.isArray(s) || (s = [s]), r.push(s);
      }return r;
    }var LAYERS_MODEL_FORMAT_NAME = "layers-model",
        LayersModel = function (e) {
      function t(t) {
        var n = e.call(this, t) || this;return n.isTraining = !1, n;
      }return __extends(t, e), t.prototype.summary = function (e, t, n) {
        if (void 0 === n && (n = console.log), !this.built) throw new ValueError("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).");printSummary(this, e, t, n);
      }, t.prototype.compile = function (e) {
        var t = this;if (null == e.loss && (e.loss = []), this.loss = e.loss, "string" == typeof e.optimizer) this.optimizer_ = getOptimizer(e.optimizer), this.isOptimizerOwned = !0;else {
          if (!(e.optimizer instanceof qh)) throw new ValueError("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_ = e.optimizer, this.isOptimizerOwned = !1;
        }var n = [];if (Array.isArray(e.loss) || "string" == typeof e.loss || "function" == typeof e.loss) {
          if (Array.isArray(e.loss)) {
            if (e.loss.length !== this.outputs.length) throw new ValueError("When passing an Array as loss, it should have one entry per model output. The model has " + this.outputs.length + " output(s), but you passed loss=" + e.loss + ".");var r = e.loss;n = r.map(function (e) {
              return get(e);
            });
          } else {
            var i = get(e.loss);this.outputs.forEach(function (e) {
              n.push(i);
            });
          }
        } else {
          for (var a$$1 in e.loss = e.loss, e.loss) if (-1 === this.outputNames.indexOf(a$$1)) throw new ValueError('Unknown entry in loss dictionary: "' + a$$1 + '". Only expected the following keys: ' + this.outputNames);for (var o = 0, s = this.outputNames; o < s.length; o++) {
            var l$$1 = s[o];null == e.loss[l$$1] && console.warn('Output "' + l$$1 + '" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ' + l$$1 + " during training"), n.push(get(e.loss[l$$1]));
          }
        }this.lossFunctions = n, this.feedOutputNames = [], this.feedOutputShapes = [], this.feedLossFns = [];for (var u = 0; u < this.outputs.length; ++u) {
          var c = this.internalOutputShapes[u],
              p = this.outputNames[u];this.feedOutputNames.push(p), this.feedOutputShapes.push(c), this.feedLossFns.push(this.lossFunctions[u]);
        }var h = [];this.metrics = e.metrics, this.metricsNames = ["loss"], this.metricsTensors = [], nameScope("loss", function () {
          for (var e = 0; e < t.outputs.length; ++e) if (-1 === h.indexOf(e)) {
            var n = t.lossFunctions[e];t.outputs.length > 1 && (t.metricsTensors.push([n, e]), t.metricsNames.push(t.outputNames[e] + "_loss"));
          }
        });var d = collectMetrics(e.metrics, this.outputNames);nameScope("metric", function () {
          for (var e = function (e) {
            if (-1 !== h.indexOf(e)) return "continue";!function (n) {
              for (var r, i, a$$1, o = function (n) {
                if ("string" == typeof n && -1 !== ["accuracy", "acc", "crossentropy", "ce"].indexOf(n)) {
                  var o = t.internalOutputShapes[e];1 === o[o.length - 1] || t.lossFunctions[e] === binaryCrossentropy ? -1 !== ["accuracy", "acc"].indexOf(n) ? i = binaryAccuracy : -1 !== ["crossentropy", "ce"].indexOf(n) && (i = binaryCrossentropy$1) : t.lossFunctions[e] === sparseCategoricalCrossentropy ? -1 !== ["accuracy", "acc"].indexOf(n) ? i = sparseCategoricalAccuracy : -1 !== ["crossentropy", "ce"].indexOf(n) && (i = sparseCategoricalCrossentropy$1) : -1 !== ["accuracy", "acc"].indexOf(n) ? i = categoricalAccuracy : -1 !== ["crossentropy", "ce"].indexOf(n) && (i = categoricalCrossentropy$1);var s = void 0;-1 !== ["accuracy", "acc"].indexOf(n) ? s = "acc" : -1 !== ["crossentropy", "ce"].indexOf(n) && (s = "ce"), a$$1 = i, r = "" + s;
                } else {
                  var l$$1 = get$1(n);a$$1 = l$$1, r = "" + getLossOrMetricName(n);
                }var u;nameScope(r, function () {
                  u = a$$1;
                }), function (e, n, r) {
                  t.outputNames.length > 1 && (n = t.outputNames[e] + "_" + n), t.metricsNames.push(n), t.metricsTensors.push([r, e]);
                }(e, r, u);
              }, s = 0, l$$1 = n; s < l$$1.length; s++) o(l$$1[s]);
            }(d[e]);
          }, n = 0; n < t.outputs.length; ++n) e(n);
        }), this.collectedTrainableWeights = this.trainableWeights;
      }, t.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?");
      }, t.prototype.evaluate = function (e, t, n) {
        void 0 === n && (n = {});var r = null == n.batchSize ? 32 : n.batchSize;checkBatchSize(r);var i = this.standardizeUserDataXY(e, t, !0, r);try {
          var a$$1 = i[0].concat(i[1]);this.makeTestFunction();var o = this.testFunction;return singletonOrArray(this.testLoop(o, a$$1, r, n.verbose, n.steps));
        } finally {
          disposeNewTensors(i[0], e), disposeNewTensors(i[1], t);
        }
      }, t.prototype.evaluateDataset = function (e, t) {
        return __awaiter(this, void 0, void 0, function () {
          return __generator(this, function (n) {
            return this.makeTestFunction(), [2, evaluateDataset(this, e, t)];
          });
        });
      }, t.prototype.checkNumSamples = function (e, t, n, r) {
        var i;if (void 0 === r && (r = "steps"), null != n) {
          if (i = null, null != t) throw new ValueError("If " + r + " is set, batchSize must be null or undefined.Got batchSize = " + t);
        } else {
          if (null == e) throw new ValueError("Either the input data should have a defined shape, or " + r + " shoud be specified.");i = Array.isArray(e) ? e[0].shape[0] : e.shape[0];
        }return i;
      }, t.prototype.execute = function (e, t) {
        if (Array.isArray(t) && 0 === t.length) throw new ValueError("`outputs` is an empty Array, which is not allowed.");var n = Array.isArray(t),
            r = n ? t : [t],
            i = this.retrieveSymbolicTensors(r),
            a$$1 = new FeedDict();if (e instanceof ft && (e = [e]), Array.isArray(e)) {
          if (e.length !== this.inputs.length) throw new ValueError("The number of inputs provided (" + e.length + ") does not match the number of inputs of this model (" + this.inputs.length + ").");for (var o = 0; o < this.inputs.length; ++o) a$$1.add(this.inputs[o], e[o]);
        } else for (var s = 0, l$$1 = this.inputs; s < l$$1.length; s++) {
          var u = l$$1[s],
              c = e[u.name];if (null == c) throw new ValueError("No value is provided for the model's input " + u.name);a$$1.add(u, c);
        }var p = execute(i, a$$1);return n ? p : p[0];
      }, t.prototype.retrieveSymbolicTensors = function (e) {
        for (var t = pyListRepeat(null, e.length), n = e.length, r = 0, i = this.layers; r < i.length; r++) {
          for (var a$$1 = i[r], o = Array.isArray(a$$1.output) ? a$$1.output : [a$$1.output], s = o.map(function (e) {
            return e.name;
          }), l$$1 = 0; l$$1 < e.length; ++l$$1) {
            var u = s.indexOf(e[l$$1]);if (-1 !== u && (t[l$$1] = o[u], n--), 0 === n) break;
          }if (0 === n) break;
        }if (n > 0) {
          var c = [];throw t.forEach(function (t, n) {
            null == t && c.push(e[n]);
          }), new ValueError("Cannot find SymbolicTensors for output name(s): " + JSON.stringify(c));
        }return t;
      }, t.prototype.predictLoop = function (e, t, n) {
        var r = this;return void 0 === t && (t = 32), void 0 === n && (n = !1), Pe(function () {
          var i = r.checkNumSamples(e);if (n) throw new NotImplementedError("Verbose predictLoop() is not implemented yet.");for (var a$$1 = makeBatches(i, t), o = r.outputs.map(function (e) {
            return [];
          }), s = function (t) {
            Pe(function () {
              var n = a$$1[t][0],
                  i = a$$1[t][1],
                  o = sliceArrays(e, n, i),
                  s = [];if (Array.isArray(o)) for (var l$$1 = 0; l$$1 < o.length; ++l$$1) s.push({ key: r.inputs[l$$1], value: o[l$$1] });else s.push({ key: r.inputs[0], value: o });var u = new FeedDict(s);return execute(r.outputs, u);
            }).forEach(function (e, t) {
              return o[t].push(e);
            });
          }, l$$1 = 0; l$$1 < a$$1.length; ++l$$1) s(l$$1);return singletonOrArray(o.map(function (e) {
            return _n(e, 0);
          }));
        });
      }, t.prototype.predict = function (e, t) {
        void 0 === t && (t = {});var n = ensureTensorsRank2OrHigher(e);checkInputData(n, this.inputNames, this.feedInputShapes, !1);try {
          var r = null == t.batchSize ? 32 : t.batchSize;return checkBatchSize(r), this.predictLoop(n, r);
        } finally {
          disposeNewTensors(n, e);
        }
      }, t.prototype.predictOnBatch = function (e) {
        return checkInputData(e, this.inputNames, this.feedInputShapes, !0), this.predictLoop(e, e.shape[0]);
      }, t.prototype.standardizeUserDataXY = function (e, t, n, r) {
        if (void 0 === n && (n = !0), null == this.optimizer_) throw new RuntimeError("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");for (var i = [], a$$1 = 0; a$$1 < this.feedOutputShapes.length; ++a$$1) {
          var o = this.feedOutputShapes[a$$1];this.feedLossFns[a$$1] === sparseCategoricalCrossentropy ? i.push(o.slice(0, o.length - 1).concat([1])) : i.push(o);
        }if (checkArrayLengths(e = standardizeInputData(e, this.feedInputNames, this.feedInputShapes, !1, "input"), t = standardizeInputData(t, this.feedOutputNames, i, !1, "target"), null), checkLossAndTargetCompatibility(t, this.feedLossFns, this.feedOutputShapes), this.stateful && null != r && r > 0 && e[0].shape[0] % r != 0) throw new ValueError("In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size " + r + ". Found: " + e[0].shape[0] + " sample(s).");return [e, t];
      }, t.prototype.standardizeUserData = function (e, t, n, r, i, a$$1) {
        return void 0 === i && (i = !0), __awaiter(this, void 0, void 0, function () {
          var o, s, l$$1, u, c, p, h, d;return __generator(this, function (f) {
            switch (f.label) {case 0:
                if (o = this.standardizeUserDataXY(e, t, i, a$$1), s = o[0], l$$1 = o[1], null != n) throw new Error("sample weight is not supported yet.");if (u = null, null == r) return [3, 4];c = standardizeClassWeights(r, this.outputNames), u = [], p = 0, f.label = 1;case 1:
                return p < c.length ? (d = (h = u).push, [4, standardizeWeights(l$$1[p], null, c[p])]) : [3, 4];case 2:
                d.apply(h, [f.sent()]), f.label = 3;case 3:
                return ++p, [3, 1];case 4:
                return [2, [s, l$$1, u]];}
          });
        });
      }, t.prototype.testLoop = function (e, t, n, r, i) {
        var a$$1 = this;return void 0 === r && (r = 0), Pe(function () {
          var o = a$$1.checkNumSamples(t, n, i, "steps"),
              s = [];if (r > 0) throw new NotImplementedError("Verbose mode is not implemented yet.");if (null != i) throw new NotImplementedError("steps mode in testLoop() is not implemented yet");for (var l$$1 = makeBatches(o, n), u = xn(range(0, o)), c = 0; c < l$$1.length; ++c) {
            var p = l$$1[c][0],
                h = l$$1[c][1],
                d = sliceAlongFirstAxis(u, p, h - p),
                f = sliceArraysByIndices(t, d),
                g = e(f);if (0 === c) for (var m = 0; m < g.length; ++m) s.push(yn(0));for (m = 0; m < g.length; ++m) {
              var y = g[m];s[m] = Zu(s[m], pl(h - p, y));
            }
          }for (m = 0; m < s.length; ++m) s[m] = rl(s[m], o);return s;
        });
      }, t.prototype.getDedupedMetricsNames = function () {
        for (var e = this.metricsNames, t = [], n = 0; n < e.length; ++n) {
          var r = e[n],
              i = r;if (count(e, r) > 1) i += "_" + count(e.slice(0, n), r);t.push(i);
        }return t;
      }, t.prototype.makeTrainFunction = function () {
        var e = this;return function (t) {
          var n = [],
              r = t.slice(0, e.inputs.length),
              i = t.slice(e.inputs.length, e.inputs.length + e.outputs.length),
              a$$1 = t.slice(e.inputs.length + e.outputs.length, e.inputs.length + 2 * e.outputs.length),
              o = [],
              s = e.collectedTrainableWeights.map(function (e) {
            return e.read();
          });return [e.optimizer_.minimize(function () {
            for (var t = [], s = 0; s < e.inputs.length; ++s) t.push({ key: e.inputs[s], value: r[s] });var l$$1,
                u = new FeedDict(t),
                c = execute(e.outputs, u, { training: !0 });for (s = 0; s < e.lossFunctions.length; ++s) {
              var p = (0, e.lossFunctions[s])(i[s], c[s]);null != a$$1[s] && (p = computeWeightedLoss(p, a$$1[s]));var h = Bu(p);n.push(h), l$$1 = 0 === s ? p : Zu(l$$1, p);
            }for (s = 0; s < e.metricsTensors.length; ++s) {
              var d = void 0;if (e.outputs.length > 1 && s < e.outputs.length) d = n[s];else {
                var f = e.metricsTensors[s][0],
                    g = e.metricsTensors[s][1];d = Bu(f(i[g], c[g]));
              }We(d), o.push(d);
            }return l$$1 = Bu(l$$1), e.calculateLosses().forEach(function (e) {
              l$$1 = Zu(l$$1, e);
            }), l$$1;
          }, !0, s)].concat(o);
        };
      }, t.prototype.makeTestFunction = function () {
        var e = this;this.testFunction = function (t) {
          return Pe(function () {
            for (var n, r = [], i = t.slice(0, e.inputs.length), a$$1 = t.slice(e.inputs.length, e.inputs.length + e.outputs.length), o = [], s = 0; s < e.inputs.length; ++s) o.push({ key: e.inputs[s], value: i[s] });var l$$1 = new FeedDict(o),
                u = execute(e.outputs, l$$1);for (s = 0; s < e.lossFunctions.length; ++s) {
              var c = e.lossFunctions[s],
                  p = Bu(c(a$$1[s], u[s]));n = 0 === s ? p : Zu(n, p), r.push(n);
            }for (s = 0; s < e.metricsTensors.length; ++s) {
              var h = e.metricsTensors[s][0],
                  d = e.metricsTensors[s][1],
                  f = Bu(h(a$$1[d], u[d]));r.push(f);
            }return r;
          });
        };
      }, t.prototype.fit = function (e, t, n) {
        return void 0 === n && (n = {}), __awaiter(this, void 0, void 0, function () {
          return __generator(this, function (r) {
            return [2, fitTensors(this, e, t, n)];
          });
        });
      }, t.prototype.fitDataset = function (e, t) {
        return __awaiter(this, void 0, void 0, function () {
          return __generator(this, function (n) {
            return [2, fitDataset(this, e, t)];
          });
        });
      }, t.prototype.trainOnBatch = function (e, t) {
        return __awaiter(this, void 0, void 0, function () {
          var n, r, i, a$$1, o, s, l$$1, u, c;return __generator(this, function (p) {
            switch (p.label) {case 0:
                return [4, this.standardizeUserData(e, t)];case 1:
                n = p.sent(), r = n[0], i = n[1], a$$1 = this.makeTrainFunction(), o = a$$1(r.concat(i)), s = [], l$$1 = 0, u = o, p.label = 2;case 2:
                return l$$1 < u.length ? [4, u[l$$1].data()] : [3, 5];case 3:
                c = p.sent(), s.push(c[0]), p.label = 4;case 4:
                return l$$1++, [3, 2];case 5:
                return Le(o), [2, singletonOrArray(s)];}
          });
        });
      }, t.prototype.getNamedWeights = function (e) {
        for (var t = [], n = null != e && e.trainableOnly, r = n ? this.trainableWeights : this.weights, i = this.getWeights(n), a$$1 = 0; a$$1 < r.length; ++a$$1) n && !r[a$$1].trainable || t.push({ name: r[a$$1].originalName, tensor: i[a$$1] });return t;
      }, Object.defineProperty(t.prototype, "stopTraining", { get: function () {
          return this.stopTraining_;
        }, set: function (e) {
          this.stopTraining_ = e;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "optimizer", { get: function () {
          return this.optimizer_;
        }, set: function (e) {
          this.optimizer_ !== e && (this.optimizer_ = e, this.isOptimizerOwned = !1);
        }, enumerable: !0, configurable: !0 }), t.prototype.dispose = function () {
        var t = e.prototype.dispose.call(this);if (0 === t.refCountAfterDispose && null != this.optimizer && this.isOptimizerOwned) {
          var n = Fe().numTensors;this.optimizer_.dispose(), t.numDisposedVariables += n - Fe().numTensors;
        }return t;
      }, t.prototype.getLossIdentifiers = function () {
        var e;if ("string" == typeof this.loss) e = toSnakeCase(this.loss);else if (Array.isArray(this.loss)) {
          for (var t = 0, n = this.loss; t < n.length; t++) {
            if ("string" != typeof n[t]) throw new Error("Serialization of non-string loss is not supported.");
          }e = this.loss.map(function (e) {
            return toSnakeCase(e);
          });
        } else {
          var r = Object.keys(this.loss);e = {};for (var i = this.loss, a$$1 = 0, o = r; a$$1 < o.length; a$$1++) {
            var s = o[a$$1];if ("string" != typeof i[s]) throw new Error("Serialization of non-string loss is not supported.");e[s] = toSnakeCase(i[s]);
          }
        }return e;
      }, t.prototype.getMetricIdentifiers = function () {
        if ("string" == typeof this.metrics || "function" == typeof this.metrics) return [toSnakeCase(getLossOrMetricName(this.metrics))];if (Array.isArray(this.metrics)) return this.metrics.map(function (e) {
          return toSnakeCase(getLossOrMetricName(e));
        });var e = {};for (var t in this.metrics) e[t] = toSnakeCase(getLossOrMetricName(this.metrics[t]));return e;
      }, t.prototype.getTrainingConfig = function () {
        return { loss: this.getLossIdentifiers(), metrics: this.getMetricIdentifiers(), optimizer_config: { class_name: this.optimizer.getClassName(), config: this.optimizer.getConfig() } };
      }, t.prototype.loadTrainingConfig = function (e) {
        if (null != e.weighted_metrics) throw new Error("Loading weight_metrics is not supported yet.");if (null != e.loss_weights) throw new Error("Loading loss_weights is not supported yet.");if (null != e.sample_weight_mode) throw new Error("Loading sample_weight_mode is not supported yet.");var t,
            n,
            r = deserialize(convertPythonicToTs(e.optimizer_config));if ("string" == typeof e.loss) t = toCamelCase(e.loss);else if (Array.isArray(e.loss)) t = e.loss.map(function (e) {
          return toCamelCase(e);
        });else if (null != e.loss) for (var i in t = {}, e.loss) t[i] = toCamelCase(e.loss[i]);if (Array.isArray(e.metrics)) n = e.metrics.map(function (e) {
          return toCamelCase(e);
        });else if (null != e.metrics) for (var i in n = {}, e.metrics) n[i] = toCamelCase(e.metrics[i]);this.compile({ loss: t, metrics: n, optimizer: r });
      }, t.prototype.save = function (e, t) {
        return __awaiter(this, void 0, void 0, function () {
          var n, r, i, a$$1, o, s, l$$1, u, c, p, h, d, f;return __generator(this, function (g) {
            switch (g.label) {case 0:
                if ("string" == typeof e) {
                  if (0 === (r = Nh.getSaveHandlers(e)).length) throw new ValueError("Cannot find any save handlers for URL '" + e + "'");if (r.length > 1) throw new ValueError("Found more than one (" + r.length + ") save handlers for URL '" + e + "'");e = r[0];
                }if (null == e.save) throw new ValueError("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return [4, Nh.encodeWeights(this.getNamedWeights(t))];case 1:
                return i = g.sent(), a$$1 = !1, o = null, s = this.toJSON(o, a$$1), l$$1 = { modelTopology: s, format: LAYERS_MODEL_FORMAT_NAME, generatedBy: "TensorFlow.js tfjs-layers v" + version, convertedBy: null }, null != t && t.includeOptimizer && null != this.optimizer ? (l$$1.trainingConfig = this.getTrainingConfig(), u = "optimizer", f = (d = Nh).encodeWeights, [4, this.optimizer.getWeights()]) : [3, 4];case 2:
                return [4, f.apply(d, [g.sent(), u])];case 3:
                c = g.sent(), p = c.data, h = c.specs, (n = i.specs).push.apply(n, h), i.data = Nh.concatenateArrayBuffers([i.data, p]), g.label = 4;case 4:
                return l$$1.weightData = i.data, l$$1.weightSpecs = i.specs, [2, e.save(l$$1)];}
          });
        });
      }, t.className = "Model", t;
    }(Container);function modelFromJSON(e, t) {
      return __awaiter(this, void 0, void 0, function () {
        var n, r, i, a$$1, o, s, l$$1, u;return __generator(this, function (c) {
          switch (c.label) {case 0:
              return "modelTopology" in e || (e = { modelTopology: e }), null != (n = (e = e).modelTopology).model_config && (n = n.model_config), r = convertPythonicToTs(n), i = deserialize(r, t), null == e.weightsManifest ? [3, 2] : [4, Nh.loadWeights(e.weightsManifest, e.pathPrefix, i.weights.map(function (e) {
                return e.originalName;
              }))];case 1:
              for (a$$1 = c.sent(), o = {}, s = 0, l$$1 = i.weights; s < l$$1.length; s++) u = l$$1[s], o[u.originalName] = a$$1[u.originalName];i.loadWeights(o), Le(a$$1), c.label = 2;case 2:
              return [2, i];}
        });
      });
    }function loadLayersModelInternal(e, t) {
      return __awaiter(this, void 0, void 0, function () {
        var n;return __generator(this, function (r) {
          if (null == t && (t = {}), "string" == typeof e) {
            if (0 === (n = Nh.getLoadHandlers(e, t.onProgress)).length) n.push(Nh.browserHTTPRequest(e, t));else if (n.length > 1) throw new ValueError("Found more than one (" + n.length + ") load handlers for URL '" + e + "'");e = n[0];
          }return [2, loadLayersModelFromIOHandler(e, void 0, t)];
        });
      });
    }function loadLayersModelFromIOHandler(e, t, n) {
      return __awaiter(this, void 0, void 0, function () {
        var r, i, a$$1, o, s, l$$1, u, c, p;return __generator(this, function (h) {
          switch (h.label) {case 0:
              if (null == n && (n = {}), null == e.load) throw new ValueError("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");return [4, e.load()];case 1:
              if (r = h.sent(), null != (i = r.modelTopology).model_config && (i = i.model_config), a$$1 = null == n.strict || n.strict, o = null != r.weightData && null != r.weightSpecs && a$$1, s = deserialize(convertPythonicToTs(i), t, o), null != (l$$1 = r.trainingConfig) && s.loadTrainingConfig(l$$1), null == r.weightData) return [3, 4];if (null == r.weightSpecs) throw new ValueError("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");return u = decodeModelAndOptimizerWeights(r.weightData, r.weightSpecs), c = u.modelWeights, p = u.optimizerWeights, s.loadWeights(c, a$$1), null != s.optimizer && p.length > 0 ? [4, s.optimizer.setWeights(p)] : [3, 3];case 2:
              h.sent(), h.label = 3;case 3:
              Le(c), Le(p.map(function (e) {
                return e.tensor;
              })), h.label = 4;case 4:
              return [2, s];}
        });
      });
    }function decodeModelAndOptimizerWeights(e, t) {
      var n = Nh.decodeWeights(e, t),
          r = {},
          i = [];return t.forEach(function (e) {
        "optimizer" === e.group ? i.push({ name: e.name, tensor: n[e.name] }) : r[e.name] = n[e.name];
      }), { modelWeights: r, optimizerWeights: i };
    }Fh.registerClass(LayersModel);var Sequential = function (e) {
      function t(t) {
        var n = e.call(this, { inputs: [], outputs: [] }) || this;if (t = t || {}, n.trainable = !0, n.built = !1, n.name = null != t.name ? t.name : getUid("sequential_"), null != t.layers) for (var r = 0, i = t.layers; r < i.length; r++) {
          var a$$1 = i[r];n.add(a$$1);
        }return n;
      }return __extends(t, e), t.prototype.checkShape = function (e) {
        if (e.inboundNodes[0].outputTensors[0].shape.some(function (e) {
          return e < 0;
        })) throw new ValueError("Negative dimension size caused by adding layer " + e.name + " with input shape [" + e.inboundNodes[0].inputTensors[0].shape + "]");
      }, t.prototype.add = function (e) {
        var n,
            r = e instanceof t || e instanceof LayersModel;if (r) {
          if (1 !== (n = e).outputs.length) throw new ValueError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if (1 !== n.inputs.length) throw new ValueError("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.");
        }if (0 === this.outputs.length) {
          if (0 === e.inboundNodes.length) {
            if (null == e.batchInputShape) throw new ValueError("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");var i = Input({ batchShape: e.batchInputShape, dtype: e.dtype, name: e.name + "_input" });e.apply(i);
          }if (r) this.outputs = n.outputs, this.inputs = n.inputs;else {
            if (1 !== e.inboundNodes.length) throw new ValueError("A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer " + e.name + " which has " + e.inboundNodes.length + " pre-existing inbound connections.");if (1 !== e.inboundNodes[0].outputTensors.length) throw new ValueError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e), this.outputs = [e.inboundNodes[0].outputTensors[0]], this.inputs = getSourceInputs(this.outputs[0]);
          }this.inboundNodes = [], new Node({ outboundLayer: this, inboundLayers: [], nodeIndices: [], tensorIndices: [], inputTensors: this.inputs, outputTensors: this.outputs, inputMasks: pyListRepeat(null, this.inputs.length), outputMasks: [null], inputShapes: this.inputs.map(function (e) {
              return e.shape;
            }), outputShapes: this.outputs[0].shape });
        } else {
          var a$$1 = e.apply(this.outputs[0]);if (Array.isArray(a$$1)) throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e), this.outputs = [a$$1], this.inboundNodes[0].outputTensors = this.outputs, this.inboundNodes[0].outputShapes = [this.outputs[0].shape];
        }this.layers.push(e), this.built = !1;
      }, t.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 e = this.layers.length - 1;this.layers[e].outboundNodes = [], this.outputs = [this.layers[e].output], this.inboundNodes[0].outputTensors = this.outputs, this.inboundNodes[0].outputShapes = [this.outputs[0].shape];
        }
      }, t.prototype.call = function (e, t) {
        return null == this.model && this.build(), this.model.call(e, t);
      }, t.prototype.build = function (e) {
        if (getExactlyOneShape(e), 0 === this.inputs.length || 0 === this.outputs.length) throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model = new LayersModel({ 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;
      }, t.prototype.countParams = function () {
        return this.built || this.build(), e.prototype.countParams.call(this);
      }, t.prototype.summary = function (t, n, r) {
        void 0 === r && (r = console.log), this.built || this.build(), e.prototype.summary.call(this, t, n, r);
      }, t.prototype.setWeights = function (e) {
        null == this.model && this.build(), this.model.setWeights(e);
      }, t.prototype.evaluate = function (e, t, n) {
        if (void 0 === n && (n = {}), !this.built) throw new RuntimeError("The model needs to be compiled before being used.");return this.model.evaluate(e, t, n);
      }, t.prototype.evaluateDataset = function (e, t) {
        return __awaiter(this, void 0, void 0, function () {
          return __generator(this, function (n) {
            if (!this.built) throw new RuntimeError("The model needs to be compiled before being used.");return [2, this.model.evaluateDataset(e, t)];
          });
        });
      }, t.prototype.predict = function (e, t) {
        return void 0 === t && (t = {}), null == this.model && this.build(), this.model.predict(e, t);
      }, t.prototype.predictOnBatch = function (e) {
        return null == this.model && this.build(), this.model.predictOnBatch(e);
      }, t.prototype.compile = function (e) {
        this.build(), this.model.compile(e), this.optimizer_ = this.model.optimizer, this.isOptimizerOwned = this.model.isOptimizerOwned, this.loss = this.model.loss, this.metrics = this.model.metrics, this.metricsTensors = this.model.metricsTensors, this.metricsNames = this.model.metricsNames;
      }, Object.defineProperty(t.prototype, "optimizer", { get: function () {
          return null == this.model ? void 0 : this.model.optimizer;
        }, set: function (e) {
          this.model.optimizer = e;
        }, enumerable: !0, configurable: !0 }), t.prototype.fit = function (e, t, n) {
        return void 0 === n && (n = {}), __awaiter(this, void 0, void 0, function () {
          return __generator(this, function (r) {
            if (!this.built) throw new RuntimeError("The model needs to be compiled before being used.");return [2, this.model.fit(e, t, n)];
          });
        });
      }, t.prototype.fitDataset = function (e, t) {
        return __awaiter(this, void 0, void 0, function () {
          return __generator(this, function (n) {
            if (!this.built) throw new RuntimeError("The model needs to be compiled before being used.");return [2, this.model.fitDataset(e, t)];
          });
        });
      }, t.prototype.trainOnBatch = function (e, t) {
        return __awaiter(this, void 0, void 0, function () {
          return __generator(this, function (n) {
            return [2, this.model.trainOnBatch(e, t)];
          });
        });
      }, t.fromConfig = function (e, n, r, i) {
        var a$$1;void 0 === r && (r = {}), void 0 === i && (i = !1);var o = {};if (n instanceof Array) {
          if (null == n[0].className || "Merge" === n[0].className) throw new ValueError("Legacy serialization format not supported yet.");a$$1 = n;
        } else Z.assert(null != n.layers, function () {
          return "When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field.";
        }), a$$1 = n.layers, delete n.layers, o = n;var s = new e(o);if (!(s instanceof t)) throw new NotImplementedError("Sequential.fromConfig called on non-Sequential input: " + s);for (var l$$1 = 0, u = a$$1; l$$1 < u.length; l$$1++) {
          var c = deserialize(u[l$$1], void 0, i);i && c.setFastWeightInitDuringBuild(!0), s.add(c);
        }return s;
      }, Object.defineProperty(t.prototype, "stopTraining", { get: function () {
          if (null == this.model) throw new ValueError("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining;
        }, set: function (e) {
          if (null == this.model) throw new ValueError("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining = e;
        }, enumerable: !0, configurable: !0 }), t.prototype.getConfig = function () {
        for (var e = [], t = 0, n = this.layers; t < n.length; t++) {
          var r = n[t],
              i = {};i.className = r.getClassName(), i.config = r.getConfig(), e.push(i);
        }return e;
      }, t.className = "Sequential", t;
    }(LayersModel);function model(e) {
      return new LayersModel(e);
    }function sequential(e) {
      return new Sequential(e);
    }function loadLayersModel(e, t) {
      return null == t && (t = {}), loadLayersModelInternal(e, t);
    }function input(e) {
      return Input(e);
    }function registerCallbackConstructor(e, t) {
      CallbackConstructorRegistry.registerCallbackConstructor(e, t);
    }Fh.registerClass(Sequential);var Activation = function (e) {
      function t() {
        return null !== e && e.apply(this, arguments) || this;
      }return __extends(t, e), t.prototype.getConfig = function () {
        return {};
      }, t;
    }(Fh.Serializable),
        Elu = function (e) {
      function t() {
        return null !== e && e.apply(this, arguments) || this;
      }return __extends(t, e), t.prototype.apply = function (e, t) {
        return void 0 === t && (t = 1), elu$1(e, t);
      }, t.className = "elu", t;
    }(Activation);Fh.registerClass(Elu);var Selu = function (e) {
      function t() {
        return null !== e && e.apply(this, arguments) || this;
      }return __extends(t, e), t.prototype.apply = function (e) {
        return Tl(e);
      }, t.className = "selu", t;
    }(Activation);Fh.registerClass(Selu);var Relu = function (e) {
      function t() {
        return null !== e && e.apply(this, arguments) || this;
      }return __extends(t, e), t.prototype.apply = function (e) {
        return Al(e);
      }, t.className = "relu", t;
    }(Activation);Fh.registerClass(Relu);var Relu6 = function (e) {
      function t() {
        return null !== e && e.apply(this, arguments) || this;
      }return __extends(t, e), t.prototype.apply = function (e) {
        return Pe(function () {
          return ul(6, Al(e));
        });
      }, t.className = "relu6", t;
    }(Activation);Fh.registerClass(Relu6);var Linear = function (e) {
      function t() {
        return null !== e && e.apply(this, arguments) || this;
      }return __extends(t, e), t.prototype.apply = function (e) {
        return e;
      }, t.className = "linear", t;
    }(Activation);Fh.registerClass(Linear);var Sigmoid = function (e) {
      function t() {
        return null !== e && e.apply(this, arguments) || this;
      }return __extends(t, e), t.prototype.apply = function (e) {
        return ks(e);
      }, t.className = "sigmoid", t;
    }(Activation);Fh.registerClass(Sigmoid);var HardSigmoid = function (e) {
      function t() {
        return null !== e && e.apply(this, arguments) || this;
      }return __extends(t, e), t.prototype.apply = function (e) {
        return hardSigmoid(e);
      }, t.className = "hardSigmoid", t;
    }(Activation);Fh.registerClass(HardSigmoid);var Softplus = function (e) {
      function t() {
        return null !== e && e.apply(this, arguments) || this;
      }return __extends(t, e), t.prototype.apply = function (e) {
        return Fs(e);
      }, t.className = "softplus", t;
    }(Activation);Fh.registerClass(Softplus);var Softsign = function (e) {
      function t() {
        return null !== e && e.apply(this, arguments) || this;
      }return __extends(t, e), t.prototype.apply = function (e) {
        return softsign(e);
      }, t.className = "softsign", t;
    }(Activation);Fh.registerClass(Softsign);var Tanh = function (e) {
      function t() {
        return null !== e && e.apply(this, arguments) || this;
      }return __extends(t, e), t.prototype.apply = function (e) {
        return Us(e);
      }, t.className = "tanh", t;
    }(Activation);Fh.registerClass(Tanh);var Softmax = function (e) {
      function t() {
        return null !== e && e.apply(this, arguments) || this;
      }return __extends(t, e), t.prototype.apply = function (e, t) {
        return void 0 === t && (t = -1), qr(e, t);
      }, t.className = "softmax", t;
    }(Activation);Fh.registerClass(Softmax);var LogSoftmax = function (e) {
      function t() {
        return null !== e && e.apply(this, arguments) || this;
      }return __extends(t, e), t.prototype.apply = function (e, t) {
        return void 0 === t && (t = -1), Hr(e, t);
      }, t.className = "logSoftmax", t;
    }(Activation);function serializeActivation(e) {
      return e.getClassName();
    }function deserializeActivation(e, t) {
      return void 0 === t && (t = {}), deserializeKerasObject(e, Fh.SerializationMap.getMap().classNameMap, t, "activation");
    }function getActivation(e) {
      var t;return null == e ? deserializeActivation(t = { className: "linear", config: {} }) : "string" == typeof e ? ((t = {}).className = e, t.config = {}, deserializeActivation(t)) : e instanceof Activation ? e : deserializeActivation(e);
    }Fh.registerClass(LogSoftmax);var Regularizer = function (e) {
      function t() {
        return null !== e && e.apply(this, arguments) || this;
      }return __extends(t, e), t;
    }(Fh.Serializable),
        L1L2 = function (e) {
      function t(t) {
        var n = e.call(this) || this;return n.l1 = null == t || null == t.l1 ? .01 : t.l1, n.l2 = null == t || null == t.l2 ? .01 : t.l2, n.hasL1 = 0 !== n.l1, n.hasL2 = 0 !== n.l2, n;
      }return __extends(t, e), t.prototype.apply = function (e) {
        var t = this;return Pe(function () {
          var n = Sn([1]);return t.hasL1 && (n = Zu(n, Wu(pl(t.l1, is(e))))), t.hasL2 && (n = Zu(n, Wu(pl(t.l2, square(e))))), n.asScalar();
        });
      }, t.prototype.getConfig = function () {
        return { l1: this.l1, l2: this.l2 };
      }, t.fromConfig = function (e, t) {
        return new e({ l1: t.l1, l2: t.l2 });
      }, t.className = "L1L2", t;
    }(Regularizer);function l1(e) {
      return new L1L2({ l1: null != e ? e.l1 : null, l2: 0 });
    }function l2(e) {
      return new L1L2({ l2: null != e ? e.l2 : null, l1: 0 });
    }Fh.registerClass(L1L2);var REGULARIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP = { l1l2: "L1L2" };function serializeRegularizer(e) {
      return serializeKerasObject(e);
    }function deserializeRegularizer(e, t) {
      return void 0 === t && (t = {}), deserializeKerasObject(e, Fh.SerializationMap.getMap().classNameMap, t, "regularizer");
    }function getRegularizer(e) {
      return null == e ? null : "string" == typeof e ? deserializeRegularizer({ className: e in REGULARIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP ? REGULARIZER_IDENTIFIER_REGISTRY_SYMBOL_MAP[e] : e, config: {} }) : e instanceof Regularizer ? e : deserializeRegularizer(e);
    }var ReLU = function (e) {
      function t(t) {
        var n = e.call(this, null == t ? {} : t) || this;return n.supportsMasking = !0, null != t && (n.maxValue = t.maxValue), n;
      }return __extends(t, e), t.prototype.call = function (e, t) {
        e = getExactlyOneTensor(e);var n = Al(e);return null != this.maxValue && (n = ds(n, 0, this.maxValue)), n;
      }, t.prototype.computeOutputShape = function (e) {
        return e;
      }, t.prototype.getConfig = function () {
        var t = { maxValue: this.maxValue },
            n = e.prototype.getConfig.call(this);return Object.assign(t, n), t;
      }, t.className = "ReLU", t;
    }(Layer);Fh.registerClass(ReLU);var LeakyReLU = function (e) {
      function t(t) {
        var n = e.call(this, null == t ? {} : t) || this;return n.DEFAULT_ALPHA = .3, null == t && (t = {}), n.alpha = null == t.alpha ? n.DEFAULT_ALPHA : t.alpha, n;
      }return __extends(t, e), t.prototype.call = function (e, t) {
        var n = getExactlyOneTensor(e);return Nl(n, this.alpha);
      }, t.prototype.computeOutputShape = function (e) {
        return e;
      }, t.prototype.getConfig = function () {
        var t = { alpha: this.alpha },
            n = e.prototype.getConfig.call(this);return Object.assign(t, n), t;
      }, t.className = "LeakyReLU", t;
    }(Layer);Fh.registerClass(LeakyReLU);var PReLU = function (e) {
      function t(t) {
        var n = e.call(this, null == t ? {} : t) || this;if (n.DEFAULT_ALPHA_INITIALIZER = "zeros", null == t && (t = {}), n.supportsMasking = !0, n.alphaInitializer = getInitializer(t.alphaInitializer || n.DEFAULT_ALPHA_INITIALIZER), n.alphaRegularizer = getRegularizer(t.alphaRegularizer), n.alphaConstraint = getConstraint(t.alphaConstraint), null == t.sharedAxes) n.sharedAxes = null;else if (Array.isArray(t.sharedAxes)) n.sharedAxes = t.sharedAxes;else {
          if ("number" != typeof t.sharedAxes) throw new ValueError("Expected sharedAxes to be a number or an array of numbers, but got " + t.sharedAxes);n.sharedAxes = [t.sharedAxes];
        }return n;
      }return __extends(t, e), t.prototype.build = function (e) {
        var t = (e = getExactlyOneShape(e)).slice(1);if (null != this.sharedAxes) for (var n = 0, r = this.sharedAxes; n < r.length; n++) {
          t[(a$$1 = r[n]) - 1] = 1;
        }this.alpha = this.addWeight("alpha", t, "float32", this.alphaInitializer, this.alphaRegularizer, !0, this.alphaConstraint);var i = {};if (null != this.sharedAxes) for (var a$$1 = 1; a$$1 < e.length; ++a$$1) i[a$$1] = e[a$$1];this.inputSpec = [new InputSpec({ ndim: e.length, axes: i })], this.built = !0;
      }, t.prototype.call = function (e, t) {
        return e = getExactlyOneTensor(e), kl(e, this.alpha.read());
      }, t.prototype.getConfig = function () {
        var t = { alphaInitializer: serializeInitializer(this.alphaInitializer), alphaRegularizer: serializeRegularizer(this.alphaRegularizer), alphaConstraint: serializeConstraint(this.alphaConstraint), sharedAxes: this.sharedAxes },
            n = e.prototype.getConfig.call(this);return Object.assign(t, n), t;
      }, t.className = "PReLU", t;
    }(Layer);Fh.registerClass(PReLU);var ELU = function (e) {
      function t(t) {
        var n = e.call(this, null == t ? {} : t) || this;if (n.DEFAULT_ALPHA = 1, null == t && (t = {}), null != t.alpha && t.alpha !== n.DEFAULT_ALPHA) throw new NotImplementedError("Non-default alpha value (" + t.alpha + ") is not supported by the ELU layer yet.");return n.alpha = null == t.alpha ? n.DEFAULT_ALPHA : t.alpha, n;
      }return __extends(t, e), t.prototype.call = function (e, t) {
        var n = getExactlyOneTensor(e);return Sl(n);
      }, t.prototype.computeOutputShape = function (e) {
        return e;
      }, t.prototype.getConfig = function () {
        var t = { alpha: this.alpha },
            n = e.prototype.getConfig.call(this);return Object.assign(t, n), t;
      }, t.className = "ELU", t;
    }(Layer);Fh.registerClass(ELU);var ThresholdedReLU = function (e) {
      function t(t) {
        var n = e.call(this, null == t ? {} : t) || this;return n.DEFAULT_THETA = 1, null == t && (t = {}), n.theta = null == t.theta ? n.DEFAULT_THETA : t.theta, n;
      }return __extends(t, e), t.prototype.call = function (e, t) {
        var n = getExactlyOneTensor(e);return n.mul(cast$1(n.greater(this.theta), "float32"));
      }, t.prototype.computeOutputShape = function (e) {
        return e;
      }, t.prototype.getConfig = function () {
        var t = { theta: this.theta },
            n = e.prototype.getConfig.call(this);return Object.assign(t, n), t;
      }, t.className = "ThresholdedReLU", t;
    }(Layer);Fh.registerClass(ThresholdedReLU);var Softmax$1 = function (e) {
      function t(t) {
        var n = e.call(this, null == t ? {} : t) || this;return n.DEFAULT_AXIS = 1, null == t && (t = {}), n.softmax = new Softmax().apply, n.axis = null == t.axis ? n.DEFAULT_AXIS : t.axis, n;
      }return __extends(t, e), t.prototype.call = function (e, t) {
        var n = getExactlyOneTensor(e);return this.softmax(n, this.axis);
      }, t.prototype.computeOutputShape = function (e) {
        return e;
      }, t.prototype.getConfig = function () {
        var t = { axis: this.axis },
            n = e.prototype.getConfig.call(this);return Object.assign(t, n), t;
      }, t.className = "Softmax", t;
    }(Layer);function normalizeArray(e, t, n) {
      if ("number" == typeof e) return pyListRepeat(e, t);if (e.length !== t) throw new ValueError("The " + n + " argument must be an integer or tuple of " + t + " integers. Received: " + e.length + " elements.");for (var r = 0; r < t; ++r) {
        var i = e[r];if (!isInteger(i)) throw new ValueError("The " + n + " argument must be an integer or tuple of " + t + " integers. Received: " + JSON.stringify(e) + " including a non-integer number " + i);
      }return e;
    }function convOutputLength(e, t, n, r, i) {
      return void 0 === i && (i = 1), null == e ? e : (a$$1 = "same" === n ? e : e - (t + (t - 1) * (i - 1)) + 1, Math.floor((a$$1 + r - 1) / r));var a$$1;
    }function deconvLength(e, t, n, r) {
      if (null == e) return null;if ("valid" === r) e = e * t + max$1([n - t, 0]);else {
        if ("same" !== r) throw new ValueError("Unsupport padding mode: " + r + ".");e *= t;
      }return e;
    }function preprocessConv2DInput(e, t) {
      return Pe(function () {
        return checkDataFormat(t), "channelsFirst" === t ? Dl(e, [0, 2, 3, 1]) : e;
      });
    }function preprocessConv3DInput(e, t) {
      return Pe(function () {
        return checkDataFormat(t), "channelsFirst" === t ? Dl(e, [0, 2, 3, 4, 1]) : e;
      });
    }function conv1dWithBias(e, t, n, r, i, a$$1, o) {
      return void 0 === r && (r = 1), void 0 === i && (i = "valid"), void 0 === o && (o = 1), Pe(function () {
        if (null == a$$1 && (a$$1 = imageDataFormat()), checkDataFormat(a$$1), 3 !== e.shape.length) throw new ValueError("The input of a conv1dWithBias operation should be 3, but is " + e.shape.length + " instead.");if (3 !== t.shape.length) throw new ValueError("The kernel for a conv1dWithBias operation should be 3, but is " + t.shape.length + " instead");if (null != n && 1 !== n.shape.length) throw new ValueError("The bias for a conv1dWithBias operation should be 1, but is " + t.shape.length + " instead");if ("channelsFirst" === a$$1 && (e = Dl(e, [0, 2, 1])), "causal" === i) throw new NotImplementedError("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");var s = ou(e, t, r, "same" === i ? "same" : "valid", "NWC", o);return null != n && (s = biasAdd(s, n)), s;
      });
    }function conv2dWithBias(e, t, n, r, i, a$$1, o) {
      return void 0 === r && (r = [1, 1]), void 0 === i && (i = "valid"), Pe(function () {
        if (null == a$$1 && (a$$1 = imageDataFormat()), checkDataFormat(a$$1), 3 !== e.rank && 4 !== e.rank) throw new ValueError("conv2dWithBias expects input to be of rank 3 or 4, but received " + e.rank + ".");if (3 !== t.rank && 4 !== t.rank) throw new ValueError("conv2dWithBias expects kernel to be of rank 3 or 4, but received " + e.rank + ".");var s = preprocessConv2DInput(e, a$$1);if ("causal" === i) throw new NotImplementedError("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return s = au(s, t, r, "same" === i ? "same" : "valid", "NHWC", o), null != n && (s = biasAdd(s, n)), "channelsFirst" === a$$1 && (s = Dl(s, [0, 3, 1, 2])), s;
      });
    }function conv3dWithBias(e, t, n, r, i, a$$1, o) {
      return void 0 === r && (r = [1, 1, 1]), void 0 === i && (i = "valid"), Pe(function () {
        if (null == a$$1 && (a$$1 = imageDataFormat()), checkDataFormat(a$$1), 4 !== e.rank && 5 !== e.rank) throw new ValueError("conv3dWithBias expects input to be of rank 4 or 5, but received " + e.rank + ".");if (4 !== t.rank && 5 !== t.rank) throw new ValueError("conv3dWithBias expects kernel to be of rank 4 or 5, but received " + e.rank + ".");var s = preprocessConv3DInput(e, a$$1);if ("causal" === i) throw new NotImplementedError("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return s = iu(s, t, r, "same" === i ? "same" : "valid", "NDHWC", o), null != n && (s = biasAdd(s, n)), "channelsFirst" === a$$1 && (s = Dl(s, [0, 4, 1, 2, 3])), s;
      });
    }Fh.registerClass(Softmax$1);var BaseConv = function (e) {
      function t(n, r) {
        var i = e.call(this, r) || this;if (i.bias = null, i.DEFAULT_KERNEL_INITIALIZER = "glorotNormal", i.DEFAULT_BIAS_INITIALIZER = "zeros", t.verifyArgs(r), i.rank = n, assertPositiveInteger(i.rank, "rank"), 1 !== i.rank && 2 !== i.rank && 3 !== i.rank) throw new NotImplementedError("Convolution layer for rank other than 1, 2, or 3 (" + i.rank + ") is not implemented yet.");if (i.kernelSize = normalizeArray(r.kernelSize, n, "kernelSize"), i.strides = normalizeArray(null == r.strides ? 1 : r.strides, n, "strides"), i.padding = null == r.padding ? "valid" : r.padding, checkPaddingMode(i.padding), i.dataFormat = null == r.dataFormat ? "channelsLast" : r.dataFormat, checkDataFormat(i.dataFormat), i.activation = getActivation(r.activation), i.useBias = null == r.useBias || r.useBias, i.biasInitializer = getInitializer(r.biasInitializer || i.DEFAULT_BIAS_INITIALIZER), i.biasConstraint = getConstraint(r.biasConstraint), i.biasRegularizer = getRegularizer(r.biasRegularizer), i.activityRegularizer = getRegularizer(r.activityRegularizer), i.dilationRate = normalizeArray(null == r.dilationRate ? 1 : r.dilationRate, n, "dilationRate"), 1 === i.rank && Array.isArray(i.dilationRate) && 1 !== i.dilationRate.length) throw new ValueError("dilationRate must be a number or an array of a single number for 1D convolution, but received " + JSON.stringify(i.dilationRate));if (2 === i.rank) {
          if ("number" == typeof i.dilationRate) i.dilationRate = [i.dilationRate, i.dilationRate];else if (2 !== i.dilationRate.length) throw new ValueError("dilationRate must be a number or array of two numbers for 2D convolution, but received " + JSON.stringify(i.dilationRate));
        } else if (3 === i.rank) if ("number" == typeof i.dilationRate) i.dilationRate = [i.dilationRate, i.dilationRate, i.dilationRate];else if (3 !== i.dilationRate.length) throw new ValueError("dilationRate must be a number or array of three numbers for 3D convolution, but received " + JSON.stringify(i.dilationRate));return i;
      }return __extends(t, e), t.verifyArgs = function (e) {
        if (assert("kernelSize" in e, "required key 'kernelSize' not in config"), "number" != typeof e.kernelSize && !checkArrayTypeAndLength(e.kernelSize, "number", 1, 3)) throw new ValueError("BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received " + JSON.stringify(e.kernelSize) + ".");
      }, t.prototype.getConfig = function () {
        var t = { kernelSize: this.kernelSize, strides: this.strides, padding: this.padding, dataFormat: this.dataFormat, dilationRate: this.dilationRate, activation: serializeActivation(this.activation), useBias: this.useBias, biasInitializer: serializeInitializer(this.biasInitializer), biasRegularizer: serializeRegularizer(this.biasRegularizer), activityRegularizer: serializeRegularizer(this.activityRegularizer), biasConstraint: serializeConstraint(this.biasConstraint) },
            n = e.prototype.getConfig.call(this);return Object.assign(t, n), t;
      }, t;
    }(Layer),
        Conv = function (e) {
      function t(n, r) {
        var i = e.call(this, n, r) || this;return i.kernel = null, t.verifyArgs(r), i.filters = r.filters, assertPositiveInteger(i.filters, "filters"), i.kernelInitializer = getInitializer(r.kernelInitializer || i.DEFAULT_KERNEL_INITIALIZER), i.kernelConstraint = getConstraint(r.kernelConstraint), i.kernelRegularizer = getRegularizer(r.kernelRegularizer), i;
      }return __extends(t, e), t.prototype.build = function (e) {
        var t;e = getExactlyOneShape(e);var n = "channelsFirst" === this.dataFormat ? 1 : e.length - 1;if (null == e[n]) throw new ValueError("The channel dimension of the input should be defined. Found " + e[n]);var r = e[n],
            i = this.kernelSize.concat([r, this.filters]);this.kernel = this.addWeight("kernel", i, null, this.kernelInitializer, this.kernelRegularizer, !0, this.kernelConstraint), this.useBias && (this.bias = this.addWeight("bias", [this.filters], null, this.biasInitializer, this.biasRegularizer, !0, this.biasConstraint)), this.inputSpec = [{ ndim: this.rank + 2, axes: (t = {}, t[n] = r, t) }], this.built = !0;
      }, t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          var t;e = getExactlyOneTensor(e);var r = null == n.bias ? null : n.bias.read();if (1 === n.rank) t = conv1dWithBias(e, n.kernel.read(), r, n.strides[0], n.padding, n.dataFormat, n.dilationRate[0]);else if (2 === n.rank) t = conv2dWithBias(e, n.kernel.read(), r, n.strides, n.padding, n.dataFormat, n.dilationRate);else {
            if (3 !== n.rank) throw new NotImplementedError("convolutions greater than 3D are not implemented yet.");t = conv3dWithBias(e, n.kernel.read(), r, n.strides, n.padding, n.dataFormat, n.dilationRate);
          }return null != n.activation && (t = n.activation.apply(t)), t;
        });
      }, t.prototype.computeOutputShape = function (e) {
        e = getExactlyOneShape(e);for (var t = [], n = "channelsLast" === this.dataFormat ? e.slice(1, e.length - 1) : e.slice(2), r = 0; r < n.length; ++r) {
          var i = convOutputLength(n[r], this.kernelSize[r], this.padding, this.strides[r], "number" == typeof this.dilationRate ? this.dilationRate : this.dilationRate[r]);t.push(i);
        }var a$$1 = [e[0]];return "channelsLast" === this.dataFormat ? (a$$1 = a$$1.concat(t)).push(this.filters) : (a$$1.push(this.filters), a$$1 = a$$1.concat(t)), a$$1;
      }, t.prototype.getConfig = function () {
        var t = { filters: this.filters, kernelInitializer: serializeInitializer(this.kernelInitializer), kernelRegularizer: serializeRegularizer(this.kernelRegularizer), kernelConstraint: serializeConstraint(this.kernelConstraint) },
            n = e.prototype.getConfig.call(this);return Object.assign(t, n), t;
      }, t.verifyArgs = function (e) {
        if (!("filters" in e) || "number" != typeof e.filters || e.filters < 1) throw new ValueError("Convolution layer expected config.filters to be a 'number' > 0 but got " + JSON.stringify(e.filters));
      }, t;
    }(BaseConv),
        Conv2D = function (e) {
      function t(n) {
        var r = e.call(this, 2, n) || this;return t.verifyArgs(n), r;
      }return __extends(t, e), t.prototype.getConfig = function () {
        var t = e.prototype.getConfig.call(this);return delete t.rank, t;
      }, t.verifyArgs = function (e) {
        if ("number" != typeof e.kernelSize && !checkArrayTypeAndLength(e.kernelSize, "number", 1, 2)) throw new ValueError("Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received " + JSON.stringify(e.kernelSize) + ".");
      }, t.className = "Conv2D", t;
    }(Conv);Fh.registerClass(Conv2D);var Conv3D = function (e) {
      function t(n) {
        var r = e.call(this, 3, n) || this;return t.verifyArgs(n), r;
      }return __extends(t, e), t.prototype.getConfig = function () {
        var t = e.prototype.getConfig.call(this);return delete t.rank, t;
      }, t.verifyArgs = function (e) {
        if ("number" != typeof e.kernelSize && (!Array.isArray(e.kernelSize) || 1 !== e.kernelSize.length && 3 !== e.kernelSize.length)) throw new ValueError("Conv3D expects config.kernelSize to be number or [number, number, number], but received " + JSON.stringify(e.kernelSize) + ".");
      }, t.className = "Conv3D", t;
    }(Conv);Fh.registerClass(Conv3D);var Conv2DTranspose = function (e) {
      function t(t) {
        var n = e.call(this, t) || this;if (n.inputSpec = [new InputSpec({ ndim: 4 })], "same" !== n.padding && "valid" !== n.padding) throw new ValueError("Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode " + n.padding);return n;
      }return __extends(t, e), t.prototype.build = function (e) {
        var t;if (4 !== (e = getExactlyOneShape(e)).length) throw new ValueError("Input should have rank 4; Received input shape: " + JSON.stringify(e));var n = "channelsFirst" === this.dataFormat ? 1 : e.length - 1;if (null == e[n]) throw new ValueError("The channel dimension of the inputs should be defined. Found `None`.");var r = e[n],
            i = this.kernelSize.concat([this.filters, r]);this.kernel = this.addWeight("kernel", i, "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 InputSpec({ ndim: 4, axes: (t = {}, t[n] = r, t) })], this.built = !0;
      }, t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          var t = getExactlyOneTensor(e);if (4 !== t.shape.length) throw new ValueError("Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-" + t.shape.length);var r,
              i,
              a$$1 = t.shape,
              o = a$$1[0];"channelsFirst" === n.dataFormat ? (r = 2, i = 3) : (r = 1, i = 2);var s = a$$1[r],
              l$$1 = a$$1[i],
              u = n.kernelSize[0],
              c = n.kernelSize[1],
              p = n.strides[0],
              h = n.strides[1],
              d = [o, deconvLength(s, p, u, n.padding), deconvLength(l$$1, h, c, n.padding), n.filters];"channelsLast" !== n.dataFormat && (t = Dl(t, [0, 2, 3, 1]));var f = cu(t, n.kernel.read(), d, n.strides, n.padding);return "channelsLast" !== n.dataFormat && (f = Dl(f, [0, 3, 1, 2])), null != n.bias && (f = biasAdd(f, n.bias.read(), n.dataFormat)), null != n.activation && (f = n.activation.apply(f)), f;
        });
      }, t.prototype.computeOutputShape = function (e) {
        var t,
            n,
            r,
            i = (e = getExactlyOneShape(e)).slice();"channelsFirst" === this.dataFormat ? (t = 1, n = 2, r = 3) : (t = 3, n = 1, r = 2);var a$$1 = this.kernelSize[0],
            o = this.kernelSize[1],
            s = this.strides[0],
            l$$1 = this.strides[1];return i[t] = this.filters, i[n] = deconvLength(i[n], s, a$$1, this.padding), i[r] = deconvLength(i[r], l$$1, o, this.padding), i;
      }, t.prototype.getConfig = function () {
        var t = e.prototype.getConfig.call(this);return delete t.dilationRate, t;
      }, t.className = "Conv2DTranspose", t;
    }(Conv2D);Fh.registerClass(Conv2DTranspose);var SeparableConv = function (e) {
      function t(t, n) {
        var r = e.call(this, t, n) || this;if (r.DEFAULT_DEPTHWISE_INITIALIZER = "glorotUniform", r.DEFAULT_POINTWISE_INITIALIZER = "glorotUniform", r.depthwiseKernel = null, r.pointwiseKernel = null, null == n.filters) throw new ValueError("The `filters` configuration field is required by SeparableConv, but is unspecified.");if (null != n.kernelInitializer || null != n.kernelRegularizer || null != n.kernelConstraint) throw new ValueError("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if (null != n.padding && "same" !== n.padding && "valid" !== n.padding) throw new ValueError("SeparableConv" + r.rank + "D supports only padding modes: 'same' and 'valid', but received " + JSON.stringify(n.padding));return r.depthMultiplier = null == n.depthMultiplier ? 1 : n.depthMultiplier, r.depthwiseInitializer = getInitializer(n.depthwiseInitializer || r.DEFAULT_DEPTHWISE_INITIALIZER), r.depthwiseRegularizer = getRegularizer(n.depthwiseRegularizer), r.depthwiseConstraint = getConstraint(n.depthwiseConstraint), r.pointwiseInitializer = getInitializer(n.depthwiseInitializer || r.DEFAULT_POINTWISE_INITIALIZER), r.pointwiseRegularizer = getRegularizer(n.pointwiseRegularizer), r.pointwiseConstraint = getConstraint(n.pointwiseConstraint), r;
      }return __extends(t, e), t.prototype.build = function (e) {
        var t;if ((e = getExactlyOneShape(e)).length < this.rank + 2) throw new ValueError("Inputs to SeparableConv" + this.rank + "D should have rank " + (this.rank + 2) + ", but received input shape: " + JSON.stringify(e));var n = "channelsFirst" === this.dataFormat ? 1 : e.length - 1;if (null == e[n] || e[n] < 0) throw new ValueError("The channel dimension of the inputs should be defined, but found " + JSON.stringify(e[n]));for (var r = e[n], i = this.kernelSize.concat([r, this.depthMultiplier]), a$$1 = [], o = 0; o < this.rank; ++o) a$$1.push(1);a$$1.push(r * this.depthMultiplier, this.filters);this.depthwiseKernel = this.addWeight("depthwise_kernel", i, "float32", this.depthwiseInitializer, this.depthwiseRegularizer, !0, this.depthwiseConstraint), this.pointwiseKernel = this.addWeight("pointwise_kernel", a$$1, "float32", this.pointwiseInitializer, this.pointwiseRegularizer, !0, this.pointwiseConstraint), this.useBias ? this.bias = this.addWeight("bias", [this.filters], "float32", this.biasInitializer, this.biasRegularizer, !0, this.biasConstraint) : this.bias = null, this.inputSpec = [new InputSpec({ ndim: this.rank + 2, axes: (t = {}, t[n] = r, t) })], this.built = !0;
      }, t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          var t;if (e = getExactlyOneTensor(e), 1 === n.rank) throw new NotImplementedError("1D separable convolution is not implemented yet.");return 2 === n.rank && ("channelsFirst" === n.dataFormat && (e = Dl(e, [0, 2, 3, 1])), t = lu(e, n.depthwiseKernel.read(), n.pointwiseKernel.read(), n.strides, n.padding, n.dilationRate, "NHWC")), n.useBias && (t = biasAdd(t, n.bias.read(), n.dataFormat)), null != n.activation && (t = n.activation.apply(t)), "channelsFirst" === n.dataFormat && (t = Dl(t, [0, 3, 1, 2])), t;
        });
      }, t.prototype.getConfig = function () {
        var t = e.prototype.getConfig.call(this);return delete t.rank, delete t.kernelInitializer, delete t.kernelRegularizer, delete t.kernelConstraint, t.depthwiseInitializer = serializeInitializer(this.depthwiseInitializer), t.pointwiseInitializer = serializeInitializer(this.pointwiseInitializer), t.depthwiseRegularizer = serializeRegularizer(this.depthwiseRegularizer), t.pointwiseRegularizer = serializeRegularizer(this.pointwiseRegularizer), t.depthwiseConstraint = serializeConstraint(this.depthwiseConstraint), t.pointwiseConstraint = serializeConstraint(this.pointwiseConstraint), t;
      }, t.className = "SeparableConv", t;
    }(Conv),
        SeparableConv2D = function (e) {
      function t(t) {
        return e.call(this, 2, t) || this;
      }return __extends(t, e), t.className = "SeparableConv2D", t;
    }(SeparableConv);Fh.registerClass(SeparableConv2D);var Conv1D = function (e) {
      function t(n) {
        var r = e.call(this, 1, n) || this;return t.verifyArgs(n), r.inputSpec = [{ ndim: 3 }], r;
      }return __extends(t, e), t.prototype.getConfig = function () {
        var t = e.prototype.getConfig.call(this);return delete t.rank, delete t.dataFormat, t;
      }, t.verifyArgs = function (e) {
        if ("number" != typeof e.kernelSize && !checkArrayTypeAndLength(e.kernelSize, "number", 1, 1)) throw new ValueError("Conv1D expects config.kernelSize to be number or number[] with length 1, but received " + JSON.stringify(e.kernelSize) + ".");
      }, t.className = "Conv1D", t;
    }(Conv);Fh.registerClass(Conv1D);var Cropping2D = function (e) {
      function t(t) {
        var n = e.call(this, t) || this;return "number" == typeof t.cropping ? n.cropping = [[t.cropping, t.cropping], [t.cropping, t.cropping]] : "number" == typeof t.cropping[0] ? n.cropping = [[t.cropping[0], t.cropping[0]], [t.cropping[1], t.cropping[1]]] : n.cropping = t.cropping, n.dataFormat = void 0 === t.dataFormat ? "channelsLast" : t.dataFormat, n.inputSpec = [{ ndim: 4 }], n;
      }return __extends(t, e), t.prototype.computeOutputShape = function (e) {
        return "channelsFirst" === this.dataFormat ? [e[0], e[1], e[2] - this.cropping[0][0] - this.cropping[0][1], e[3] - this.cropping[1][0] - this.cropping[1][1]] : [e[0], e[1] - this.cropping[0][0] - this.cropping[0][1], e[2] - this.cropping[1][0] - this.cropping[1][1], e[3]];
      }, t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          return e = getExactlyOneTensor(e), "channelsLast" === n.dataFormat ? sliceAlongAxis(sliceAlongAxis(e, n.cropping[0][0], e.shape[1] - n.cropping[0][0] - n.cropping[0][1], 2), n.cropping[1][0], e.shape[2] - n.cropping[1][1] - n.cropping[1][0], 3) : sliceAlongAxis(sliceAlongAxis(e, n.cropping[0][0], e.shape[2] - n.cropping[0][0] - n.cropping[0][1], 3), n.cropping[1][0], e.shape[3] - n.cropping[1][1] - n.cropping[1][0], 4);
        });
      }, t.prototype.getConfig = function () {
        var t = { cropping: this.cropping, dataFormat: this.dataFormat },
            n = e.prototype.getConfig.call(this);return Object.assign(t, n), t;
      }, t.className = "Cropping2D", t;
    }(Layer);Fh.registerClass(Cropping2D);var UpSampling2D = function (e) {
      function t(t) {
        var n = e.call(this, t) || this;return n.DEFAULT_SIZE = [2, 2], n.inputSpec = [{ ndim: 4 }], n.size = null == t.size ? n.DEFAULT_SIZE : t.size, n.dataFormat = null == t.dataFormat ? "channelsLast" : t.dataFormat, n;
      }return __extends(t, e), t.prototype.computeOutputShape = function (e) {
        if ("channelsFirst" === this.dataFormat) {
          var t = null == e[2] ? null : this.size[0] * e[2],
              n = null == e[3] ? null : this.size[1] * e[3];return [e[0], e[1], t, n];
        }t = null == e[1] ? null : this.size[0] * e[1], n = null == e[2] ? null : this.size[1] * e[2];return [e[0], t, n, e[3]];
      }, t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          var t = getExactlyOneTensor(e),
              r = t.shape;if ("channelsFirst" === n.dataFormat) {
            t = Dl(t, [0, 2, 3, 1]);var i = n.size[0] * r[2],
                a$$1 = n.size[1] * r[3],
                o = t.resizeNearestNeighbor([i, a$$1]);return Dl(o, [0, 3, 1, 2]);
          }i = n.size[0] * r[1], a$$1 = n.size[1] * r[2];return t.resizeNearestNeighbor([i, a$$1]);
        });
      }, t.prototype.getConfig = function () {
        var t = { size: this.size, dataFormat: this.dataFormat },
            n = e.prototype.getConfig.call(this);return Object.assign(t, n), t;
      }, t.className = "UpSampling2D", t;
    }(Layer);function depthwiseConv2d$1(e, t, n, r, i, a$$1) {
      return void 0 === n && (n = [1, 1]), void 0 === r && (r = "valid"), Pe(function () {
        null == i && (i = imageDataFormat()), checkDataFormat(i);var o = preprocessConv2DInput(e, i);if (4 !== e.rank) throw new ValueError("Input for depthwiseConv2d is required to be 4-D, but is instead " + e.rank + "-D");if (4 !== t.rank) throw new ValueError("depthwiseKernel is required to be 4-D, but is instead " + t.rank + "-D");return o = uu(o, t, n, "same" === r ? "same" : "valid", "NHWC", a$$1), "channelsFirst" === i && (o = Dl(o, [0, 3, 1, 2])), o;
      });
    }Fh.registerClass(UpSampling2D);var DepthwiseConv2D = function (e) {
      function t(t) {
        var n = e.call(this, 2, t) || this;return n.depthwiseKernel = null, n.depthMultiplier = null == t.depthMultiplier ? 1 : t.depthMultiplier, n.depthwiseInitializer = getInitializer(t.depthwiseInitializer || n.DEFAULT_KERNEL_INITIALIZER), n.depthwiseConstraint = getConstraint(t.depthwiseConstraint), n.depthwiseRegularizer = getRegularizer(t.depthwiseRegularizer), n;
      }return __extends(t, e), t.prototype.build = function (e) {
        if ((e = getExactlyOneShape(e)).length < 4) throw new ValueError("Inputs to DepthwiseConv2D should have rank 4. Received input shape: " + JSON.stringify(e) + ".");var t = "channelsFirst" === this.dataFormat ? 1 : 3;if (null == e[t] || e[t] < 0) throw new ValueError("The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (" + e[t] + ").");var n = e[t],
            r = [this.kernelSize[0], this.kernelSize[1], n, this.depthMultiplier];this.depthwiseKernel = this.addWeight("depthwise_kernel", r, null, this.depthwiseInitializer, this.depthwiseRegularizer, !0, this.depthwiseConstraint), this.useBias ? this.bias = this.addWeight("bias", [n * this.depthMultiplier], null, this.biasInitializer, this.biasRegularizer, !0, this.biasConstraint) : this.bias = null, this.built = !0;
      }, t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          var t = depthwiseConv2d$1(e = getExactlyOneTensor(e), n.depthwiseKernel.read(), n.strides, n.padding, n.dataFormat, null);return n.useBias && (t = biasAdd(t, n.bias.read(), n.dataFormat)), null != n.activation && (t = n.activation.apply(t)), t;
        });
      }, t.prototype.computeOutputShape = function (e) {
        e = getExactlyOneShape(e);var t = "channelsFirst" === this.dataFormat ? e[2] : e[1],
            n = "channelsFirst" === this.dataFormat ? e[3] : e[2],
            r = "channelsFirst" === this.dataFormat ? e[1] * this.depthMultiplier : e[3] * this.depthMultiplier,
            i = convOutputLength(t, this.kernelSize[0], this.padding, this.strides[0]),
            a$$1 = convOutputLength(n, this.kernelSize[1], this.padding, this.strides[1]);return "channelsFirst" === this.dataFormat ? [e[0], r, i, a$$1] : [e[0], i, a$$1, r];
      }, t.prototype.getConfig = function () {
        var t = e.prototype.getConfig.call(this);return t.depthMultiplier = this.depthMultiplier, t.depthwiseInitializer = serializeInitializer(this.depthwiseInitializer), t.depthwiseRegularizer = serializeRegularizer(this.depthwiseRegularizer), t.depthwiseConstraint = serializeConstraint(this.depthwiseRegularizer), t;
      }, t.className = "DepthwiseConv2D", t;
    }(BaseConv);function mapActivationToFusedKernel(e) {
      return "relu" === e ? "relu" : "linear" === e ? "linear" : null;
    }Fh.registerClass(DepthwiseConv2D);var Dropout = function (e) {
      function t(t) {
        var n = e.call(this, t) || this;if (n.rate = Math.max(Math.min(t.rate, 1), 0), n.noiseShape = t.noiseShape, n.seed = t.seed, null != n.seed) throw new NotImplementedError("Non-default seed is not implemented in Dropout layer yet: " + n.seed);return n.supportsMasking = !0, n;
      }return __extends(t, e), t.prototype.getNoiseShape = function (e) {
        if (null == this.noiseShape) return this.noiseShape;for (var t = e.shape, n = [], r = 0; r < this.noiseShape.length; ++r) n.push(null == this.noiseShape[r] ? t[r] : this.noiseShape[r]);return n;
      }, t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          n.invokeCallHook(e, t);var r = getExactlyOneTensor(e);if (null != n.noiseShape && !Z.arraysEqual(r.shape, n.noiseShape)) throw new NotImplementedError("Non-default noise shape is not implemented in Dropout layer yet: " + JSON.stringify(n.noiseShape));if (0 < n.rate && n.rate < 1) {
            var i = null != t.training && t.training,
                a$$1 = n.getNoiseShape(r);return inTrainPhase(function () {
              return dropout$1(r, n.rate, a$$1, n.seed);
            }, function () {
              return r;
            }, i);
          }return e;
        });
      }, t.prototype.getConfig = function () {
        var t = { rate: this.rate, noiseShape: this.noiseShape, seed: this.seed },
            n = e.prototype.getConfig.call(this);return Object.assign(t, n), t;
      }, t.prototype.dispose = function () {
        return e.prototype.dispose.call(this);
      }, t.className = "Dropout", t;
    }(Layer);Fh.registerClass(Dropout);var Dense = function (e) {
      function t(t) {
        var n = e.call(this, t) || this;if (n.activation = null, n.useBias = !0, n.kernel = null, n.bias = null, n.DEFAULT_KERNEL_INITIALIZER = "glorotNormal", n.DEFAULT_BIAS_INITIALIZER = "zeros", null == t.batchInputShape && null == t.inputShape && null != t.inputDim) {
          var r = null;null != t.batchSize && (r = t.batchSize), n.batchInputShape = [r, t.inputDim];
        }return n.units = t.units, assertPositiveInteger(n.units, "units"), n.activation = getActivation(t.activation), null != t.useBias && (n.useBias = t.useBias), n.kernelInitializer = getInitializer(t.kernelInitializer || n.DEFAULT_KERNEL_INITIALIZER), n.biasInitializer = getInitializer(t.biasInitializer || n.DEFAULT_BIAS_INITIALIZER), n.kernelConstraint = getConstraint(t.kernelConstraint), n.biasConstraint = getConstraint(t.biasConstraint), n.kernelRegularizer = getRegularizer(t.kernelRegularizer), n.biasRegularizer = getRegularizer(t.biasRegularizer), n.activityRegularizer = getRegularizer(t.activityRegularizer), n.supportsMasking = !0, n.inputSpec = [{ minNDim: 2 }], n;
      }return __extends(t, e), t.prototype.build = function (e) {
        var t,
            n = (e = getExactlyOneShape(e))[e.length - 1];null == this.kernel && (this.kernel = this.addWeight("kernel", [n, this.units], null, this.kernelInitializer, this.kernelRegularizer, !0, this.kernelConstraint), this.useBias && (this.bias = this.addWeight("bias", [this.units], null, this.biasInitializer, this.biasRegularizer, !0, this.biasConstraint))), this.inputSpec = [{ minNDim: 2, axes: (t = {}, t[-1] = n, t) }], this.built = !0;
      }, t.prototype.computeOutputShape = function (e) {
        var t = (e = getExactlyOneShape(e)).slice();return t[t.length - 1] = this.units, t;
      }, t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          n.invokeCallHook(e, t);var r,
              i = getExactlyOneTensor(e),
              a$$1 = mapActivationToFusedKernel(n.activation.getClassName());return null != a$$1 ? r = dot(i, n.kernel.read(), a$$1, n.bias ? n.bias.read() : null) : (r = dot(i, n.kernel.read()), null != n.bias && (r = biasAdd(r, n.bias.read())), null != n.activation && (r = n.activation.apply(r))), r;
        });
      }, t.prototype.getConfig = function () {
        var t = { units: this.units, activation: serializeActivation(this.activation), useBias: this.useBias, kernelInitializer: serializeInitializer(this.kernelInitializer), biasInitializer: serializeInitializer(this.biasInitializer), kernelRegularizer: serializeRegularizer(this.kernelRegularizer), biasRegularizer: serializeRegularizer(this.biasRegularizer), activityRegularizer: serializeRegularizer(this.activityRegularizer), kernelConstraint: serializeConstraint(this.kernelConstraint), biasConstraint: serializeConstraint(this.biasConstraint) },
            n = e.prototype.getConfig.call(this);return Object.assign(t, n), t;
      }, t.className = "Dense", t;
    }(Layer);Fh.registerClass(Dense);var Flatten = function (e) {
      function t(t) {
        var n = e.call(this, t || {}) || this;return n.inputSpec = [{ minNDim: 3 }], n;
      }return __extends(t, e), t.prototype.computeOutputShape = function (e) {
        for (var t = 0, n = (e = getExactlyOneShape(e)).slice(1); t < n.length; t++) {
          if (null == n[t]) throw new ValueError('The shape of the input to "Flatten" is not fully defined (got ' + e.slice(1) + '). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.');
        }return [e[0], arrayProd(e, 1)];
      }, t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          return n.invokeCallHook(e, t), batchFlatten(getExactlyOneTensor(e));
        });
      }, t.className = "Flatten", t;
    }(Layer);Fh.registerClass(Flatten);var Activation$1 = function (e) {
      function t(t) {
        var n = e.call(this, t) || this;return n.supportsMasking = !0, n.activation = getActivation(t.activation), n;
      }return __extends(t, e), t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          n.invokeCallHook(e, t);var r = getExactlyOneTensor(e);return n.activation.apply(r);
        });
      }, t.prototype.getConfig = function () {
        var t = { activation: serializeActivation(this.activation) },
            n = e.prototype.getConfig.call(this);return Object.assign(t, n), t;
      }, t.className = "Activation", t;
    }(Layer);Fh.registerClass(Activation$1);var RepeatVector = function (e) {
      function t(t) {
        var n = e.call(this, t) || this;return n.n = t.n, n.inputSpec = [{ ndim: 2 }], n;
      }return __extends(t, e), t.prototype.computeOutputShape = function (e) {
        return [e[0], this.n, e[1]];
      }, t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          return repeat(e = getExactlyOneTensor(e), n.n);
        });
      }, t.prototype.getConfig = function () {
        var t = { n: this.n },
            n = e.prototype.getConfig.call(this);return Object.assign(t, n), t;
      }, t.className = "RepeatVector", t;
    }(Layer);Fh.registerClass(RepeatVector);var Reshape = function (e) {
      function t(t) {
        var n = e.call(this, t) || this;n.targetShape = t.targetShape;for (var r = 0; r < n.targetShape.length; ++r) n.isUnknown(n.targetShape[r]) && (n.targetShape[r] = null);return n;
      }return __extends(t, e), t.prototype.isUnknown = function (e) {
        return e < 0 || null == e;
      }, t.prototype.fixUnknownDimension = function (e, t) {
        for (var n = "Total size of new array must be unchanged.", r = t.slice(), i = 1, a$$1 = null, o = 0; o < r.length; ++o) {
          var s = r[o];if (this.isUnknown(s)) {
            if (null !== a$$1) throw new ValueError("Can only specifiy one unknown dimension.");a$$1 = o;
          } else i *= s;
        }var l$$1 = arrayProd(e);if (null !== a$$1) {
          if (0 === i || l$$1 % i != 0) throw new ValueError(n);r[a$$1] = l$$1 / i;
        } else if (l$$1 !== i) throw new ValueError(n);return r;
      }, t.prototype.computeOutputShape = function (e) {
        for (var t = !1, n = 0; n < e.length; ++n) if (this.isUnknown(e[n])) {
          t = !0;break;
        }return t ? e.slice(0, 1).concat(this.targetShape) : e.slice(0, 1).concat(this.fixUnknownDimension(e.slice(1), this.targetShape));
      }, t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          n.invokeCallHook(e, t);var r = getExactlyOneTensor(e),
              i = r.shape,
              a$$1 = i.slice(0, 1).concat(n.fixUnknownDimension(i.slice(1), n.targetShape));return r.reshape(a$$1);
        });
      }, t.prototype.getConfig = function () {
        var t = { targetShape: this.targetShape },
            n = e.prototype.getConfig.call(this);return Object.assign(t, n), t;
      }, t.className = "Reshape", t;
    }(Layer);Fh.registerClass(Reshape);var Permute = function (e) {
      function t(t) {
        var n = e.call(this, t) || this;if (null == t.dims) throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if (!Array.isArray(t.dims)) throw new Error("Permute constructor requires `dims` to be an Array, but received " + t.dims + " instead.");var r = range(1, t.dims.length + 1);if (!Z.arraysEqual(t.dims.slice().sort(), r)) throw new Error("Invalid permutation `dims`: " + JSON.stringify(t.dims) + " `dims` must contain consecutive integers starting from 1.");return n.dims = t.dims, n.dimsIncludingBatch = [0].concat(n.dims), n.inputSpec = [new InputSpec({ ndim: n.dims.length + 1 })], n;
      }return __extends(t, e), t.prototype.computeOutputShape = function (e) {
        var t = (e = getExactlyOneShape(e)).slice();return this.dims.forEach(function (n, r) {
          t[r + 1] = e[n];
        }), t;
      }, t.prototype.call = function (e, t) {
        return Dl(getExactlyOneTensor(e), this.dimsIncludingBatch);
      }, t.prototype.getConfig = function () {
        var t = { dims: this.dims },
            n = e.prototype.getConfig.call(this);return Object.assign(t, n), t;
      }, t.className = "Permute", t;
    }(Layer);Fh.registerClass(Permute);var Masking = function (e) {
      function t(t) {
        var n = e.call(this, null == t ? {} : t) || this;return n.supportsMasking = !0, n.maskValue = null != t ? null == t.maskValue ? 0 : t.maskValue : 0, n;
      }return __extends(t, e), t.prototype.computeOutputShape = function (e) {
        return e;
      }, t.prototype.getConfig = function () {
        var t = e.prototype.getConfig.call(this),
            n = { maskValue: this.maskValue };return Object.assign(n, t), n;
      }, t.prototype.computeMask = function (e, t) {
        var n = getExactlyOneTensor(e);return Du(Qu(n, this.maskValue), -1);
      }, t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          n.invokeCallHook(e, t);var r = getExactlyOneTensor(e),
              i = Du(Qu(r, n.maskValue), -1, !0);return r.mul(i.asType(r.dtype));
        });
      }, t.className = "Masking", t;
    }(Layer);Fh.registerClass(Masking);var Embedding = function (e) {
      function t(t) {
        var n = e.call(this, t) || this;if (n.embeddings = null, n.DEFAULT_EMBEDDINGS_INITIALIZER = "randomUniform", null == t.batchInputShape && null == t.inputShape) {
          var r = null;null != t.batchSize && (r = t.batchSize), null == t.inputLength ? n.batchInputShape = [r, null] : n.batchInputShape = [r].concat(toList(t.inputLength));
        }return n.inputDim = t.inputDim, assertPositiveInteger(n.inputDim, "inputDim"), n.outputDim = t.outputDim, assertPositiveInteger(n.outputDim, "outputDim"), n.embeddingsInitializer = getInitializer(t.embeddingsInitializer || n.DEFAULT_EMBEDDINGS_INITIALIZER), n.embeddingsRegularizer = getRegularizer(t.embeddingsRegularizer), n.activityRegularizer = getRegularizer(t.activityRegularizer), n.embeddingsConstraint = getConstraint(t.embeddingsConstraint), n.maskZero = t.maskZero, n.supportsMasking = t.maskZero, n.inputLength = t.inputLength, n;
      }return __extends(t, e), t.prototype.build = function (e) {
        this.embeddings = this.addWeight("embeddings", [this.inputDim, this.outputDim], this.dtype, this.embeddingsInitializer, this.embeddingsRegularizer, !0, this.embeddingsConstraint), this.built = !0;
      }, t.prototype.warnOnIncompatibleInputShape = function (e) {}, t.prototype.computeMask = function (e, t) {
        var n = this;return Pe(function () {
          return n.maskZero ? (e = getExactlyOneTensor(e), Qu(e, Dn(e))) : null;
        });
      }, t.prototype.computeOutputShape = function (e) {
        if (e = getExactlyOneShape(e), null == this.inputLength) return e.concat([this.outputDim]);var t = toList(this.inputLength);if (t.length !== e.length - 1) throw new ValueError('"inputLength" is ' + this.inputLength + ", but received input shape has shape " + e);for (var n = 0, r = 0; r < t.length; ++r) {
          var i = t[r],
              a$$1 = e[r + 1];if (null != i && null != a$$1 && i !== a$$1) throw new ValueError('"inputLength" is ' + this.inputLength + ", but received input shape has shape " + e);null == i && (t[n] = a$$1), n++;
        }return [e[0]].concat(t, [this.outputDim]);
      }, t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          n.invokeCallHook(e, t);var r = getExactlyOneTensor(e);return "int32" !== r.dtype && (r = cast$1(r, "int32")), gather$1(n.embeddings.read(), r.as1D()).reshape(getExactlyOneShape(n.computeOutputShape(r.shape)));
        });
      }, t.prototype.getConfig = function () {
        var t = { inputDim: this.inputDim, outputDim: this.outputDim, embeddingsInitializer: serializeInitializer(this.embeddingsInitializer), embeddingsRegularizer: serializeRegularizer(this.embeddingsRegularizer), activityRegularizer: serializeRegularizer(this.activityRegularizer), embeddingsConstraint: serializeConstraint(this.embeddingsConstraint), maskZero: this.maskZero, inputLength: this.inputLength },
            n = e.prototype.getConfig.call(this);return Object.assign(t, n), t;
      }, t.className = "Embedding", t;
    }(Layer);Fh.registerClass(Embedding);var Merge = function (e) {
      function t(t) {
        var n = e.call(this, t || {}) || this;return n.supportsMasking = !0, n;
      }return __extends(t, e), t.prototype.mergeFunction = function (e) {
        throw new NotImplementedError();
      }, t.prototype.computeElementwiseOpOutputShape = function (e, t) {
        if (null == e || null == t) return null;if (e.length < t.length) return this.computeElementwiseOpOutputShape(t, e);if (0 === t.length) return e;for (var n = e.slice(0, e.length - t.length), r = 0; r < t.length; ++r) {
          var i = e[e.length - t.length + r],
              a$$1 = t[r];if (null == i || null == a$$1 || i < 0 || a$$1 < 0) n.push(null);else if (1 === i) n.push(a$$1);else if (1 === a$$1) n.push(i);else {
            if (i !== a$$1) throw new ValueError("Operands could not be broadcast together with shapes " + JSON.stringify(e) + " " + JSON.stringify(t));n.push(i);
          }
        }return n;
      }, t.prototype.build = function (e) {
        if (Array.isArray(e) && !Array.isArray(e[0]) && (e = [getExactlyOneShape(e)]), (e = e).length < 2) throw new ValueError("A merge layer should be called on an Array of at least 2 inputs. Got " + e.length + " input(s).");for (var t = [], n = 0, r = e; n < r.length; n++) {
          null != (o = r[n]) && null !== o[0] && t.push(o[0]);
        }if ((t = unique(t)).length > 1) throw new ValueError("Can not merge tensors with different batch sizes. Got tensors with shapes: " + JSON.stringify(e) + ".");for (var i = null == e[0] ? null : e[0].slice(1), a$$1 = 1; a$$1 < e.length; ++a$$1) {
          var o = null == e[a$$1] ? null : e[a$$1].slice(1);i = this.computeElementwiseOpOutputShape(i, o);
        }var s = e.map(function (e) {
          return e.length;
        });-1 === e.indexOf(null) && 1 === unique(s).length ? this.reshapeRequired = !1 : this.reshapeRequired = !0;
      }, t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          if (e = e, n.reshapeRequired) {
            var t = [],
                r = e.map(function (e) {
              return e.rank;
            });if (-1 === r.indexOf(null)) {
              for (var i = max$1(r), a$$1 = 0, o = e; a$$1 < o.length; a$$1++) {
                for (var s = (h = o[a$$1]).rank, l$$1 = 0; l$$1 < i - s; ++l$$1) h = expandDims$1(h, 1);t.push(h);
              }return n.mergeFunction(t);
            }for (var u = !1, c = 0, p = e; c < p.length; c++) {
              var h;if (null == (s = (h = p[c]).rank)) {
                var d = h.shape,
                    f = d[0],
                    g = d.slice(1).concat([f]),
                    m = h.reshape([f].concat(arrayProd(d.slice(1))));m = (m = Dl(m, [1, 0])).reshape(g), t.push(m), u = !0;
              } else if (s > 1) {
                var y = range(1, s).concat([0]);t.push(Dl(h, y)), u = !0;
              } else t.push(h);
            }var v = n.mergeFunction(t),
                b = v.rank;if (u) if (null == b) {
              var w = v.shape;g = [f = w[w.length - 1]].concat(w.slice(0, w.length - 1));v = Dl(v.reshape([-1, f]), [1, 0]).reshape(g);
            } else if (b > 1) {
              y = [b - 1].concat(range(0, b - 1));v = Dl(v, y);
            }return v;
          }return n.mergeFunction(e);
        });
      }, t.prototype.computeOutputShape = function (e) {
        var t;t = null == (e = e)[0] ? null : e[0].slice(1);for (var n = 1; n < e.length; ++n) {
          var r = null == e[n] ? null : e[n].slice(1);t = this.computeElementwiseOpOutputShape(t, r);
        }for (var i = [], a$$1 = 0, o = e; a$$1 < o.length; a$$1++) {
          null != (r = o[a$$1]) && null !== r[0] && i.push(r[0]);
        }return t = 1 === (i = unique(i)).length ? i.concat(t) : [null].concat(t);
      }, t.prototype.computeMask = function (e, t) {
        return Pe(function () {
          if (null == t) return null;if (!Array.isArray(t)) throw new ValueError("`mask` should be an Array");if (!Array.isArray(e)) throw new ValueError("`inputs` should be an Array");if (t.length !== e.length) throw new ValueError("The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (" + e.length + " vs " + t.length + ")");if (t.every(function (e) {
            return null == e;
          })) return null;for (var n = (t = t.map(function (e) {
            return null == e ? e : nr(e, 0);
          }))[0], r = 1; r < t.length - 1; ++r) n = bl(n, t[r]);return n;
        });
      }, t;
    }(Layer),
        Add = function (e) {
      function t(t) {
        return e.call(this, t) || this;
      }return __extends(t, e), t.prototype.mergeFunction = function (e) {
        return Pe(function () {
          for (var t = e[0].clone(), n = 1; n < e.length; ++n) t = Zu(t, e[n]);return t;
        });
      }, t.className = "Add", t;
    }(Merge);Fh.registerClass(Add);var Multiply = function (e) {
      function t(t) {
        return e.call(this, t) || this;
      }return __extends(t, e), t.prototype.mergeFunction = function (e) {
        return Pe(function () {
          for (var t = e[0].clone(), n = 1; n < e.length; ++n) t = pl(t, e[n]);return t;
        });
      }, t.className = "Multiply", t;
    }(Merge);Fh.registerClass(Multiply);var Average = function (e) {
      function t(t) {
        return e.call(this, t) || this;
      }return __extends(t, e), t.prototype.mergeFunction = function (e) {
        return Pe(function () {
          for (var t = e[0].clone(), n = 1; n < e.length; ++n) t = Zu(t, e[n]);return pl(1 / e.length, t);
        });
      }, t.className = "Average", t;
    }(Merge);Fh.registerClass(Average);var Maximum = function (e) {
      function t(t) {
        return e.call(this, t) || this;
      }return __extends(t, e), t.prototype.mergeFunction = function (e) {
        return Pe(function () {
          for (var t = e[0], n = 1; n < e.length; ++n) t = il(t, e[n]);return t;
        });
      }, t.className = "Maximum", t;
    }(Merge);Fh.registerClass(Maximum);var Minimum = function (e) {
      function t(t) {
        return e.call(this, t) || this;
      }return __extends(t, e), t.prototype.mergeFunction = function (e) {
        return Pe(function () {
          for (var t = e[0], n = 1; n < e.length; ++n) t = ul(t, e[n]);return t;
        });
      }, t.className = "Minimum", t;
    }(Merge);Fh.registerClass(Minimum);var Concatenate = function (e) {
      function t(t) {
        var n = e.call(this, t) || this;return n.DEFAULT_AXIS = -1, null == t && (t = {}), n.axis = null == t.axis ? n.DEFAULT_AXIS : t.axis, n.supportsMasking = !0, n.reshapeRequired = !1, n;
      }return __extends(t, e), t.prototype.build = function (e) {
        if (!Array.isArray(e) || !Array.isArray(e[0]) || 1 === e.length) throw new ValueError("A `Concatenate` layer should be called on a list of at least 2 inputs");for (var t = !0, n = 0, r = e = e; n < r.length; n++) {
          if (null != (c = r[n])) {
            t = !1;break;
          }
        }if (!t) {
          for (var i = [], a$$1 = 0; a$$1 < e.length; ++a$$1) {
            var o = e[a$$1].slice();o.splice(this.axis, 1);for (var s = !1, l$$1 = 0, u = i; l$$1 < u.length; l$$1++) {
              var c = u[l$$1];if (Z.arraysEqual(c, o)) {
                s = !0;break;
              }
            }s || i.push(o);
          }if (i.length > 1) throw new ValueError("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: " + JSON.stringify(e));
        }
      }, t.prototype.mergeFunction = function (e) {
        var t = this;return Pe(function () {
          return concatenate(e, t.axis);
        });
      }, t.prototype.computeOutputShape = function (e) {
        if (!Array.isArray(e) || !Array.isArray(e[0])) throw new ValueError("A `Concatenate` layer should be called on a list of inputs.");for (var t = e, n = t[0].slice(), r = this.axis < 0 ? n.length + this.axis : this.axis, i = 0, a$$1 = t.slice(1); i < a$$1.length; i++) {
          var o = a$$1[i];if (null == n[r] || null == o[r]) {
            n[r] = null;break;
          }n[r] += o[r];
        }return n;
      }, t.prototype.computeMask = function (e, t) {
        var n = this;if (null == t) return null;if (!Array.isArray(t)) throw new ValueError("`mask` should be an array for Concatenate");if (!Array.isArray(e)) throw new ValueError("`inputs` should be an array for Concatenate");if (t.length !== e.length) throw new ValueError("Mismatch in the length of mask (" + t.length + ") and the legnth of inputs (" + e.length + ")");return Pe(function () {
          var r = !0;if (t.forEach(function (e) {
            null == e || (r = !1);
          }), r) return null;for (var i = [], a$$1 = 0; a$$1 < e.length; ++a$$1) null == t[a$$1] ? i.push(Tn(e[a$$1]).asType("bool")) : t[a$$1].rank < e[a$$1].rank ? i.push(nr(t[a$$1], -1)) : i.push(t[a$$1]);var o = _n(i, n.axis);return Tu(o, -1, !1);
        });
      }, t.prototype.getConfig = function () {
        var t = { axis: this.axis },
            n = e.prototype.getConfig.call(this);return Object.assign(t, n), t;
      }, t.className = "Concatenate", t;
    }(Merge);function interpretAxis(e, t) {
      for (; e < 0;) e += t;return e;
    }function batchDot(e, t, n) {
      if (e.shape.length > 3 || t.shape.length > 3) throw new NotImplementedError("batchDot is not implemented for tensors of 4D or higher rank yet");if (Z.assert(e.shape.length >= 2, function () {
        return "batchDot requires the rank of x to be >= 2, but got " + e.shape.length;
      }), Z.assert(e.shape.length >= 2, function () {
        return "batchDot requires the rank of y to be >= 2, but got " + t.shape.length;
      }), "number" == typeof n && (n = [n, n]), "complex64" === e.dtype || "complex64" === t.dtype) throw new NotImplementedError("batchDot is not implemented for complex64-type Tensors yet.");var r = e.shape.length,
          i = t.shape.length;null == n && (n = [r - 1, i - 2]);var a$$1 = n;return Pe(function () {
        var n, o;if (r > i) {
          n = r - i;for (var s = [], l$$1 = 0; l$$1 < n; ++l$$1) s.push(1);t = t.reshape(t.shape.concat(s));
        } else if (i > r) {
          n = i - r;for (s = [], l$$1 = 0; l$$1 < n; ++l$$1) s.push(1);e = e.reshape(e.shape.concat(s));
        } else n = 0;if (2 === e.shape.length && 2 === t.shape.length) o = a$$1[0] === a$$1[1] ? e.mulStrict(t).sum(a$$1[0]) : e.transpose([1, 0]).mulStrict(t).sum(a$$1[1]);else {
          var u = a$$1[0] !== e.shape.length - 1,
              c = a$$1[1] === t.shape.length - 1;o = e.matMul(t, u, c);
        }if (n > 0) {
          var p = void 0,
              h = [];for (l$$1 = p = r > i ? r + i - 3 : r - 1; l$$1 < p + n; ++l$$1) h.push(l$$1);o = o.squeeze(h);
        }return 1 === o.shape.length && (o = o.expandDims(1)), o;
      });
    }Fh.registerClass(Concatenate);var Dot = function (e) {
      function t(t) {
        var n = e.call(this, t) || this;return n.axes = t.axes, n.normalize = null != t.normalize && t.normalize, n.supportsMasking = !0, n.reshapeRequired = !1, n;
      }return __extends(t, e), t.prototype.build = function (e) {
        Z.assert(Array.isArray(e) && 2 === e.length && Array.isArray(e[0]) && Array.isArray(e[1]), function () {
          return "A `Dot` layer should be called on a list of exactly 2 inputs.";
        });var t = e[0],
            n = e[1];if (t.length > 3 || n.length > 3) throw new NotImplementedError("Dot layer does not support tensors of 4D or higher rank yet.");var r = this.interpretAxes(t, n);if (t[r[0]] !== n[r[1]]) throw new ValueError("Dimension incompatibility: " + t[r[0]] + " !== " + n[r[1]]);
      }, t.prototype.mergeFunction = function (e) {
        if (2 !== e.length) throw new ValueError("A `Dot` layer must be called on exactly 2 inputs, but received " + e.length + " input(s).");var t,
            n = e[0],
            r = e[1];return t = Array.isArray(this.axes) ? this.axes.map(function (t, n) {
          return interpretAxis(t, e[n].shape.length);
        }) : [interpretAxis(this.axes, n.shape.length), interpretAxis(this.axes, r.shape.length)], this.normalize && (n = l2Normalize(n, t[0]), r = l2Normalize(r, t[1])), batchDot(n, r, t);
      }, t.prototype.interpretAxes = function (e, t) {
        return Array.isArray(this.axes) ? this.axes : [interpretAxis(this.axes, e.length), interpretAxis(this.axes, t.length)];
      }, t.prototype.computeOutputShape = function (e) {
        Z.assert(Array.isArray(e) && 2 === e.length && Array.isArray(e[0]) && Array.isArray(e[1]), function () {
          return "A `Dot` layer should be called on a list of exactly 2 inputs.";
        });var t = e[0].slice(),
            n = e[1].slice();if (t.length > 3 || n.length > 3) throw new NotImplementedError("Dot layer does not support tensors of 4D or higher rank yet.");var r = this.interpretAxes(t, n);t.splice(r[0], 1), n.splice(r[1], 1), n.splice(0, 1);var i = t.concat(n);return 1 === i.length && i.push(1), i;
      }, t.prototype.computeMask = function (e, t) {
        return null;
      }, t.prototype.getConfig = function () {
        var t = { axes: this.axes, normalize: this.normalize },
            n = e.prototype.getConfig.call(this);return Object.assign(t, n), t;
      }, t.className = "Dot", t;
    }(Merge);Fh.registerClass(Dot);var GaussianNoise = function (e) {
      function t(t) {
        var n = e.call(this, t) || this;return n.supportsMasking = !0, n.stddev = t.stddev, n;
      }return __extends(t, e), t.prototype.computeOutputShape = function (e) {
        return e;
      }, t.prototype.getConfig = function () {
        var t = e.prototype.getConfig.call(this),
            n = { stddev: this.stddev };return Object.assign(n, t), n;
      }, t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          n.invokeCallHook(e, t);var r = getExactlyOneTensor(e);return inTrainPhase(function () {
            return randomNormal$1(r.shape, 0, n.stddev).add(r);
          }, function () {
            return r;
          }, t.training || !1);
        });
      }, t.className = "GaussianNoise", t;
    }(Layer);Fh.registerClass(GaussianNoise);var GaussianDropout = function (e) {
      function t(t) {
        var n = e.call(this, t) || this;return n.supportsMasking = !0, n.rate = t.rate, n;
      }return __extends(t, e), t.prototype.computeOutputShape = function (e) {
        return e;
      }, t.prototype.getConfig = function () {
        var t = e.prototype.getConfig.call(this),
            n = { rate: this.rate };return Object.assign(n, t), n;
      }, t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          n.invokeCallHook(e, t);var r = getExactlyOneTensor(e);if (n.rate > 0 && n.rate < 1) {
            return inTrainPhase(function () {
              var e = Math.sqrt(n.rate / (1 - n.rate));return r.mul(randomNormal$1(r.shape, 1, e));
            }, function () {
              return r;
            }, t.training || !1);
          }return r;
        });
      }, t.className = "GaussianDropout", t;
    }(Layer);Fh.registerClass(GaussianDropout);var AlphaDropout = function (e) {
      function t(t) {
        var n = e.call(this, t) || this;return n.supportsMasking = !0, n.rate = t.rate, n.noiseShape = t.noiseShape, n;
      }return __extends(t, e), t.prototype._getNoiseShape = function (e) {
        return this.noiseShape || getExactlyOneTensor(e).shape;
      }, t.prototype.computeOutputShape = function (e) {
        return e;
      }, t.prototype.getConfig = function () {
        var t = e.prototype.getConfig.call(this),
            n = { rate: this.rate };return Object.assign(n, t), n;
      }, t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          if (n.rate < 1 && n.rate > 0) {
            var r = n._getNoiseShape(e);return inTrainPhase(function () {
              var t = getExactlyOneTensor(e),
                  i = -1.7580993408473766,
                  a$$1 = qu(fr(r), n.rate);a$$1 = cast$1(a$$1, "float32");var o = Math.pow((1 - n.rate) * (1 + n.rate * Math.pow(i, 2)), -.5),
                  s = -o * i * n.rate;return t.mul(a$$1).add(a$$1.add(-1).mul(i)).mul(o).add(s);
            }, function () {
              return getExactlyOneTensor(e);
            }, t.training || !1);
          }return e;
        });
      }, t.className = "AlphaDropout", t;
    }(Layer);function batchNormalization(e, t, n, r, i, a$$1) {
      var o;if (void 0 === a$$1 && (a$$1 = .001), 2 === e.rank) o = Js(e, t, n, r, i, a$$1);else if (3 === e.rank) o = Zs(e, t, n, r, i, a$$1);else {
        if (4 !== e.rank) throw new NotImplementedError("batchNormalization is not implemented for array of rank " + e.rank + " yet");o = tu(e, t, n, r, i, a$$1);
      }return o;
    }function regularNormalizeBatchInTraining(e, t, n, r, i) {
      return void 0 === i && (i = .001), Pe(function () {
        var a$$1 = Lu(e, r),
            o = a$$1.mean,
            s = a$$1.variance;return [batchNormalization(e, o, s, n, t, i), o, s];
      });
    }function broadcastNormalizeBatchInTraining(e, t, n, r, i) {
      return void 0 === i && (i = .001), Pe(function () {
        for (var a$$1 = Lu(e, r), o = a$$1.mean, s = a$$1.variance, l$$1 = [], u = 0, c = range(0, e.rank); u < c.length; u++) {
          var p = c[u];-1 !== r.indexOf(p) ? l$$1.push(1) : l$$1.push(e.shape[p]);
        }var h = o.reshape(l$$1),
            d = s.reshape(l$$1),
            f = null == t ? null : t.reshape(l$$1),
            g = null == n ? null : n.reshape(l$$1);return [batchNormalization(e, h, d, g, f, i), o, s];
      });
    }function normalizeBatchInTraining(e, t, n, r, i) {
      return void 0 === i && (i = .001), Z.arraysEqual(r.slice().sort(), range(0, e.rank - 1)) ? regularNormalizeBatchInTraining(e, t, n, r, i) : broadcastNormalizeBatchInTraining(e, t, n, r, i);
    }Fh.registerClass(AlphaDropout);var BatchNormalization = function (e) {
      function t(t) {
        var n = this;return null == t && (t = {}), (n = e.call(this, t) || this).supportsMasking = !0, n.axis = null == t.axis ? -1 : t.axis, n.momentum = null == t.momentum ? .99 : t.momentum, n.epsilon = null == t.epsilon ? .001 : t.epsilon, n.center = null == t.center || t.center, n.scale = null == t.scale || t.scale, n.betaInitializer = getInitializer(t.betaInitializer || "zeros"), n.gammaInitializer = getInitializer(t.gammaInitializer || "ones"), n.movingMeanInitializer = getInitializer(t.movingMeanInitializer || "zeros"), n.movingVarianceInitializer = getInitializer(t.movingVarianceInitializer || "ones"), n.betaConstraint = getConstraint(t.betaConstraint), n.gammaConstraint = getConstraint(t.gammaConstraint), n.betaRegularizer = getRegularizer(t.betaRegularizer), n.gammaRegularizer = getRegularizer(t.gammaRegularizer), n;
      }return __extends(t, e), t.prototype.build = function (e) {
        var t;e = getExactlyOneShape(e);var n = this.axis >= 0 ? this.axis : this.axis + e.length,
            r = e[n];if (null == r) throw new ValueError("Axis " + n + " of input tensor should have a defined dimension but the layer received an input with shape " + JSON.stringify(e) + ".");this.inputSpec = [new InputSpec({ ndim: e.length, axes: (t = {}, t[n] = r, t) })];var i = [r];this.scale && (this.gamma = this.addWeight("gamma", i, null, this.gammaInitializer, this.gammaRegularizer, !0, this.gammaConstraint)), this.center && (this.beta = this.addWeight("beta", i, null, this.betaInitializer, this.betaRegularizer, !0, this.betaConstraint)), this.movingMean = this.addWeight("moving_mean", i, null, this.movingMeanInitializer, null, !1), this.movingVariance = this.addWeight("moving_variance", i, null, this.movingVarianceInitializer, null, !1), this.built = !0;
      }, t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          var r = null != t.training && t.training,
              i = getExactlyOneTensor(e),
              a$$1 = i.shape,
              o = a$$1.length,
              s = range(0, o),
              l$$1 = n.axis >= 0 ? n.axis : n.axis + o;s.splice(l$$1, 1);var u = pyListRepeat(1, o);u[l$$1] = a$$1[l$$1];var c = s.slice();c.sort();var p = !Z.arraysEqual(c, range(0, o).slice(0, o - 1));if (!r) return function () {
            if (p) {
              var e = n.movingMean.read().reshape(u),
                  t = n.movingVariance.read().reshape(u),
                  r = n.center ? n.beta.read().reshape(u) : null,
                  a$$1 = n.scale ? n.gamma.read().reshape(u) : null;return batchNormalization(i, e, t, r, a$$1, n.epsilon);
            }return batchNormalization(i, n.movingMean.read(), n.movingVariance.read(), null == n.beta ? null : n.beta.read(), null == n.gamma ? null : n.gamma.read(), n.epsilon);
          }();var h = normalizeBatchInTraining(i, n.gamma.read(), n.beta.read(), s, n.epsilon),
              d = h[0],
              f = h[1],
              g = h[2],
              m = function (e, t, n) {
            Pe(function () {
              var r = 1 - n,
                  i = e.read(),
                  a$$1 = i.sub(t).mul(r);e.write(i.sub(a$$1));
            });
          };return m(n.movingMean, f, n.momentum), m(n.movingVariance, g, n.momentum), d;
        });
      }, t.prototype.getConfig = function () {
        var t = { axis: this.axis, momentum: this.momentum, epsilon: this.epsilon, center: this.center, scale: this.scale, betaInitializer: serializeInitializer(this.betaInitializer), gammaInitializer: serializeInitializer(this.gammaInitializer), movingMeanInitializer: serializeInitializer(this.movingMeanInitializer), movingVarianceInitializer: serializeInitializer(this.movingVarianceInitializer), betaRegularizer: serializeRegularizer(this.betaRegularizer), gammaRegularizer: serializeRegularizer(this.gammaRegularizer), betaConstraint: serializeConstraint(this.betaConstraint), gammaConstraint: serializeConstraint(this.gammaConstraint) },
            n = e.prototype.getConfig.call(this);return Object.assign(t, n), t;
      }, t.className = "BatchNormalization", t;
    }(Layer);function spatial2dPadding(e, t, n) {
      return Pe(function () {
        if (4 !== e.rank) throw new ValueError("temporalPadding expects input tensor to be 4-D, but received a " + e.rank + "-D tensor.");if (null == t && (t = [[1, 1], [1, 1]]), 2 !== t.length || 2 !== t[0].length || 2 !== t[1].length) throw new ValueError("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if (null == n && (n = imageDataFormat()), "channelsLast" !== n && "channelsFirst" !== n) throw new ValueError("Unknown data format: " + n + ". Supported data formats are 'channelsLast' and 'channelsFirst.");var r;return r = "channelsFirst" === n ? [[0, 0], [0, 0], t[0], t[1]] : [[0, 0], t[0], t[1], [0, 0]], ir(e, r);
      });
    }Fh.registerClass(BatchNormalization);var ZeroPadding2D = function (e) {
      function t(t) {
        var n = this;if (null == t && (t = {}), (n = e.call(this, t) || this).dataFormat = null == t.dataFormat ? imageDataFormat() : t.dataFormat, null == t.padding) n.padding = [[1, 1], [1, 1]];else if ("number" == typeof t.padding) n.padding = [[t.padding, t.padding], [t.padding, t.padding]];else {
          if (t.padding = t.padding, 2 !== t.padding.length) throw new ValueError("ZeroPadding2D expects padding to be a length-2 array, but received a length-" + t.padding.length + " array.");var r = void 0,
              i = void 0;if ("number" == typeof t.padding[0]) r = [t.padding[0], t.padding[0]], i = [t.padding[1], t.padding[1]];else {
            if (t.padding = t.padding, 2 !== t.padding[0].length) throw new ValueError("ZeroPadding2D expects height padding to be a length-2 array, but received a length-" + t.padding[0].length + " array.");if (r = t.padding[0], 2 !== t.padding[1].length) throw new ValueError("ZeroPadding2D expects width padding to be a length-2 array, but received a length-" + t.padding[1].length + " array.");i = t.padding[1];
          }n.padding = [r, i];
        }return n.inputSpec = [new InputSpec({ ndim: 4 })], n;
      }return __extends(t, e), t.prototype.computeOutputShape = function (e) {
        var t, n;return e = getExactlyOneShape(e), "channelsFirst" === this.dataFormat ? (t = null != e[2] && e[2] >= 0 ? e[2] + this.padding[0][0] + this.padding[0][1] : null, n = null != e[3] && e[3] >= 0 ? e[3] + this.padding[1][0] + this.padding[1][1] : null, [e[0], e[1], t, n]) : (t = null != e[1] && e[1] >= 0 ? e[1] + this.padding[0][0] + this.padding[0][1] : null, n = null != e[2] && e[2] >= 0 ? e[2] + this.padding[1][0] + this.padding[1][1] : null, [e[0], t, n, e[3]]);
      }, t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          return spatial2dPadding(getExactlyOneTensor(e), n.padding, n.dataFormat);
        });
      }, t.prototype.getConfig = function () {
        var t = { padding: this.padding, dataFormat: this.dataFormat },
            n = e.prototype.getConfig.call(this);return Object.assign(t, n), t;
      }, t.className = "ZeroPadding2D", t;
    }(Layer);function pool2d(e, t, n, r, i, a$$1) {
      return Pe(function () {
        var o;checkDataFormat(i), checkPoolMode(a$$1), checkPaddingMode(r), null == n && (n = [1, 1]), null == r && (r = "valid"), null == i && (i = imageDataFormat()), null == a$$1 && (a$$1 = "max"), e = preprocessConv2DInput(e, i);var s = "same" === r ? "same" : "valid";return o = "max" === a$$1 ? wu(e, t, n, s) : Cu(e, t, n, s), "channelsFirst" === i && (o = Dl(o, [0, 3, 1, 2])), o;
      });
    }Fh.registerClass(ZeroPadding2D);var Pooling1D = function (e) {
      function t(t) {
        var n = this;if (null == t.poolSize && (t.poolSize = 2), n = e.call(this, t) || this, "number" == typeof t.poolSize) n.poolSize = [t.poolSize];else {
          if (!Array.isArray(t.poolSize) || 1 !== t.poolSize.length || "number" != typeof t.poolSize[0]) throw new ValueError("poolSize for 1D convolutional layer must be a number or an Array of a single number, but received " + JSON.stringify(t.poolSize));n.poolSize = t.poolSize;
        }if (assertPositiveInteger(n.poolSize, "poolSize"), null == t.strides) n.strides = n.poolSize;else if ("number" == typeof t.strides) n.strides = [t.strides];else {
          if (!Array.isArray(t.strides) || 1 !== t.strides.length || "number" != typeof t.strides[0]) throw new ValueError("strides for 1D convolutional layer must be a number or an Array of a single number, but received " + JSON.stringify(t.strides));n.strides = t.strides;
        }return assertPositiveInteger(n.strides, "strides"), n.padding = null == t.padding ? "valid" : t.padding, checkPaddingMode(n.padding), n.inputSpec = [new InputSpec({ ndim: 3 })], n;
      }return __extends(t, e), t.prototype.computeOutputShape = function (e) {
        var t = convOutputLength((e = getExactlyOneShape(e))[1], this.poolSize[0], this.padding, this.strides[0]);return [e[0], t, e[2]];
      }, t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          n.invokeCallHook(e, t), e = expandDims$1(getExactlyOneTensor(e), 2);var r = n.poolingFunction(getExactlyOneTensor(e), [n.poolSize[0], 1], [n.strides[0], 1], n.padding, "channelsLast");return mr(r, [2]);
        });
      }, t.prototype.getConfig = function () {
        var t = { poolSize: this.poolSize, padding: this.padding, strides: this.strides },
            n = e.prototype.getConfig.call(this);return Object.assign(t, n), t;
      }, t;
    }(Layer),
        MaxPooling1D = function (e) {
      function t(t) {
        return e.call(this, t) || this;
      }return __extends(t, e), t.prototype.poolingFunction = function (e, t, n, r, i) {
        return checkDataFormat(i), checkPaddingMode(r), pool2d(e, t, n, r, i, "max");
      }, t.className = "MaxPooling1D", t;
    }(Pooling1D);Fh.registerClass(MaxPooling1D);var AveragePooling1D = function (e) {
      function t(t) {
        return e.call(this, t) || this;
      }return __extends(t, e), t.prototype.poolingFunction = function (e, t, n, r, i) {
        return checkDataFormat(i), checkPaddingMode(r), pool2d(e, t, n, r, i, "avg");
      }, t.className = "AveragePooling1D", t;
    }(Pooling1D);Fh.registerClass(AveragePooling1D);var Pooling2D = function (e) {
      function t(t) {
        var n = this;if (null == t.poolSize && (t.poolSize = [2, 2]), (n = e.call(this, t) || this).poolSize = Array.isArray(t.poolSize) ? t.poolSize : [t.poolSize, t.poolSize], null == t.strides) n.strides = n.poolSize;else if (Array.isArray(t.strides)) {
          if (2 !== t.strides.length) throw new ValueError("If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length " + t.strides.length + ".");n.strides = t.strides;
        } else n.strides = [t.strides, t.strides];return assertPositiveInteger(n.poolSize, "poolSize"), assertPositiveInteger(n.strides, "strides"), n.padding = null == t.padding ? "valid" : t.padding, n.dataFormat = null == t.dataFormat ? "channelsLast" : t.dataFormat, checkDataFormat(n.dataFormat), checkPaddingMode(n.padding), n.inputSpec = [new InputSpec({ ndim: 4 })], n;
      }return __extends(t, e), t.prototype.computeOutputShape = function (e) {
        e = getExactlyOneShape(e);var t = "channelsFirst" === this.dataFormat ? e[2] : e[1],
            n = "channelsFirst" === this.dataFormat ? e[3] : e[2];return t = convOutputLength(t, this.poolSize[0], this.padding, this.strides[0]), n = convOutputLength(n, this.poolSize[1], this.padding, this.strides[1]), "channelsFirst" === this.dataFormat ? [e[0], e[1], t, n] : [e[0], t, n, e[3]];
      }, t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          return n.invokeCallHook(e, t), n.poolingFunction(getExactlyOneTensor(e), n.poolSize, n.strides, n.padding, n.dataFormat);
        });
      }, t.prototype.getConfig = function () {
        var t = { poolSize: this.poolSize, padding: this.padding, strides: this.strides, dataFormat: this.dataFormat },
            n = e.prototype.getConfig.call(this);return Object.assign(t, n), t;
      }, t;
    }(Layer),
        MaxPooling2D = function (e) {
      function t(t) {
        return e.call(this, t) || this;
      }return __extends(t, e), t.prototype.poolingFunction = function (e, t, n, r, i) {
        return checkDataFormat(i), checkPaddingMode(r), pool2d(e, t, n, r, i, "max");
      }, t.className = "MaxPooling2D", t;
    }(Pooling2D);Fh.registerClass(MaxPooling2D);var AveragePooling2D = function (e) {
      function t(t) {
        return e.call(this, t) || this;
      }return __extends(t, e), t.prototype.poolingFunction = function (e, t, n, r, i) {
        return checkDataFormat(i), checkPaddingMode(r), pool2d(e, t, n, r, i, "avg");
      }, t.className = "AveragePooling2D", t;
    }(Pooling2D);Fh.registerClass(AveragePooling2D);var GlobalPooling1D = function (e) {
      function t(t) {
        var n = e.call(this, t) || this;return n.inputSpec = [new InputSpec({ ndim: 3 })], n;
      }return __extends(t, e), t.prototype.computeOutputShape = function (e) {
        return [e[0], e[2]];
      }, t.prototype.call = function (e, t) {
        throw new NotImplementedError();
      }, t;
    }(Layer),
        GlobalAveragePooling1D = function (e) {
      function t(t) {
        return e.call(this, t || {}) || this;
      }return __extends(t, e), t.prototype.call = function (e, t) {
        return Pe(function () {
          var t = getExactlyOneTensor(e);return Bu(t, 1);
        });
      }, t.className = "GlobalAveragePooling1D", t;
    }(GlobalPooling1D);Fh.registerClass(GlobalAveragePooling1D);var GlobalMaxPooling1D = function (e) {
      function t(t) {
        return e.call(this, t || {}) || this;
      }return __extends(t, e), t.prototype.call = function (e, t) {
        return Pe(function () {
          var t = getExactlyOneTensor(e);return Fu(t, 1);
        });
      }, t.className = "GlobalMaxPooling1D", t;
    }(GlobalPooling1D);Fh.registerClass(GlobalMaxPooling1D);var GlobalPooling2D = function (e) {
      function t(t) {
        var n = e.call(this, t) || this;return n.dataFormat = null == t.dataFormat ? "channelsLast" : t.dataFormat, checkDataFormat(n.dataFormat), n.inputSpec = [new InputSpec({ ndim: 4 })], n;
      }return __extends(t, e), t.prototype.computeOutputShape = function (e) {
        return e = e, "channelsLast" === this.dataFormat ? [e[0], e[3]] : [e[0], e[1]];
      }, t.prototype.call = function (e, t) {
        throw new NotImplementedError();
      }, t.prototype.getConfig = function () {
        var t = { dataFormat: this.dataFormat },
            n = e.prototype.getConfig.call(this);return Object.assign(t, n), t;
      }, t;
    }(Layer),
        GlobalAveragePooling2D = function (e) {
      function t() {
        return null !== e && e.apply(this, arguments) || this;
      }return __extends(t, e), t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          var t = getExactlyOneTensor(e);return "channelsLast" === n.dataFormat ? Bu(t, [1, 2]) : Bu(t, [2, 3]);
        });
      }, t.className = "GlobalAveragePooling2D", t;
    }(GlobalPooling2D);Fh.registerClass(GlobalAveragePooling2D);var GlobalMaxPooling2D = function (e) {
      function t() {
        return null !== e && e.apply(this, arguments) || this;
      }return __extends(t, e), t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          var t = getExactlyOneTensor(e);return "channelsLast" === n.dataFormat ? Fu(t, [1, 2]) : Fu(t, [2, 3]);
        });
      }, t.className = "GlobalMaxPooling2D", t;
    }(GlobalPooling2D);function standardizeArgs(e, t, n, r) {
      if (Array.isArray(e)) {
        if (null != t || null != n) throw new ValueError("When inputs is an array, neither initialState or constants should be provided");null != r && (n = e.slice(e.length - r, e.length), e = e.slice(0, e.length - r)), e.length > 1 && (t = e.slice(1, e.length)), e = e[0];
      }function i(e) {
        return null == e || Array.isArray(e) ? e : [e];
      }return { inputs: e, initialState: t = i(t), constants: n = i(n) };
    }function rnn(e, t, n, r, i, a$$1, o, s) {
      return void 0 === r && (r = !1), void 0 === o && (o = !1), void 0 === s && (s = !1), Pe(function () {
        var l$$1 = t.shape.length;if (l$$1 < 3) throw new ValueError("Input should be at least 3D, but is " + l$$1 + "D.");var u = [1, 0].concat(range(2, l$$1));if (t = Dl(t, u), null != a$$1) throw new NotImplementedError("The rnn() functoin of the deeplearn.js backend does not support constants yet.");o && console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."), null != i && ((i = i.asType("bool").asType("float32")).rank === l$$1 - 1 && (i = nr(i, -1)), i = Dl(i, u)), r && (t = du(t, 0), null != i && (i = du(i, 0)));var c,
            p,
            h = [],
            d = n,
            f = t.shape[0],
            g = br(t);null != i && (p = br(i));for (var m, y = function (t) {
          var n = g[t],
              r = Pe(function () {
            return e(n, d);
          });if (null == i) c = r[0], d = r[1];else {
            var a$$1 = Pe(function () {
              var e = p[t],
                  n = Tn(e).sub(e);return { output: r[0].mul(e).addStrict(d[0].mul(n)), newStates: d.map(function (t, i) {
                  return r[1][i].mul(e).addStrict(t.mul(n));
                }) };
            });c = a$$1.output, d = a$$1.newStates;
          }s && h.push(c);
        }, v = 0; v < f; ++v) y(v);if (s) {
          m = gr(h, 1);
        }return [c, m, d];
      });
    }Fh.registerClass(GlobalMaxPooling2D);var RNN = function (e) {
      function t(t) {
        var n,
            r = e.call(this, t) || this;if (null == t.cell) throw new ValueError("cell property is missing for the constructor of RNN.");if (null == (n = Array.isArray(t.cell) ? new StackedRNNCells({ cells: t.cell }) : t.cell).stateSize) throw new ValueError("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");return r.cell = n, r.returnSequences = null != t.returnSequences && t.returnSequences, r.returnState = null != t.returnState && t.returnState, r.goBackwards = null != t.goBackwards && t.goBackwards, r._stateful = null != t.stateful && t.stateful, r.unroll = null != t.unroll && t.unroll, r.supportsMasking = !0, r.inputSpec = [new InputSpec({ ndim: 3 })], r.stateSpec = null, r.states_ = null, r.numConstants = null, r.keptStates = [], r;
      }return __extends(t, e), t.prototype.getStates = function () {
        return null == this.states_ ? range(0, Array.isArray(this.cell.stateSize) ? this.cell.stateSize.length : 1).map(function (e) {
          return null;
        }) : this.states_;
      }, t.prototype.setStates = function (e) {
        this.states_ = e;
      }, t.prototype.computeOutputShape = function (e) {
        isArrayOfShapes(e) && (e = e[0]), e = e;var t = this.cell.stateSize;Array.isArray(t) || (t = [t]);var n,
            r = t[0];if (n = this.returnSequences ? [e[0], e[1], r] : [e[0], r], this.returnState) {
          for (var i = [], a$$1 = 0, o = t; a$$1 < o.length; a$$1++) {
            var s = o[a$$1];i.push([e[0], s]);
          }return [n].concat(i);
        }return n;
      }, t.prototype.computeMask = function (e, t) {
        var n = this;return Pe(function () {
          Array.isArray(t) && (t = t[0]);var e = n.returnSequences ? t : null;if (n.returnState) {
            var r = n.states.map(function (e) {
              return null;
            });return [e].concat(r);
          }return e;
        });
      }, Object.defineProperty(t.prototype, "states", { get: function () {
          if (null == this.states_) {
            for (var e = Array.isArray(this.cell.stateSize) ? this.cell.stateSize.length : 1, t = [], n = 0; n < e; ++n) t.push(null);return t;
          }return this.states_;
        }, set: function (e) {
          this.states_ = e;
        }, enumerable: !0, configurable: !0 }), t.prototype.build = function (e) {
        if (null != this.numConstants) throw new NotImplementedError("Constants support is not implemented in RNN yet.");isArrayOfShapes(e) && (e = e[0]), e = e;var t = this.stateful ? e[0] : null,
            n = e[e.length - 1];this.inputSpec[0] = new InputSpec({ shape: [t, null, n] });var r,
            i = [e[0]].concat(e.slice(2));if (this.cell.build(i), r = Array.isArray(this.cell.stateSize) ? this.cell.stateSize : [this.cell.stateSize], null != this.stateSpec) {
          if (!Z.arraysEqual(this.stateSpec.map(function (e) {
            return e.shape[e.shape.length - 1];
          }), r)) throw new ValueError("An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=" + this.stateSpec + "; However cell.stateSize is " + this.cell.stateSize);
        } else this.stateSpec = r.map(function (e) {
          return new InputSpec({ shape: [null, e] });
        });this.stateful && this.resetStates();
      }, t.prototype.resetStates = function (e, t) {
        var n = this;void 0 === t && (t = !1), Pe(function () {
          if (!n.stateful) throw new AttributeError("Cannot call resetStates() on an RNN Layer that is not stateful.");var r = n.inputSpec[0].shape[0];if (null == r) throw new ValueError("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if (null == n.states_) Array.isArray(n.cell.stateSize) ? n.states_ = n.cell.stateSize.map(function (e) {
            return Sn([r, e]);
          }) : n.states_ = [Sn([r, n.cell.stateSize])];else if (null == e) Le(n.states_), null != n.keptStates && (Le(n.keptStates), n.keptStates = []), Array.isArray(n.cell.stateSize) ? n.states_ = n.cell.stateSize.map(function (e) {
            return Sn([r, e]);
          }) : n.states_[0] = Sn([r, n.cell.stateSize]);else {
            if (Array.isArray(e) || (e = [e]), e.length !== n.states_.length) throw new ValueError("Layer " + n.name + " expects " + n.states_.length + " state(s), but it received " + e.length + " state value(s). Input received: " + e);!0 === t ? n.keptStates.push(n.states_.slice()) : Le(n.states_);for (var i = 0; i < n.states_.length; ++i) {
              var a$$1 = e[i],
                  o = Array.isArray(n.cell.stateSize) ? n.cell.stateSize[i] : n.cell.stateSize,
                  s = [r, o];if (!Z.arraysEqual(a$$1.shape, s)) throw new ValueError("State " + i + " is incompatible with layer " + n.name + ": expected shape=" + s + ", received shape=" + a$$1.shape);n.states_[i] = a$$1;
            }
          }n.states_ = n.states_.map(function (e) {
            return We(e.clone());
          });
        });
      }, t.prototype.apply = function (t, n) {
        var r = null == n ? null : n.initialState,
            i = null == n ? null : n.constants;null == n && (n = {});var a$$1 = standardizeArgs(t, r, i, this.numConstants);t = a$$1.inputs, r = a$$1.initialState, i = a$$1.constants;var o = [],
            s = [];if (null != r) {
          n.initialState = r, o = o.concat(r), this.stateSpec = [];for (var l$$1 = 0, u = r; l$$1 < u.length; l$$1++) {
            var c = u[l$$1];this.stateSpec.push(new InputSpec({ shape: c.shape }));
          }s = s.concat(this.stateSpec);
        }if (null != i && (n.constants = i, o = o.concat(i), this.numConstants = i.length), o[0] instanceof SymbolicTensor) {
          var p = [t].concat(o),
              h = this.inputSpec.concat(s),
              d = this.inputSpec;this.inputSpec = h;var f = e.prototype.apply.call(this, p, n);return this.inputSpec = d, f;
        }return e.prototype.apply.call(this, t, n);
      }, t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          var r = null == t ? null : t.mask,
              i = null == t ? null : t.training,
              a$$1 = null == t ? null : t.initialState;e = getExactlyOneTensor(e), null == a$$1 && (a$$1 = n.stateful ? n.states_ : n.getInitialState(e));var o = Array.isArray(n.cell.stateSize) ? n.cell.stateSize.length : 1;if (a$$1.length !== o) throw new ValueError("RNN Layer has " + o + " state(s) but was passed " + a$$1.length + " initial state(s).");n.unroll && console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");var s = { training: i },
              l$$1 = rnn(function (e, t) {
            var r = n.cell.call([e].concat(t), s);return [r[0], r.slice(1)];
          }, e, a$$1, n.goBackwards, r, null, n.unroll, n.returnSequences),
              u = l$$1[0],
              c = l$$1[1],
              p = l$$1[2];n.stateful && n.resetStates(p, i);var h = n.returnSequences ? c : u;return n.returnState ? [h].concat(p) : h;
        });
      }, t.prototype.getInitialState = function (e) {
        var t = this;return Pe(function () {
          var n = Sn(e.shape);return n = expandDims$1(n = Wu(n, [1, 2])), Array.isArray(t.cell.stateSize) ? t.cell.stateSize.map(function (e) {
            return e > 1 ? tile$1(n, [1, e]) : n;
          }) : t.cell.stateSize > 1 ? [tile$1(n, [1, t.cell.stateSize])] : [n];
        });
      }, Object.defineProperty(t.prototype, "trainableWeights", { get: function () {
          return this.trainable ? this.cell.trainableWeights : [];
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "nonTrainableWeights", { get: function () {
          return this.trainable ? this.cell.nonTrainableWeights : this.cell.weights;
        }, enumerable: !0, configurable: !0 }), t.prototype.setFastWeightInitDuringBuild = function (t) {
        e.prototype.setFastWeightInitDuringBuild.call(this, t), null != this.cell && this.cell.setFastWeightInitDuringBuild(t);
      }, t.prototype.getConfig = function () {
        var t = { returnSequences: this.returnSequences, returnState: this.returnState, goBackwards: this.goBackwards, stateful: this.stateful, unroll: this.unroll };null != this.numConstants && (t.numConstants = this.numConstants);var n = this.cell.getConfig();t.cell = { className: this.cell.getClassName(), config: n };var r = e.prototype.getConfig.call(this);return Object.assign(t, r), t;
      }, t.fromConfig = function (e, t, n) {
        void 0 === n && (n = {});var r = deserialize(t.cell, n);return new e(Object.assign(t, { cell: r }));
      }, t.className = "RNN", t;
    }(Layer);Fh.registerClass(RNN);var RNNCell = function (e) {
      function t() {
        return null !== e && e.apply(this, arguments) || this;
      }return __extends(t, e), t;
    }(Layer),
        SimpleRNNCell = function (e) {
      function t(t) {
        var n = e.call(this, t) || this;return n.DEFAULT_ACTIVATION = "tanh", n.DEFAULT_KERNEL_INITIALIZER = "glorotNormal", n.DEFAULT_RECURRENT_INITIALIZER = "orthogonal", n.DEFAULT_BIAS_INITIALIZER = "zeros", n.units = t.units, assertPositiveInteger(n.units, "units"), n.activation = getActivation(null == t.activation ? n.DEFAULT_ACTIVATION : t.activation), n.useBias = null == t.useBias || t.useBias, n.kernelInitializer = getInitializer(t.kernelInitializer || n.DEFAULT_KERNEL_INITIALIZER), n.recurrentInitializer = getInitializer(t.recurrentInitializer || n.DEFAULT_RECURRENT_INITIALIZER), n.biasInitializer = getInitializer(t.biasInitializer || n.DEFAULT_BIAS_INITIALIZER), n.kernelRegularizer = getRegularizer(t.kernelRegularizer), n.recurrentRegularizer = getRegularizer(t.recurrentRegularizer), n.biasRegularizer = getRegularizer(t.biasRegularizer), n.kernelConstraint = getConstraint(t.kernelConstraint), n.recurrentConstraint = getConstraint(t.recurrentConstraint), n.biasConstraint = getConstraint(t.biasConstraint), n.dropout = min$1([1, max$1([0, null == t.dropout ? 0 : t.dropout])]), n.recurrentDropout = min$1([1, max$1([0, null == t.recurrentDropout ? 0 : t.recurrentDropout])]), n.stateSize = n.units, n.dropoutMask = null, n.recurrentDropoutMask = null, n;
      }return __extends(t, e), t.prototype.build = function (e) {
        e = getExactlyOneShape(e), this.kernel = this.addWeight("kernel", [e[e.length - 1], this.units], null, this.kernelInitializer, this.kernelRegularizer, !0, this.kernelConstraint), this.recurrentKernel = this.addWeight("recurrent_kernel", [this.units, this.units], null, this.recurrentInitializer, this.recurrentRegularizer, !0, this.recurrentConstraint), this.useBias ? this.bias = this.addWeight("bias", [this.units], null, this.biasInitializer, this.biasRegularizer, !0, this.biasConstraint) : this.bias = null, this.built = !0;
      }, t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          if (2 !== (e = e).length) throw new ValueError("SimpleRNNCell expects 2 input Tensors, got " + e.length + ".");var r = e[1];e = e[0];var i,
              a$$1 = null != t.training && t.training;0 < n.dropout && n.dropout < 1 && null == n.dropoutMask && (n.dropoutMask = generateDropoutMask(function () {
            return Tn(e);
          }, n.dropout, a$$1)), 0 < n.recurrentDropout && n.recurrentDropout < 1 && null == n.recurrentDropoutMask && (n.recurrentDropoutMask = generateDropoutMask(function () {
            return Tn(r);
          }, n.recurrentDropout, a$$1));var o = n.dropoutMask,
              s = n.recurrentDropoutMask;i = dot(null != o ? pl(e, o) : e, n.kernel.read()), null != n.bias && (i = biasAdd(i, n.bias.read())), null != s && (r = pl(r, s));var l$$1 = Zu(i, dot(r, n.recurrentKernel.read()));return null != n.activation && (l$$1 = n.activation.apply(l$$1)), [l$$1, l$$1];
        });
      }, t.prototype.getConfig = function () {
        var t = { units: this.units, activation: serializeActivation(this.activation), useBias: this.useBias, kernelInitializer: serializeInitializer(this.kernelInitializer), recurrentInitializer: serializeInitializer(this.recurrentInitializer), biasInitializer: serializeInitializer(this.biasInitializer), kernelRegularizer: serializeRegularizer(this.kernelRegularizer), recurrentRegularizer: serializeRegularizer(this.recurrentRegularizer), biasRegularizer: serializeRegularizer(this.biasRegularizer), activityRegularizer: serializeRegularizer(this.activityRegularizer), kernelConstraint: serializeConstraint(this.kernelConstraint), recurrentConstraint: serializeConstraint(this.recurrentConstraint), biasConstraint: serializeConstraint(this.biasConstraint), dropout: this.dropout, recurrentDropout: this.recurrentDropout },
            n = e.prototype.getConfig.call(this);return Object.assign(t, n), t;
      }, t.className = "SimpleRNNCell", t;
    }(RNNCell);Fh.registerClass(SimpleRNNCell);var SimpleRNN = function (e) {
      function t(t) {
        return t.cell = new SimpleRNNCell(t), e.call(this, t) || this;
      }return __extends(t, e), t.prototype.call = function (t, n) {
        var r = this;return Pe(function () {
          null != r.cell.dropoutMask && (Le(r.cell.dropoutMask), r.cell.dropoutMask = null), null != r.cell.recurrentDropoutMask && (Le(r.cell.recurrentDropoutMask), r.cell.recurrentDropoutMask = null);var i = null == n ? null : n.mask,
              a$$1 = null == n ? null : n.training,
              o = null == n ? null : n.initialState;return e.prototype.call.call(r, t, { mask: i, training: a$$1, initialState: o });
        });
      }, Object.defineProperty(t.prototype, "units", { get: function () {
          return this.cell.units;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "activation", { get: function () {
          return this.cell.activation;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "useBias", { get: function () {
          return this.cell.useBias;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "kernelInitializer", { get: function () {
          return this.cell.kernelInitializer;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "recurrentInitializer", { get: function () {
          return this.cell.recurrentInitializer;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "biasInitializer", { get: function () {
          return this.cell.biasInitializer;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "kernelRegularizer", { get: function () {
          return this.cell.kernelRegularizer;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "recurrentRegularizer", { get: function () {
          return this.cell.recurrentRegularizer;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "biasRegularizer", { get: function () {
          return this.cell.biasRegularizer;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "kernelConstraint", { get: function () {
          return this.cell.kernelConstraint;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "recurrentConstraint", { get: function () {
          return this.cell.recurrentConstraint;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "biasConstraint", { get: function () {
          return this.cell.biasConstraint;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "dropout", { get: function () {
          return this.cell.dropout;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "recurrentDropout", { get: function () {
          return this.cell.recurrentDropout;
        }, enumerable: !0, configurable: !0 }), t.prototype.getConfig = function () {
        var t = { units: this.units, activation: serializeActivation(this.activation), useBias: this.useBias, kernelInitializer: serializeInitializer(this.kernelInitializer), recurrentInitializer: serializeInitializer(this.recurrentInitializer), biasInitializer: serializeInitializer(this.biasInitializer), kernelRegularizer: serializeRegularizer(this.kernelRegularizer), recurrentRegularizer: serializeRegularizer(this.recurrentRegularizer), biasRegularizer: serializeRegularizer(this.biasRegularizer), activityRegularizer: serializeRegularizer(this.activityRegularizer), kernelConstraint: serializeConstraint(this.kernelConstraint), recurrentConstraint: serializeConstraint(this.recurrentConstraint), biasConstraint: serializeConstraint(this.biasConstraint), dropout: this.dropout, recurrentDropout: this.recurrentDropout },
            n = e.prototype.getConfig.call(this);return delete n.cell, Object.assign(t, n), t;
      }, t.fromConfig = function (e, t) {
        return new e(t);
      }, t.className = "SimpleRNN", t;
    }(RNN);Fh.registerClass(SimpleRNN);var GRUCell = function (e) {
      function t(t) {
        var n = e.call(this, t) || this;return n.DEFAULT_ACTIVATION = "tanh", n.DEFAULT_RECURRENT_ACTIVATION = "hardSigmoid", n.DEFAULT_KERNEL_INITIALIZER = "glorotNormal", n.DEFAULT_RECURRENT_INITIALIZER = "orthogonal", n.DEFAULT_BIAS_INITIALIZER = "zeros", n.units = t.units, assertPositiveInteger(n.units, "units"), n.activation = getActivation(void 0 === t.activation ? n.DEFAULT_ACTIVATION : t.activation), n.recurrentActivation = getActivation(void 0 === t.recurrentActivation ? n.DEFAULT_RECURRENT_ACTIVATION : t.recurrentActivation), n.useBias = null == t.useBias || t.useBias, n.kernelInitializer = getInitializer(t.kernelInitializer || n.DEFAULT_KERNEL_INITIALIZER), n.recurrentInitializer = getInitializer(t.recurrentInitializer || n.DEFAULT_RECURRENT_INITIALIZER), n.biasInitializer = getInitializer(t.biasInitializer || n.DEFAULT_BIAS_INITIALIZER), n.kernelRegularizer = getRegularizer(t.kernelRegularizer), n.recurrentRegularizer = getRegularizer(t.recurrentRegularizer), n.biasRegularizer = getRegularizer(t.biasRegularizer), n.kernelConstraint = getConstraint(t.kernelConstraint), n.recurrentConstraint = getConstraint(t.recurrentConstraint), n.biasConstraint = getConstraint(t.biasConstraint), n.dropout = min$1([1, max$1([0, null == t.dropout ? 0 : t.dropout])]), n.recurrentDropout = min$1([1, max$1([0, null == t.recurrentDropout ? 0 : t.recurrentDropout])]), n.implementation = t.implementation, n.stateSize = n.units, n.dropoutMask = null, n.recurrentDropoutMask = null, n;
      }return __extends(t, e), t.prototype.build = function (e) {
        var t = (e = getExactlyOneShape(e))[e.length - 1];this.kernel = this.addWeight("kernel", [t, 3 * this.units], null, this.kernelInitializer, this.kernelRegularizer, !0, this.kernelConstraint), this.recurrentKernel = this.addWeight("recurrent_kernel", [this.units, 3 * this.units], null, this.recurrentInitializer, this.recurrentRegularizer, !0, this.recurrentConstraint), this.useBias ? this.bias = this.addWeight("bias", [3 * this.units], null, this.biasInitializer, this.biasRegularizer, !0, this.biasConstraint) : this.bias = null, this.built = !0;
      }, t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          if (2 !== (e = e).length) throw new ValueError("GRUCell expects 2 input Tensors (inputs, h, c), got " + e.length + ".");var r = null != t.training && t.training,
              i = e[1];e = e[0], 0 < n.dropout && n.dropout < 1 && null == n.dropoutMask && (n.dropoutMask = generateDropoutMask(function () {
            return Tn(e);
          }, n.dropout, r, 3)), 0 < n.recurrentDropout && n.recurrentDropout < 1 && null == n.recurrentDropoutMask && (n.recurrentDropoutMask = generateDropoutMask(function () {
            return Tn(i);
          }, n.recurrentDropout, r, 3));var a$$1,
              o,
              s,
              l$$1 = n.dropoutMask,
              u = n.recurrentDropoutMask;0 < n.dropout && n.dropout < 1 && (e = pl(e, l$$1[0]));var c = dot(e, n.kernel.read());n.useBias && (c = biasAdd(c, n.bias.read())), 0 < n.recurrentDropout && n.recurrentDropout < 1 && (i = pl(i, u[0]));var p = n.recurrentKernel.read(),
              h = Pn(p, [2 * n.units, n.units], p.rank - 1),
              d = h[0],
              f = h[1],
              g = dot(i, d),
              m = Pn(c, 3, c.rank - 1),
              y = m[0],
              v = m[1],
              b = m[2],
              w = Pn(g, 2, g.rank - 1),
              z = w[0],
              S = w[1];a$$1 = n.recurrentActivation.apply(Zu(y, z)), o = n.recurrentActivation.apply(Zu(v, S));var A = dot(pl(o, i), f);s = n.activation.apply(Zu(b, A));var _ = Zu(pl(a$$1, i), pl(Zu(1, Rs(a$$1)), s));return [_, _];
        });
      }, t.prototype.getConfig = function () {
        var t = { units: this.units, activation: serializeActivation(this.activation), recurrentActivation: serializeActivation(this.recurrentActivation), useBias: this.useBias, kernelInitializer: serializeInitializer(this.kernelInitializer), recurrentInitializer: serializeInitializer(this.recurrentInitializer), biasInitializer: serializeInitializer(this.biasInitializer), kernelRegularizer: serializeRegularizer(this.kernelRegularizer), recurrentRegularizer: serializeRegularizer(this.recurrentRegularizer), biasRegularizer: serializeRegularizer(this.biasRegularizer), activityRegularizer: serializeRegularizer(this.activityRegularizer), kernelConstraint: serializeConstraint(this.kernelConstraint), recurrentConstraint: serializeConstraint(this.recurrentConstraint), biasConstraint: serializeConstraint(this.biasConstraint), dropout: this.dropout, recurrentDropout: this.recurrentDropout, implementation: this.implementation },
            n = e.prototype.getConfig.call(this);return Object.assign(t, n), t;
      }, t.className = "GRUCell", t;
    }(RNNCell);Fh.registerClass(GRUCell);var GRU = function (e) {
      function t(t) {
        return 0 === t.implementation && console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."), t.cell = new GRUCell(t), e.call(this, t) || this;
      }return __extends(t, e), t.prototype.call = function (t, n) {
        var r = this;return Pe(function () {
          null != r.cell.dropoutMask && (Le(r.cell.dropoutMask), r.cell.dropoutMask = null), null != r.cell.recurrentDropoutMask && (Le(r.cell.recurrentDropoutMask), r.cell.recurrentDropoutMask = null);var i = null == n ? null : n.mask,
              a$$1 = null == n ? null : n.training,
              o = null == n ? null : n.initialState;return e.prototype.call.call(r, t, { mask: i, training: a$$1, initialState: o });
        });
      }, Object.defineProperty(t.prototype, "units", { get: function () {
          return this.cell.units;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "activation", { get: function () {
          return this.cell.activation;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "recurrentActivation", { get: function () {
          return this.cell.recurrentActivation;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "useBias", { get: function () {
          return this.cell.useBias;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "kernelInitializer", { get: function () {
          return this.cell.kernelInitializer;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "recurrentInitializer", { get: function () {
          return this.cell.recurrentInitializer;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "biasInitializer", { get: function () {
          return this.cell.biasInitializer;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "kernelRegularizer", { get: function () {
          return this.cell.kernelRegularizer;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "recurrentRegularizer", { get: function () {
          return this.cell.recurrentRegularizer;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "biasRegularizer", { get: function () {
          return this.cell.biasRegularizer;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "kernelConstraint", { get: function () {
          return this.cell.kernelConstraint;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "recurrentConstraint", { get: function () {
          return this.cell.recurrentConstraint;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "biasConstraint", { get: function () {
          return this.cell.biasConstraint;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "dropout", { get: function () {
          return this.cell.dropout;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "recurrentDropout", { get: function () {
          return this.cell.recurrentDropout;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "implementation", { get: function () {
          return this.cell.implementation;
        }, enumerable: !0, configurable: !0 }), t.prototype.getConfig = function () {
        var t = { units: this.units, activation: serializeActivation(this.activation), recurrentActivation: serializeActivation(this.recurrentActivation), useBias: this.useBias, kernelInitializer: serializeInitializer(this.kernelInitializer), recurrentInitializer: serializeInitializer(this.recurrentInitializer), biasInitializer: serializeInitializer(this.biasInitializer), kernelRegularizer: serializeRegularizer(this.kernelRegularizer), recurrentRegularizer: serializeRegularizer(this.recurrentRegularizer), biasRegularizer: serializeRegularizer(this.biasRegularizer), activityRegularizer: serializeRegularizer(this.activityRegularizer), kernelConstraint: serializeConstraint(this.kernelConstraint), recurrentConstraint: serializeConstraint(this.recurrentConstraint), biasConstraint: serializeConstraint(this.biasConstraint), dropout: this.dropout, recurrentDropout: this.recurrentDropout, implementation: this.implementation },
            n = e.prototype.getConfig.call(this);return delete n.cell, Object.assign(t, n), t;
      }, t.fromConfig = function (e, t) {
        return 0 === t.implmentation && (t.implementation = 1), new e(t);
      }, t.className = "GRU", t;
    }(RNN);Fh.registerClass(GRU);var LSTMCell = function (e) {
      function t(t) {
        var n = e.call(this, t) || this;return n.DEFAULT_ACTIVATION = "tanh", n.DEFAULT_RECURRENT_ACTIVATION = "hardSigmoid", n.DEFAULT_KERNEL_INITIALIZER = "glorotNormal", n.DEFAULT_RECURRENT_INITIALIZER = "orthogonal", n.DEFAULT_BIAS_INITIALIZER = "zeros", n.units = t.units, assertPositiveInteger(n.units, "units"), n.activation = getActivation(void 0 === t.activation ? n.DEFAULT_ACTIVATION : t.activation), n.recurrentActivation = getActivation(void 0 === t.recurrentActivation ? n.DEFAULT_RECURRENT_ACTIVATION : t.recurrentActivation), n.useBias = null == t.useBias || t.useBias, n.kernelInitializer = getInitializer(t.kernelInitializer || n.DEFAULT_KERNEL_INITIALIZER), n.recurrentInitializer = getInitializer(t.recurrentInitializer || n.DEFAULT_RECURRENT_INITIALIZER), n.biasInitializer = getInitializer(t.biasInitializer || n.DEFAULT_BIAS_INITIALIZER), n.unitForgetBias = t.unitForgetBias, n.kernelRegularizer = getRegularizer(t.kernelRegularizer), n.recurrentRegularizer = getRegularizer(t.recurrentRegularizer), n.biasRegularizer = getRegularizer(t.biasRegularizer), n.kernelConstraint = getConstraint(t.kernelConstraint), n.recurrentConstraint = getConstraint(t.recurrentConstraint), n.biasConstraint = getConstraint(t.biasConstraint), n.dropout = min$1([1, max$1([0, null == t.dropout ? 0 : t.dropout])]), n.recurrentDropout = min$1([1, max$1([0, null == t.recurrentDropout ? 0 : t.recurrentDropout])]), n.implementation = t.implementation, n.stateSize = [n.units, n.units], n.dropoutMask = null, n.recurrentDropoutMask = null, n;
      }return __extends(t, e), t.prototype.build = function (e) {
        var t,
            n,
            r = (e = getExactlyOneShape(e))[e.length - 1];if (this.kernel = this.addWeight("kernel", [r, 4 * this.units], null, this.kernelInitializer, this.kernelRegularizer, !0, this.kernelConstraint), this.recurrentKernel = this.addWeight("recurrent_kernel", [this.units, 4 * this.units], null, this.recurrentInitializer, this.recurrentRegularizer, !0, this.recurrentConstraint), this.useBias) {
          if (this.unitForgetBias) {
            var i = this.biasInitializer,
                a$$1 = this.units;n = new ((t = function (e) {
              function t() {
                return null !== e && e.apply(this, arguments) || this;
              }return __extends(t, e), t.prototype.apply = function (e, t) {
                var n = i.apply([a$$1]),
                    r = new Ones().apply([a$$1]),
                    o = i.apply([2 * a$$1]);return concatAlongFirstAxis(concatAlongFirstAxis(n, r), o);
              }, t;
            }(Initializer)).className = "CustomInit", t)();
          } else n = this.biasInitializer;this.bias = this.addWeight("bias", [4 * this.units], null, n, this.biasRegularizer, !0, this.biasConstraint);
        } else this.bias = null;this.built = !0;
      }, t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          var r = null != t.training && t.training;if (3 !== (e = e).length) throw new ValueError("LSTMCell expects 3 input Tensors (inputs, h, c), got " + e.length + ".");var i = e[1],
              a$$1 = e[2];e = e[0], 0 < n.dropout && n.dropout < 1 && null == n.dropoutMask && (n.dropoutMask = generateDropoutMask(function () {
            return Tn(e);
          }, n.dropout, r, 4)), 0 < n.recurrentDropout && n.recurrentDropout < 1 && null == n.recurrentDropoutMask && (n.recurrentDropoutMask = generateDropoutMask(function () {
            return Tn(i);
          }, n.recurrentDropout, r, 4));var o,
              s,
              l$$1,
              u,
              c = n.dropoutMask,
              p = n.recurrentDropoutMask;0 < n.dropout && n.dropout < 1 && (e = pl(e, c[0]));var h = dot(e, n.kernel.read());0 < n.recurrentDropout && n.recurrentDropout < 1 && (i = pl(i, p[0])), h = Zu(h, dot(i, n.recurrentKernel.read())), n.useBias && (h = biasAdd(h, n.bias.read()));var d = Pn(h, 4, h.rank - 1),
              f = d[0],
              g = d[1],
              m = d[2],
              y = d[3];o = n.recurrentActivation.apply(f), s = n.recurrentActivation.apply(g), l$$1 = Zu(pl(s, a$$1), pl(o, n.activation.apply(m))), u = n.recurrentActivation.apply(y);var v = pl(u, n.activation.apply(l$$1));return [v, v, l$$1];
        });
      }, t.prototype.getConfig = function () {
        var t = { units: this.units, activation: serializeActivation(this.activation), recurrentActivation: serializeActivation(this.recurrentActivation), useBias: this.useBias, kernelInitializer: serializeInitializer(this.kernelInitializer), recurrentInitializer: serializeInitializer(this.recurrentInitializer), biasInitializer: serializeInitializer(this.biasInitializer), unitForgetBias: this.unitForgetBias, kernelRegularizer: serializeRegularizer(this.kernelRegularizer), recurrentRegularizer: serializeRegularizer(this.recurrentRegularizer), biasRegularizer: serializeRegularizer(this.biasRegularizer), activityRegularizer: serializeRegularizer(this.activityRegularizer), kernelConstraint: serializeConstraint(this.kernelConstraint), recurrentConstraint: serializeConstraint(this.recurrentConstraint), biasConstraint: serializeConstraint(this.biasConstraint), dropout: this.dropout, recurrentDropout: this.recurrentDropout, implementation: this.implementation },
            n = e.prototype.getConfig.call(this);return Object.assign(t, n), t;
      }, t.className = "LSTMCell", t;
    }(RNNCell);Fh.registerClass(LSTMCell);var LSTM = function (e) {
      function t(t) {
        return 0 === t.implementation && console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."), t.cell = new LSTMCell(t), e.call(this, t) || this;
      }return __extends(t, e), t.prototype.call = function (t, n) {
        var r = this;return Pe(function () {
          null != r.cell.dropoutMask && (Le(r.cell.dropoutMask), r.cell.dropoutMask = null), null != r.cell.recurrentDropoutMask && (Le(r.cell.recurrentDropoutMask), r.cell.recurrentDropoutMask = null);var i = null == n ? null : n.mask,
              a$$1 = null == n ? null : n.training,
              o = null == n ? null : n.initialState;return e.prototype.call.call(r, t, { mask: i, training: a$$1, initialState: o });
        });
      }, Object.defineProperty(t.prototype, "units", { get: function () {
          return this.cell.units;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "activation", { get: function () {
          return this.cell.activation;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "recurrentActivation", { get: function () {
          return this.cell.recurrentActivation;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "useBias", { get: function () {
          return this.cell.useBias;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "kernelInitializer", { get: function () {
          return this.cell.kernelInitializer;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "recurrentInitializer", { get: function () {
          return this.cell.recurrentInitializer;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "biasInitializer", { get: function () {
          return this.cell.biasInitializer;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "unitForgetBias", { get: function () {
          return this.cell.unitForgetBias;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "kernelRegularizer", { get: function () {
          return this.cell.kernelRegularizer;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "recurrentRegularizer", { get: function () {
          return this.cell.recurrentRegularizer;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "biasRegularizer", { get: function () {
          return this.cell.biasRegularizer;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "kernelConstraint", { get: function () {
          return this.cell.kernelConstraint;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "recurrentConstraint", { get: function () {
          return this.cell.recurrentConstraint;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "biasConstraint", { get: function () {
          return this.cell.biasConstraint;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "dropout", { get: function () {
          return this.cell.dropout;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "recurrentDropout", { get: function () {
          return this.cell.recurrentDropout;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "implementation", { get: function () {
          return this.cell.implementation;
        }, enumerable: !0, configurable: !0 }), t.prototype.getConfig = function () {
        var t = { units: this.units, activation: serializeActivation(this.activation), recurrentActivation: serializeActivation(this.recurrentActivation), useBias: this.useBias, kernelInitializer: serializeInitializer(this.kernelInitializer), recurrentInitializer: serializeInitializer(this.recurrentInitializer), biasInitializer: serializeInitializer(this.biasInitializer), unitForgetBias: this.unitForgetBias, kernelRegularizer: serializeRegularizer(this.kernelRegularizer), recurrentRegularizer: serializeRegularizer(this.recurrentRegularizer), biasRegularizer: serializeRegularizer(this.biasRegularizer), activityRegularizer: serializeRegularizer(this.activityRegularizer), kernelConstraint: serializeConstraint(this.kernelConstraint), recurrentConstraint: serializeConstraint(this.recurrentConstraint), biasConstraint: serializeConstraint(this.biasConstraint), dropout: this.dropout, recurrentDropout: this.recurrentDropout, implementation: this.implementation },
            n = e.prototype.getConfig.call(this);return delete n.cell, Object.assign(t, n), t;
      }, t.fromConfig = function (e, t) {
        return 0 === t.implmentation && (t.implementation = 1), new e(t);
      }, t.className = "LSTM", t;
    }(RNN);Fh.registerClass(LSTM);var StackedRNNCells = function (e) {
      function t(t) {
        var n = e.call(this, t) || this;return n.cells = t.cells, n;
      }return __extends(t, e), Object.defineProperty(t.prototype, "stateSize", { get: function () {
          for (var e = [], t = 0, n = this.cells.slice().reverse(); t < n.length; t++) {
            var r = n[t];Array.isArray(r.stateSize) ? e.push.apply(e, r.stateSize) : e.push(r.stateSize);
          }return e;
        }, enumerable: !0, configurable: !0 }), t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          for (var r = (e = e).slice(1), i = [], a$$1 = 0, o = n.cells.slice().reverse(); a$$1 < o.length; a$$1++) {
            var s = o[a$$1];Array.isArray(s.stateSize) ? i.push(r.splice(0, s.stateSize.length)) : i.push(r.splice(0, 1));
          }i.reverse();for (var l$$1, u = [], c = 0; c < n.cells.length; ++c) {
            s = n.cells[c];r = i[c], l$$1 = 0 === c ? [e[0]].concat(r) : [l$$1[0]].concat(r), l$$1 = s.call(l$$1, t), u.push(l$$1.slice(1));
          }r = [];for (var p = 0, h = u.slice().reverse(); p < h.length; p++) {
            var d = h[p];r.push.apply(r, d);
          }return [l$$1[0]].concat(r);
        });
      }, t.prototype.build = function (e) {
        var t;isArrayOfShapes(e) && (e = e[0]), e = e;for (var n = 0, r = this.cells; n < r.length; n++) {
          var i = r[n];i.build(e), t = Array.isArray(i.stateSize) ? i.stateSize[0] : i.stateSize, e = [e[0], t];
        }this.built = !0;
      }, t.prototype.getConfig = function () {
        for (var t = [], n = 0, r = this.cells; n < r.length; n++) {
          var i = r[n];t.push({ className: i.getClassName(), config: i.getConfig() });
        }var a$$1 = { cells: t },
            o = e.prototype.getConfig.call(this);return Object.assign(a$$1, o), a$$1;
      }, t.fromConfig = function (e, t, n) {
        void 0 === n && (n = {});for (var r = [], i = 0, a$$1 = t.cells; i < a$$1.length; i++) {
          var o = a$$1[i];r.push(deserialize(o, n));
        }return new e({ cells: r });
      }, Object.defineProperty(t.prototype, "trainableWeights", { get: function () {
          if (!this.trainable) return [];for (var e = [], t = 0, n = this.cells; t < n.length; t++) {
            var r = n[t];e.push.apply(e, r.trainableWeights);
          }return e;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "nonTrainableWeights", { get: function () {
          for (var e = [], t = 0, n = this.cells; t < n.length; t++) {
            var r = n[t];e.push.apply(e, r.nonTrainableWeights);
          }if (!this.trainable) {
            for (var i = [], a$$1 = 0, o = this.cells; a$$1 < o.length; a$$1++) {
              r = o[a$$1];i.push.apply(i, r.trainableWeights);
            }return i.concat(e);
          }return e;
        }, enumerable: !0, configurable: !0 }), t.prototype.getWeights = function () {
        for (var e = [], t = 0, n = this.cells; t < n.length; t++) {
          var r = n[t];e.push.apply(e, r.weights);
        }return batchGetValue(e);
      }, t.prototype.setWeights = function (e) {
        for (var t = [], n = 0, r = this.cells; n < r.length; n++) for (var i = r[n], a$$1 = i.weights.length, o = e.splice(a$$1), s = 0; s < i.weights.length; ++s) t.push([i.weights[s], o[s]]);batchSetValue(t);
      }, t.className = "StackedRNNCells", t;
    }(RNNCell);function generateDropoutMask(e, t, n, r) {
      function i() {
        return dropout$1(e(), t);
      }if (void 0 === n && (n = null), void 0 === r && (r = 1), r > 1) {
        for (var a$$1 = [], o = 0; o < r; o++) a$$1.push(inTrainPhase(i, e, n));return a$$1.map(function (e) {
          return We(e.clone());
        });
      }return We(inTrainPhase(i, e, n).clone());
    }Fh.registerClass(StackedRNNCells);var Wrapper = function (e) {
      function t(t) {
        var n = e.call(this, t) || this;return n.layer = t.layer, n;
      }return __extends(t, e), t.prototype.build = function (e) {
        this.built = !0;
      }, Object.defineProperty(t.prototype, "trainable", { get: function () {
          return null != this.layer && this.layer.trainable;
        }, set: function (e) {
          null != this.layer && (this.layer.trainable = e);
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "trainableWeights", { get: function () {
          return this.layer.trainableWeights;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "nonTrainableWeights", { get: function () {
          return this.layer.nonTrainableWeights;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "updates", { get: function () {
          return this.layer._updates;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "losses", { get: function () {
          return this.layer.losses;
        }, enumerable: !0, configurable: !0 }), t.prototype.getWeights = function () {
        return this.layer.getWeights();
      }, t.prototype.setWeights = function (e) {
        this.layer.setWeights(e);
      }, t.prototype.getConfig = function () {
        var t = { layer: { className: this.layer.getClassName(), config: this.layer.getConfig() } },
            n = e.prototype.getConfig.call(this);return Object.assign(t, n), t;
      }, t.prototype.setFastWeightInitDuringBuild = function (t) {
        e.prototype.setFastWeightInitDuringBuild.call(this, t), null != this.layer && this.layer.setFastWeightInitDuringBuild(t);
      }, t.fromConfig = function (e, t, n) {
        void 0 === n && (n = {});var r = deserialize(t.layer, n);delete t.layer;var i = { layer: r };return Object.assign(i, t), new e(i);
      }, t;
    }(Layer),
        TimeDistributed = function (e) {
      function t(t) {
        var n = e.call(this, t) || this;return n.supportsMasking = !0, n;
      }return __extends(t, e), t.prototype.build = function (t) {
        if ((t = getExactlyOneShape(t)).length < 3) throw new ValueError("TimeDistributed layer expects an input shape >= 3D, but received input shape " + JSON.stringify(t));this.inputSpec = [{ shape: t }];var n = [t[0]].concat(t.slice(2));this.layer.built || (this.layer.build(n), this.layer.built = !0), e.prototype.build.call(this, t);
      }, t.prototype.computeOutputShape = function (e) {
        var t = [(e = getExactlyOneShape(e))[0]].concat(e.slice(2)),
            n = this.layer.computeOutputShape(t),
            r = e[1];return [n[0], r].concat(n.slice(1));
      }, t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          return rnn(function (e, r) {
            return [getExactlyOneTensor(n.layer.call(e, t)), []];
          }, e = getExactlyOneTensor(e), [], !1, null, null, !1, !0)[1];
        });
      }, t.className = "TimeDistributed", t;
    }(Wrapper);function checkBidirectionalMergeMode(e) {
      checkStringTypeUnionValue(VALID_BIDIRECTIONAL_MERGE_MODES, "BidirectionalMergeMode", e);
    }Fh.registerClass(TimeDistributed);var DEFAULT_BIDIRECTIONAL_MERGE_MODE = "concat",
        Bidirectional = function (e) {
      function t(t) {
        var n = e.call(this, t) || this,
            r = t.layer.getConfig(),
            i = {};i.className = t.layer.getClassName(), i.config = r, n.forwardLayer = deserialize(i), r.goBackwards = !0 !== r.goBackwards;var a$$1 = {};if (a$$1.className = t.layer.getClassName(), a$$1.config = r, n.backwardLayer = deserialize(a$$1), n.forwardLayer.name = "forward_" + n.forwardLayer.name, n.backwardLayer.name = "backward_" + n.backwardLayer.name, n.mergeMode = void 0 === t.mergeMode ? DEFAULT_BIDIRECTIONAL_MERGE_MODE : t.mergeMode, checkBidirectionalMergeMode(n.mergeMode), t.weights) throw new NotImplementedError("weights support is not implemented for Bidirectional layer yet.");return n._stateful = t.layer.stateful, n.returnSequences = t.layer.returnSequences, n.returnState = t.layer.returnState, n.supportsMasking = !0, n._trainable = !0, n.inputSpec = t.layer.inputSpec, n.numConstants = null, n;
      }return __extends(t, e), Object.defineProperty(t.prototype, "trainable", { get: function () {
          return this._trainable;
        }, set: function (e) {
          this._trainable = e, null != this.forwardLayer && (this.forwardLayer.trainable = e), null != this.backwardLayer && (this.backwardLayer.trainable = e);
        }, enumerable: !0, configurable: !0 }), t.prototype.getWeights = function () {
        return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights());
      }, t.prototype.setWeights = function (e) {
        var t = e.length,
            n = Math.floor(t / 2);this.forwardLayer.setWeights(e.slice(0, n)), this.backwardLayer.setWeights(e.slice(n));
      }, t.prototype.computeOutputShape = function (e) {
        var t,
            n,
            r,
            i = this.forwardLayer.computeOutputShape(e);return Array.isArray(i) && Array.isArray(i[0]) || (i = [i]), i = i, this.returnState ? (r = i.slice(1), t = i[0]) : t = i[0], t = t, "concat" === this.mergeMode ? (t[t.length - 1] *= 2, n = [t]) : n = null == this.mergeMode ? [t, t.slice()] : [t], this.returnState ? null == this.mergeMode ? n.concat(r).concat(r.slice()) : [t].concat(r).concat(r.slice()) : singletonOrArray(n);
      }, t.prototype.apply = function (t, n) {
        var r = null == n ? null : n.initialState,
            i = null == n ? null : n.constants;null == n && (n = {});var a$$1 = standardizeArgs(t, r, i, this.numConstants);if (t = a$$1.inputs, r = a$$1.initialState, i = a$$1.constants, Array.isArray(t) && (r = t.slice(1), t = t[0]), (null == r || 0 === r.length) && null == i) return e.prototype.apply.call(this, t, n);var o = [],
            s = [];if (null != r) {
          var l$$1 = r.length;if (l$$1 % 2 > 0) throw new ValueError("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");n.initialState = r, o.push.apply(o, r);var u = r.map(function (e) {
            return new InputSpec({ shape: e.shape });
          });this.forwardLayer.stateSpec = u.slice(0, l$$1 / 2), this.backwardLayer.stateSpec = u.slice(l$$1 / 2), s.push.apply(s, u);
        }if (null != i) throw new NotImplementedError("Support for constants in Bidirectional layers is not implemented yet.");for (var c = o[0] instanceof SymbolicTensor, p = 0, h = o; p < h.length; p++) {
          if (h[p] instanceof SymbolicTensor !== c) throw new ValueError("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");
        }if (c) {
          var d = [t].concat(o),
              f = this.inputSpec.concat(s),
              g = this.inputSpec;this.inputSpec = f;var m = e.prototype.apply.call(this, d, n);return this.inputSpec = g, m;
        }return e.prototype.apply.call(this, t, n);
      }, t.prototype.call = function (e, t) {
        var n = this;return Pe(function () {
          if (null != t.mask) throw new NotImplementedError("The support for masking is not implemented for Bidirectional layers yet.");var r,
              i,
              a$$1,
              o,
              s = t.initialState;if (null == s) r = n.forwardLayer.call(e, t), i = n.backwardLayer.call(e, t);else {
            var l$$1 = s.slice(0, s.length / 2),
                u = s.slice(s.length / 2);r = n.forwardLayer.call(e, Object.assign(t, { initialState: l$$1 })), i = n.backwardLayer.call(e, Object.assign(t, { initialState: u }));
          }return n.returnState && (Array.isArray(r) && (a$$1 = r.slice(1).concat(i.slice(1))), r = r[0], i = i[0]), n.returnSequences && (i = du(i, 1)), "concat" === n.mergeMode ? o = concatenate([r, i]) : "sum" === n.mergeMode ? o = Zu(r, i) : "ave" === n.mergeMode ? o = pl(.5, Zu(r, i)) : "mul" === n.mergeMode ? o = pl(r, i) : null == n.mergeMode && (o = [r, i]), n.returnState ? null == n.mergeMode ? o.concat(a$$1) : [o].concat(a$$1) : o;
        });
      }, t.prototype.resetStates = function (e) {
        this.forwardLayer.resetStates(), this.backwardLayer.resetStates();
      }, t.prototype.build = function (e) {
        var t = this;nameScope(this.forwardLayer.name, function () {
          t.forwardLayer.build(e);
        }), nameScope(this.backwardLayer.name, function () {
          t.backwardLayer.build(e);
        }), this.built = !0;
      }, Object.defineProperty(t.prototype, "trainableWeights", { get: function () {
          return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights);
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(t.prototype, "nonTrainableWeights", { get: function () {
          return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights);
        }, enumerable: !0, configurable: !0 }), t.prototype.setFastWeightInitDuringBuild = function (t) {
        e.prototype.setFastWeightInitDuringBuild.call(this, t), null != this.forwardLayer && this.forwardLayer.setFastWeightInitDuringBuild(t), null != this.backwardLayer && this.backwardLayer.setFastWeightInitDuringBuild(t);
      }, t.prototype.getConfig = function () {
        var t = { mergeMode: this.mergeMode },
            n = e.prototype.getConfig.call(this);return Object.assign(t, n), t;
      }, t.fromConfig = function (e, t) {
        var n = deserialize(t.layer);if (delete t.layer, null != t.numConstants) throw new NotImplementedError("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");var r = t;return r.layer = n, new e(r);
      }, t.className = "Bidirectional", t;
    }(Wrapper);function inputLayer(e) {
      return new InputLayer(e);
    }function elu$2(e) {
      return new ELU(e);
    }function reLU(e) {
      return new ReLU(e);
    }function leakyReLU(e) {
      return new LeakyReLU(e);
    }function prelu$1(e) {
      return new PReLU(e);
    }function softmax$1(e) {
      return new Softmax$1(e);
    }function thresholdedReLU(e) {
      return new ThresholdedReLU(e);
    }function conv1d$2(e) {
      return new Conv1D(e);
    }function conv2d$2(e) {
      return new Conv2D(e);
    }function conv2dTranspose$1(e) {
      return new Conv2DTranspose(e);
    }function conv3d$2(e) {
      return new Conv3D(e);
    }function separableConv2d$1(e) {
      return new SeparableConv2D(e);
    }function cropping2D(e) {
      return new Cropping2D(e);
    }function upSampling2d(e) {
      return new UpSampling2D(e);
    }function depthwiseConv2d$2(e) {
      return new DepthwiseConv2D(e);
    }function activation(e) {
      return new Activation$1(e);
    }function dense(e) {
      return new Dense(e);
    }function dropout$2(e) {
      return new Dropout(e);
    }function flatten$1(e) {
      return new Flatten(e);
    }function repeatVector(e) {
      return new RepeatVector(e);
    }function reshape(e) {
      return new Reshape(e);
    }function permute(e) {
      return new Permute(e);
    }function embedding(e) {
      return new Embedding(e);
    }function add$2(e) {
      return new Add(e);
    }function average$1(e) {
      return new Average(e);
    }function concatenate$2(e) {
      return new Concatenate(e);
    }function maximum$2(e) {
      return new Maximum(e);
    }function minimum$2(e) {
      return new Minimum(e);
    }function multiply$1(e) {
      return new Multiply(e);
    }function dot$1(e) {
      return new Dot(e);
    }function batchNormalization$1(e) {
      return new BatchNormalization(e);
    }function zeroPadding2d(e) {
      return new ZeroPadding2D(e);
    }function averagePooling1d(e) {
      return new AveragePooling1D(e);
    }function avgPool1d(e) {
      return averagePooling1d(e);
    }function avgPooling1d(e) {
      return averagePooling1d(e);
    }function averagePooling2d(e) {
      return new AveragePooling2D(e);
    }function avgPool2d(e) {
      return averagePooling2d(e);
    }function avgPooling2d(e) {
      return averagePooling2d(e);
    }function globalAveragePooling1d(e) {
      return new GlobalAveragePooling1D(e);
    }function globalAveragePooling2d(e) {
      return new GlobalAveragePooling2D(e);
    }function globalMaxPooling1d(e) {
      return new GlobalMaxPooling1D(e);
    }function globalMaxPooling2d(e) {
      return new GlobalMaxPooling2D(e);
    }function maxPooling1d(e) {
      return new MaxPooling1D(e);
    }function maxPooling2d(e) {
      return new MaxPooling2D(e);
    }function gru(e) {
      return new GRU(e);
    }function gruCell(e) {
      return new GRUCell(e);
    }function lstm(e) {
      return new LSTM(e);
    }function lstmCell(e) {
      return new LSTMCell(e);
    }function simpleRNN(e) {
      return new SimpleRNN(e);
    }function simpleRNNCell(e) {
      return new SimpleRNNCell(e);
    }function rnn$1(e) {
      return new RNN(e);
    }function stackedRNNCells(e) {
      return new StackedRNNCells(e);
    }function bidirectional(e) {
      return new Bidirectional(e);
    }function timeDistributed(e) {
      return new TimeDistributed(e);
    }Fh.registerClass(Bidirectional);var globalMaxPool1d = globalMaxPooling1d,
        globalMaxPool2d = globalMaxPooling2d,
        maxPool1d = maxPooling1d,
        maxPool2d = maxPooling2d;function gaussianNoise(e) {
      return new GaussianNoise(e);
    }function gaussianDropout(e) {
      return new GaussianDropout(e);
    }function alphaDropout(e) {
      return new AlphaDropout(e);
    }function masking(e) {
      return new Masking(e);
    }var exports_layers = Object.freeze({ inputLayer: inputLayer, elu: elu$2, reLU: reLU, leakyReLU: leakyReLU, prelu: prelu$1, softmax: softmax$1, thresholdedReLU: thresholdedReLU, conv1d: conv1d$2, conv2d: conv2d$2, conv2dTranspose: conv2dTranspose$1, conv3d: conv3d$2, separableConv2d: separableConv2d$1, cropping2D: cropping2D, upSampling2d: upSampling2d, depthwiseConv2d: depthwiseConv2d$2, activation: activation, dense: dense, dropout: dropout$2, flatten: flatten$1, repeatVector: repeatVector, reshape: reshape, permute: permute, embedding: embedding, add: add$2, average: average$1, concatenate: concatenate$2, maximum: maximum$2, minimum: minimum$2, multiply: multiply$1, dot: dot$1, batchNormalization: batchNormalization$1, zeroPadding2d: zeroPadding2d, averagePooling1d: averagePooling1d, avgPool1d: avgPool1d, avgPooling1d: avgPooling1d, averagePooling2d: averagePooling2d, avgPool2d: avgPool2d, avgPooling2d: avgPooling2d, globalAveragePooling1d: globalAveragePooling1d, globalAveragePooling2d: globalAveragePooling2d, globalMaxPooling1d: globalMaxPooling1d, globalMaxPooling2d: globalMaxPooling2d, maxPooling1d: maxPooling1d, maxPooling2d: maxPooling2d, gru: gru, gruCell: gruCell, lstm: lstm, lstmCell: lstmCell, simpleRNN: simpleRNN, simpleRNNCell: simpleRNNCell, rnn: rnn$1, stackedRNNCells: stackedRNNCells, bidirectional: bidirectional, timeDistributed: timeDistributed, globalMaxPool1d: globalMaxPool1d, globalMaxPool2d: globalMaxPool2d, maxPool1d: maxPool1d, maxPool2d: maxPool2d, Layer: Layer, RNN: RNN, RNNCell: RNNCell, input: input, gaussianNoise: gaussianNoise, gaussianDropout: gaussianDropout, alphaDropout: alphaDropout, masking: masking });function binaryAccuracy$1(e, t) {
      return binaryAccuracy(e, t);
    }function binaryCrossentropy$2(e, t) {
      return binaryCrossentropy$1(e, t);
    }function sparseCategoricalAccuracy$1(e, t) {
      return sparseCategoricalAccuracy(e, t);
    }function categoricalAccuracy$1(e, t) {
      return categoricalAccuracy(e, t);
    }function categoricalCrossentropy$2(e, t) {
      return categoricalCrossentropy$1(e, t);
    }function precision$1(e, t) {
      return precision(e, t);
    }function recall$1(e, t) {
      return recall(e, t);
    }function cosineProximity$1(e, t) {
      return cosineProximity(e, t);
    }function meanAbsoluteError$1(e, t) {
      return meanAbsoluteError(e, t);
    }function meanAbsolutePercentageError$1(e, t) {
      return meanAbsolutePercentageError(e, t);
    }function MAPE$2(e, t) {
      return meanAbsolutePercentageError(e, t);
    }function mape$2(e, t) {
      return meanAbsolutePercentageError(e, t);
    }function meanSquaredError$1(e, t) {
      return meanSquaredError(e, t);
    }function MSE$2(e, t) {
      return meanSquaredError(e, t);
    }function mse$2(e, t) {
      return meanSquaredError(e, t);
    }var exports_metrics = Object.freeze({ binaryAccuracy: binaryAccuracy$1, binaryCrossentropy: binaryCrossentropy$2, sparseCategoricalAccuracy: sparseCategoricalAccuracy$1, categoricalAccuracy: categoricalAccuracy$1, categoricalCrossentropy: categoricalCrossentropy$2, precision: precision$1, recall: recall$1, cosineProximity: cosineProximity$1, meanAbsoluteError: meanAbsoluteError$1, meanAbsolutePercentageError: meanAbsolutePercentageError$1, MAPE: MAPE$2, mape: mape$2, meanSquaredError: meanSquaredError$1, MSE: MSE$2, mse: mse$2 }),
        exports_models = Object.freeze({ modelFromJSON: modelFromJSON });function l1l2(e) {
      return new L1L2(e);
    }function l1$1(e) {
      return l1(e);
    }function l2$1(e) {
      return l2(e);
    }var exports_regularizers = Object.freeze({ l1l2: l1l2, l1: l1$1, l2: l2$1 }),
        Callback = function (e) {
      function t() {
        var t = null !== e && e.apply(this, arguments) || this;return t.model = null, t;
      }return __extends(t, e), t.prototype.setModel = function (e) {
        if (!(e instanceof LayersModel)) throw new Error("model must be a LayersModel, not some other Container");this.model = e;
      }, t;
    }(BaseCallback);function less(e, t) {
      return e < t;
    }function greater$1(e, t) {
      return e > t;
    }var EarlyStopping = function (e) {
      function t(t) {
        var n = e.call(this) || this;if (null == t && (t = {}), t.restoreBestWeights) throw new NotImplementedError("restoreBestWeights = True is not implemented in EarlyStopping yet.");return n.monitor = t.monitor || "val_loss", n.minDelta = Math.abs(t.minDelta || 0), n.patience = t.patience || 0, n.verbose = t.verbose || 0, n.mode = t.mode || "auto", n.baseline = t.baseline, -1 === ["auto", "min", "max"].indexOf(n.mode) && (console.warn("EarlyStopping mode '" + n.mode + "' is invalid. Falling back to mode 'auto'."), n.mode = "auto"), "min" === n.mode ? n.monitorFunc = less : "max" === n.mode ? n.monitorFunc = greater$1 : -1 !== n.monitor.indexOf("acc") ? n.monitorFunc = greater$1 : n.monitorFunc = less, n.monitorFunc === less && (n.minDelta *= -1), n;
      }return __extends(t, e), t.prototype.onTrainBegin = function (e) {
        return __awaiter(this, void 0, void 0, function () {
          return __generator(this, function (e) {
            return this.wait = 0, this.stoppedEpoch = 0, null != this.baseline ? this.best = this.baseline : this.best = this.monitorFunc === less ? 1 / 0 : -1 / 0, [2];
          });
        });
      }, t.prototype.onEpochEnd = function (e, t) {
        return __awaiter(this, void 0, void 0, function () {
          var n;return __generator(this, function (r) {
            switch (r.label) {case 0:
                return [4, resolveScalarsInLogs(t)];case 1:
                return r.sent(), null == (n = this.getMonitorValue(t)) ? [2] : (this.monitorFunc(n - this.minDelta, this.best) ? (this.best = n, this.wait = 0) : (this.wait++, this.wait >= this.patience && (this.stoppedEpoch = e, this.model.stopTraining = !0)), [2]);}
          });
        });
      }, t.prototype.onTrainEnd = function (e) {
        return __awaiter(this, void 0, void 0, function () {
          return __generator(this, function (e) {
            return this.stoppedEpoch > 0 && this.verbose && console.log("Epoch " + this.stoppedEpoch + ": early stopping."), [2];
          });
        });
      }, t.prototype.getMonitorValue = function (e) {
        null == e && (e = {});var t = e[this.monitor];return null == t && console.warn("Metric for EarlyStopping " + this.monitor + " is not available. Available metrics are: " + Object.keys(e)), t;
      }, t;
    }(Callback);function earlyStopping(e) {
      return new EarlyStopping(e);
    }var callbacks = { earlyStopping: earlyStopping };
  
    /**
     * @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 DataType,
        SaverDef,
        __assign$1 = function () {
      return (__assign$1 = Object.assign || function (e) {
        for (var t, a$$1 = 1, r = arguments.length; a$$1 < r; a$$1++) for (var n in t = arguments[a$$1]) Object.prototype.hasOwnProperty.call(t, n) && (e[n] = t[n]);return e;
      }).apply(this, arguments);
    };function __awaiter$1(e, t, a$$1, r) {
      return new (a$$1 || (a$$1 = Promise))(function (n, s) {
        function o(e) {
          try {
            i(r.next(e));
          } catch (e) {
            s(e);
          }
        }function p(e) {
          try {
            i(r.throw(e));
          } catch (e) {
            s(e);
          }
        }function i(e) {
          e.done ? n(e.value) : new a$$1(function (t) {
            t(e.value);
          }).then(o, p);
        }i((r = r.apply(e, t || [])).next());
      });
    }function __generator$1(e, t) {
      var a$$1,
          r,
          n,
          s,
          o = { label: 0, sent: function () {
          if (1 & n[0]) throw n[1];return n[1];
        }, trys: [], ops: [] };return s = { next: p(0), throw: p(1), return: p(2) }, "function" == typeof Symbol && (s[Symbol.iterator] = function () {
        return this;
      }), s;function p(s) {
        return function (p) {
          return function (s) {
            if (a$$1) throw new TypeError("Generator is already executing.");for (; o;) try {
              if (a$$1 = 1, r && (n = 2 & s[0] ? r.return : s[0] ? r.throw || ((n = r.return) && n.call(r), 0) : r.next) && !(n = n.call(r, s[1])).done) return n;switch (r = 0, n && (s = [2 & s[0], n.value]), s[0]) {case 0:case 1:
                  n = s;break;case 4:
                  return o.label++, { value: s[1], done: !1 };case 5:
                  o.label++, r = s[1], s = [0];continue;case 7:
                  s = o.ops.pop(), o.trys.pop();continue;default:
                  if (!(n = (n = o.trys).length > 0 && n[n.length - 1]) && (6 === s[0] || 2 === s[0])) {
                    o = 0;continue;
                  }if (3 === s[0] && (!n || s[1] > n[0] && s[1] < n[3])) {
                    o.label = s[1];break;
                  }if (6 === s[0] && o.label < n[1]) {
                    o.label = n[1], n = s;break;
                  }if (n && o.label < n[2]) {
                    o.label = n[2], o.ops.push(s);break;
                  }n[2] && o.ops.pop(), o.trys.pop();continue;}s = t.call(e, o);
            } catch (e) {
              s = [6, e], r = 0;
            } finally {
              a$$1 = n = 0;
            }if (5 & s[0]) throw s[1];return { value: s[0] ? s[1] : void 0, done: !0 };
          }([s, p]);
        };
      }
    }!function (e) {
      e[e.DT_INVALID = 0] = "DT_INVALID", e[e.DT_FLOAT = 1] = "DT_FLOAT", e[e.DT_DOUBLE = 2] = "DT_DOUBLE", e[e.DT_INT32 = 3] = "DT_INT32", e[e.DT_UINT8 = 4] = "DT_UINT8", e[e.DT_INT16 = 5] = "DT_INT16", e[e.DT_INT8 = 6] = "DT_INT8", e[e.DT_STRING = 7] = "DT_STRING", e[e.DT_COMPLEX64 = 8] = "DT_COMPLEX64", e[e.DT_INT64 = 9] = "DT_INT64", e[e.DT_BOOL = 10] = "DT_BOOL", e[e.DT_QINT8 = 11] = "DT_QINT8", e[e.DT_QUINT8 = 12] = "DT_QUINT8", e[e.DT_QINT32 = 13] = "DT_QINT32", e[e.DT_BFLOAT16 = 14] = "DT_BFLOAT16", e[e.DT_FLOAT_REF = 101] = "DT_FLOAT_REF", e[e.DT_DOUBLE_REF = 102] = "DT_DOUBLE_REF", e[e.DT_INT32_REF = 103] = "DT_INT32_REF", e[e.DT_UINT8_REF = 104] = "DT_UINT8_REF", e[e.DT_INT16_REF = 105] = "DT_INT16_REF", e[e.DT_INT8_REF = 106] = "DT_INT8_REF", e[e.DT_STRING_REF = 107] = "DT_STRING_REF", e[e.DT_COMPLEX64_REF = 108] = "DT_COMPLEX64_REF", e[e.DT_INT64_REF = 109] = "DT_INT64_REF", e[e.DT_BOOL_REF = 110] = "DT_BOOL_REF", e[e.DT_QINT8_REF = 111] = "DT_QINT8_REF", e[e.DT_QUINT8_REF = 112] = "DT_QUINT8_REF", e[e.DT_QINT32_REF = 113] = "DT_QINT32_REF", e[e.DT_BFLOAT16_REF = 114] = "DT_BFLOAT16_REF";
    }(DataType || (DataType = {})), function (e) {
      !function (e) {
        e[e.LEGACY = 0] = "LEGACY", e[e.V1 = 1] = "V1", e[e.V2 = 2] = "V2";
      }(e.CheckpointFormatVersion || (e.CheckpointFormatVersion = {}));
    }(SaverDef || (SaverDef = {}));var CUSTOM_OPS = {};function registerOp(e, t) {
      var a$$1 = { tfOpName: e, category: "custom", inputs: [], attrs: [], customExecutor: t };CUSTOM_OPS[e] = a$$1;
    }function getRegisteredOp(e) {
      return CUSTOM_OPS[e];
    }function deregisterOp(e) {
      delete CUSTOM_OPS[e];
    }function getParamValue(e, t, a$$1, r) {
      var n = t.inputParams[e];if (n && void 0 !== n.inputIndexStart) {
        var s = n.inputIndexStart,
            o = 0 === n.inputIndexEnd ? void 0 : void 0 === n.inputIndexEnd ? s + 1 : n.inputIndexEnd;if ("tensor" === n.type) return getTensor(t.inputNames[n.inputIndexStart], a$$1, r);if ("tensors" === n.type) return t.inputNames.slice(s, o).map(function (e) {
          return getTensor(e, a$$1, r);
        });var p = Array.prototype.slice.call(getTensor(t.inputNames.slice(s)[0], a$$1, r).dataSync());return "number" === n.type ? p[0] : p;
      }var i = t.attrParams[e];return i && i.value;
    }function getTensor(e, t, a$$1) {
      var r = parseNodeName(e),
          n = r[0],
          s = r[1],
          o = a$$1.currentContextIds.find(function (e) {
        return !!t[getNodeNameWithContextId(n, e)];
      });return void 0 !== o ? t[getNodeNameWithContextId(n, o)][s] : void 0;
    }function getTensorsForCurrentContenxt(e, t, a$$1) {
      return t[getNodeNameWithContextId(e, a$$1.currentContextId)];
    }function getNodeNameAndIndex(e, t) {
      var a$$1 = parseNodeName(e),
          r = a$$1[0],
          n = a$$1[1];return [getNodeNameWithContextId(r, t && t.currentContextId), n];
    }function getNodeNameWithContextId(e, t) {
      return t ? e + "-" + t : e;
    }function parseNodeName(e) {
      var t = e.lastIndexOf(":");return -1 === t ? [e, 0] : [e.substring(0, t), Number(e.substring(t + 1))];
    }function split$1(e, t) {
      for (var a$$1 = [], r = 0; r < e.length; r += t) a$$1.push(e.slice(r, r + t));return a$$1;
    }var 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 }] }],
        arithmetic = Object.freeze({ json: json }),
        json$1 = [{ 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 }] }],
        basicMath = Object.freeze({ json: json$1 }),
        json$2 = [{ 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" }] }],
        control = Object.freeze({ json: json$2 }),
        json$3 = [{ 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[]" }] }],
        convolution = Object.freeze({ json: json$3 }),
        json$4 = [{ 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" }] }],
        creation = Object.freeze({ json: json$4 }),
        json$5 = [{ 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 }] }],
        dynamic = Object.freeze({ json: json$5 }),
        json$6 = [{ tfOpName: "TopKV2", category: "evaluation", inputs: [{ start: 0, name: "x", type: "tensor" }, { start: 1, name: "k", type: "number" }], attrs: [{ tfName: "sorted", name: "sorted", type: "bool" }] }],
        evaluation = Object.freeze({ json: json$6 }),
        json$7 = [{ 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" }] }],
        graph = Object.freeze({ json: json$7 }),
        json$8 = [{ 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" }] }],
        image$1 = Object.freeze({ json: json$8 }),
        json$9 = [{ 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 }] }],
        logical = Object.freeze({ json: json$9 }),
        json$10 = [{ 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 }] }],
        matrices = Object.freeze({ json: json$10 }),
        json$11 = [{ 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 }] }],
        normalization = Object.freeze({ json: json$11 }),
        json$12 = [{ 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" }] }],
        reduction = Object.freeze({ json: json$12 }),
        json$13 = [{ 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 }] }],
        sliceJoin = Object.freeze({ json: json$13 }),
        json$14 = [{ 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 }] }],
        spectral = Object.freeze({ json: json$14 }),
        json$15 = [{ 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" }] }],
        transformation = Object.freeze({ json: json$15 }),
        OperationMapper = function () {
      function e() {
        var e = [arithmetic, basicMath, control, convolution, creation, dynamic, evaluation, logical, image$1, graph, matrices, normalization, reduction, sliceJoin, spectral, transformation],
            t = [].concat.apply([], e.map(function (e) {
          return e.json;
        }));this.opMappers = t.reduce(function (e, t) {
          return e[t.tfOpName] = t, e;
        }, {});
      }return Object.defineProperty(e, "Instance", { get: function () {
          return this._instance || (this._instance = new this());
        }, enumerable: !0, configurable: !0 }), e.prototype.transformGraph = function (e) {
        var t = this,
            a$$1 = [],
            r = [],
            n = e.node.reduce(function (e, n) {
          return e[n.name] = t.mapNode(n), "Placeholder" === n.op && a$$1.push(e[n.name]), "Const" === n.op && r.push(e[n.name]), e;
        }, {}),
            s = [],
            o = [],
            p = Object.keys(n);return p.forEach(function (e) {
          var t = n[e];t.inputNames.forEach(function (e) {
            var a$$1 = getNodeNameAndIndex(e)[0];t.inputs.push(n[a$$1]), n[a$$1].children.push(t);
          }), 0 === t.inputs.length && s.push(t);
        }), p.forEach(function (e) {
          var t = n[e];0 === t.children.length && o.push(t);
        }), { nodes: n, inputs: s, outputs: o, weights: r, placeholders: a$$1 };
      }, e.prototype.mapNode = function (e) {
        var t = getRegisteredOp(e.op) || this.opMappers[e.op] || {};null == e.attr && (e.attr = {});var a$$1 = { name: e.name, op: e.op, category: t.category, inputNames: (e.input || []).map(function (e) {
            return e.startsWith("^") ? e.substr(1) : e;
          }), inputs: [], children: [], inputParams: {}, attrParams: {}, rawAttrs: e.attr };return null != t.inputs && (a$$1.inputParams = t.inputs.reduce(function (e, t) {
          return e[t.name] = { type: t.type, inputIndexStart: t.start, inputIndexEnd: t.end }, e;
        }, {})), null != t.attrs && (a$$1.attrParams = t.attrs.reduce(function (t, a$$1) {
          var r = a$$1.type,
              n = void 0;switch (a$$1.type) {case "string":
              void 0 === (n = getStringParam(e.attr, a$$1.tfName, a$$1.defaultValue)) && a$$1.tfDeprecatedName && (n = getStringParam(e.attr, a$$1.tfDeprecatedName, a$$1.defaultValue));break;case "string[]":
              void 0 === (n = getStringArrayParam(e.attr, a$$1.tfName, a$$1.defaultValue)) && a$$1.tfDeprecatedName && (n = getStringArrayParam(e.attr, a$$1.tfDeprecatedName, a$$1.defaultValue));break;case "number":
              void 0 === (n = getNumberParam(e.attr, a$$1.tfName, a$$1.defaultValue || 0)) && a$$1.tfDeprecatedName && (n = getNumberParam(e.attr, a$$1.tfDeprecatedName, a$$1.defaultValue));break;case "number[]":
              void 0 === (n = getNumericArrayParam(e.attr, a$$1.tfName, a$$1.defaultValue)) && a$$1.tfDeprecatedName && (n = getNumericArrayParam(e.attr, a$$1.tfDeprecatedName, a$$1.defaultValue));break;case "bool":
              void 0 === (n = getBoolParam(e.attr, a$$1.tfName, a$$1.defaultValue)) && a$$1.tfDeprecatedName && (n = getBoolParam(e.attr, a$$1.tfDeprecatedName, a$$1.defaultValue));break;case "bool[]":
              void 0 === (n = getBoolArrayParam(e.attr, a$$1.tfName, a$$1.defaultValue)) && a$$1.tfDeprecatedName && (n = getBoolArrayParam(e.attr, a$$1.tfDeprecatedName, a$$1.defaultValue));break;case "shape":
              void 0 === (n = getTensorShapeParam(e.attr, a$$1.tfName, a$$1.defaultValue)) && a$$1.tfDeprecatedName && (n = getTensorShapeParam(e.attr, a$$1.tfDeprecatedName, a$$1.defaultValue));break;case "shape[]":
              void 0 === (n = getTensorShapeArrayParam(e.attr, a$$1.tfName, a$$1.defaultValue)) && a$$1.tfDeprecatedName && (n = getTensorShapeArrayParam(e.attr, a$$1.tfDeprecatedName, a$$1.defaultValue));break;case "dtype":
              void 0 === (n = getDtypeParam(e.attr, a$$1.tfName, a$$1.defaultValue)) && a$$1.tfDeprecatedName && (n = getDtypeParam(e.attr, a$$1.tfDeprecatedName, a$$1.defaultValue));break;case "dtype[]":
              void 0 === (n = getDtypeArrayParam(e.attr, a$$1.tfName, a$$1.defaultValue)) && a$$1.tfDeprecatedName && (n = getDtypeArrayParam(e.attr, a$$1.tfDeprecatedName, a$$1.defaultValue));break;case "tensor":case "tensors":
              break;default:
              throw new Error("Unsupported param type: " + a$$1.type + " for op: " + e.op);}return t[a$$1.name] = { value: n, type: r }, t;
        }, {})), a$$1;
      }, e;
    }();function decodeBase64(e) {
      var t = exports.ENV.global;if (void 0 !== t.atob) return t.atob(e);if ("undefined" != typeof Buffer) return new Buffer(e, "base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()");
    }function parseStringParam(e, t) {
      var a$$1 = Array.isArray(e) ? String.fromCharCode.apply(null, e) : decodeBase64(e);return t ? a$$1 : a$$1.toLowerCase();
    }function getStringParam(e, t, a$$1, r) {
      void 0 === r && (r = !1);var n = e[t];return null != n ? parseStringParam(n.s, r) : a$$1;
    }function getBoolParam(e, t, a$$1) {
      var r = e[t];return r ? r.b : a$$1;
    }function getNumberParam(e, t, a$$1) {
      var r = e[t] || {},
          n = null != r.i ? r.i : null != r.f ? r.f : a$$1;return "number" == typeof n ? n : parseInt(n, 10);
    }function parseDtypeParam(e) {
      switch ("string" == typeof e && (e = DataType[e]), e) {case DataType.DT_FLOAT:
          return "float32";case DataType.DT_INT32:
          return "int32";case DataType.DT_BOOL:
          return "bool";case DataType.DT_DOUBLE:
          return "float32";case DataType.DT_STRING:
          return "string";default:
          return null;}
    }function getDtypeParam(e, t, a$$1) {
      var r = e[t];return r && r.type ? parseDtypeParam(r.type) : a$$1;
    }function getDtypeArrayParam(e, t, a$$1) {
      var r = e[t];return r && r.list && r.list.type ? r.list.type.map(function (e) {
        return parseDtypeParam(e);
      }) : a$$1;
    }function parseTensorShapeParam(e) {
      if (!e.unknownRank) return null != e.dim ? e.dim.map(function (e) {
        return "number" == typeof e.size ? e.size : parseInt(e.size, 10);
      }) : [];
    }function getTensorShapeParam(e, t, a$$1) {
      var r = e[t];return r && r.shape ? parseTensorShapeParam(r.shape) : a$$1;
    }function getNumericArrayParam(e, t, a$$1) {
      var r = e[t];return r ? (r.list.f && r.list.f.length ? r.list.f : r.list.i).map(function (e) {
        return "number" == typeof e ? e : parseInt(e, 10);
      }) : a$$1;
    }function getStringArrayParam(e, t, a$$1, r) {
      void 0 === r && (r = !1);var n = e[t];return n && n.list && n.list.s ? n.list.s.map(function (e) {
        return parseStringParam(e, r);
      }) : a$$1;
    }function getTensorShapeArrayParam(e, t, a$$1) {
      var r = e[t];return r && r.list && r.list.shape ? r.list.shape.map(function (e) {
        return parseTensorShapeParam(e);
      }) : a$$1;
    }function getBoolArrayParam(e, t, a$$1) {
      var r = e[t];return r && r.list && r.list.b ? r.list.b : a$$1;
    }var NodeValueImpl = function () {
      function e(e, t, a$$1) {
        var r = this;this.node = e, this.tensorMap = t, this.context = a$$1, this.inputs = [], this.attrs = {}, this.inputs = e.inputNames.map(function (e) {
          return r.getInput(e);
        }), null != e.rawAttrs && (this.attrs = Object.keys(e.rawAttrs).reduce(function (e, t) {
          return e[t] = r.getAttr(t), e;
        }, {}));
      }return e.prototype.getInput = function (e) {
        return getTensor(e, this.tensorMap, this.context);
      }, e.prototype.getAttr = function (e, t) {
        var a$$1 = this.node.rawAttrs[e];if (null != a$$1.tensor) return getTensor(e, this.tensorMap, this.context);if (null != a$$1.i || null != a$$1.f) return getNumberParam(this.node.rawAttrs, e, t);if (null != a$$1.s) return getStringParam(this.node.rawAttrs, e, t);if (null != a$$1.b) return getBoolParam(this.node.rawAttrs, e, t);if (null != a$$1.shape) return getTensorShapeParam(this.node.rawAttrs, e, t);if (null != a$$1.type) return getDtypeParam(this.node.rawAttrs, e, t);if (null != a$$1.list) {
          if (null != a$$1.list.i || null != a$$1.list.f) return getNumericArrayParam(this.node.rawAttrs, e, t);if (null != a$$1.list.s) return getStringArrayParam(this.node.rawAttrs, e, t);if (null != a$$1.list.shape) return getTensorShapeArrayParam(this.node.rawAttrs, e, t);if (null != a$$1.list.b) return getBoolArrayParam(this.node.rawAttrs, e, t);if (null != a$$1.list.type) return getDtypeArrayParam(this.node.rawAttrs, e, t);
        }return t;
      }, e;
    }(),
        executeOp = function (e, t, a$$1) {
      switch (e.op) {case "BiasAdd":case "AddV2":case "Add":
          return [Zu(getParamValue("a", e, t, a$$1), getParamValue("b", e, t, a$$1))];case "AddN":
          return [tl(getParamValue("tensors", e, t, a$$1))];case "FloorMod":case "Mod":
          return [cl(getParamValue("a", e, t, a$$1), getParamValue("b", e, t, a$$1))];case "Mul":
          return [pl(getParamValue("a", e, t, a$$1), getParamValue("b", e, t, a$$1))];case "RealDiv":case "Div":
          return [rl(getParamValue("a", e, t, a$$1), getParamValue("b", e, t, a$$1))];case "FloorDiv":
          return [al(getParamValue("a", e, t, a$$1), getParamValue("b", e, t, a$$1))];case "Sub":
          return [yl(getParamValue("a", e, t, a$$1), getParamValue("b", e, t, a$$1))];case "Minimum":
          return [ul(getParamValue("a", e, t, a$$1), getParamValue("b", e, t, a$$1))];case "Maximum":
          return [il(getParamValue("a", e, t, a$$1), getParamValue("b", e, t, a$$1))];case "Pow":
          return [dl(getParamValue("a", e, t, a$$1), getParamValue("b", e, t, a$$1))];case "SquaredDifference":
          return [ml(getParamValue("a", e, t, a$$1), getParamValue("b", e, t, a$$1))];default:
          throw TypeError("Node type " + e.op + " is not implemented");}
    },
        executeOp$1 = function (e, t, a$$1) {
      switch (e.op) {case "Abs":case "ComplexAbs":
          return [is(getParamValue("x", e, t, a$$1))];case "Acos":
          return [ss(getParamValue("x", e, t, a$$1))];case "Acosh":
          return [us(getParamValue("x", e, t, a$$1))];case "Asin":
          return [ls(getParamValue("x", e, t, a$$1))];case "Asinh":
          return [cs(getParamValue("x", e, t, a$$1))];case "Atan":
          return [hs(getParamValue("x", e, t, a$$1))];case "Atan2":
          return [nl(getParamValue("x", e, t, a$$1), getParamValue("y", e, t, a$$1))];case "Atanh":
          return [ps(getParamValue("x", e, t, a$$1))];case "Ceil":
          return [fs(getParamValue("x", e, t, a$$1))];case "Complex":
          return [fn(getParamValue("real", e, t, a$$1), getParamValue("imag", e, t, a$$1))];case "Cos":
          return [vs(getParamValue("x", e, t, a$$1))];case "Cosh":
          return [ms(getParamValue("x", e, t, a$$1))];case "Elu":
          return [Sl(getParamValue("x", e, t, a$$1))];case "Erf":
          return [gs(getParamValue("x", e, t, a$$1))];case "Exp":
          return [ys(getParamValue("x", e, t, a$$1))];case "Expm1":
          return [xs(getParamValue("x", e, t, a$$1))];case "Floor":
          return [bs(getParamValue("x", e, t, a$$1))];case "Log":
          return [ws(getParamValue("x", e, t, a$$1))];case "Log1p":
          return [Cs(getParamValue("x", e, t, a$$1))];case "Neg":
          return [Rs(getParamValue("x", e, t, a$$1))];case "Reciprocal":
          return [Is(getParamValue("x", e, t, a$$1))];case "Relu":
          return [Al(getParamValue("x", e, t, a$$1))];case "Round":
          return [Ss(getParamValue("x", e, t, a$$1))];case "Selu":
          return [Tl(getParamValue("x", e, t, a$$1))];case "Sigmoid":
          return [ks(getParamValue("x", e, t, a$$1))];case "Sin":
          return [Os(getParamValue("x", e, t, a$$1))];case "Sign":
          return [As(getParamValue("x", e, t, a$$1))];case "Sinh":
          return [Ms(getParamValue("x", e, t, a$$1))];case "Softplus":
          return [Fs(getParamValue("x", e, t, a$$1))];case "Sqrt":
          return [Bs(getParamValue("x", e, t, a$$1))];case "Square":
          return [Ps(getParamValue("x", e, t, a$$1))];case "Tanh":
          return [Us(getParamValue("x", e, t, a$$1))];case "Tan":
          return [Ws(getParamValue("x", e, t, a$$1))];case "Relu6":case "ClipByValue":
          return [ds(getParamValue("x", e, t, a$$1), getParamValue("clipValueMin", e, t, a$$1), getParamValue("clipValueMax", e, t, a$$1))];case "Rsqrt":
          return [Ns(getTensor(e.inputNames[0], t, a$$1))];case "Prod":
          return [Uu(getParamValue("x", e, t, a$$1), getParamValue("axes", e, t, a$$1))];case "LeakyRelu":
          return [Nl(getParamValue("x", e, t, a$$1), getParamValue("alpha", e, t, a$$1))];default:
          throw TypeError("Node type " + e.op + " is not implemented");}
    },
        TensorArray = function () {
      function e(t, a$$1, r, n, s, o, p) {
        this.name = t, this.dtype = a$$1, this.maxSize = r, this.elementShape = n, this.identicalElementShapes = s, this.dynamicSize = o, this.clearAfterRead = p, this.tensors = [], this.closed_ = !1, this.id = e.nextId++;
      }return Object.defineProperty(e.prototype, "closed", { get: function () {
          return this.closed_;
        }, enumerable: !0, configurable: !0 }), e.prototype.clearAndClose = function () {
        this.tensors.forEach(function (e) {
          return e.tensor.dispose();
        }), this.tensors = [], this.closed_ = !0;
      }, e.prototype.size = function () {
        return this.tensors.length;
      }, e.prototype.read = function (e) {
        if (this.closed_) throw new Error("TensorArray " + this.name + " has already been closed.");if (e < 0 || e >= this.tensors.length) throw new Error("Tried to read from index " + e + ", but array size is: " + this.tensors.length);var t = this.tensors[e];if (t.cleared) throw new Error("TensorArray " + this.name + ": Could not read index " + e + " twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).");return this.clearAfterRead && (t.cleared = !0), t.read = !0, t.tensor;
      }, e.prototype.readMany = function (e) {
        var t = this;return e.map(function (e) {
          return t.read(e);
        });
      }, e.prototype.write = function (e, t) {
        if (this.closed_) throw new Error("TensorArray " + this.name + " has already been closed.");if (e < 0 || !this.dynamicSize && e >= this.maxSize) throw new Error("Tried to write to index " + e + ", but array is not resizeable and size is: " + this.maxSize);var a$$1 = this.tensors[e] || {};if (t.dtype !== this.dtype) throw new Error("TensorArray " + this.name + ": Could not write to TensorArray index " + e + ",\n          because the value dtype is " + t.dtype + ", but TensorArray dtype is " + this.dtype + ".");if (0 !== this.size() || null != this.elementShape && 0 !== this.elementShape.length || (this.elementShape = t.shape), this.assertShapesMatchAllowUndefinedSize(this.elementShape, t.shape, "TensorArray " + this.name + ": Could not write to TensorArray index " + e + "."), a$$1 && a$$1.read) throw new Error("TensorArray " + this.name + ": Could not write to TensorArray index " + e + ", because it has already been read.");if (a$$1 && a$$1.written) throw new Error("TensorArray " + this.name + ": Could not write to TensorArray index " + e + ", because it has already been written.");a$$1.tensor = t, a$$1.written = !0, this.tensors[e] = a$$1;
      }, e.prototype.writeMany = function (e, t) {
        var a$$1 = this;if (e.length !== t.length) throw new Error("TensorArray " + this.name + ": could not write multiple tensors,because the index size: " + e.length + " is not the same as tensors size: " + t.length + ".");e.forEach(function (e, r) {
          return a$$1.write(e, t[r]);
        });
      }, e.prototype.gather = function (e, t) {
        if (t && t !== this.dtype) throw new Error("TensorArray dtype is " + this.dtype + " but gather requested dtype " + t);if (!e) {
          e = [];for (var a$$1 = 0; a$$1 < this.size(); a$$1++) e.push(a$$1);
        }if (0 === e.length) return mn([], [0].concat(this.elementShape));var r = this.readMany(e);return this.assertShapesMatchAllowUndefinedSize(this.elementShape, r[0].shape, "TensorArray shape mismatch: "), gr(r, 0);
      }, e.prototype.concat = function (e) {
        if (e && e !== this.dtype) throw new Error("TensorArray dtype is " + this.dtype + " but concat requested dtype " + e);if (0 === this.size()) return mn([], [0].concat(this.elementShape));for (var t = [], a$$1 = 0; a$$1 < this.size(); a$$1++) t.push(a$$1);var r = this.readMany(t);return this.assertShapesMatchAllowUndefinedSize(this.elementShape, r[0].shape, "TensorArray shape mismatch: tensor array shape (" + this.elementShape + ") vs first tensor shape (" + r[0].shape + ")"), _n(r, 0);
      }, e.prototype.scatter = function (e, t) {
        if (t.dtype !== this.dtype) throw new Error("TensorArray dtype is " + this.dtype + " but tensor has dtype " + t.dtype);if (e.length !== t.shape[0]) throw new Error("Expected len(indices) == tensor.shape[0], but saw: " + e.length + " vs. " + t.shape[0]);var a$$1 = Math.max.apply(Math, e);if (!this.dynamicSize && a$$1 >= this.maxSize) throw new Error("Max index must be < array size (" + a$$1 + "  vs. " + this.maxSize + ")");this.writeMany(e, br(t, 0));
      }, e.prototype.split = function (e, t) {
        var a$$1 = this;if (t.dtype !== this.dtype) throw new Error("TensorArray dtype is " + this.dtype + " but tensor has dtype " + t.dtype);var r = 0,
            n = e.map(function (e) {
          return r += e;
        });if (r !== t.shape[0]) throw new Error("Expected sum of lengths to be equal to\n          tensor.shape[0], but sum of lengths is\n        " + r + ", and tensor's shape is: " + t.shape);if (!this.dynamicSize && e.length !== this.maxSize) throw new Error("TensorArray's size is not equal to the size of lengths (" + this.maxSize + " vs. " + e.length + "), and the TensorArray is not marked as dynamically resizeable");var s = 0 === r ? 0 : t.size / r,
            o = [];Pe(function () {
          t = t.reshape([1, r, s]);for (var p = 0; p < e.length; ++p) {
            var i = [0, 0 === p ? 0 : n[p - 1], 0],
                u = [1, e[p], s];o[p] = Ru(t, i, u).reshape(a$$1.elementShape);
          }return o;
        });for (var p = [], i = 0; i < e.length; i++) p[i] = i;this.writeMany(p, o);
      }, e.prototype.assertShapesMatchAllowUndefinedSize = function (e, t, a$$1) {
        void 0 === a$$1 && (a$$1 = ""), Z.assert(this.shapesEqualAllowUndefinedSize(e, t), function () {
          return a$$1 + " Shapes " + e + " and " + t + " must match";
        });
      }, e.prototype.shapesEqualAllowUndefinedSize = function (e, t) {
        if (e.length !== t.length) return !1;for (var a$$1 = 0; a$$1 < e.length; a$$1++) if (-1 !== e[a$$1] && -1 !== t[a$$1] && e[a$$1] !== t[a$$1]) return !1;return !0;
      }, e.nextId = 0, e;
    }();function executeOp$2(e, t, a$$1) {
      return __awaiter$1(this, void 0, void 0, function () {
        var r, n, s, o, p, i, u, m, c, l$$1, d, y, f, h, g, N, x, b, V, P, T, O, S, v, _, w, A, D, E, I, C, M, k, z, j;return __generator$1(this, function (F) {
          switch (F.label) {case 0:
              switch (e.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, [getParamValue("pred", e, t, a$$1).clone()]];case 2:
              return r = getParamValue("pred", e, t, a$$1), n = getParamValue("data", e, t, a$$1), [4, r.data()];case 3:
              return [2, F.sent()[0] ? [void 0, n.clone()] : [n.clone(), void 0]];case 4:
              return [2, (s = e.inputNames.find(function (e) {
                return void 0 !== getTensor(e, t, a$$1);
              })) ? [getTensor(s, t, a$$1).clone()] : void 0];case 5:
              return o = getParamValue("frameName", e, t, a$$1), p = getParamValue("tensor", e, t, a$$1), a$$1.enterFrame(o), [2, [p.clone()]];case 6:
              return i = getParamValue("tensor", e, t, a$$1), a$$1.exitFrame(), [2, [i.clone()]];case 7:
              return u = getParamValue("tensor", e, t, a$$1), a$$1.nextIteration(), [2, [u.clone()]];case 8:
              return m = getParamValue("size", e, t, a$$1), c = getParamValue("dtype", e, t, a$$1), l$$1 = getParamValue("elementShape", e, t, a$$1), d = getParamValue("dynamicSize", e, t, a$$1), y = getParamValue("clearAfterRead", e, t, a$$1), f = getParamValue("identicalElementShapes", e, t, a$$1), h = getParamValue("name", e, t, a$$1), g = new TensorArray(h, c, m, l$$1, f, d, y), a$$1.addTensorArray(g), [2, [yn(g.id), yn(1)]];case 9:
              return N = getParamValue("tensorArrayId", e, t, a$$1), x = getParamValue("index", e, t, a$$1), b = getParamValue("tensor", e, t, a$$1), a$$1.getTensorArray(N).write(x, b), [2, [yn(1)]];case 10:
              return V = getParamValue("tensorArrayId", e, t, a$$1), P = getParamValue("index", e, t, a$$1), [2, [a$$1.getTensorArray(V).read(P)]];case 11:
              return T = getParamValue("tensorArrayId", e, t, a$$1), O = getParamValue("indices", e, t, a$$1), S = getParamValue("dtype", e, t, a$$1), [2, [a$$1.getTensorArray(T).gather(O, S)]];case 12:
              return v = getParamValue("tensorArrayId", e, t, a$$1), _ = getParamValue("indices", e, t, a$$1), w = getParamValue("tensor", e, t, a$$1), a$$1.getTensorArray(v).scatter(_, w), [2, [yn(1)]];case 13:
              return A = getParamValue("tensorArrayId", e, t, a$$1), D = a$$1.getTensorArray(A), E = getParamValue("dtype", e, t, a$$1), [2, [D.concat(E)]];case 14:
              return I = getParamValue("tensorArrayId", e, t, a$$1), C = getParamValue("tensor", e, t, a$$1), M = getParamValue("lengths", e, t, a$$1), a$$1.getTensorArray(I).split(M, C), [2, [yn(1)]];case 15:
              return k = getParamValue("tensorArrayId", e, t, a$$1), z = a$$1.getTensorArray(k), [2, [yn(z.size(), "int32")]];case 16:
              return j = getParamValue("tensorArrayId", e, t, a$$1), a$$1.getTensorArray(j).clearAndClose(), [2, []];case 17:
              throw TypeError("Node type " + e.op + " is not implemented");}
        });
      });
    }var executeOp$3 = function (e, t, a$$1) {
      switch (e.op) {case "Conv1D":
          var r = getParamValue("stride", e, t, a$$1),
              n = getParamValue("pad", e, t, a$$1),
              s = getParamValue("dataFormat", e, t, a$$1).toUpperCase(),
              o = getParamValue("dilation", e, t, a$$1);return [ou(getParamValue("x", e, t, a$$1), getParamValue("filter", e, t, a$$1), r, n, s, o)];case "Conv2D":
          r = getParamValue("strides", e, t, a$$1), n = getParamValue("pad", e, t, a$$1), s = getParamValue("dataFormat", e, t, a$$1).toUpperCase();var p = getParamValue("dilations", e, t, a$$1);return [au(getParamValue("x", e, t, a$$1), getParamValue("filter", e, t, a$$1), [r[1], r[2]], n, s, [p[1], p[2]])];case "Conv2DBackpropInput":case "Conv2dTranspose":
          var i = getParamValue("outputShape", e, t, a$$1);r = getParamValue("strides", e, t, a$$1), n = getParamValue("pad", e, t, a$$1);return [cu(getParamValue("x", e, t, a$$1), getParamValue("filter", e, t, a$$1), i, [r[1], r[2]], n)];case "DepthwiseConv2dNative":case "DepthwiseConv2d":
          r = getParamValue("strides", e, t, a$$1), n = getParamValue("pad", e, t, a$$1), p = getParamValue("dilations", e, t, a$$1), s = getParamValue("dataFormat", e, t, a$$1).toUpperCase();return [uu(getParamValue("input", e, t, a$$1), getParamValue("filter", e, t, a$$1), [r[1], r[2]], n, s, [p[1], p[2]])];case "AvgPool":
          r = getParamValue("strides", e, t, a$$1), n = getParamValue("pad", e, t, a$$1);var u = getParamValue("kernelSize", e, t, a$$1);return [Cu(getParamValue("x", e, t, a$$1), [u[1], u[2]], [r[1], r[2]], n)];case "MaxPool":
          r = getParamValue("strides", e, t, a$$1), n = getParamValue("pad", e, t, a$$1), u = getParamValue("kernelSize", e, t, a$$1);return [wu(getParamValue("x", e, t, a$$1), [u[1], u[2]], [r[1], r[2]], n)];default:
          throw TypeError("Node type " + e.op + " is not implemented");}
    },
        executeOp$4 = function (e, t, a$$1) {
      switch (e.op) {case "Fill":
          var r = getParamValue("shape", e, t, a$$1),
              n = getParamValue("dtype", e, t, a$$1),
              s = getParamValue("value", e, t, a$$1);return [Nn(r, s, n)];case "LinSpace":
          var o = getParamValue("start", e, t, a$$1),
              p = getParamValue("stop", e, t, a$$1),
              i = getParamValue("num", e, t, a$$1);return [kn(o, p, i)];case "OneHot":
          var u = getParamValue("indices", e, t, a$$1),
              m = getParamValue("depth", e, t, a$$1),
              c = getParamValue("onValue", e, t, a$$1),
              l$$1 = getParamValue("offValue", e, t, a$$1);return [ar(u, m, c, l$$1)];case "Ones":
          return [In(getParamValue("shape", e, t, a$$1), getParamValue("dtype", e, t, a$$1))];case "OnesLike":
          return [Tn(getParamValue("x", e, t, a$$1))];case "RandomUniform":
          return [fr(getParamValue("shape", e, t, a$$1), getParamValue("minval", e, t, a$$1), getParamValue("maxval", e, t, a$$1), getParamValue("dtype", e, t, a$$1))];case "Range":
          o = getParamValue("start", e, t, a$$1);var d = getParamValue("stop", e, t, a$$1),
              y = getParamValue("step", e, t, a$$1);return [An(o, d, y, getParamValue("dtype", e, t, a$$1))];case "TruncatedNormal":
          r = getParamValue("shape", e, t, a$$1);var f = getParamValue("mean", e, t, a$$1),
              h = getParamValue("stdDev", e, t, a$$1),
              g = getParamValue("seed", e, t, a$$1);return [xr(r, f, h, getParamValue("dtype", e, t, a$$1), g)];case "Zeros":
          return [Sn(getParamValue("shape", e, t, a$$1), getParamValue("dtype", e, t, a$$1))];case "ZerosLike":
          return [Dn(getParamValue("x", e, t, a$$1))];default:
          throw TypeError("Node type " + e.op + " is not implemented");}
    };function executeOp$5(e, t, a$$1) {
      return __awaiter$1(this, void 0, void 0, function () {
        var r, n, s, o, p;return __generator$1(this, function (i) {
          switch (i.label) {case 0:
              switch (e.op) {case "NonMaxSuppressionV3":case "NonMaxSuppressionV2":
                  return [3, 1];case "Where":
                  return [3, 3];case "ListDiff":
                  return [3, 5];}return [3, 7];case 1:
              return r = getParamValue("boxes", e, t, a$$1), n = getParamValue("scores", e, t, a$$1), s = getParamValue("maxOutputSize", e, t, a$$1), o = getParamValue("iouThreshold", e, t, a$$1), p = getParamValue("scoreThreshold", e, t, a$$1), [4, Rc.nonMaxSuppressionAsync(r, n, s, o, p)];case 2:
              return [2, [i.sent()]];case 3:
              return [4, Il(getParamValue("condition", e, t, a$$1))];case 4:
              return [2, [i.sent()]];case 5:
              return [4, wr(getParamValue("x", e, t, a$$1), getParamValue("y", e, t, a$$1))];case 6:
              return [2, i.sent()];case 7:
              throw TypeError("Node type " + e.op + " is not implemented");}
        });
      });
    }var executeOp$6 = function (e, t, a$$1) {
      switch (e.op) {case "TopKV2":
          var r = getParamValue("x", e, t, a$$1),
              n = getParamValue("k", e, t, a$$1),
              s = getParamValue("sorted", e, t, a$$1),
              o = Vl(r, n, s);return [o.values, o.indices];default:
          throw TypeError("Node type " + e.op + " is not implemented");}
    },
        executeOp$7 = function (e, t, a$$1) {
      switch (e.op) {case "Const":
          return t[e.name];case "PlaceholderWithDefault":
          var r = getParamValue("default", e, t, a$$1);return [getTensor(e.name, t, a$$1) || r];case "Placeholder":
          return [getTensor(e.name, t, a$$1)];case "Identity":case "StopGradient":case "FakeQuantWithMinMaxVars":
          return [getParamValue("x", e, t, a$$1).clone()];case "IdentityN":
          return getParamValue("x", e, t, a$$1).map(function (e) {
            return e.clone();
          });case "Snapshot":
          return [getParamValue("x", e, t, a$$1).clone()];case "Shape":
          return [xn(getParamValue("x", e, t, a$$1).shape, "int32")];case "ShapeN":
          return getParamValue("x", e, t, a$$1).map(function (e) {
            return xn(e.shape);
          });case "Size":
          return [yn(getParamValue("x", e, t, a$$1).size, "int32")];case "Rank":
          return [yn(getParamValue("x", e, t, a$$1).rank, "int32")];case "NoOp":
          return [];case "Print":
          var n = getParamValue("x", e, t, a$$1),
              s = getParamValue("data", e, t, a$$1),
              o = getParamValue("message", e, t, a$$1),
              p = getParamValue("summarize", e, t, a$$1);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."), console.log(o);for (var i = 0; i < s.length; i++) console.log(Array.prototype.slice.call(s[i].dataSync()).slice(0, p));return [n];default:
          throw TypeError("Node type " + e.op + " is not implemented");}
    },
        executeOp$8 = function (e, t, a$$1) {
      switch (e.op) {case "ResizeBilinear":
          var r = getParamValue("images", e, t, a$$1),
              n = getParamValue("size", e, t, a$$1),
              s = getParamValue("alignCorners", e, t, a$$1);return [Rc.resizeBilinear(r, [n[0], n[1]], s)];case "ResizeNearestNeighbor":
          r = getParamValue("images", e, t, a$$1), n = getParamValue("size", e, t, a$$1), s = getParamValue("alignCorners", e, t, a$$1);return [Rc.resizeNearestNeighbor(r, [n[0], n[1]], s)];case "CropAndResize":
          var o = getParamValue("image", e, t, a$$1),
              p = getParamValue("boxes", e, t, a$$1),
              i = getParamValue("boxInd", e, t, a$$1),
              u = getParamValue("cropSize", e, t, a$$1),
              m = getParamValue("method", e, t, a$$1),
              c = getParamValue("extrapolationValue", e, t, a$$1);return [Rc.cropAndResize(o, p, i, u, m, c)];default:
          throw TypeError("Node type " + e.op + " is not implemented");}
    },
        executeOp$9 = function (e, t, a$$1) {
      switch (e.op) {case "Equal":
          return [zu(getParamValue("a", e, t, a$$1), getParamValue("b", e, t, a$$1))];case "NotEqual":
          return [Qu(getParamValue("a", e, t, a$$1), getParamValue("b", e, t, a$$1))];case "Greater":
          return [Gu(getParamValue("a", e, t, a$$1), getParamValue("b", e, t, a$$1))];case "GreaterEqual":
          return [qu(getParamValue("a", e, t, a$$1), getParamValue("b", e, t, a$$1))];case "Less":
          return [ju(getParamValue("a", e, t, a$$1), getParamValue("b", e, t, a$$1))];case "LessEqual":
          return [Ku(getParamValue("a", e, t, a$$1), getParamValue("b", e, t, a$$1))];case "LogicalAnd":
          return [bl(getParamValue("a", e, t, a$$1), getParamValue("b", e, t, a$$1))];case "LogicalNot":
          return [wl(getParamValue("a", e, t, a$$1))];case "LogicalOr":
          return [Cl(getParamValue("a", e, t, a$$1), getParamValue("b", e, t, a$$1))];case "Select":
          return [Rl(getParamValue("condition", e, t, a$$1), getParamValue("a", e, t, a$$1), getParamValue("b", e, t, a$$1))];default:
          throw TypeError("Node type " + e.op + " is not implemented");}
    },
        executeOp$10 = function (e, t, a$$1) {
      switch (e.op) {case "BatchMatMul":case "BatchMatMulV2":case "MatMul":
          return [hu(getParamValue("a", e, t, a$$1), getParamValue("b", e, t, a$$1), getParamValue("transposeA", e, t, a$$1), getParamValue("transposeB", e, t, a$$1))];case "Transpose":
          return [Dl(getParamValue("x", e, t, a$$1), getParamValue("perm", e, t, a$$1))];default:
          throw TypeError("Node type " + e.op + " is not implemented");}
    },
        executeOp$11 = function (e, t, a$$1) {
      switch (e.op) {case "FusedBatchNorm":case "FusedBatchNormV2":case "FusedBatchNormV3":
          return [Qs(getParamValue("x", e, t, a$$1), getParamValue("mean", e, t, a$$1), getParamValue("variance", e, t, a$$1), getParamValue("offset", e, t, a$$1), getParamValue("scale", e, t, a$$1), getParamValue("epsilon", e, t, a$$1))];case "LRN":
          return [_l(getParamValue("x", e, t, a$$1), getParamValue("radius", e, t, a$$1), getParamValue("bias", e, t, a$$1), getParamValue("alpha", e, t, a$$1), getParamValue("beta", e, t, a$$1))];case "Softmax":
          return [qr(getParamValue("x", e, t, a$$1))];case "LogSoftmax":
          return [Hr(getParamValue("x", e, t, a$$1))];case "SparseToDense":
          return [Xl(getParamValue("sparseIndices", e, t, a$$1), getParamValue("outputShape", e, t, a$$1), getParamValue("sparseValues", e, t, a$$1), getParamValue("defaultValue", e, t, a$$1))];default:
          throw TypeError("Node type " + e.op + " is not implemented");}
    },
        executeOp$12 = function (e, t, a$$1) {
      switch (e.op) {case "Max":
          var r = getParamValue("axis", e, t, a$$1),
              n = getParamValue("keepDims", e, t, a$$1);return [Fu(getParamValue("x", e, t, a$$1), r, n)];case "Mean":
          r = getParamValue("axis", e, t, a$$1), n = getParamValue("keepDims", e, t, a$$1);return [Bu(getParamValue("x", e, t, a$$1), r, n)];case "Min":
          r = getParamValue("axis", e, t, a$$1), n = getParamValue("keepDims", e, t, a$$1);return [Pu(getParamValue("x", e, t, a$$1), r, n)];case "Sum":
          r = getParamValue("axis", e, t, a$$1), n = getParamValue("keepDims", e, t, a$$1);return [Wu(getParamValue("x", e, t, a$$1), r, n)];case "All":
          r = getParamValue("axis", e, t, a$$1), n = getParamValue("keepDims", e, t, a$$1);return [Tu(getParamValue("x", e, t, a$$1), r, n)];case "Any":
          r = getParamValue("axis", e, t, a$$1), n = getParamValue("keepDims", e, t, a$$1);return [Du(getParamValue("x", e, t, a$$1), r, n)];case "ArgMax":
          r = getParamValue("axis", e, t, a$$1);return [_u(getParamValue("x", e, t, a$$1), r)];case "ArgMin":
          r = getParamValue("axis", e, t, a$$1);return [Ou(getParamValue("x", e, t, a$$1), r)];case "Prod":
          r = getParamValue("axis", e, t, a$$1), n = getParamValue("keepDims", e, t, a$$1);return [Uu(getParamValue("x", e, t, a$$1), r, n)];default:
          throw TypeError("Node type " + e.op + " is not implemented");}
    },
        executeOp$13 = function (e, t, a$$1) {
      switch (e.op) {case "ConcatV2":case "Concat":
          var r = getParamValue("axis", e, t, a$$1),
              n = getParamValue("tensors", e, t, a$$1);return [_n(n, r)];case "GatherV2":case "Gather":
          r = getParamValue("axis", e, t, a$$1);var s = getParamValue("x", e, t, a$$1),
              o = getParamValue("indices", e, t, a$$1);return [Bl(s, o.asType("int32"), r)];case "ReverseV2":case "Reverse":
          r = getParamValue("axis", e, t, a$$1), s = getParamValue("x", e, t, a$$1);return [du(s, r)];case "Slice":
          var p = getParamValue("begin", e, t, a$$1),
              i = getParamValue("size", e, t, a$$1);return [Ru(getParamValue("x", e, t, a$$1), p, i)];case "StridedSlice":
          p = getParamValue("begin", e, t, a$$1);var u = getParamValue("end", e, t, a$$1),
              m = getParamValue("strides", e, t, a$$1),
              c = getParamValue("beginMask", e, t, a$$1),
              l$$1 = getParamValue("endMask", e, t, a$$1),
              d = getParamValue("ellipsisMask", e, t, a$$1),
              y = getParamValue("newAxisMask", e, t, a$$1),
              f = getParamValue("shrinkAxisMask", e, t, a$$1),
              h = getParamValue("x", e, t, a$$1);if (1 === p.length && h.shape.length > 1) for (var g = 1; g < h.shape.length; g++) p.push(0), u.push(h.shape[g]), m.push(m[0]);return [zl(h, p, u, m, c, l$$1, d, y, f)];case "Pack":
          return Pe(function () {
            var r = getParamValue("axis", e, t, a$$1),
                n = getParamValue("tensors", e, t, a$$1),
                s = n[0].shape,
                o = n[0].squeeze().shape,
                p = n.map(function (e) {
              var t = Z.arraysEqual(e.shape, s);if (!t && !Z.arraysEqual(e.squeeze().shape, o)) throw new Error("the input tensors shape does not match");return t ? e : e.reshape(s);
            });return [gr(p, r)];
          });case "Unpack":
          return Pe(function () {
            var r = getParamValue("axis", e, t, a$$1),
                n = getParamValue("tensor", e, t, a$$1);return br(n, r);
          });case "Tile":
          var N = getParamValue("reps", e, t, a$$1);return [yr(getParamValue("x", e, t, a$$1), N)];case "Split":case "SplitV":
          r = getParamValue("axis", e, t, a$$1);var x = getParamValue("numOrSizeSplits", e, t, a$$1);return Pn(getParamValue("x", e, t, a$$1), x, r);case "ScatterNd":
          o = getParamValue("indices", e, t, a$$1);var b = getParamValue("values", e, t, a$$1),
              V = getParamValue("shape", e, t, a$$1);return [Gl(o, b, V)];case "GatherNd":
          var P = getParamValue("x", e, t, a$$1);o = getParamValue("indices", e, t, a$$1);return [Yl(P, o)];case "SparseToDense":
          o = getParamValue("sparseIndices", e, t, a$$1), V = getParamValue("outputShape", e, t, a$$1);var T = getParamValue("sparseValues", e, t, a$$1),
              O = getParamValue("defaultValue", e, t, a$$1);return [Xl(o, T, V, T.dtype === O.dtype ? O : O.asType(T.dtype))];default:
          throw TypeError("Node type " + e.op + " is not implemented");}
    },
        executeOp$14 = function (e, t, a$$1) {
      switch (e.op) {case "FFT":
          return [ql(getParamValue("x", e, t, a$$1))];case "IFFT":
          return [Hl(getParamValue("x", e, t, a$$1))];case "RFFT":
          return [$l(getParamValue("x", e, t, a$$1))];case "IRFFT":
          return [jl(getParamValue("x", e, t, a$$1))];default:
          throw TypeError("Node type " + e.op + " is not implemented");}
    },
        executeOp$15 = function (e, t, a$$1) {
      switch (e.op) {case "Cast":
          return [Jn(getParamValue("x", e, t, a$$1), getParamValue("dtype", e, t, a$$1))];case "ExpandDims":
          var r = getParamValue("axis", e, t, a$$1);return [nr(getParamValue("x", e, t, a$$1), r)];case "Squeeze":
          r = getParamValue("axis", e, t, a$$1);return [mr(getParamValue("x", e, t, a$$1), r)];case "Reshape":
          return [dr(getParamValue("x", e, t, a$$1), getParamValue("shape", e, t, a$$1))];case "PadV2":case "Pad":
          return [ir(getParamValue("x", e, t, a$$1), split$1(getParamValue("padding", e, t, a$$1), 2), getParamValue("constantValue", e, t, a$$1))];case "SpaceToBatchND":
          var n = getParamValue("blockShape", e, t, a$$1),
              s = split$1(getParamValue("paddings", e, t, a$$1), 2);return [vr(getParamValue("x", e, t, a$$1), n, s)];case "BatchToSpaceND":
          n = getParamValue("blockShape", e, t, a$$1);var o = split$1(getParamValue("crops", e, t, a$$1), 2);return [Qn(getParamValue("x", e, t, a$$1), n, o)];case "DepthToSpace":
          var p = getParamValue("blockSize", e, t, a$$1),
              i = getParamValue("dataFormat", e, t, a$$1).toUpperCase();return [er(getParamValue("x", e, t, a$$1), p, i)];default:
          throw TypeError("Node type " + e.op + " is not implemented");}
    };function executeOp$16(e, t, a$$1) {
      var r = function (e, t, a$$1) {
        switch (e.category) {case "arithmetic":
            return executeOp(e, t, a$$1);case "basic_math":
            return executeOp$1(e, t, a$$1);case "control":
            return executeOp$2(e, t, a$$1);case "convolution":
            return executeOp$3(e, t, a$$1);case "creation":
            return executeOp$4(e, t, a$$1);case "dynamic":
            return executeOp$5(e, t, a$$1);case "evaluation":
            return executeOp$6(e, t, a$$1);case "image":
            return executeOp$8(e, t, a$$1);case "graph":
            return executeOp$7(e, t, a$$1);case "logical":
            return executeOp$9(e, t, a$$1);case "matrices":
            return executeOp$10(e, t, a$$1);case "normalization":
            return executeOp$11(e, t, a$$1);case "reduction":
            return executeOp$12(e, t, a$$1);case "slice_join":
            return executeOp$13(e, t, a$$1);case "spectral":
            return executeOp$14(e, t, a$$1);case "transformation":
            return executeOp$15(e, t, a$$1);case "custom":
            var r = getRegisteredOp(e.op);if (r && r.customExecutor) return r.customExecutor(new NodeValueImpl(e, t, a$$1));throw TypeError("Custom op " + e.op + " is not registered.");default:
            throw TypeError("Unknown op '" + e.op + "'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()");}
      }(e, t, a$$1);return r instanceof Promise ? r.then(function (e) {
        return [].concat(e);
      }) : [].concat(r);
    }var ExecutionContext = function () {
      function e(e, t) {
        this.weightMap = e, this.tensorArrayMap = t, this.rootContext = { id: 0, frameName: "", iterationId: 0 }, this.contexts = [this.rootContext], this.lastId = 0, this.generateCurrentContextIds();
      }return e.prototype.newFrame = function (e, t) {
        return { id: e, frameName: t, iterationId: 0 };
      }, Object.defineProperty(e.prototype, "currentContext", { get: function () {
          return this.contexts;
        }, set: function (e) {
          this.contexts !== e && (this.contexts = e, this.generateCurrentContextIds());
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(e.prototype, "currentContextId", { get: function () {
          return this._currentContextIds[0];
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(e.prototype, "currentContextIds", { get: function () {
          return this._currentContextIds;
        }, enumerable: !0, configurable: !0 }), e.prototype.generateCurrentContextIds = function () {
        for (var e = [], t = 0; t < this.contexts.length - 1; t++) {
          var a$$1 = this.contexts.slice(0, this.contexts.length - t);e.push(this.contextIdforContexts(a$$1));
        }e.push(""), this._currentContextIds = e;
      }, e.prototype.contextIdforContexts = function (e) {
        return e ? e.map(function (e) {
          return 0 === e.id && 0 === e.iterationId ? "" : e.frameName + "-" + e.iterationId;
        }).join("/") : "";
      }, e.prototype.enterFrame = function (e) {
        this.contexts && (this.lastId++, this.contexts = this.contexts.slice(), this.contexts.push(this.newFrame(this.lastId, e)), this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)));
      }, e.prototype.exitFrame = function () {
        if (!(this.contexts && this.contexts.length > 1)) throw new Error("Cannot exit frame, the context is empty");this.contexts = this.contexts.slice(), this.contexts.splice(-1), this.currentContextIds.shift();
      }, e.prototype.nextIteration = function () {
        if (!(this.contexts && this.contexts.length > 0)) throw new Error("Cannot increase frame iteration, the context is empty");this.contexts = this.contexts.slice(), this.lastId++;var e = Object.assign({}, this.contexts[this.contexts.length - 1]);e.iterationId += 1, e.id = this.lastId, this.contexts.splice(-1, 1, e), this._currentContextIds.splice(0, 1, this.contextIdforContexts(this.contexts));
      }, e.prototype.getWeight = function (e) {
        return this.weightMap[e];
      }, e.prototype.addTensorArray = function (e) {
        this.tensorArrayMap[e.id] = e;
      }, e.prototype.getTensorArray = function (e) {
        return this.tensorArrayMap[e];
      }, e;
    }();function getExecutionSubgraph(e, t, a$$1) {
      for (var r = new Set(), n = [], s = null, o = null, p = new Set(), i = t.slice(); i.length > 0;) {
        var u = i.pop();(isControlFlow(u) || isDynamicShape(u)) && null == s && (o = (s = u).children.map(function (e) {
          return e.name;
        }).filter(function (e) {
          return r.has(e);
        })), r.add(u.name), null == a$$1[u.name] && null == e[u.name] && (0 !== u.inputs.length ? u.inputs.forEach(function (e) {
          p.has(e.name) || (p.add(e.name), i.push(e));
        }) : n.push(u.name));
      }return { inputs: e, outputs: t, usedNodes: r, missingInputs: n, dynamicNode: s, syncInputs: o };
    }function getNodesInTopologicalOrder(e, t, a$$1) {
      var r = a$$1.usedNodes,
          n = a$$1.inputs,
          s = [];Object.keys(n).map(function (t) {
        return e.nodes[t];
      }).forEach(function (e) {
        r.has(e.name) && s.push(e);
      }), e.weights.forEach(function (e) {
        r.has(e.name) && s.push(e);
      });for (var o = new Set(), p = []; s.length > 0;) {
        var i = s.pop();o.add(i.name), t[i.name] || p.push(i), i.children.forEach(function (e) {
          !o.has(e.name) && r.has(e.name) && e.inputs.every(function (e) {
            return o.has(e.name);
          }) && s.push(e);
        });
      }return p;
    }var CONTROL_FLOW_OPS = ["Switch", "Merge", "Enter", "Exit", "NextIteration"],
        DYNAMIC_SHAPE_OPS = ["NonMaxSuppressionV2", "NonMaxSuppressionV3", "Where"];function isControlFlow(e) {
      return CONTROL_FLOW_OPS.indexOf(e.op) >= 0;
    }function isDynamicShape(e) {
      return DYNAMIC_SHAPE_OPS.indexOf(e.op) >= 0;
    }var GraphExecutor = function () {
      function e(e) {
        this.graph = e, this.compiledMap = new Map(), this._weightMap = {}, this.SEPERATOR = ",", this.placeholders = e.placeholders, this._outputs = e.outputs;
      }return Object.defineProperty(e.prototype, "weightMap", { get: function () {
          return this._weightMap;
        }, set: function (e) {
          var t = Object.keys(e).map(function (t) {
            return e[t].map(function (e) {
              return e.id;
            });
          });this.weightIds = [].concat.apply([], t), this._weightMap = e;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(e.prototype, "inputs", { get: function () {
          return this.placeholders.map(function (e) {
            return { name: e.name, shape: e.attrParams.shape ? e.attrParams.shape.value : void 0, dtype: e.attrParams.dtype ? e.attrParams.dtype.value : void 0 };
          });
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(e.prototype, "outputs", { get: function () {
          return this._outputs.map(function (e) {
            return { name: e.name, shape: e.attrParams.shape ? e.attrParams.shape.value : void 0, dtype: e.attrParams.dtype ? e.attrParams.dtype.value : void 0 };
          });
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(e.prototype, "inputNodes", { get: function () {
          return this.placeholders.map(function (e) {
            return e.name;
          });
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(e.prototype, "outputNodes", { get: function () {
          return this.outputs.map(function (e) {
            return e.name;
          });
        }, enumerable: !0, configurable: !0 }), e.prototype.getCompilationKey = function (e, t) {
        var a$$1 = e.map(function (e) {
          return e.name;
        }).sort(),
            r = t.map(function (e) {
          return e.name;
        }).sort();return a$$1.join(this.SEPERATOR) + "--" + r.join(this.SEPERATOR);
      }, e.prototype.compile = function (e, t) {
        var a$$1 = getExecutionSubgraph(e, t, this.weightMap),
            r = a$$1.missingInputs,
            n = a$$1.dynamicNode,
            s = a$$1.syncInputs;if (null != n) throw new Error("This execution contains the node '" + n.name + "', which has the dynamic op '" + n.op + "'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [" + s + "]");if (r.length > 0) {
          var o = t.map(function (e) {
            return e.name;
          }),
              p = Object.keys(e);throw new Error("Cannot compute the outputs [" + o + "] from the provided inputs [" + p + "]. Missing the following inputs: [" + r + "]");
        }return getNodesInTopologicalOrder(this.graph, this.weightMap, a$$1);
      }, e.prototype.execute = function (e, t) {
        var a$$1 = this,
            r = Object.keys(e).sort();this.checkInputs(e), this.checkInputShapeAndType(e), this.checkOutputs(t);var n = r.map(function (e) {
          return a$$1.graph.nodes[e];
        }),
            s = t.map(function (e) {
          return a$$1.graph.nodes[parseNodeName(e)[0]];
        }),
            o = this.getCompilationKey(n, s),
            p = this.compiledMap.get(o);null == p && (p = this.compile(e, s), this.compiledMap.set(o, p));var i = {};return Pe(function () {
          var r = new ExecutionContext(a$$1._weightMap, i),
              n = __assign$1({}, a$$1.weightMap);Object.keys(e).forEach(function (t) {
            n[t] = [e[t]];
          });for (var s = a$$1.getFrozenTensorIds(n), o = {}, u = 0; u < p.length; u++) {
            var m = p[u];if (!n[m.name]) {
              var c = executeOp$16(m, n, r);if (c instanceof Promise) throw new Error("The execution of the op '" + m.op + "' returned a promise. Please use model.executeAsync() instead.");n[m.name] = c, a$$1.checkTensorForDisposal(m.name, m, n, r, s, t, o);
            }
          }return t.map(function (e) {
            return getTensor(e, n, r);
          });
        });
      }, e.prototype.getFrozenTensorIds = function (e) {
        var t = [].concat.apply([], Object.keys(e).map(function (t) {
          return e[t];
        }).map(function (e) {
          return e.map(function (e) {
            return e.id;
          });
        }));return new Set(t);
      }, e.prototype.checkTensorForDisposal = function (e, t, a$$1, r, n, s, o) {
        "control" !== t.category && -1 === s.indexOf(e) && (a$$1[e].forEach(function (e) {
          null != e && (o[e.id] = (o[e.id] || 0) + t.children.length);
        }), t.inputs.forEach(function (e) {
          if ("control" !== e.category) {
            var t = getTensorsForCurrentContenxt(e.name, a$$1, r);null != t && t.forEach(function (e) {
              if (e && !n.has(e.id)) {
                var t = o[e.id];1 === t ? (e.dispose(), delete o[e.id]) : null != t && o[e.id]--;
              }
            });
          }
        }));
      }, e.prototype.executeAsync = function (e, t) {
        return __awaiter$1(this, void 0, void 0, function () {
          var a$$1,
              r,
              n,
              s,
              o,
              p,
              i = this;return __generator$1(this, function (u) {
            switch (u.label) {case 0:
                return this.checkInputs(e), this.checkInputShapeAndType(e), this.checkOutputs(t), a$$1 = {}, r = new ExecutionContext(this._weightMap, a$$1), [4, this.executeWithControlFlow(e, r, t)];case 1:
                return n = u.sent(), s = t.map(function (e) {
                  return getTensor(e, n, r);
                }), o = new Set(s.map(function (e) {
                  return e.id;
                })), p = new Set(Object.keys(e).map(function (t) {
                  return e[t].id;
                })), Object.keys(n).forEach(function (e) {
                  n[e].forEach(function (e) {
                    !e || e.isDisposed || o.has(e.id) || p.has(e.id) || -1 !== i.weightIds.indexOf(e.id) || e.dispose();
                  });
                }), [2, s];}
          });
        });
      }, e.prototype.executeWithControlFlow = function (e, t, a$$1) {
        return __awaiter$1(this, void 0, void 0, function () {
          var r,
              n,
              s,
              o,
              p,
              i,
              u,
              m,
              c,
              l$$1,
              d,
              y,
              f,
              h,
              g,
              N,
              x = this;return __generator$1(this, function (b) {
            switch (b.label) {case 0:
                r = Object.keys(e), n = r.map(function (e) {
                  return x.graph.nodes[e];
                }), s = a$$1.map(function (e) {
                  return x.graph.nodes[parseNodeName(e)[0]];
                }), o = getExecutionSubgraph(e, s, this.weightMap), p = o.usedNodes, i = o.missingInputs, u = o.dynamicNode, m = o.syncInputs, c = n.concat(this.graph.weights).map(function (e) {
                  return { node: e, contexts: t.currentContext };
                }), l$$1 = __assign$1({}, this.weightMap), Object.keys(e).forEach(function (t) {
                  l$$1[t] = [e[t]];
                }), d = {}, y = this.getFrozenTensorIds(l$$1), f = {}, b.label = 1;case 1:
                return c.length > 0 ? (h = this.processStack(n, c, t, l$$1, f, y, a$$1, d, p), [4, Promise.all(h)]) : [3, 3];case 2:
                return b.sent(), [3, 1];case 3:
                if (null == u && console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead."), (g = s.filter(function (e) {
                  return !isControlFlow(e) && !getTensor(e.name, l$$1, t);
                }).map(function (e) {
                  return e.name;
                })).length > 0) throw N = "", null != u && (N = "Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [" + m + "]"), new Error("Cannot compute the outputs [" + g + "] from the provided inputs [" + r + "]. Consider providing the following inputs: [" + i + "]. " + N);return [2, l$$1];}
          });
        });
      }, e.prototype.processStack = function (e, t, a$$1, r, n, s, o, p, i) {
        for (var u = this, m = [], c = function () {
          var c = t.pop();a$$1.currentContext = c.contexts;var d = "";if ("Enter" === c.node.op && getParamValue("isConstant", c.node, r, a$$1) && (d = getNodeNameAndIndex(c.node.name, a$$1)[0]), -1 === e.indexOf(c.node)) {
            var y = executeOp$16(c.node, r, a$$1);d || (d = getNodeNameAndIndex(c.node.name, a$$1)[0]);var f = a$$1.currentContext;y instanceof Promise ? m.push(y.then(function (e) {
              return r[d] = e, a$$1.currentContext = f, u.checkTensorForDisposal(d, c.node, r, a$$1, s, o, p), u.processChildNodes(c.node, t, a$$1, r, n, i), e;
            })) : (r[d] = y, l$$1.checkTensorForDisposal(d, c.node, r, a$$1, s, o, p), l$$1.processChildNodes(c.node, t, a$$1, r, n, i));
          } else l$$1.processChildNodes(c.node, t, a$$1, r, n, i);
        }, l$$1 = this; t.length > 0;) c();return m;
      }, e.prototype.processChildNodes = function (e, t, a$$1, r, n, s) {
        e.children.forEach(function (e) {
          var o = getNodeNameAndIndex(e.name, a$$1)[0];!n[o] && s.has(e.name) && ("Merge" === e.op ? e.inputNames.some(function (e) {
            return !!getTensor(e, r, a$$1);
          }) && (n[o] = !0, t.push({ contexts: a$$1.currentContext, node: e })) : e.inputNames.every(function (e) {
            return !!getTensor(e, r, a$$1);
          }) && (n[o] = !0, t.push({ contexts: a$$1.currentContext, node: e })));
        });
      }, e.prototype.dispose = function () {
        var e = this;Object.keys(this.weightMap).forEach(function (t) {
          return e.weightMap[t].forEach(function (e) {
            return e.dispose();
          });
        });
      }, e.prototype.checkInputShapeAndType = function (e) {
        var t = this;Object.keys(e).forEach(function (a$$1) {
          var r = e[a$$1],
              n = t.graph.nodes[a$$1];if (n.attrParams.shape && n.attrParams.shape.value) {
            var s = n.attrParams.shape.value,
                o = s.length === r.shape.length && r.shape.every(function (e, t) {
              return -1 === s[t] || s[t] === e;
            });Z.assert(o, function () {
              return "The shape of dict['" + n.name + "'] provided in model.execute(dict) must be [" + s + "], but was [" + r.shape + "]";
            });
          }n.attrParams.dtype && n.attrParams.dtype.value && Z.assert(r.dtype === n.attrParams.dtype.value, function () {
            return "The dtype of dict['" + n.name + "'] provided in model.execute(dict) must be " + n.attrParams.dtype.value + ", but was " + r.dtype;
          });
        });
      }, e.prototype.checkInputs = function (e) {
        var t = this,
            a$$1 = Object.keys(e).filter(function (e) {
          return !t.graph.nodes[e];
        });if (a$$1.length > 0) throw new Error("The dict provided in model.execute(dict) has keys: [" + a$$1 + "] that are not part of graph");
      }, e.prototype.checkOutputs = function (e) {
        var t = this;e.forEach(function (e) {
          var a$$1 = parseNodeName(e)[0];if (!t.graph.nodes[a$$1]) throw new Error("The output '" + e + "' is not found in the graph");
        });
      }, e;
    }(),
        TFHUB_SEARCH_PARAM = "?tfjs-format=file",
        DEFAULT_MODEL_NAME = "model.json",
        GraphModel = function () {
      function e(e, t) {
        void 0 === t && (t = {}), this.modelUrl = e, this.loadOptions = t, this.version = "n/a", null == t && (this.loadOptions = {});
      }return Object.defineProperty(e.prototype, "modelVersion", { get: function () {
          return this.version;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(e.prototype, "inputNodes", { get: function () {
          return this.executor.inputNodes;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(e.prototype, "outputNodes", { get: function () {
          return this.executor.outputNodes;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(e.prototype, "inputs", { get: function () {
          return this.executor.inputs;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(e.prototype, "outputs", { get: function () {
          return this.executor.outputs;
        }, enumerable: !0, configurable: !0 }), Object.defineProperty(e.prototype, "weights", { get: function () {
          return this.executor.weightMap;
        }, enumerable: !0, configurable: !0 }), e.prototype.findIOHandler = function () {
        var e = this.modelUrl;if (null != e.load) this.handler = e;else if (null != this.loadOptions.requestInit) this.handler = Nh.browserHTTPRequest(e, this.loadOptions);else {
          var t = Nh.getLoadHandlers(e, this.loadOptions.onProgress);if (0 === t.length) t.push(Nh.browserHTTPRequest(e, this.loadOptions));else if (t.length > 1) throw new Error("Found more than one (" + t.length + ") load handlers for URL '" + [e] + "'");this.handler = t[0];
        }
      }, e.prototype.load = function () {
        return __awaiter$1(this, void 0, void 0, function () {
          var e, t, a$$1;return __generator$1(this, function (r) {
            switch (r.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 e = r.sent(), t = e.modelTopology, this.version = t.versions.producer + "." + t.versions.minConsumer, a$$1 = Nh.decodeWeights(e.weightData, e.weightSpecs), this.executor = new GraphExecutor(OperationMapper.Instance.transformGraph(t)), this.executor.weightMap = this.convertTensorMapToTensorsMap(a$$1), [2, !0];}
          });
        });
      }, e.prototype.predict = function (e, t) {
        return this.execute(e, this.outputNodes);
      }, e.prototype.normalizeInputs = function (e) {
        if (!(e instanceof ft || Array.isArray(e))) return e;if ((e = Array.isArray(e) ? e : [e]).length !== this.inputNodes.length) throw new Error("Input tensor count mismatch,the graph model has " + this.inputNodes.length + " placeholders, while there are " + e.length + " input tensors.");return this.inputNodes.reduce(function (t, a$$1, r) {
          return t[a$$1] = e[r], t;
        }, {});
      }, e.prototype.normalizeOutputs = function (e) {
        return e = e || this.outputNodes, Array.isArray(e) ? e : [e];
      }, e.prototype.execute = function (e, t) {
        e = this.normalizeInputs(e), t = this.normalizeOutputs(t);var a$$1 = this.executor.execute(e, t);return a$$1.length > 1 ? a$$1 : a$$1[0];
      }, e.prototype.executeAsync = function (e, t) {
        return __awaiter$1(this, void 0, void 0, function () {
          var a$$1;return __generator$1(this, function (r) {
            switch (r.label) {case 0:
                return e = this.normalizeInputs(e), t = this.normalizeOutputs(t), [4, this.executor.executeAsync(e, t)];case 1:
                return [2, (a$$1 = r.sent()).length > 1 ? a$$1 : a$$1[0]];}
          });
        });
      }, e.prototype.convertTensorMapToTensorsMap = function (e) {
        return Object.keys(e).reduce(function (t, a$$1) {
          return t[a$$1] = [e[a$$1]], t;
        }, {});
      }, e.prototype.dispose = function () {
        this.executor.dispose();
      }, e;
    }();function loadGraphModel(e, t) {
      return void 0 === t && (t = {}), __awaiter$1(this, void 0, void 0, function () {
        var a$$1;return __generator$1(this, function (r) {
          switch (r.label) {case 0:
              if (null == e) throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");return null == t && (t = {}), t.fromTFHub && null == e.load && (e.endsWith("/") || (e += "/"), e = "" + e + DEFAULT_MODEL_NAME + TFHUB_SEARCH_PARAM), [4, (a$$1 = new GraphModel(e, t)).load()];case 1:
              return r.sent(), [2, a$$1];}
        });
      });
    }var version$1 = "1.2.3";
  
    /**
     * @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 extendStatics$1 = function (t, e) {
      return (extendStatics$1 = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function (t, e) {
        t.__proto__ = e;
      } || function (t, e) {
        for (var r in e) e.hasOwnProperty(r) && (t[r] = e[r]);
      })(t, e);
    };function __extends$1(t, e) {
      function r() {
        this.constructor = t;
      }extendStatics$1(t, e), t.prototype = null === e ? Object.create(e) : (r.prototype = e.prototype, new r());
    }function __awaiter$2(t, e, r, n) {
      return new (r || (r = Promise))(function (i, o) {
        function a$$1(t) {
          try {
            u(n.next(t));
          } catch (t) {
            o(t);
          }
        }function s(t) {
          try {
            u(n.throw(t));
          } catch (t) {
            o(t);
          }
        }function u(t) {
          t.done ? i(t.value) : new r(function (e) {
            e(t.value);
          }).then(a$$1, s);
        }u((n = n.apply(t, e || [])).next());
      });
    }function __generator$2(t, e) {
      var r,
          n,
          i,
          o,
          a$$1 = { label: 0, sent: function () {
          if (1 & i[0]) throw i[1];return i[1];
        }, trys: [], ops: [] };return o = { next: s(0), throw: s(1), return: s(2) }, "function" == typeof Symbol && (o[Symbol.iterator] = function () {
        return this;
      }), o;function s(o) {
        return function (s) {
          return function (o) {
            if (r) throw new TypeError("Generator is already executing.");for (; a$$1;) try {
              if (r = 1, n && (i = 2 & o[0] ? n.return : o[0] ? n.throw || ((i = n.return) && i.call(n), 0) : n.next) && !(i = i.call(n, o[1])).done) return i;switch (n = 0, i && (o = [2 & o[0], i.value]), o[0]) {case 0:case 1:
                  i = o;break;case 4:
                  return a$$1.label++, { value: o[1], done: !1 };case 5:
                  a$$1.label++, n = o[1], o = [0];continue;case 7:
                  o = a$$1.ops.pop(), a$$1.trys.pop();continue;default:
                  if (!(i = (i = a$$1.trys).length > 0 && i[i.length - 1]) && (6 === o[0] || 2 === o[0])) {
                    a$$1 = 0;continue;
                  }if (3 === o[0] && (!i || o[1] > i[0] && o[1] < i[3])) {
                    a$$1.label = o[1];break;
                  }if (6 === o[0] && a$$1.label < i[1]) {
                    a$$1.label = i[1], i = o;break;
                  }if (i && a$$1.label < i[2]) {
                    a$$1.label = i[2], a$$1.ops.push(o);break;
                  }i[2] && a$$1.ops.pop(), a$$1.trys.pop();continue;}o = e.call(t, a$$1);
            } catch (t) {
              o = [6, t], n = 0;
            } finally {
              r = i = 0;
            }if (5 & o[0]) throw o[1];return { value: o[0] ? o[1] : void 0, done: !0 };
          }([o, s]);
        };
      }
    }function createCommonjsModule(t, e) {
      return t(e = { exports: {} }, e.exports), e.exports;
    }var alea = createCommonjsModule(function (t) {
      !function (t, e, r) {
        function n(t, e) {
          return e.c = t.c, e.s0 = t.s0, e.s1 = t.s1, e.s2 = t.s2, e;
        }function i(t, e) {
          var r = new function (t) {
            var e,
                r = this,
                n = (e = 4022871197, function (t) {
              t = t.toString();for (var r = 0; r < t.length; r++) {
                var n = .02519603282416938 * (e += t.charCodeAt(r));n -= e = n >>> 0, e = (n *= e) >>> 0, e += 4294967296 * (n -= e);
              }return 2.3283064365386963e-10 * (e >>> 0);
            });r.next = function () {
              var t = 2091639 * r.s0 + 2.3283064365386963e-10 * r.c;return r.s0 = r.s1, r.s1 = r.s2, r.s2 = t - (r.c = 0 | t);
            }, r.c = 1, r.s0 = n(" "), r.s1 = n(" "), r.s2 = n(" "), r.s0 -= n(t), r.s0 < 0 && (r.s0 += 1), r.s1 -= n(t), r.s1 < 0 && (r.s1 += 1), r.s2 -= n(t), r.s2 < 0 && (r.s2 += 1), n = null;
          }(t),
              i = e && e.state,
              o = r.next;return o.int32 = function () {
            return 4294967296 * r.next() | 0;
          }, o.double = function () {
            return o() + 1.1102230246251565e-16 * (2097152 * o() | 0);
          }, o.quick = o, i && ("object" == typeof i && n(i, r), o.state = function () {
            return n(r, {});
          }), o;
        }e && e.exports ? e.exports = i : r && r.amd ? r(function () {
          return i;
        }) : this.alea = i;
      }(0, t, !1);
    }),
        xor128 = createCommonjsModule(function (t) {
      !function (t, e, r) {
        function n(t, e) {
          return e.x = t.x, e.y = t.y, e.z = t.z, e.w = t.w, e;
        }function i(t, e) {
          var r = new function (t) {
            var e = this,
                r = "";e.x = 0, e.y = 0, e.z = 0, e.w = 0, e.next = function () {
              var t = e.x ^ e.x << 11;return e.x = e.y, e.y = e.z, e.z = e.w, e.w ^= e.w >>> 19 ^ t ^ t >>> 8;
            }, t === (0 | t) ? e.x = t : r += t;for (var n = 0; n < r.length + 64; n++) e.x ^= 0 | r.charCodeAt(n), e.next();
          }(t),
              i = e && e.state,
              o = function () {
            return (r.next() >>> 0) / 4294967296;
          };return o.double = function () {
            do {
              var t = ((r.next() >>> 11) + (r.next() >>> 0) / 4294967296) / (1 << 21);
            } while (0 === t);return t;
          }, o.int32 = r.next, o.quick = o, i && ("object" == typeof i && n(i, r), o.state = function () {
            return n(r, {});
          }), o;
        }e && e.exports ? e.exports = i : r && r.amd ? r(function () {
          return i;
        }) : this.xor128 = i;
      }(0, t, !1);
    }),
        xorwow = createCommonjsModule(function (t) {
      !function (t, e, r) {
        function n(t, e) {
          return e.x = t.x, e.y = t.y, e.z = t.z, e.w = t.w, e.v = t.v, e.d = t.d, e;
        }function i(t, e) {
          var r = new function (t) {
            var e = this,
                r = "";e.next = function () {
              var t = e.x ^ e.x >>> 2;return e.x = e.y, e.y = e.z, e.z = e.w, e.w = e.v, (e.d = e.d + 362437 | 0) + (e.v = e.v ^ e.v << 4 ^ t ^ t << 1) | 0;
            }, e.x = 0, e.y = 0, e.z = 0, e.w = 0, e.v = 0, t === (0 | t) ? e.x = t : r += t;for (var n = 0; n < r.length + 64; n++) e.x ^= 0 | r.charCodeAt(n), n == r.length && (e.d = e.x << 10 ^ e.x >>> 4), e.next();
          }(t),
              i = e && e.state,
              o = function () {
            return (r.next() >>> 0) / 4294967296;
          };return o.double = function () {
            do {
              var t = ((r.next() >>> 11) + (r.next() >>> 0) / 4294967296) / (1 << 21);
            } while (0 === t);return t;
          }, o.int32 = r.next, o.quick = o, i && ("object" == typeof i && n(i, r), o.state = function () {
            return n(r, {});
          }), o;
        }e && e.exports ? e.exports = i : r && r.amd ? r(function () {
          return i;
        }) : this.xorwow = i;
      }(0, t, !1);
    }),
        xorshift7 = createCommonjsModule(function (t) {
      !function (t, e, r) {
        function n(t, e) {
          return e.x = t.x.slice(), e.i = t.i, e;
        }function i(t, e) {
          null == t && (t = +new Date());var r = new function (t) {
            var e = this;e.next = function () {
              var t,
                  r,
                  n = e.x,
                  i = e.i;return t = n[i], r = (t ^= t >>> 7) ^ t << 24, r ^= (t = n[i + 1 & 7]) ^ t >>> 10, r ^= (t = n[i + 3 & 7]) ^ t >>> 3, r ^= (t = n[i + 4 & 7]) ^ t << 7, t = n[i + 7 & 7], r ^= (t ^= t << 13) ^ t << 9, n[i] = r, e.i = i + 1 & 7, r;
            }, function (t, e) {
              var r,
                  n = [];if (e === (0 | e)) n[0] = e;else for (e = "" + e, r = 0; r < e.length; ++r) n[7 & r] = n[7 & r] << 15 ^ e.charCodeAt(r) + n[r + 1 & 7] << 13;for (; n.length < 8;) n.push(0);for (r = 0; r < 8 && 0 === n[r]; ++r);for (8 == r ? n[7] = -1 : n[r], t.x = n, t.i = 0, r = 256; r > 0; --r) t.next();
            }(e, t);
          }(t),
              i = e && e.state,
              o = function () {
            return (r.next() >>> 0) / 4294967296;
          };return o.double = function () {
            do {
              var t = ((r.next() >>> 11) + (r.next() >>> 0) / 4294967296) / (1 << 21);
            } while (0 === t);return t;
          }, o.int32 = r.next, o.quick = o, i && (i.x && n(i, r), o.state = function () {
            return n(r, {});
          }), o;
        }e && e.exports ? e.exports = i : r && r.amd ? r(function () {
          return i;
        }) : this.xorshift7 = i;
      }(0, t, !1);
    }),
        xor4096 = createCommonjsModule(function (t) {
      !function (t, e, r) {
        function n(t, e) {
          return e.i = t.i, e.w = t.w, e.X = t.X.slice(), e;
        }function i(t, e) {
          null == t && (t = +new Date());var r = new function (t) {
            var e = this;e.next = function () {
              var t,
                  r,
                  n = e.w,
                  i = e.X,
                  o = e.i;return e.w = n = n + 1640531527 | 0, r = i[o + 34 & 127], t = i[o = o + 1 & 127], r ^= r << 13, t ^= t << 17, r ^= r >>> 15, t ^= t >>> 12, r = i[o] = r ^ t, e.i = o, r + (n ^ n >>> 16) | 0;
            }, function (t, e) {
              var r,
                  n,
                  i,
                  o,
                  a$$1,
                  s = [],
                  u = 128;for (e === (0 | e) ? (n = e, e = null) : (e += "\0", n = 0, u = Math.max(u, e.length)), i = 0, o = -32; o < u; ++o) e && (n ^= e.charCodeAt((o + 32) % e.length)), 0 === o && (a$$1 = n), n ^= n << 10, n ^= n >>> 15, n ^= n << 4, n ^= n >>> 13, o >= 0 && (a$$1 = a$$1 + 1640531527 | 0, i = 0 == (r = s[127 & o] ^= n + a$$1) ? i + 1 : 0);for (i >= 128 && (s[127 & (e && e.length || 0)] = -1), i = 127, o = 512; o > 0; --o) n = s[i + 34 & 127], r = s[i = i + 1 & 127], n ^= n << 13, r ^= r << 17, n ^= n >>> 15, r ^= r >>> 12, s[i] = n ^ r;t.w = a$$1, t.X = s, t.i = i;
            }(e, t);
          }(t),
              i = e && e.state,
              o = function () {
            return (r.next() >>> 0) / 4294967296;
          };return o.double = function () {
            do {
              var t = ((r.next() >>> 11) + (r.next() >>> 0) / 4294967296) / (1 << 21);
            } while (0 === t);return t;
          }, o.int32 = r.next, o.quick = o, i && (i.X && n(i, r), o.state = function () {
            return n(r, {});
          }), o;
        }e && e.exports ? e.exports = i : r && r.amd ? r(function () {
          return i;
        }) : this.xor4096 = i;
      }(0, t, !1);
    }),
        tychei = createCommonjsModule(function (t) {
      !function (t, e, r) {
        function n(t, e) {
          return e.a = t.a, e.b = t.b, e.c = t.c, e.d = t.d, e;
        }function i(t, e) {
          var r = new function (t) {
            var e = this,
                r = "";e.next = function () {
              var t = e.b,
                  r = e.c,
                  n = e.d,
                  i = e.a;return t = t << 25 ^ t >>> 7 ^ r, r = r - n | 0, n = n << 24 ^ n >>> 8 ^ i, i = i - t | 0, e.b = t = t << 20 ^ t >>> 12 ^ r, e.c = r = r - n | 0, e.d = n << 16 ^ r >>> 16 ^ i, e.a = i - t | 0;
            }, e.a = 0, e.b = 0, e.c = -1640531527, e.d = 1367130551, t === Math.floor(t) ? (e.a = t / 4294967296 | 0, e.b = 0 | t) : r += t;for (var n = 0; n < r.length + 20; n++) e.b ^= 0 | r.charCodeAt(n), e.next();
          }(t),
              i = e && e.state,
              o = function () {
            return (r.next() >>> 0) / 4294967296;
          };return o.double = function () {
            do {
              var t = ((r.next() >>> 11) + (r.next() >>> 0) / 4294967296) / (1 << 21);
            } while (0 === t);return t;
          }, o.int32 = r.next, o.quick = o, i && ("object" == typeof i && n(i, r), o.state = function () {
            return n(r, {});
          }), o;
        }e && e.exports ? e.exports = i : r && r.amd ? r(function () {
          return i;
        }) : this.tychei = i;
      }(0, t, !1);
    }),
        seedrandom = createCommonjsModule(function (t) {
      !function (e, r) {
        var n,
            i = this,
            o = 256,
            a$$1 = 6,
            s = "random",
            u = r.pow(o, a$$1),
            c = r.pow(2, 52),
            l$$1 = 2 * c,
            h = o - 1;function f(t, f, v) {
          var _ = [],
              w = p(function t(e, r) {
            var n,
                i = [],
                o = typeof e;if (r && "object" == o) for (n in e) try {
              i.push(t(e[n], r - 1));
            } catch (t) {}return i.length ? i : "string" == o ? e : e + "\0";
          }((f = 1 == f ? { entropy: !0 } : f || {}).entropy ? [t, m(e)] : null == t ? function () {
            try {
              var t;return n && (t = n.randomBytes) ? t = t(o) : (t = new Uint8Array(o), (i.crypto || i.msCrypto).getRandomValues(t)), m(t);
            } catch (t) {
              var r = i.navigator,
                  a$$1 = r && r.plugins;return [+new Date(), i, a$$1, i.screen, m(e)];
            }
          }() : t, 3), _),
              y = new function (t) {
            var e,
                r = t.length,
                n = this,
                i = 0,
                a$$1 = n.i = n.j = 0,
                s = n.S = [];r || (t = [r++]);for (; i < o;) s[i] = i++;for (i = 0; i < o; i++) s[i] = s[a$$1 = h & a$$1 + t[i % r] + (e = s[i])], s[a$$1] = e;(n.g = function (t) {
              for (var e, r = 0, i = n.i, a$$1 = n.j, s = n.S; t--;) e = s[i = h & i + 1], r = r * o + s[h & (s[i] = s[a$$1 = h & a$$1 + e]) + (s[a$$1] = e)];return n.i = i, n.j = a$$1, r;
            })(o);
          }(_),
              g = function () {
            for (var t = y.g(a$$1), e = u, r = 0; t < c;) t = (t + r) * o, e *= o, r = y.g(1);for (; t >= l$$1;) t /= 2, e /= 2, r >>>= 1;return (t + r) / e;
          };return g.int32 = function () {
            return 0 | y.g(4);
          }, g.quick = function () {
            return y.g(4) / 4294967296;
          }, g.double = g, p(m(y.S), e), (f.pass || v || function (t, e, n, i) {
            return i && (i.S && d(i, y), t.state = function () {
              return d(y, {});
            }), n ? (r[s] = t, e) : t;
          })(g, w, "global" in f ? f.global : this == r, f.state);
        }function d(t, e) {
          return e.i = t.i, e.j = t.j, e.S = t.S.slice(), e;
        }function p(t, e) {
          for (var r, n = t + "", i = 0; i < n.length;) e[h & i] = h & (r ^= 19 * e[h & i]) + n.charCodeAt(i++);return m(e);
        }function m(t) {
          return String.fromCharCode.apply(0, t);
        }if (r["seed" + s] = f, p(r.random(), e), t.exports) {
          t.exports = f;try {
            n = require("crypto");
          } catch (t) {}
        }
      }([], Math);
    });seedrandom.alea = alea, seedrandom.xor128 = xor128, seedrandom.xorwow = xorwow, seedrandom.xorshift7 = xorshift7, seedrandom.xor4096 = xor4096, seedrandom.tychei = tychei;var seedrandom$1 = seedrandom,
        seedrandom_1 = seedrandom$1.alea;function deepMap(t, e) {
      return deepMapInternal(t, e);
    }function deepMapInternal(t, e, r, n) {
      if (void 0 === r && (r = new Map()), void 0 === n && (n = new Set()), null == t) return null;if (n.has(t)) throw new Error("Circular references are not supported.");if (r.has(t)) return r.get(t);var i = e(t);if (i.recurse && null !== i.value) throw new Error("A deep map function may not return both a value and recurse=true.");if (i.recurse) {
        if (isIterable(t)) {
          var o = Array.isArray(t) ? [] : {};for (var a$$1 in n.add(t), t) {
            var s = deepMapInternal(t[a$$1], e, r, n);o[a$$1] = s;
          }return n.delete(t), o;
        }throw new Error("Can't recurse into non-iterable type: " + t);
      }return r.set(t, i.value), i.value;
    }function deepZip(t, e) {
      return void 0 === e && (e = zipToList), deepZipInternal(t, e);
    }function deepZipInternal(t, e, r) {
      void 0 === r && (r = new Set());var n = t[0];if (r.has(n)) throw new Error("Circular references are not supported.");var i = e(t);if (i.recurse && null !== i.value) throw new Error("A deep zip function may not return both a value and recurse=true.");if (i.recurse) {
        if (isIterable(n)) {
          var o = Array.isArray(n) ? [] : {};r.add(n);var a$$1 = function (n) {
            var i = deepZipInternal(t.map(function (t) {
              return t[n];
            }), e, r);o[n] = i;
          };for (var s in n) a$$1(s);return r.delete(n), o;
        }throw new Error("Can't recurse into non-iterable type: " + n);
      }return i.value;
    }function zipToList(t) {
      return null === t ? null : isIterable(t[0]) ? { value: null, recurse: !0 } : { value: t, recurse: !1 };
    }function deepMapAndAwaitAll(t, e) {
      return __awaiter$2(this, void 0, void 0, function () {
        var r, n, i, o, a$$1, s;return __generator$2(this, function (u) {
          switch (u.label) {case 0:
              r = new Map(), deepMapInternal(t, e, r), n = 0, i = Array.from(r.keys()), u.label = 1;case 1:
              return n < i.length ? (o = i[n], (a$$1 = r.get(o)) instanceof Promise ? [4, a$$1] : [3, 3]) : [3, 4];case 2:
              s = u.sent(), r.set(o, s), u.label = 3;case 3:
              return n++, [3, 1];case 4:
              return [2, deepMapInternal(t, e, r)];}
        });
      });
    }function isIterable(t) {
      return null != t && (Array.isArray(t) || "object" == typeof t && !(t instanceof ft));
    }function canTensorify(t) {
      return null == t || isPrimitive(t) || Array.isArray(t) || "object" == typeof t && t instanceof ft || Z.isTypedArray(t);
    }function isPrimitive(t) {
      return null === t || "object" != typeof t && "function" != typeof t;
    }function deepClone(t) {
      return deepMap(t, cloneIfTensor);
    }function cloneIfTensor(t) {
      return t instanceof ft ? { value: t.clone(), recurse: !1 } : isIterable(t) ? { value: null, recurse: !0 } : { value: t, recurse: !1 };
    }var RingBuffer = function () {
      function t(t) {
        if (this.capacity = t, this.begin = 0, this.end = 0, null == t) throw new RangeError("Can't create a ring buffer of unknown capacity.");if (t < 1) throw new RangeError("Can't create ring buffer of capacity < 1.");this.data = new Array(t), this.doubledCapacity = 2 * t;
      }return t.prototype.wrap = function (t) {
        for (; t < 0;) t += this.doubledCapacity;return t % this.doubledCapacity;
      }, t.prototype.get = function (t) {
        if (t < 0) throw new RangeError("Can't get item at a negative index.");return this.data[t % this.capacity];
      }, t.prototype.set = function (t, e) {
        if (t < 0) throw new RangeError("Can't set item at a negative index.");this.data[t % this.capacity] = e;
      }, t.prototype.length = function () {
        var t = this.end - this.begin;return t < 0 && (t = this.doubledCapacity + t), t;
      }, t.prototype.isFull = function () {
        return this.length() === this.capacity;
      }, t.prototype.isEmpty = function () {
        return 0 === this.length();
      }, t.prototype.push = function (t) {
        if (this.isFull()) throw new RangeError("Ring buffer is full.");this.set(this.end, t), this.end = this.wrap(this.end + 1);
      }, t.prototype.pushAll = function (t) {
        for (var e = 0, r = t; e < r.length; e++) {
          var n = r[e];this.push(n);
        }
      }, t.prototype.pop = function () {
        if (this.isEmpty()) throw new RangeError("Ring buffer is empty.");this.end = this.wrap(this.end - 1);var t = this.get(this.end);return this.set(this.end, void 0), t;
      }, t.prototype.unshift = function (t) {
        if (this.isFull()) throw new RangeError("Ring buffer is full.");this.begin = this.wrap(this.begin - 1), this.set(this.begin, t);
      }, t.prototype.shift = function () {
        if (this.isEmpty()) throw new RangeError("Ring buffer is empty.");var t = this.get(this.begin);return this.set(this.begin, void 0), this.begin = this.wrap(this.begin + 1), t;
      }, t.prototype.shuffleExcise = function (t) {
        if (this.isEmpty()) throw new RangeError("Ring buffer is empty.");var e = this.wrap(this.begin + t),
            r = this.get(e);return this.set(e, this.pop()), r;
      }, t;
    }(),
        GrowingRingBuffer = function (t) {
      function e() {
        return t.call(this, e.INITIAL_CAPACITY) || this;
      }return __extends$1(e, t), e.prototype.isFull = function () {
        return !1;
      }, e.prototype.push = function (e) {
        t.prototype.isFull.call(this) && this.expand(), t.prototype.push.call(this, e);
      }, e.prototype.unshift = function (e) {
        t.prototype.isFull.call(this) && this.expand(), t.prototype.unshift.call(this, e);
      }, e.prototype.expand = function () {
        for (var t = 2 * this.capacity, e = new Array(t), r = this.length(), n = 0; n < r; n++) e[n] = this.get(this.wrap(this.begin + n));this.data = e, this.capacity = t, this.doubledCapacity = 2 * this.capacity, this.begin = 0, this.end = r;
      }, e.INITIAL_CAPACITY = 32, e;
    }(RingBuffer);function iteratorFromItems(t) {
      return new ArrayIterator(t);
    }function iteratorFromFunction(t) {
      return new FunctionCallIterator(t);
    }function iteratorFromConcatenated(t, e) {
      return new ChainedIterator(t, e);
    }function iteratorFromZipped(t, e) {
      return void 0 === e && (e = ZipMismatchMode.FAIL), new ZipIterator(t, e);
    }var ZipMismatchMode,
        LazyIterator = function () {
      function t() {}return t.prototype.toArray = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t, e;return __generator$2(this, function (r) {
            switch (r.label) {case 0:
                return t = [], [4, this.next()];case 1:
                e = r.sent(), r.label = 2;case 2:
                return e.done ? [3, 4] : (t.push(e.value), [4, this.next()]);case 3:
                return e = r.sent(), [3, 2];case 4:
                return [2, t];}
          });
        });
      }, t.prototype.toArrayForTest = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t, e, r;return __generator$2(this, function (n) {
            switch (n.label) {case 0:
                return t = this.prefetch(100), e = [], [4, t.next()];case 1:
                r = n.sent(), n.label = 2;case 2:
                return r.done ? [3, 4] : (e.push(r.value), [4, t.next()]);case 3:
                return r = n.sent(), [3, 2];case 4:
                return [2, e];}
          });
        });
      }, t.prototype.resolveFully = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t;return __generator$2(this, function (e) {
            switch (e.label) {case 0:
                return [4, this.next()];case 1:
                t = e.sent(), e.label = 2;case 2:
                return t.done ? [3, 4] : [4, this.next()];case 3:
                return t = e.sent(), [3, 2];case 4:
                return [2];}
          });
        });
      }, t.prototype.resolveWhile = function (t) {
        return __awaiter$2(this, void 0, void 0, function () {
          var e, r;return __generator$2(this, function (n) {
            switch (n.label) {case 0:
                return [4, this.next()];case 1:
                e = n.sent(), r = t(e.value), n.label = 2;case 2:
                return e.done || !r ? [3, 4] : [4, this.next()];case 3:
                return e = n.sent(), r = t(e.value), [3, 2];case 4:
                return [2];}
          });
        });
      }, t.prototype.handleErrors = function (t) {
        return new ErrorHandlingLazyIterator(this, t);
      }, t.prototype.filter = function (t) {
        return new FilterIterator(this, t);
      }, t.prototype.map = function (t) {
        return new MapIterator(this, t);
      }, t.prototype.mapAsync = function (t) {
        return new AsyncMapIterator(this, t);
      }, t.prototype.serialMapAsync = function (t) {
        return new AsyncMapIterator(this, t).serial();
      }, t.prototype.flatmap = function (t) {
        return new FlatmapIterator(this, t);
      }, t.prototype.forEachAsync = function (t) {
        return __awaiter$2(this, void 0, void 0, function () {
          return __generator$2(this, function (e) {
            return [2, this.map(t).resolveFully()];
          });
        });
      }, t.prototype.serialForEach = function (t) {
        return __awaiter$2(this, void 0, void 0, function () {
          return __generator$2(this, function (e) {
            return [2, this.serialMapAsync(t).resolveWhile(function (t) {
              return !0 === t;
            })];
          });
        });
      }, t.prototype.rowMajorBatch = function (t, e) {
        return void 0 === e && (e = !0), new RowMajorBatchIterator(this, t, e);
      }, t.prototype.columnMajorBatch = function (t, e, r) {
        return void 0 === e && (e = !0), void 0 === r && (r = zipToList), this.rowMajorBatch(t, e).map(function (t) {
          return deepZip(t, r);
        });
      }, t.prototype.concatenate = function (t, e) {
        return new ChainedIterator(iteratorFromItems([this, t]), e);
      }, t.prototype.take = function (t) {
        return t < 0 || null == t ? this : new TakeIterator(this, t);
      }, t.prototype.skip = function (t) {
        return t < 0 || null == t ? this : new SkipIterator(this, t);
      }, t.prototype.prefetch = function (t) {
        return new PrefetchIterator(this, t);
      }, t.prototype.shuffle = function (t, e) {
        return new ShuffleIterator(this, t, e);
      }, t.prototype.serial = function () {
        return new SerialIterator(this);
      }, t;
    }(),
        ArrayIterator = function (t) {
      function e(e) {
        var r = t.call(this) || this;return r.items = e, r.trav = 0, r;
      }return __extends$1(e, t), e.prototype.summary = function () {
        return "Array of " + this.items.length + " items";
      }, e.prototype.next = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t;return __generator$2(this, function (e) {
            return this.trav >= this.items.length ? [2, { value: null, done: !0 }] : (t = this.items[this.trav], this.trav++, [2, { value: deepClone(t), done: !1 }]);
          });
        });
      }, e;
    }(LazyIterator),
        FunctionCallIterator = function (t) {
      function e(e) {
        var r = t.call(this) || this;return r.nextFn = e, r;
      }return __extends$1(e, t), e.prototype.summary = function () {
        return "Function call";
      }, e.prototype.next = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          return __generator$2(this, function (t) {
            try {
              return [2, this.nextFn()];
            } catch (t) {
              throw t.message = "Error thrown while iterating through a dataset: " + t.message, t;
            }return [2];
          });
        });
      }, e;
    }(LazyIterator),
        SerialIterator = function (t) {
      function e(e) {
        var r = t.call(this) || this;return r.upstream = e, r.lastRead = Promise.resolve({ value: null, done: !1 }), r;
      }return __extends$1(e, t), e.prototype.summary = function () {
        return this.upstream.summary() + " -> Serial";
      }, e.prototype.next = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t = this;return __generator$2(this, function (e) {
            return this.lastRead = this.lastRead.then(function () {
              return t.serialNext();
            }), [2, this.lastRead];
          });
        });
      }, e.prototype.serialNext = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          return __generator$2(this, function (t) {
            return [2, this.upstream.next()];
          });
        });
      }, e;
    }(LazyIterator),
        SkipIterator = function (t) {
      function e(e, r) {
        var n = t.call(this) || this;return n.upstream = e, n.maxCount = r, n.count = 0, n.lastRead = Promise.resolve({ value: null, done: !1 }), n;
      }return __extends$1(e, t), e.prototype.summary = function () {
        return this.upstream.summary() + " -> Skip";
      }, e.prototype.next = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t = this;return __generator$2(this, function (e) {
            return this.lastRead = this.lastRead.then(function () {
              return t.serialNext();
            }), [2, this.lastRead];
          });
        });
      }, e.prototype.serialNext = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t;return __generator$2(this, function (e) {
            switch (e.label) {case 0:
                return this.count++ < this.maxCount ? [4, this.upstream.next()] : [3, 2];case 1:
                return (t = e.sent()).done ? [2, t] : (Le(t.value), [3, 0]);case 2:
                return [2, this.upstream.next()];}
          });
        });
      }, e;
    }(LazyIterator),
        TakeIterator = function (t) {
      function e(e, r) {
        var n = t.call(this) || this;return n.upstream = e, n.maxCount = r, n.count = 0, n;
      }return __extends$1(e, t), e.prototype.summary = function () {
        return this.upstream.summary() + " -> Take";
      }, e.prototype.next = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          return __generator$2(this, function (t) {
            return this.count++ >= this.maxCount ? [2, { value: null, done: !0 }] : [2, this.upstream.next()];
          });
        });
      }, e;
    }(LazyIterator),
        RowMajorBatchIterator = function (t) {
      function e(e, r, n) {
        void 0 === n && (n = !0);var i = t.call(this) || this;return i.upstream = e, i.batchSize = r, i.enableSmallLastBatch = n, i.lastRead = Promise.resolve({ value: null, done: !1 }), i;
      }return __extends$1(e, t), e.prototype.summary = function () {
        return this.upstream.summary() + " -> RowMajorBatch";
      }, e.prototype.next = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t = this;return __generator$2(this, function (e) {
            return this.lastRead = this.lastRead.then(function () {
              return t.serialNext();
            }), [2, this.lastRead];
          });
        });
      }, e.prototype.serialNext = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t, e;return __generator$2(this, function (r) {
            switch (r.label) {case 0:
                t = [], r.label = 1;case 1:
                return t.length < this.batchSize ? [4, this.upstream.next()] : [3, 3];case 2:
                return (e = r.sent()).done ? this.enableSmallLastBatch && t.length > 0 ? [2, { value: t, done: !1 }] : [2, { value: null, done: !0 }] : (t.push(e.value), [3, 1]);case 3:
                return [2, { value: t, done: !1 }];}
          });
        });
      }, e;
    }(LazyIterator),
        FilterIterator = function (t) {
      function e(e, r) {
        var n = t.call(this) || this;return n.upstream = e, n.predicate = r, n.lastRead = Promise.resolve({ value: null, done: !1 }), n;
      }return __extends$1(e, t), e.prototype.summary = function () {
        return this.upstream.summary() + " -> Filter";
      }, e.prototype.next = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t = this;return __generator$2(this, function (e) {
            return this.lastRead = this.lastRead.then(function () {
              return t.serialNext();
            }), [2, this.lastRead];
          });
        });
      }, e.prototype.serialNext = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t;return __generator$2(this, function (e) {
            switch (e.label) {case 0:
                return [4, this.upstream.next()];case 1:
                return (t = e.sent()).done || this.predicate(t.value) ? [2, t] : (Le(t.value), [3, 0]);case 2:
                return [2];}
          });
        });
      }, e;
    }(LazyIterator),
        MapIterator = function (t) {
      function e(e, r) {
        var n = t.call(this) || this;return n.upstream = e, n.transform = r, n;
      }return __extends$1(e, t), e.prototype.summary = function () {
        return this.upstream.summary() + " -> Map";
      }, e.prototype.next = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t, e, r, n, i, o, a$$1;return __generator$2(this, function (s) {
            switch (s.label) {case 0:
                return [4, this.upstream.next()];case 1:
                if ((t = s.sent()).done) return [2, { value: null, done: !0 }];for (e = kt.getTensorsInContainer(t.value), r = this.transform(t.value), n = kt.getTensorsInContainer(r), i = 0, o = e; i < o.length; i++) a$$1 = o[i], kt.isTensorInList(a$$1, n) || a$$1.dispose();return [2, { value: r, done: !1 }];}
          });
        });
      }, e;
    }(LazyIterator),
        ErrorHandlingLazyIterator = function (t) {
      function e(e, r) {
        var n = t.call(this) || this;return n.upstream = e, n.handler = r, n.count = 0, n.lastRead = Promise.resolve({ value: null, done: !1 }), n;
      }return __extends$1(e, t), e.prototype.summary = function () {
        return this.upstream.summary() + " -> handleErrors";
      }, e.prototype.next = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t = this;return __generator$2(this, function (e) {
            return this.lastRead = this.lastRead.then(function () {
              return t.serialNext();
            }), [2, this.lastRead];
          });
        });
      }, e.prototype.serialNext = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t;return __generator$2(this, function (e) {
            switch (e.label) {case 0:
                e.label = 1;case 1:
                return e.trys.push([1, 3,, 4]), [4, this.upstream.next()];case 2:
                return [2, e.sent()];case 3:
                return t = e.sent(), this.handler(t) ? [3, 4] : [2, { value: null, done: !0 }];case 4:
                return [3, 0];case 5:
                return [2];}
          });
        });
      }, e;
    }(LazyIterator),
        AsyncMapIterator = function (t) {
      function e(e, r) {
        var n = t.call(this) || this;return n.upstream = e, n.transform = r, n;
      }return __extends$1(e, t), e.prototype.summary = function () {
        return this.upstream.summary() + " -> AsyncMap";
      }, e.prototype.next = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t, e, r, n, i, o, a$$1;return __generator$2(this, function (s) {
            switch (s.label) {case 0:
                return [4, this.upstream.next()];case 1:
                return (t = s.sent()).done ? [2, { value: null, done: !0 }] : (e = kt.getTensorsInContainer(t.value), [4, this.transform(t.value)]);case 2:
                for (r = s.sent(), n = kt.getTensorsInContainer(r), i = 0, o = e; i < o.length; i++) a$$1 = o[i], kt.isTensorInList(a$$1, n) || a$$1.dispose();return [2, { value: r, done: !1 }];}
          });
        });
      }, e;
    }(LazyIterator),
        OneToManyIterator = function (t) {
      function e() {
        var e = t.call(this) || this;return e.outputQueue = new GrowingRingBuffer(), e.lastRead = Promise.resolve({ value: null, done: !1 }), e;
      }return __extends$1(e, t), e.prototype.next = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t = this;return __generator$2(this, function (e) {
            return this.lastRead = this.lastRead.then(function () {
              return t.serialNext();
            }), [2, this.lastRead];
          });
        });
      }, e.prototype.serialNext = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          return __generator$2(this, function (t) {
            switch (t.label) {case 0:
                return 0 !== this.outputQueue.length() ? [3, 2] : [4, this.pump()];case 1:
                return t.sent() ? [3, 0] : [2, { value: null, done: !0 }];case 2:
                return [2, { value: this.outputQueue.shift(), done: !1 }];}
          });
        });
      }, e;
    }(LazyIterator),
        FlatmapIterator = function (t) {
      function e(e, r) {
        var n = t.call(this) || this;return n.upstream = e, n.transform = r, n;
      }return __extends$1(e, t), e.prototype.summary = function () {
        return this.upstream.summary() + " -> Flatmap";
      }, e.prototype.pump = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t, e, r, n, i, o, a$$1;return __generator$2(this, function (s) {
            switch (s.label) {case 0:
                return [4, this.upstream.next()];case 1:
                if ((t = s.sent()).done) return [2, !1];for (e = kt.getTensorsInContainer(t.value), r = this.transform(t.value), n = kt.getTensorsInContainer(r), this.outputQueue.pushAll(r), i = 0, o = e; i < o.length; i++) a$$1 = o[i], kt.isTensorInList(a$$1, n) || a$$1.dispose();return [2, !0];}
          });
        });
      }, e;
    }(OneToManyIterator),
        ChainedIterator = function (t) {
      function e(e, r) {
        var n = t.call(this) || this;return n.baseErrorHandler = r, n.lastRead = null, n.iterator = null, n.moreIterators = e, n;
      }return __extends$1(e, t), e.prototype.summary = function () {
        return "TODO: fill in upstream of chained summaries -> Chained";
      }, e.prototype.next = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          return __generator$2(this, function (t) {
            return this.lastRead = this.readFromChain(this.lastRead), [2, this.lastRead];
          });
        });
      }, e.prototype.readFromChain = function (t) {
        return __awaiter$2(this, void 0, void 0, function () {
          var e, r;return __generator$2(this, function (n) {
            switch (n.label) {case 0:
                return [4, t];case 1:
                return n.sent(), null != this.iterator ? [3, 3] : [4, this.moreIterators.next()];case 2:
                if ((e = n.sent()).done) return [2, { value: null, done: !0 }];this.iterator = e.value, null != this.baseErrorHandler && (this.iterator = this.iterator.handleErrors(this.baseErrorHandler)), n.label = 3;case 3:
                return [4, this.iterator.next()];case 4:
                return (r = n.sent()).done ? (this.iterator = null, [2, this.readFromChain(t)]) : [2, r];}
          });
        });
      }, e;
    }(LazyIterator);!function (t) {
      t[t.FAIL = 0] = "FAIL", t[t.SHORTEST = 1] = "SHORTEST", t[t.LONGEST = 2] = "LONGEST";
    }(ZipMismatchMode || (ZipMismatchMode = {}));var ZipIterator = function (t) {
      function e(e, r) {
        void 0 === r && (r = ZipMismatchMode.FAIL);var n = t.call(this) || this;return n.iterators = e, n.mismatchMode = r, n.count = 0, n.currentPromise = null, n;
      }return __extends$1(e, t), e.prototype.summary = function () {
        return "{TODO: fill in upstream of zip summaries} -> Zip";
      }, e.prototype.nextState = function (t) {
        return __awaiter$2(this, void 0, void 0, function () {
          function e(t) {
            return t instanceof LazyIterator ? { value: t.next().then(function (t) {
                return r++, t.done && n++, t.value;
              }), recurse: !1 } : { value: null, recurse: !0 };
          }var r, n, i;return __generator$2(this, function (o) {
            switch (o.label) {case 0:
                return [4, t];case 1:
                return o.sent(), r = 0, n = 0, [4, deepMapAndAwaitAll(this.iterators, e)];case 2:
                if (i = o.sent(), r === n) return [2, { value: null, done: !0 }];if (n > 0) switch (this.mismatchMode) {case ZipMismatchMode.FAIL:
                    throw new Error("Zipped streams should have the same length. Mismatched at element " + this.count + ".");case ZipMismatchMode.SHORTEST:
                    return [2, { value: null, done: !0 }];case ZipMismatchMode.LONGEST:}return this.count++, [2, { value: i, done: !1 }];}
          });
        });
      }, e.prototype.next = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          return __generator$2(this, function (t) {
            switch (t.label) {case 0:
                return this.currentPromise = this.nextState(this.currentPromise), [4, this.currentPromise];case 1:
                return [2, t.sent()];}
          });
        });
      }, e;
    }(LazyIterator),
        PrefetchIterator = function (t) {
      function e(e, r) {
        var n = t.call(this) || this;return n.upstream = e, n.bufferSize = r, n.buffer = new RingBuffer(r), n;
      }return __extends$1(e, t), e.prototype.summary = function () {
        return this.upstream.summary() + " -> Prefetch";
      }, e.prototype.refill = function () {
        for (; !this.buffer.isFull();) {
          var t = this.upstream.next();this.buffer.push(t);
        }
      }, e.prototype.next = function () {
        return this.refill(), this.buffer.shift();
      }, e;
    }(LazyIterator),
        ShuffleIterator = function (t) {
      function e(e, r, n) {
        var i = t.call(this, e, r) || this;return i.upstream = e, i.windowSize = r, i.upstreamExhausted = !1, i.random = seedrandom_1(n || Z.now().toString()), i.lastRead = Promise.resolve({ value: null, done: !1 }), i;
      }return __extends$1(e, t), e.prototype.next = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t = this;return __generator$2(this, function (e) {
            return this.lastRead = this.lastRead.then(function () {
              return t.serialNext();
            }), [2, this.lastRead];
          });
        });
      }, e.prototype.randomInt = function (t) {
        return Math.floor(this.random() * t);
      }, e.prototype.chooseIndex = function () {
        return this.randomInt(this.buffer.length());
      }, e.prototype.serialNext = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t, e;return __generator$2(this, function (r) {
            switch (r.label) {case 0:
                this.upstreamExhausted || this.refill(), r.label = 1;case 1:
                return this.buffer.isEmpty() ? [3, 3] : (t = this.chooseIndex(), [4, this.buffer.shuffleExcise(t)]);case 2:
                return (e = r.sent()).done ? (this.upstreamExhausted = !0, [3, 1]) : (this.refill(), [2, e]);case 3:
                return [2, { value: null, done: !0 }];}
          });
        });
      }, e;
    }(PrefetchIterator),
        Dataset = function () {
      function t() {
        this.size = null;
      }return t.prototype.batch = function (t, e) {
        var r = this;void 0 === e && (e = !0);var n = this;return Z.assert(t > 0, function () {
          return "batchSize needs to be positive, but it is\n      " + t;
        }), datasetFromIteratorFn(function () {
          return __awaiter$2(r, void 0, void 0, function () {
            return __generator$2(this, function (r) {
              switch (r.label) {case 0:
                  return [4, n.iterator()];case 1:
                  return [2, r.sent().columnMajorBatch(t, e, deepBatchConcat)];}
            });
          });
        }, this.size === 1 / 0 || null == this.size ? this.size : e ? Math.ceil(this.size / t) : Math.floor(this.size / t));
      }, t.prototype.concatenate = function (t) {
        var e = this,
            r = this;return datasetFromIteratorFn(function () {
          return __awaiter$2(e, void 0, void 0, function () {
            var e, n;return __generator$2(this, function (i) {
              switch (i.label) {case 0:
                  return [4, r.iterator()];case 1:
                  return n = (e = i.sent()).concatenate, [4, t.iterator()];case 2:
                  return [2, n.apply(e, [i.sent()])];}
            });
          });
        }, this.size === 1 / 0 || t.size === 1 / 0 ? 1 / 0 : null != this.size && null != t.size ? this.size + t.size : null);
      }, t.prototype.filter = function (t) {
        var e = this,
            r = this;return datasetFromIteratorFn(function () {
          return __awaiter$2(e, void 0, void 0, function () {
            return __generator$2(this, function (e) {
              switch (e.label) {case 0:
                  return [4, r.iterator()];case 1:
                  return [2, e.sent().filter(function (e) {
                    return Pe(function () {
                      return t(e);
                    });
                  })];}
            });
          });
        }, this.size === 1 / 0 ? 1 / 0 : null);
      }, t.prototype.forEachAsync = function (t) {
        return __awaiter$2(this, void 0, void 0, function () {
          return __generator$2(this, function (e) {
            switch (e.label) {case 0:
                return [4, this.iterator()];case 1:
                return [2, e.sent().forEachAsync(t)];}
          });
        });
      }, t.prototype.forEach = function (t) {
        return __awaiter$2(this, void 0, void 0, function () {
          return __generator$2(this, function (e) {
            return Oe("dataset.forEach() is deprecated and will be removed. Please use dataset.forEachAsync() instead"), [2, this.forEachAsync(t)];
          });
        });
      }, t.prototype.map = function (t) {
        var e = this,
            r = this;return datasetFromIteratorFn(function () {
          return __awaiter$2(e, void 0, void 0, function () {
            return __generator$2(this, function (e) {
              switch (e.label) {case 0:
                  return [4, r.iterator()];case 1:
                  return [2, e.sent().map(function (e) {
                    return Pe(function () {
                      return t(e);
                    });
                  })];}
            });
          });
        }, this.size);
      }, t.prototype.mapAsync = function (t) {
        var e = this,
            r = this;return datasetFromIteratorFn(function () {
          return __awaiter$2(e, void 0, void 0, function () {
            return __generator$2(this, function (e) {
              switch (e.label) {case 0:
                  return [4, r.iterator()];case 1:
                  return [2, e.sent().mapAsync(t)];}
            });
          });
        }, this.size);
      }, t.prototype.prefetch = function (t) {
        var e = this;if (null == t) throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");var r = this;return datasetFromIteratorFn(function () {
          return __awaiter$2(e, void 0, void 0, function () {
            return __generator$2(this, function (e) {
              switch (e.label) {case 0:
                  return [4, r.iterator()];case 1:
                  return [2, e.sent().prefetch(t)];}
            });
          });
        }, this.size);
      }, t.prototype.repeat = function (t) {
        var e = this,
            r = this;return datasetFromIteratorFn(function () {
          return __awaiter$2(e, void 0, void 0, function () {
            var e = this;return __generator$2(this, function (n) {
              return [2, iteratorFromConcatenated(iteratorFromFunction(function () {
                return __awaiter$2(e, void 0, void 0, function () {
                  var t;return __generator$2(this, function (e) {
                    switch (e.label) {case 0:
                        return t = {}, [4, r.iterator()];case 1:
                        return [2, (t.value = e.sent(), t.done = !1, t)];}
                  });
                });
              }).take(t))];
            });
          });
        }, null != this.size && t > 0 ? this.size * t : 0 === t ? 0 : null != this.size && (void 0 === t || t < 0) ? 1 / 0 : null);
      }, t.prototype.skip = function (t) {
        var e = this,
            r = this;return datasetFromIteratorFn(function () {
          return __awaiter$2(e, void 0, void 0, function () {
            return __generator$2(this, function (e) {
              switch (e.label) {case 0:
                  return [4, r.iterator()];case 1:
                  return [2, e.sent().skip(t)];}
            });
          });
        }, null != this.size && t >= 0 && this.size >= t ? this.size - t : null != this.size && (this.size < t || void 0 === t || t < 0) ? 0 : null);
      }, t.prototype.shuffle = function (t, e, r) {
        var n = this;if (void 0 === r && (r = !0), null == t || t < 0) throw null == this.size ? new RangeError("`Dataset.shuffle()` requires bufferSize to be specified.") : new RangeError("`Dataset.shuffle()` requires bufferSize to be specified.  If your data fits in main memory (for regular JS objects), and/or GPU memory (for `tf.Tensor`s), consider setting bufferSize to the dataset size (" + this.size + " elements)");var i = this,
            o = seedrandom_1(e || Z.now().toString());return datasetFromIteratorFn(function () {
          return __awaiter$2(n, void 0, void 0, function () {
            var e;return __generator$2(this, function (n) {
              switch (n.label) {case 0:
                  return e = o.int32(), r && (e += o.int32()), [4, i.iterator()];case 1:
                  return [2, n.sent().shuffle(t, e.toString())];}
            });
          });
        }, this.size);
      }, t.prototype.take = function (t) {
        var e = this,
            r = this;return datasetFromIteratorFn(function () {
          return __awaiter$2(e, void 0, void 0, function () {
            return __generator$2(this, function (e) {
              switch (e.label) {case 0:
                  return [4, r.iterator()];case 1:
                  return [2, e.sent().take(t)];}
            });
          });
        }, null != this.size && this.size > t ? t : null != this.size && this.size <= t ? this.size : null);
      }, t.prototype.toArray = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          return __generator$2(this, function (t) {
            switch (t.label) {case 0:
                if (this.size === 1 / 0) throw new Error("Can not convert infinite data stream to array.");return [4, this.iterator()];case 1:
                return [2, t.sent().toArray()];}
          });
        });
      }, t.prototype.toArrayForTest = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          return __generator$2(this, function (t) {
            switch (t.label) {case 0:
                if (this.size === 1 / 0) throw new Error("Can not convert infinite data stream to array.");return [4, this.iterator()];case 1:
                return [2, t.sent().toArrayForTest()];}
          });
        });
      }, t.MAX_BUFFER_SIZE = 1e4, t;
    }();function datasetFromIteratorFn(t, e) {
      return void 0 === e && (e = null), new (function (r) {
        function n() {
          var t = null !== r && r.apply(this, arguments) || this;return t.size = e, t;
        }return __extends$1(n, r), n.prototype.iterator = function () {
          return __awaiter$2(this, void 0, void 0, function () {
            return __generator$2(this, function (e) {
              return [2, t()];
            });
          });
        }, n;
      }(Dataset))();
    }function array(t) {
      var e = this;return datasetFromIteratorFn(function () {
        return __awaiter$2(e, void 0, void 0, function () {
          return __generator$2(this, function (e) {
            return [2, iteratorFromItems(t)];
          });
        });
      }, t.length);
    }function zip(t) {
      var e,
          r = this;if (!isIterable(t)) throw new Error("The argument to zip() must be an object or array.");if (Array.isArray(t)) for (var n = 0; n < t.length; n++) e = null == e ? t[n].size : Math.min(e, t[n].size);else if (t instanceof Object) for (var i in t) e = null == e ? t[i].size : Math.min(e, t[i].size);return datasetFromIteratorFn(function () {
        return __awaiter$2(r, void 0, void 0, function () {
          return __generator$2(this, function (e) {
            switch (e.label) {case 0:
                return [4, deepMapAndAwaitAll(t, function (t) {
                  if (t instanceof Dataset) return { value: t.iterator(), recurse: !1 };if (isIterable(t)) return { value: null, recurse: !0 };throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.");
                })];case 1:
                return [2, iteratorFromZipped(e.sent(), ZipMismatchMode.SHORTEST)];}
          });
        });
      }, e);
    }function deepBatchConcat(t) {
      return null === t ? null : canTensorify(t[0]) ? { value: batchConcat(t), recurse: !1 } : { value: null, recurse: !0 };
    }function batchConcat(t) {
      if (0 === t.length) throw new Error("Can't make a batch of zero elements.");return t[0] instanceof ft ? gr(t) : mn(t);
    }var TextLineDataset = function (t) {
      function e(e) {
        var r = t.call(this) || this;return r.input = e, r;
      }return __extends$1(e, t), e.prototype.iterator = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t, e;return __generator$2(this, function (r) {
            switch (r.label) {case 0:
                return [4, this.input.iterator()];case 1:
                return t = r.sent(), e = t.decodeUTF8(), [2, e.split("\n").map(function (t) {
                  return t.endsWith("\r") && (t = t.slice(0, -1)), t;
                })];}
          });
        });
      }, e;
    }(Dataset),
        CODE_QUOTE = '"',
        STATE_OUT = Symbol("out"),
        STATE_FIELD = Symbol("field"),
        STATE_QUOTE = Symbol("quote"),
        STATE_QUOTE_AFTER_QUOTE = Symbol("quoteafterquote"),
        STATE_WITHIN_QUOTE_IN_QUOTE = Symbol("quoteinquote"),
        CSVDataset = function (t) {
      function e(e, r) {
        var n = t.call(this) || this;return n.input = e, n.hasHeader = !0, n.fullColumnNames = null, n.columnNamesValidated = !1, n.columnConfigs = null, n.configuredColumnsOnly = !1, n.delimiter = ",", n.delimWhitespace = !1, n.base = new TextLineDataset(e), r || (r = {}), n.hasHeader = !1 !== r.hasHeader, n.fullColumnNames = r.columnNames, n.columnConfigs = r.columnConfigs, n.configuredColumnsOnly = r.configuredColumnsOnly, r.delimWhitespace ? (Z.assert(null == r.delimiter, function () {
          return "Delimiter should not be provided when delimWhitespace is true.";
        }), n.delimWhitespace = !0, n.delimiter = " ") : n.delimiter = r.delimiter ? r.delimiter : ",", n;
      }return __extends$1(e, t), e.prototype.columnNames = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          return __generator$2(this, function (t) {
            switch (t.label) {case 0:
                return this.columnNamesValidated ? [3, 2] : [4, this.setColumnNames()];case 1:
                t.sent(), t.label = 2;case 2:
                return [2, this.configuredColumnsOnly ? Object.keys(this.columnConfigs) : this.fullColumnNames];}
          });
        });
      }, e.prototype.setColumnNames = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t,
              e,
              r,
              n,
              i,
              o,
              a$$1 = this;return __generator$2(this, function (s) {
            switch (s.label) {case 0:
                return [4, this.maybeReadHeaderLine()];case 1:
                if (t = s.sent(), !this.fullColumnNames && !t) throw new Error("Column names must be provided if there is no header line.");if (this.fullColumnNames && t && Z.assert(t.length === this.fullColumnNames.length, function () {
                  return "The length of provided columnNames (" + a$$1.fullColumnNames.length.toString() + ") does not match the length of the header line read from file (" + t.length.toString() + ").";
                }), this.fullColumnNames || (this.fullColumnNames = t), e = this.fullColumnNames.reduce(function (t, e) {
                  return t[e] = t[e] + 1 || 1, t;
                }, {}), r = Object.keys(e).filter(function (t) {
                  return e[t] > 1;
                }), Z.assert(0 === r.length, function () {
                  return "Duplicate column names found: " + r.toString();
                }), this.columnConfigs) for (n = 0, i = Object.keys(this.columnConfigs); n < i.length; n++) if (o = i[n], -1 === this.fullColumnNames.indexOf(o)) throw new Error('The key "' + o + '" provided in columnConfigs does not match any of the column names (' + this.fullColumnNames.toString() + ").");return this.columnNamesValidated = !0, [2];}
          });
        });
      }, e.prototype.maybeReadHeaderLine = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t, e;return __generator$2(this, function (r) {
            switch (r.label) {case 0:
                return this.hasHeader ? [4, this.base.iterator()] : [3, 3];case 1:
                return [4, r.sent().next()];case 2:
                if ((t = r.sent()).done) throw new Error("No data was found for CSV parsing.");return e = t.value, [2, this.parseRow(e, !1)];case 3:
                return [2, null];}
          });
        });
      }, e.prototype.iterator = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t,
              e = this;return __generator$2(this, function (r) {
            switch (r.label) {case 0:
                return this.columnNamesValidated ? [3, 2] : [4, this.setColumnNames()];case 1:
                r.sent(), r.label = 2;case 2:
                return [4, this.base.iterator()];case 3:
                return t = r.sent(), this.hasHeader && (t = t.skip(1)), [2, t.map(function (t) {
                  return e.makeDataElement(t);
                })];}
          });
        });
      }, e.prototype.makeDataElement = function (t) {
        for (var e = this.parseRow(t), r = {}, n = {}, i = 0; i < this.fullColumnNames.length; i++) {
          var o = this.fullColumnNames[i],
              a$$1 = this.columnConfigs ? this.columnConfigs[o] : null;if (!this.configuredColumnsOnly || a$$1) {
            var s = e[i],
                u = null;if ("" === s) {
              if (a$$1 && void 0 !== a$$1.default) u = a$$1.default;else {
                if (a$$1 && (a$$1.required || a$$1.isLabel)) throw new Error("Required column " + o + " is empty in this line: " + t);u = void 0;
              }
            } else {
              var c = Number(s);if (isNaN(c)) u = a$$1 && "bool" === a$$1.dtype ? this.getBoolean(s) : s;else if (a$$1 && a$$1.dtype) switch (a$$1.dtype) {case "float32":
                  u = c;break;case "int32":
                  u = Math.floor(c);break;case "bool":
                  u = this.getBoolean(s);break;default:
                  u = c;} else u = c;
            }a$$1 && a$$1.isLabel ? n[o] = u : r[o] = u;
          }
        }return 0 === Object.keys(n).length ? r : { xs: r, ys: n };
      }, e.prototype.getBoolean = function (t) {
        return "1" === t || "true" === t.toLowerCase() ? 1 : 0;
      }, e.prototype.parseRow = function (t, e) {
        void 0 === e && (e = !0);for (var r = [], n = 0, i = t.length, o = STATE_OUT, a$$1 = 0; a$$1 < i; a$$1++) switch (o) {case STATE_OUT:
            switch (t.charAt(a$$1)) {case CODE_QUOTE:
                n = a$$1 + 1, o = STATE_QUOTE;break;case this.delimiter:
                if (n = a$$1 + 1, " " === this.delimiter && this.delimWhitespace) break;r.push(""), o = STATE_OUT;break;default:
                o = STATE_FIELD, n = a$$1;}break;case STATE_FIELD:
            switch (t.charAt(a$$1)) {case this.delimiter:
                r.push(t.substring(n, a$$1)), o = STATE_OUT, n = a$$1 + 1;}break;case STATE_QUOTE:
            switch (t.charAt(a$$1)) {case CODE_QUOTE:
                o = STATE_QUOTE_AFTER_QUOTE;}break;case STATE_QUOTE_AFTER_QUOTE:
            switch (t.charAt(a$$1)) {case this.delimiter:
                r.push(t.substring(n, a$$1 - 1)), o = STATE_OUT, n = a$$1 + 1;break;case CODE_QUOTE:
                o = STATE_QUOTE;break;default:
                o = STATE_WITHIN_QUOTE_IN_QUOTE;}break;case STATE_WITHIN_QUOTE_IN_QUOTE:
            switch (t.charAt(a$$1)) {case CODE_QUOTE:
                o = STATE_QUOTE;}}if (o === STATE_QUOTE_AFTER_QUOTE ? r.push(t.substring(n, i - 1)) : r.push(t.substring(n)), e && r.length !== this.fullColumnNames.length) throw new Error("Invalid row in csv file. Should have " + this.fullColumnNames.length + " elements in a row, but got " + r);return r;
      }, e;
    }(Dataset),
        MicrophoneIterator = function (t) {
      function e(e) {
        var r = t.call(this) || this;r.microphoneConfig = e, r.isClosed = !1, r.fftSize = e.fftSize || 1024;var n = Math.log2(r.fftSize);if (r.fftSize < 0 || n < 4 || n > 14 || !Number.isInteger(n)) throw new Error("Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got " + r.fftSize);if (r.numFrames = e.numFramesPerSpectrogram || 43, r.sampleRateHz = e.sampleRateHz, r.columnTruncateLength = e.columnTruncateLength || r.fftSize, r.audioTrackConstraints = e.audioTrackConstraints, r.smoothingTimeConstant = e.smoothingTimeConstant || 0, r.includeSpectrogram = !1 !== e.includeSpectrogram, r.includeWaveform = !0 === e.includeWaveform, !r.includeSpectrogram && !r.includeWaveform) throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.");return r;
      }return __extends$1(e, t), e.prototype.summary = function () {
        return "microphone";
      }, e.create = function (t) {
        return void 0 === t && (t = {}), __awaiter$2(this, void 0, void 0, function () {
          var r;return __generator$2(this, function (n) {
            switch (n.label) {case 0:
                if (exports.ENV.get("IS_NODE")) throw new Error("microphone API is only supported in browser environment.");return [4, (r = new e(t)).start()];case 1:
                return n.sent(), [2, r];}
          });
        });
      }, e.prototype.start = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t, e, r, n;return __generator$2(this, function (i) {
            switch (i.label) {case 0:
                return i.trys.push([0, 2,, 3]), t = this, [4, navigator.mediaDevices.getUserMedia({ audio: null == this.audioTrackConstraints || this.audioTrackConstraints, video: !1 })];case 1:
                return t.stream = i.sent(), [3, 3];case 2:
                throw e = i.sent(), new Error("Error thrown while initializing video stream: " + e.message);case 3:
                if (!this.stream) throw new Error("Could not obtain audio from microphone.");if (r = window.AudioContext || window.webkitAudioContext, this.audioContext = new r(), this.sampleRateHz) {
                  if (this.audioContext.sampleRate !== this.sampleRateHz) throw new Error("Mismatch in sampling rate: Expected: " + this.sampleRateHz + "; Actual: " + this.audioContext.sampleRate);
                } else this.sampleRateHz = this.audioContext.sampleRate;return n = this.audioContext.createMediaStreamSource(this.stream), this.analyser = this.audioContext.createAnalyser(), this.analyser.fftSize = 2 * this.fftSize, this.analyser.smoothingTimeConstant = this.smoothingTimeConstant, n.connect(this.analyser), this.freqData = new Float32Array(this.fftSize), this.timeData = new Float32Array(this.fftSize), [2];}
          });
        });
      }, e.prototype.next = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t, e, r, n, i;return __generator$2(this, function (o) {
            switch (o.label) {case 0:
                return this.isClosed ? [2, { value: null, done: !0 }] : [4, this.getAudioData()];case 1:
                return r = o.sent(), this.includeSpectrogram && (n = this.flattenQueue(r.freqDataQueue), t = this.getTensorFromAudioDataArray(n, [this.numFrames, this.columnTruncateLength, 1])), this.includeWaveform && (i = this.flattenQueue(r.timeDataQueue), e = this.getTensorFromAudioDataArray(i, [this.numFrames * this.fftSize, 1])), [2, { value: { spectrogram: t, waveform: e }, done: !1 }];}
          });
        });
      }, e.prototype.capture = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          return __generator$2(this, function (t) {
            switch (t.label) {case 0:
                return [4, this.next()];case 1:
                return [2, t.sent().value];}
          });
        });
      }, e.prototype.getAudioData = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t,
              e,
              r,
              n = this;return __generator$2(this, function (i) {
            return t = [], e = [], r = 0, [2, new Promise(function (i) {
              var o = setInterval(function () {
                n.includeSpectrogram && (n.analyser.getFloatFrequencyData(n.freqData), n.freqData[0] === -1 / 0 && i({ freqDataQueue: t, timeDataQueue: e }), t.push(n.freqData.slice(0, n.columnTruncateLength))), n.includeWaveform && (n.analyser.getFloatTimeDomainData(n.timeData), e.push(n.timeData.slice())), ++r === n.numFrames && (clearInterval(o), i({ freqDataQueue: t, timeDataQueue: e }));
              }, n.fftSize / n.sampleRateHz * 1e3);
            })];
          });
        });
      }, e.prototype.stop = function () {
        this.isClosed = !0, this.analyser.disconnect(), this.audioContext.close(), null != this.stream && this.stream.getTracks().length > 0 && this.stream.getTracks()[0].stop();
      }, e.prototype.toArray = function () {
        throw new Error("Can not convert infinite audio stream to array.");
      }, e.prototype.getSampleRate = function () {
        return this.sampleRateHz;
      }, e.prototype.flattenQueue = function (t) {
        var e = t[0].length,
            r = new Float32Array(t.length * e);return t.forEach(function (t, n) {
          return r.set(t, n * e);
        }), r;
      }, e.prototype.getTensorFromAudioDataArray = function (t, e) {
        var r = new Float32Array(Z.sizeFromShape(e));return r.set(t, r.length - t.length), mn(r, e);
      }, e;
    }(LazyIterator),
        WebcamIterator = function (t) {
      function e(e, r) {
        var n = t.call(this) || this;if (n.webcamVideoElement = e, n.webcamConfig = r, n.isClosed = !0, n.resize = !1, n.needToResize()) if (n.resize = !0, n.cropSize = [n.webcamConfig.resizeHeight, n.webcamConfig.resizeWidth], n.cropBoxInd = xn([0], "int32"), n.webcamConfig.centerCrop) {
          var i = 1 * n.webcamConfig.resizeWidth / n.webcamVideoElement.width,
              o = 1 * n.webcamConfig.resizeHeight / n.webcamVideoElement.height,
              a$$1 = (1 - i) / 2,
              s = (1 - o) / 2,
              u = a$$1 + i,
              c = o + s;n.cropBox = bn([s, a$$1, c, u], [1, 4]);
        } else n.cropBox = bn([0, 0, 1, 1], [1, 4]);return n;
      }return __extends$1(e, t), e.prototype.summary = function () {
        return "webcam";
      }, e.create = function (t, r) {
        return void 0 === r && (r = {}), __awaiter$2(this, void 0, void 0, function () {
          var n;return __generator$2(this, function (i) {
            switch (i.label) {case 0:
                if (exports.ENV.get("IS_NODE")) throw new Error("tf.data.webcam is only supported in browser environment.");if (!t) {
                  if (t = document.createElement("video"), !r.resizeWidth || !r.resizeHeight) throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");t.width = r.resizeWidth, t.height = r.resizeHeight;
                }return [4, (n = new e(t, r)).start()];case 1:
                return i.sent(), [2, n];}
          });
        });
      }, e.prototype.start = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t,
              e,
              r = this;return __generator$2(this, function (n) {
            switch (n.label) {case 0:
                this.webcamConfig.facingMode && Z.assert("user" === this.webcamConfig.facingMode || "environment" === this.webcamConfig.facingMode, function () {
                  return "Invalid webcam facing mode: " + r.webcamConfig.facingMode + ". Please provide 'user' or 'environment'";
                }), n.label = 1;case 1:
                return n.trys.push([1, 3,, 4]), t = this, [4, navigator.mediaDevices.getUserMedia({ video: { deviceId: this.webcamConfig.deviceId, facingMode: this.webcamConfig.facingMode ? this.webcamConfig.facingMode : "user", width: this.webcamVideoElement.width, height: this.webcamVideoElement.height } })];case 2:
                return t.stream = n.sent(), [3, 4];case 3:
                throw (e = n.sent()).message = "Error thrown while initializing video stream: " + e.message, e;case 4:
                if (!this.stream) throw new Error("Could not obtain video from webcam.");try {
                  this.webcamVideoElement.srcObject = this.stream;
                } catch (t) {
                  console.log(t), this.webcamVideoElement.src = window.URL.createObjectURL(this.stream);
                }return this.webcamVideoElement.play(), this.isClosed = !1, [2, new Promise(function (t) {
                  r.webcamVideoElement.onloadedmetadata = function () {
                    t();
                  };
                })];}
          });
        });
      }, e.prototype.next = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t;return __generator$2(this, function (e) {
            if (this.isClosed) return [2, { value: null, done: !0 }];try {
              t = Dh.fromPixels(this.webcamVideoElement);
            } catch (t) {
              throw new Error("Error thrown converting video to pixels: " + JSON.stringify(t));
            }if (!this.resize) return [2, { value: t, done: !1 }];try {
              return [2, { value: this.cropAndResizeFrame(t), done: !1 }];
            } catch (t) {
              throw new Error("Error thrown cropping the video: " + t.message);
            } finally {
              t.dispose();
            }return [2];
          });
        });
      }, e.prototype.needToResize = function () {
        return !(!this.webcamConfig.resizeWidth || !this.webcamConfig.resizeHeight || this.webcamVideoElement.width === this.webcamConfig.resizeWidth && this.webcamVideoElement.height === this.webcamConfig.resizeHeight);
      }, e.prototype.cropAndResizeFrame = function (t) {
        var e = this;return Pe(function () {
          var r,
              n = t.toFloat().expandDims(0),
              i = (r = Rc.cropAndResize(n, e.cropBox, e.cropBoxInd, e.cropSize, "bilinear")).shape;return r.reshape(i.slice(1));
        });
      }, e.prototype.capture = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          return __generator$2(this, function (t) {
            switch (t.label) {case 0:
                return [4, this.next()];case 1:
                return [2, t.sent().value];}
          });
        });
      }, e.prototype.stop = function () {
        this.stream.getTracks().forEach(function (t) {
          return t.stop();
        });try {
          this.webcamVideoElement.srcObject = null;
        } catch (t) {
          console.log(t), this.webcamVideoElement.src = null;
        }this.isClosed = !0;
      }, e.prototype.toArray = function () {
        throw new Error("Can not convert infinite video stream to array.");
      }, e;
    }(LazyIterator),
        DataSource = function () {
      return function () {};
    }(),
        StringIterator = function (t) {
      function e() {
        return null !== t && t.apply(this, arguments) || this;
      }return __extends$1(e, t), e.prototype.split = function (t) {
        return new SplitIterator(this, t);
      }, e;
    }(LazyIterator),
        SplitIterator = function (t) {
      function e(e, r) {
        var n = t.call(this) || this;return n.upstream = e, n.impl = new SplitIteratorImpl(e, r), n;
      }return __extends$1(e, t), e.prototype.summary = function () {
        return this.impl.summary();
      }, e.prototype.next = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          return __generator$2(this, function (t) {
            return [2, this.impl.next()];
          });
        });
      }, e;
    }(StringIterator),
        SplitIteratorImpl = function (t) {
      function e(e, r) {
        var n = t.call(this) || this;return n.upstream = e, n.separator = r, n.carryover = "", n;
      }return __extends$1(e, t), e.prototype.summary = function () {
        return this.upstream.summary() + " -> Split('" + this.separator + "')";
      }, e.prototype.pump = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t, e, r, n, i;return __generator$2(this, function (o) {
            switch (o.label) {case 0:
                return [4, this.upstream.next()];case 1:
                if ((t = o.sent()).done) return "" === this.carryover ? [2, !1] : (this.outputQueue.push(this.carryover), this.carryover = "", [2, !0]);for ((e = t.value.split(this.separator))[0] = this.carryover + e[0], r = 0, n = e.slice(0, -1); r < n.length; r++) i = n[r], this.outputQueue.push(i);return this.carryover = e[e.length - 1], [2, !0];}
          });
        });
      }, e;
    }(OneToManyIterator),
        ByteChunkIterator = function (t) {
      function e() {
        return null !== t && t.apply(this, arguments) || this;
      }return __extends$1(e, t), e.prototype.decodeUTF8 = function () {
        return new Utf8Iterator(this);
      }, e;
    }(LazyIterator),
        Utf8Iterator = function (t) {
      function e(e) {
        var r = t.call(this) || this;return r.upstream = e, r.impl = new Utf8IteratorImpl(e), r;
      }return __extends$1(e, t), e.prototype.summary = function () {
        return this.impl.summary();
      }, e.prototype.next = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          return __generator$2(this, function (t) {
            return [2, this.impl.next()];
          });
        });
      }, e;
    }(StringIterator),
        Utf8IteratorImpl = function (t) {
      function e(e) {
        var r = t.call(this) || this;if (r.upstream = e, exports.ENV.get("IS_BROWSER")) r.decoder = new TextDecoder("utf-8");else {
          var n = require("string_decoder").StringDecoder;r.decoder = new n("utf8");
        }return r;
      }return __extends$1(e, t), e.prototype.summary = function () {
        return this.upstream.summary() + " -> Utf8";
      }, e.prototype.pump = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t, e, r;return __generator$2(this, function (n) {
            switch (n.label) {case 0:
                return [4, this.upstream.next()];case 1:
                return (t = n.sent()).done ? [2, !1] : (e = t.value, r = exports.ENV.get("IS_BROWSER") ? this.decoder.decode(e, { stream: !0 }) : this.decoder.write(Buffer.from(e.buffer)), this.outputQueue.push(r), [2, !0]);}
          });
        });
      }, e;
    }(OneToManyIterator),
        FileChunkIterator = function (t) {
      function e(e, r) {
        void 0 === r && (r = {});var n = t.call(this) || this;return n.file = e, n.options = r, Z.assert(e instanceof Uint8Array || !!exports.ENV.get("IS_BROWSER") && (e instanceof File || e instanceof Blob), function () {
          return "FileChunkIterator only supports File, Blob and Uint8Array right now.";
        }), n.offset = r.offset || 0, n.chunkSize = r.chunkSize || 1048576, n;
      }return __extends$1(e, t), e.prototype.summary = function () {
        return "FileChunks " + this.file;
      }, e.prototype.next = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t,
              e,
              r = this;return __generator$2(this, function (n) {
            switch (n.label) {case 0:
                return this.offset >= (this.file instanceof Uint8Array ? this.file.byteLength : this.file.size) ? [2, { value: null, done: !0 }] : (t = new Promise(function (t, e) {
                  var n = r.offset + r.chunkSize;if (r.file instanceof Uint8Array) t(new Uint8Array(r.file.slice(r.offset, n)));else {
                    var i = new FileReader();i.onload = function (r) {
                      var n = i.result;if (n instanceof ArrayBuffer && (n = new Uint8Array(n)), !(n instanceof Uint8Array)) return e(new TypeError("FileReader returned unknown type."));t(n);
                    }, i.onabort = function (t) {
                      return e(new Error("Aborted"));
                    }, i.onerror = function (t) {
                      return e(new Error(t.type));
                    };var o = r.file.slice(r.offset, n);i.readAsArrayBuffer(o);
                  }r.offset = n;
                }), e = {}, [4, t]);case 1:
                return [2, (e.value = n.sent(), e.done = !1, e)];}
          });
        });
      }, e;
    }(ByteChunkIterator);function urlChunkIterator(t, e) {
      return void 0 === e && (e = {}), __awaiter$2(this, void 0, void 0, function () {
        var r, n, i, o, a$$1;return __generator$2(this, function (s) {
          switch (s.label) {case 0:
              return "string" == typeof t ? r = t : (r = t.url, n = getRequestInitFromRequest(t)), [4, Z.fetch(r, n)];case 1:
              return (i = s.sent()).ok ? (a$$1 = Uint8Array.bind, [4, i.arrayBuffer()]) : [3, 3];case 2:
              return o = new (a$$1.apply(Uint8Array, [void 0, s.sent()]))(), [2, new FileChunkIterator(o, e)];case 3:
              throw new Error(i.statusText);}
        });
      });
    }var getRequestInitFromRequest = function (t) {
      return { method: t.method, headers: t.headers, body: t.body, mode: t.mode, credentials: t.credentials, cache: t.cache, redirect: t.redirect, referrer: t.referrer, integrity: t.integrity };
    };function isLocalPath(t) {
      return "string" == typeof t && "file://" === t.substr(0, 7);
    }var FileDataSource = function (t) {
      function e(e, r) {
        void 0 === r && (r = {});var n = t.call(this) || this;return n.input = e, n.options = r, n;
      }return __extends$1(e, t), e.prototype.iterator = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          var t;return __generator$2(this, function (e) {
            return isLocalPath(this.input) && exports.ENV.get("IS_NODE") && (t = require("fs"), this.input = t.readFileSync(this.input.substr(7))), [2, new FileChunkIterator(this.input, this.options)];
          });
        });
      }, e;
    }(DataSource),
        URLDataSource = function (t) {
      function e(e, r) {
        void 0 === r && (r = {});var n = t.call(this) || this;return n.url = e, n.fileOptions = r, n;
      }return __extends$1(e, t), e.prototype.iterator = function () {
        return __awaiter$2(this, void 0, void 0, function () {
          return __generator$2(this, function (t) {
            return isLocalPath(this.url) ? [2, new FileDataSource(this.url, this.fileOptions).iterator()] : [2, urlChunkIterator(this.url, this.fileOptions)];
          });
        });
      }, e;
    }(DataSource);function csv(t, e) {
      return void 0 === e && (e = {}), new CSVDataset(new URLDataSource(t), e);
    }function func(t) {
      var e = this,
          r = iteratorFromFunction(t);return datasetFromIteratorFn(function () {
        return __awaiter$2(e, void 0, void 0, function () {
          return __generator$2(this, function (t) {
            return [2, r];
          });
        });
      });
    }function generator(t) {
      var e = this;return datasetFromIteratorFn(function () {
        return __awaiter$2(e, void 0, void 0, function () {
          var e;return __generator$2(this, function (r) {
            switch (r.label) {case 0:
                return [4, t()];case 1:
                return e = r.sent(), [2, iteratorFromFunction(function () {
                  return e.next();
                })];}
          });
        });
      });
    }function webcam(t, e) {
      return __awaiter$2(this, void 0, void 0, function () {
        return __generator$2(this, function (r) {
          return [2, WebcamIterator.create(t, e)];
        });
      });
    }function microphone(t) {
      return __awaiter$2(this, void 0, void 0, function () {
        return __generator$2(this, function (e) {
          return [2, MicrophoneIterator.create(t)];
        });
      });
    }var version$2 = "1.2.3";
  
    var tfData_esm = /*#__PURE__*/Object.freeze({
      array: array,
      Dataset: Dataset,
      zip: zip,
      CSVDataset: CSVDataset,
      TextLineDataset: TextLineDataset,
      csv: csv,
      func: func,
      generator: generator,
      microphone: microphone,
      webcam: webcam,
      FileDataSource: FileDataSource,
      URLDataSource: URLDataSource,
      version_data: version$2
    });
  
    /** @license See the LICENSE file. */
    // This code is auto-generated, do not modify this file!
    var version$3 = '1.2.3';
  
    /**
     * @license
     * Copyright 2018 Google LLC. All Rights Reserved.
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     * http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     * =============================================================================
     */
    var version$4 = {
      'tfjs-core': Vh,
      'tfjs-data': version$2,
      'tfjs-layers': version,
      'tfjs-converter': version$1,
      'tfjs': version$3
    };
  
    exports.data = tfData_esm;
    exports.version = version$4;
    exports.AdadeltaOptimizer = Hh;
    exports.AdagradOptimizer = $h;
    exports.AdamOptimizer = jh;
    exports.AdamaxOptimizer = Kh;
    exports.DataStorage = $r;
    exports.Environment = a;
    exports.KernelBackend = jr;
    exports.MomentumOptimizer = Yh;
    exports.Optimizer = qh;
    exports.RMSPropOptimizer = Qh;
    exports.SGDOptimizer = Xh;
    exports.Tensor = ft;
    exports.TensorBuffer = lt;
    exports.Variable = dt;
    exports.abs = is;
    exports.acos = ss;
    exports.acosh = us;
    exports.add = Zu;
    exports.addN = tl;
    exports.addStrict = el;
    exports.all = Tu;
    exports.any = Du;
    exports.argMax = _u;
    exports.argMin = Ou;
    exports.asin = ls;
    exports.asinh = cs;
    exports.atan = hs;
    exports.atan2 = nl;
    exports.atanh = ps;
    exports.avgPool = Cu;
    exports.backend = Ke;
    exports.backend_util = co;
    exports.basicLSTMCell = Ll;
    exports.batchNorm = Qs;
    exports.batchNorm2d = Js;
    exports.batchNorm3d = Zs;
    exports.batchNorm4d = tu;
    exports.batchNormalization = Ys;
    exports.batchNormalization2d = js;
    exports.batchNormalization3d = Ks;
    exports.batchNormalization4d = Xs;
    exports.batchToSpaceND = Qn;
    exports.browser = Dh;
    exports.buffer = Xn;
    exports.cast = Jn;
    exports.ceil = fs;
    exports.clipByValue = ds;
    exports.clone = Zn;
    exports.complex = fn;
    exports.concat = _n;
    exports.concat1d = On;
    exports.concat2d = Mn;
    exports.concat3d = Fn;
    exports.concat4d = Bn;
    exports.conv1d = ou;
    exports.conv2d = au;
    exports.conv2dDerFilter = su;
    exports.conv2dTranspose = cu;
    exports.conv3d = iu;
    exports.cos = vs;
    exports.cosh = ms;
    exports.cumsum = tr;
    exports.customGrad = Vr;
    exports.deprecationWarn = Oe;
    exports.depthToSpace = er;
    exports.depthwiseConv2d = uu;
    exports.disableDeprecationWarnings = _e;
    exports.dispose = Le;
    exports.disposeVariables = Me;
    exports.div = rl;
    exports.divStrict = ol;
    exports.dot = pu;
    exports.dropout = Ql;
    exports.elu = Sl;
    exports.enableDebugMode = De;
    exports.enableProdMode = Te;
    exports.environment = l;
    exports.equal = zu;
    exports.equalStrict = Vu;
    exports.erf = gs;
    exports.exp = ys;
    exports.expandDims = nr;
    exports.expm1 = xs;
    exports.eye = rr;
    exports.fft = ql;
    exports.fill = Nn;
    exports.findBackend = He;
    exports.findBackendFactory = $e;
    exports.floor = bs;
    exports.floorDiv = al;
    exports.frame = nc;
    exports.fused = Sc;
    exports.gather = Bl;
    exports.gatherND = Yl;
    exports.getBackend = Ge;
    exports.grad = Pr;
    exports.grads = Lr;
    exports.greater = Gu;
    exports.greaterEqual = qu;
    exports.greaterEqualStrict = Hu;
    exports.greaterStrict = $u;
    exports.hammingWindow = ec;
    exports.hannWindow = tc;
    exports.ifft = Hl;
    exports.imag = vn;
    exports.image = Rc;
    exports.io = Nh;
    exports.irfft = jl;
    exports.isFinite = _s;
    exports.isInf = Ds;
    exports.isNaN = Ts;
    exports.keep = We;
    exports.leakyRelu = Nl;
    exports.less = ju;
    exports.lessEqual = Ku;
    exports.lessEqualStrict = Xu;
    exports.lessStrict = Yu;
    exports.linalg = gc;
    exports.linspace = kn;
    exports.localResponseNormalization = _l;
    exports.log = ws;
    exports.log1p = Cs;
    exports.logSigmoid = Es;
    exports.logSoftmax = Hr;
    exports.logSumExp = Mu;
    exports.logicalAnd = bl;
    exports.logicalNot = wl;
    exports.logicalOr = Cl;
    exports.logicalXor = El;
    exports.losses = fc;
    exports.matMul = hu;
    exports.math = Ah;
    exports.max = Fu;
    exports.maxPool = wu;
    exports.maximum = il;
    exports.maximumStrict = sl;
    exports.mean = Bu;
    exports.memory = Fe;
    exports.min = Pu;
    exports.minimum = ul;
    exports.minimumStrict = ll;
    exports.mod = cl;
    exports.modStrict = hl;
    exports.moments = Lu;
    exports.movingAverage = Ul;
    exports.mul = pl;
    exports.mulStrict = fl;
    exports.multiRNNCell = Wl;
    exports.multinomial = or;
    exports.neg = Rs;
    exports.nextFrame = ep;
    exports.norm = Ol;
    exports.notEqual = Qu;
    exports.notEqualStrict = Ju;
    exports.oneHot = ar;
    exports.ones = In;
    exports.onesLike = Tn;
    exports.op = pn;
    exports.outerProduct = fu;
    exports.pad = ir;
    exports.pad1d = sr;
    exports.pad2d = ur;
    exports.pad3d = lr;
    exports.pad4d = cr;
    exports.pool = Eu;
    exports.pow = dl;
    exports.powStrict = vl;
    exports.prelu = kl;
    exports.print = Yn;
    exports.prod = Uu;
    exports.profile = Be;
    exports.rand = hr;
    exports.randomNormal = pr;
    exports.randomUniform = fr;
    exports.range = An;
    exports.ready = Ve;
    exports.real = dn;
    exports.reciprocal = Is;
    exports.registerBackend = je;
    exports.relu = Al;
    exports.removeBackend = qe;
    exports.reshape = dr;
    exports.reverse = du;
    exports.reverse1d = vu;
    exports.reverse2d = mu;
    exports.reverse3d = gu;
    exports.reverse4d = yu;
    exports.rfft = $l;
    exports.round = Ss;
    exports.rsqrt = Ns;
    exports.scalar = yn;
    exports.scatterND = Gl;
    exports.selu = Tl;
    exports.separableConv2d = lu;
    exports.serialization = Fh;
    exports.setBackend = ze;
    exports.setPlatform = Xe;
    exports.setdiff1dAsync = wr;
    exports.sigmoid = ks;
    exports.sign = As;
    exports.signal = rc;
    exports.sin = Os;
    exports.sinh = Ms;
    exports.slice = Ru;
    exports.slice1d = Iu;
    exports.slice2d = Su;
    exports.slice3d = Nu;
    exports.slice4d = ku;
    exports.softmax = qr;
    exports.softplus = Fs;
    exports.spaceToBatchND = vr;
    exports.sparseToDense = Xl;
    exports.spectral = Kl;
    exports.split = Pn;
    exports.sqrt = Bs;
    exports.square = Ps;
    exports.squaredDifference = ml;
    exports.squaredDifferenceStrict = gl;
    exports.squeeze = mr;
    exports.stack = gr;
    exports.step = Ls;
    exports.stridedSlice = zl;
    exports.sub = yl;
    exports.subStrict = xl;
    exports.sum = Wu;
    exports.tan = Ws;
    exports.tanh = Us;
    exports.tensor = mn;
    exports.tensor1d = xn;
    exports.tensor2d = bn;
    exports.tensor3d = wn;
    exports.tensor4d = Cn;
    exports.tensor5d = En;
    exports.tensor6d = Rn;
    exports.tensor_util = kt;
    exports.test_util = zh;
    exports.tidy = Pe;
    exports.tile = yr;
    exports.time = Ue;
    exports.topk = Vl;
    exports.train = Zh;
    exports.transpose = Dl;
    exports.truncatedNormal = xr;
    exports.unsortedSegmentSum = Pl;
    exports.unstack = br;
    exports.util = Z;
    exports.valueAndGrad = Wr;
    exports.valueAndGrads = Ur;
    exports.variable = bt;
    exports.variableGrads = zr;
    exports.version_core = Vh;
    exports.webgl = Gh;
    exports.where = Rl;
    exports.whereAsync = Il;
    exports.zeros = Sn;
    exports.zerosLike = Dn;
    exports.constraints = exports_constraints;
    exports.initializers = exports_initializers;
    exports.layers = exports_layers;
    exports.metrics = exports_metrics;
    exports.models = exports_models;
    exports.regularizers = exports_regularizers;
    exports.CallbackList = CallbackList;
    exports.CustomCallback = CustomCallback;
    exports.History = History;
    exports.Callback = Callback;
    exports.callbacks = callbacks;
    exports.EarlyStopping = EarlyStopping;
    exports.InputSpec = InputSpec;
    exports.SymbolicTensor = SymbolicTensor;
    exports.LayersModel = LayersModel;
    exports.input = input;
    exports.loadLayersModel = loadLayersModel;
    exports.model = model;
    exports.registerCallbackConstructor = registerCallbackConstructor;
    exports.sequential = sequential;
    exports.RNN = RNN;
    exports.Sequential = Sequential;
    exports.LayerVariable = LayerVariable;
    exports.version_layers = version;
    exports.GraphModel = GraphModel;
    exports.loadGraphModel = loadGraphModel;
    exports.deregisterOp = deregisterOp;
    exports.registerOp = registerOp;
    exports.version_converter = version$1;
  
    Object.defineProperty(exports, '__esModule', { value: true });
  
  })));
  //# sourceMappingURL=tf.js.map
  