mirror of
https://github.com/pierre42100/ComunicWeb
synced 2024-12-29 04:08:50 +00:00
4 lines
881 KiB
JavaScript
4 lines
881 KiB
JavaScript
// @tensorflow/tfjs Copyright 2019 Google
|
|
!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e(t.tf=t.tf||{})}(this,function(t){"use strict";var e=function(t,n){return(e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,n)};function n(t,n){function r(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}function r(t,e,n,r){return new(n||(n=Promise))(function(i,a){function o(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?i(t.value):new n(function(e){e(t.value)}).then(o,s)}u((r=r.apply(t,e||[])).next())})}function i(t,e){var n,r,i,a,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[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(;o;)try{if(n=1,r&&(i=2&a[0]?r.return:a[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,a[1])).done)return i;switch(r=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,r=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!(i=(i=o.trys).length>0&&i[i.length-1])&&(6===a[0]||2===a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){o.label=a[1];break}if(6===a[0]&&o.label<i[1]){o.label=i[1],i=a;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(a);break}i[2]&&o.ops.pop(),o.trys.pop();continue}a=e.call(t,o)}catch(t){a=[6,t],r=0}finally{n=i=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,n,r=(e=this.global.location.search,n={},e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,function(t){for(var e=[],r=1;r<arguments.length;r++)e[r-1]=arguments[r];return function(t,e,n){t[decodeURIComponent(e)]=decodeURIComponent(n||"")}(n,e[0],e[1]),e.join("=")}),n);"tfjsflags"in r&&r.tfjsflags.split(",").forEach(function(e){var n=e.split(":"),r=n[0],i=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,i)})}},t}();function o(){return t.ENV}function s(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 u(t,e,n){return Math.max(t,Math.min(e,n))}function l(t){return t%2==0?t:t+1}function c(t){for(var e=0,n=0;n<t.length;n++)e+=t[n];return e}function p(t,e){if(!t)throw new Error("string"==typeof e?e:e())}function h(t,e,n){void 0===n&&(n=""),p(g(t,e),function(){return n+" Shapes "+t+" and "+e+" must match"})}function f(t){p(null!=t,function(){return"The input to the tensor constructor must be a non-null value."})}function d(t,e,n){if(void 0===e&&(e=[]),void 0===n&&(n=!1),null==e&&(e=[]),Array.isArray(t)||T(t)&&!n)for(var r=0;r<t.length;++r)d(t[r],e,n);else e.push(t);return e}function m(t){if(0===t.length)return 1;for(var e=t[0],n=1;n<t.length;n++)e*=t[n];return e}function g(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 v(t){return t%1==0}function y(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 b(t){var e=Math.ceil(Math.sqrt(t));return[e,Math.ceil(t/e)]}function x(t,e){return e<=t.length?t:t+" ".repeat(e-t.length)}function w(t,e,n){return void 0===e&&(e=function(t){return 0}),new Promise(function(r,i){var a=0,o=function(){if(t())r();else{var s=e(++a);null!=n&&a>=n?i():setTimeout(o,s)}};o()})}function C(t,e){for(var n=1,r=-1,i=0;i<t.length;++i)if(t[i]>=0)n*=t[i];else if(-1===t[i]){if(-1!==r)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+r+" and dim "+i);r=i}else if(t[i]<0)throw Error("Shapes can not be < 0. Found "+t[i]+" at dim "+i);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 N(t,e){var n=e.length;return p((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}),p(t.every(function(t){return v(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 E(t,e){for(var n=[],r=[],i=null!=e&&Array.isArray(e)&&0===e.length,a=null==e||i?null:N(e,t).sort(),o=0,s=0;s<t.length;++s){if(null!=a){if(a[o]===s&&1!==t[s])throw new Error("Can't squeeze axis "+s+" since its dim '"+t[s]+"' is not 1");(null==a[o]||a[o]>s)&&1===t[s]&&(n.push(t[s]),r.push(s)),a[o]<=s&&o++}1!==t[s]&&(n.push(t[s]),r.push(s))}return{newShape:n,keptDims:r}}function S(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 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)n=new Uint8Array(e);else{if("string"!==t)throw new Error("Unknown data type "+t);n=new Array(e)}return n}function I(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 A(t){return"bool"===t||"complex64"===t||"float32"===t||"int32"===t||"string"===t}function R(t,e){return!("complex64"===e||"float32"===e&&"complex64"!==t||"int32"===e&&"float32"!==t&&"complex64"!==t||"bool"===e&&"bool"===t)}function T(t){return t instanceof Float32Array||t instanceof Int32Array||t instanceof Uint8Array}function D(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 O(t){if(null==t)return 0;var e=0;return t.forEach(function(t){return e+=t.length}),e}function _(t){return"string"==typeof t||t instanceof String}function F(t){return"boolean"==typeof t}function z(t){return"number"==typeof t}function M(t){return Array.isArray(t)?M(t[0]):t instanceof Float32Array?"float32":t instanceof Int32Array||t instanceof Uint8Array?"int32":z(t)?"float32":_(t)?"string":F(t)?"bool":"float32"}function L(t){return!!(t&&t.constructor&&t.call&&t.apply)}function P(t,e){for(var n=e;n<t;++n)if(t%n==0)return n;return t}function B(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 W(t,e,n){if("string"===e)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(t)&&(t=d(t)),n&&I(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),i=0;i<r.length;++i)0!==Math.round(t[i])&&(r[i]=1);return r}throw new Error("Unknown data type "+e)}function V(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 i=new Array;if(1===n.length)for(var a=n[0],o=0;o<a;o++)i[o]=r[e+o];else{a=n[0];var s=n.slice(1),u=s.reduce(function(t,e){return t*e});for(o=0;o<a;o++)i[o]=t(e+o*u,s,r)}return i}(0,t,e)}function U(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 G(){return o().platform.now()}function q(t){t.forEach(function(e){p(Number.isInteger(e)&&e>=0,function(){return"Tensor must have a shape comprised of positive integers but got shape ["+t+"]."})})}function H(t,e){return void 0===e&&(e="utf-8"),e=e||"utf-8",o().platform.encode(t,e)}function K(t,e){return void 0===e&&(e="utf-8"),e=e||"utf-8",o().platform.decode(t,e)}t.ENV=null;var $=Object.freeze({shuffle:s,clamp:u,nearestLargerEven:l,sum:c,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 i=Number(t[r])-Number(e[r]);n+=i*i}return n},assert:p,assertShapesMatch:h,assertNonNull:f,flatten:d,sizeFromShape:m,isScalarShape:function(t){return 0===t.length},arraysEqual:g,isInt:v,tanh:y,sizeToSquarishShape:b,createShuffledIndices:function(t){for(var e=new Uint32Array(t),n=0;n<t;++n)e[n]=n;return s(e),e},rightPad:x,repeatedTry:w,inferFromImplicitShape:C,parseAxisParam:N,squeezeShape:E,getTypedArrayFromDType:S,getArrayFromDType:k,checkConversionForErrors:I,isValidDtype:A,hasEncodingLoss:R,isTypedArray:T,bytesPerElement:D,bytesFromStringArray:O,isString:_,isBoolean:F,isNumber:z,inferDtype:M,isFunction:L,nearestDivisor:P,computeStrides:B,toTypedArray:W,toNestedArray:V,makeOnesTypedArray:U,makeZerosTypedArray:j,now:G,assertNonNegativeIntegerDimensions:q,fetch:function(t,e){return o().platform.fetch(t,e)},encodeString:H,decodeString:K}),X=function(){function t(t,e){this.backendTimer=t,this.logger=e,null==e&&(this.logger=new Y)}return t.prototype.profileKernel=function(t,e,n){var r,i=this,a=this.backendTimer.time(function(){r=n()});return(Array.isArray(r)?r:[r]).forEach(function(n){n.data().then(function(r){!function(t,e,n){if("float32"!==e)return!1;for(var r=0;r<t.length;r++){var i=t[r];if(isNaN(i)||!isFinite(i))return console.warn("Found "+i+" in the result of '"+n+"'"),!0}}(r,n.dtype,t),a.then(function(a){var o="";null!=a.getExtraProfileInfo&&(o=a.getExtraProfileInfo()),i.logger.logKernelProfile(t,n,r,a.kernelMs,e,o)})})}),r},t}(),Y=function(){function t(){}return t.prototype.logKernelProfile=function(t,e,n,r,i,a){var o=x(r+"ms",9),s=x(t,25),u=e.rank,l=e.size,c=x(e.shape.toString(),14),p="";for(var h in i){var f=i[h].shape,d=f.length;p+=h+": "+d+"D "+(d>0?f:"")+" "}console.log("%c"+s+"\t%c"+o+"\t%c"+u+"D "+c+"\t%c"+l+"\t%c"+p+"\t%c"+a,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")},t}(),J=20,Z=3,Q=7;function tt(t,e,n){return x(Array.isArray(t)?parseFloat(t[0].toFixed(Q))+" + "+parseFloat(t[1].toFixed(Q))+"j":_(t)?"'"+t+"'":"bool"===n?et(t):parseFloat(t.toFixed(Q)).toString(),e)}function et(t){return 0===t?"false":"true"}function nt(t){for(var e=[],n=0;n<t.length;n+=2)e.push([t[n],t[n+1]]);return e}var rt=function(){function t(t,e,n){var r=this;if(this.dtype=e,this.shape=t.slice(),this.size=m(t),null!=n){var i=n.length;p(i===this.size,function(){return"Length of values '"+i+"' 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||k(e,this.size),this.strides=B(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]),p(n.length===this.rank,function(){return"The number of provided coordinates ("+n.length+") must match the rank ("+e.rank+")"});var i=this.locToIndex(n);this.values[i]=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,i=t;r<i.length;r++){var a=i[r];if(a<0||a>=this.shape[n]){var o="Requested out of range element at "+t+". Buffer shape="+this.shape;throw new Error(o)}n++}for(var s=t[t.length-1],u=0;u<t.length-1;++u)s+=this.strides[u]*t[u];return this.values[s]},t.prototype.locToIndex=function(t){if(0===this.rank)return 0;if(1===this.rank)return t[0];for(var e=t[t.length-1],n=0;n<t.length-1;++n)e+=this.strides[n]*t[n];return e},t.prototype.indexToLoc=function(t){if(0===this.rank)return[];if(1===this.rank)return[t];for(var e=new Array(this.shape.length),n=0;n<e.length-1;++n)e[n]=Math.floor(t/this.strides[n]),t-=e[n]*this.strides[n];return e[e.length-1]=t,e},Object.defineProperty(t.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),t.prototype.toTensor=function(){return st.make(this.shape,{values:this.values},this.dtype)},t}(),it=null,at=null,ot=null,st=function(){function t(t,e,n,r,i){this.kept=!1,this.isDisposedInternal=!1,this.shape=t.slice(),this.dtype=e||"float32",this.size=m(t),this.strides=B(t),this.dataId=null!=r?r:{},this.id=it().nextTensorId(),this.rankType=this.rank<5?this.rank.toString():"higher",it().registerTensor(this,i),null!=n&&it().write(i,this.dataId,n)}return t.make=function(e,n,r,i){var a=n.values;return null!=n.values&&"string"===r&&_(n.values[0])&&(a=n.values.map(function(t){return H(t)})),new t(e,r,a,n.dataId,i)},t.prototype.flatten=function(){return this.throwIfDisposed(),this.as1D()},t.prototype.asScalar=function(){return this.throwIfDisposed(),p(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,i){return this.throwIfDisposed(),this.reshape([t,e,n,r,i])},t.prototype.asType=function(t){return this.throwIfDisposed(),at.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 i(this,function(e){switch(e.label){case 0:return[4,this.data()];case 1:return t=e.sent(),[2,at.buffer(this.shape,this.dtype,t)]}})})},t.prototype.bufferSync=function(){return at.buffer(this.shape,this.dtype,this.dataSync())},t.prototype.array=function(){return r(this,void 0,void 0,function(){var t;return i(this,function(e){switch(e.label){case 0:return[4,this.data()];case 1:return t=e.sent(),[2,V(this.shape,t)]}})})},t.prototype.arraySync=function(){return V(this.shape,this.dataSync())},t.prototype.data=function(){return r(this,void 0,void 0,function(){var t,e;return i(this,function(n){switch(n.label){case 0:return this.throwIfDisposed(),t=it().read(this.dataId),"string"!==this.dtype?[3,2]:[4,t];case 1:e=n.sent();try{return[2,e.map(function(t){return K(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=it().readSync(this.dataId);if("string"===this.dtype)try{return t.map(function(t){return K(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 i(this,function(e){switch(e.label){case 0:return this.throwIfDisposed(),[4,it().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||(it().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),at.print(this,t)},t.prototype.reshape=function(t){return this.throwIfDisposed(),at.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),at.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),at.cumsum(this,t,e,n)},t.prototype.squeeze=function(t){return this.throwIfDisposed(),at.squeeze(this,t)},t.prototype.clone=function(){return this.throwIfDisposed(),at.clone(this)},t.prototype.oneHot=function(t,e,n){return this.throwIfDisposed(),at.oneHot(this,t,e,n)},t.prototype.toString=function(t){return void 0===t&&(t=!1),function(t,e,n,r){var i=B(e),a=function(t,e,n,r){var i=m(e),a=r[r.length-1],o=new Array(a).fill(0),s=e.length,u="complex64"===n?nt(t):t;if(s>1)for(var l=0;l<i/a;l++)for(var c=l*a,p=0;p<a;p++)o[p]=Math.max(o[p],tt(u[c+p],0,n).length);return o}(t,e,n,i),o=e.length,s=function t(e,n,r,i,a,o){void 0===o&&(o=!0);var s="complex64"===r?2:1,u=n[0],l=n.length;if(0===l)return"complex64"===r?[tt(nt(e)[0],0,r)]:"bool"===r?[et(e[0])]:[e[0].toString()];if(1===l){if(u>J){var c=Z*s,p=Array.from(e.slice(0,c)),h=Array.from(e.slice(u-Z*s,u));return"complex64"===r&&(p=nt(p),h=nt(h)),["["+p.map(function(t,e){return tt(t,a[e],r)}).join(", ")+", ..., "+h.map(function(t,e){return tt(t,a[u-Z+e],r)}).join(", ")+"]"]}return["["+("complex64"===r?nt(e):Array.from(e)).map(function(t,e){return tt(t,a[e],r)}).join(", ")+"]"]}var f=n.slice(1),d=i.slice(1),m=i[0]*s,g=[];if(u>J){for(var v=0;v<Z;v++){var y=(b=v*m)+m;g.push.apply(g,t(e.slice(b,y),f,r,d,a,!1))}for(g.push("..."),v=u-Z;v<u;v++)y=(b=v*m)+m,g.push.apply(g,t(e.slice(b,y),f,r,d,a,v===u-1))}else for(v=0;v<u;v++){var b;y=(b=v*m)+m,g.push.apply(g,t(e.slice(b,y),f,r,d,a,v===u-1))}var x=2===l?",":"";for(g[0]="["+g[0]+x,v=1;v<g.length-1;v++)g[v]=" "+g[v]+x;var w=",\n";for(v=2;v<l;v++)w+="\n";return g[g.length-1]=" "+g[g.length-1]+"]"+(o?"":w),g}(t,e,n,i,a),u=["Tensor"];return r&&(u.push(" dtype: "+n),u.push(" rank: "+o),u.push(" shape: ["+e+"]"),u.push(" values:")),u.push(s.map(function(t){return" "+t}).join("\n")),u.join("\n")}(this.dataSync(),this.shape,this.dtype,t)},t.prototype.tile=function(t){return this.throwIfDisposed(),at.tile(this,t)},t.prototype.gather=function(t,e){return void 0===e&&(e=0),this.throwIfDisposed(),at.gather(this,t,e)},t.prototype.matMul=function(t,e,n){return void 0===e&&(e=!1),void 0===n&&(n=!1),this.throwIfDisposed(),at.matMul(this,t,e,n)},t.prototype.dot=function(t){return this.throwIfDisposed(),at.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(),at.norm(this,t,e,n)},t.prototype.slice=function(t,e){return this.throwIfDisposed(),at.slice(this,t,e)},t.prototype.reverse=function(t){return this.throwIfDisposed(),at.reverse(this,t)},t.prototype.concat=function(e,n){return void 0===n&&(n=0),this.throwIfDisposed(),e instanceof t&&(e=[e]),at.concat([this].concat(e),n)},t.prototype.split=function(t,e){return void 0===e&&(e=0),this.throwIfDisposed(),at.split(this,t,e)},t.prototype.stack=function(t,e){return void 0===e&&(e=0),at.stack([this,t],e)},t.prototype.unstack=function(t){return void 0===t&&(t=0),at.unstack(this,t)},t.prototype.pad=function(t,e){return void 0===e&&(e=0),at.pad(this,t,e)},t.prototype.batchNormalization=function(t,e,n,r,i){return void 0===n&&(n=.001),ot("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon"),this.batchNorm(t,e,i,r,n)},t.prototype.batchNorm=function(t,e,n,r,i){return void 0===i&&(i=.001),this.throwIfDisposed(),at.batchNorm(this,t,e,n,r,i)},t.prototype.all=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),at.all(this,t,e)},t.prototype.any=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),at.any(this,t,e)},t.prototype.logSumExp=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),at.logSumExp(this,t,e)},t.prototype.sum=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),at.sum(this,t,e)},t.prototype.prod=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),at.prod(this,t,e)},t.prototype.mean=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),at.mean(this,t,e)},t.prototype.min=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),at.min(this,t,e)},t.prototype.max=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),at.max(this,t,e)},t.prototype.argMin=function(t){return void 0===t&&(t=null),this.throwIfDisposed(),at.argMin(this,t)},t.prototype.argMax=function(t){return void 0===t&&(t=null),this.throwIfDisposed(),at.argMax(this,t)},t.prototype.cast=function(t){return this.throwIfDisposed(),at.cast(this,t)},t.prototype.add=function(t){return this.throwIfDisposed(),at.add(this,t)},t.prototype.addStrict=function(t){return this.throwIfDisposed(),at.addStrict(this,t)},t.prototype.atan2=function(t){return this.throwIfDisposed(),at.atan2(this,t)},t.prototype.sub=function(t){return this.throwIfDisposed(),at.sub(this,t)},t.prototype.subStrict=function(t){return this.throwIfDisposed(),at.subStrict(this,t)},t.prototype.pow=function(t){return this.throwIfDisposed(),at.pow(this,t)},t.prototype.powStrict=function(t){return this.throwIfDisposed(),at.powStrict(this,t)},t.prototype.mul=function(t){return this.throwIfDisposed(),at.mul(this,t)},t.prototype.mulStrict=function(t){return this.throwIfDisposed(),at.mulStrict(this,t)},t.prototype.div=function(t){return this.throwIfDisposed(),at.div(this,t)},t.prototype.floorDiv=function(t){return this.throwIfDisposed(),at.floorDiv(this,t)},t.prototype.divStrict=function(t){return this.throwIfDisposed(),at.divStrict(this,t)},t.prototype.minimum=function(t){return this.throwIfDisposed(),at.minimum(this,t)},t.prototype.minimumStrict=function(t){return this.throwIfDisposed(),at.minimumStrict(this,t)},t.prototype.maximum=function(t){return this.throwIfDisposed(),at.maximum(this,t)},t.prototype.maximumStrict=function(t){return this.throwIfDisposed(),at.maximumStrict(this,t)},t.prototype.mod=function(t){return this.throwIfDisposed(),at.mod(this,t)},t.prototype.modStrict=function(t){return this.throwIfDisposed(),at.modStrict(this,t)},t.prototype.squaredDifference=function(t){return this.throwIfDisposed(),at.squaredDifference(this,t)},t.prototype.squaredDifferenceStrict=function(t){return this.throwIfDisposed(),at.squaredDifferenceStrict(this,t)},t.prototype.transpose=function(t){return this.throwIfDisposed(),at.transpose(this,t)},t.prototype.notEqual=function(t){return this.throwIfDisposed(),at.notEqual(this,t)},t.prototype.notEqualStrict=function(t){return this.throwIfDisposed(),at.notEqualStrict(this,t)},t.prototype.less=function(t){return this.throwIfDisposed(),at.less(this,t)},t.prototype.lessStrict=function(t){return this.throwIfDisposed(),at.lessStrict(this,t)},t.prototype.equal=function(t){return this.throwIfDisposed(),at.equal(this,t)},t.prototype.equalStrict=function(t){return this.throwIfDisposed(),at.equalStrict(this,t)},t.prototype.lessEqual=function(t){return this.throwIfDisposed(),at.lessEqual(this,t)},t.prototype.lessEqualStrict=function(t){return this.throwIfDisposed(),at.lessEqualStrict(this,t)},t.prototype.greater=function(t){return this.throwIfDisposed(),at.greater(this,t)},t.prototype.greaterStrict=function(t){return this.throwIfDisposed(),at.greaterStrict(this,t)},t.prototype.greaterEqual=function(t){return this.throwIfDisposed(),at.greaterEqual(this,t)},t.prototype.greaterEqualStrict=function(t){return this.throwIfDisposed(),at.greaterEqualStrict(this,t)},t.prototype.logicalAnd=function(t){return this.throwIfDisposed(),at.logicalAnd(this,t)},t.prototype.logicalOr=function(t){return this.throwIfDisposed(),at.logicalOr(this,t)},t.prototype.logicalNot=function(){return this.throwIfDisposed(),at.logicalNot(this)},t.prototype.logicalXor=function(t){return this.throwIfDisposed(),at.logicalXor(this,t)},t.prototype.where=function(t,e){return this.throwIfDisposed(),at.where(t,this,e)},t.prototype.neg=function(){return this.throwIfDisposed(),at.neg(this)},t.prototype.ceil=function(){return this.throwIfDisposed(),at.ceil(this)},t.prototype.floor=function(){return this.throwIfDisposed(),at.floor(this)},t.prototype.sign=function(){return this.throwIfDisposed(),at.sign(this)},t.prototype.isNaN=function(){return this.throwIfDisposed(),at.isNaN(this)},t.prototype.isInf=function(){return this.throwIfDisposed(),at.isInf(this)},t.prototype.isFinite=function(){return this.throwIfDisposed(),at.isFinite(this)},t.prototype.exp=function(){return this.throwIfDisposed(),at.exp(this)},t.prototype.expm1=function(){return this.throwIfDisposed(),at.expm1(this)},t.prototype.log=function(){return this.throwIfDisposed(),at.log(this)},t.prototype.log1p=function(){return this.throwIfDisposed(),at.log1p(this)},t.prototype.sqrt=function(){return this.throwIfDisposed(),at.sqrt(this)},t.prototype.rsqrt=function(){return this.throwIfDisposed(),at.rsqrt(this)},t.prototype.square=function(){return this.throwIfDisposed(),at.square(this)},t.prototype.reciprocal=function(){return this.throwIfDisposed(),at.reciprocal(this)},t.prototype.abs=function(){return this.throwIfDisposed(),at.abs(this)},t.prototype.clipByValue=function(t,e){return this.throwIfDisposed(),at.clipByValue(this,t,e)},t.prototype.relu=function(){return this.throwIfDisposed(),at.relu(this)},t.prototype.relu6=function(){return this.throwIfDisposed(),at.relu6(this)},t.prototype.elu=function(){return this.throwIfDisposed(),at.elu(this)},t.prototype.selu=function(){return this.throwIfDisposed(),at.selu(this)},t.prototype.leakyRelu=function(t){return void 0===t&&(t=.2),this.throwIfDisposed(),at.leakyRelu(this,t)},t.prototype.prelu=function(t){return this.throwIfDisposed(),at.prelu(this,t)},t.prototype.sigmoid=function(){return this.throwIfDisposed(),at.sigmoid(this)},t.prototype.logSigmoid=function(){return this.throwIfDisposed(),at.logSigmoid(this)},t.prototype.softplus=function(){return this.throwIfDisposed(),at.softplus(this)},t.prototype.zerosLike=function(){return this.throwIfDisposed(),at.zerosLike(this)},t.prototype.onesLike=function(){return this.throwIfDisposed(),at.onesLike(this)},t.prototype.sin=function(){return this.throwIfDisposed(),at.sin(this)},t.prototype.cos=function(){return this.throwIfDisposed(),at.cos(this)},t.prototype.tan=function(){return this.throwIfDisposed(),at.tan(this)},t.prototype.asin=function(){return this.throwIfDisposed(),at.asin(this)},t.prototype.acos=function(){return this.throwIfDisposed(),at.acos(this)},t.prototype.atan=function(){return this.throwIfDisposed(),at.atan(this)},t.prototype.sinh=function(){return this.throwIfDisposed(),at.sinh(this)},t.prototype.cosh=function(){return this.throwIfDisposed(),at.cosh(this)},t.prototype.tanh=function(){return this.throwIfDisposed(),at.tanh(this)},t.prototype.asinh=function(){return this.throwIfDisposed(),at.asinh(this)},t.prototype.acosh=function(){return this.throwIfDisposed(),at.acosh(this)},t.prototype.atanh=function(){return this.throwIfDisposed(),at.atanh(this)},t.prototype.erf=function(){return this.throwIfDisposed(),at.erf(this)},t.prototype.round=function(){return this.throwIfDisposed(),at.round(this)},t.prototype.step=function(t){return void 0===t&&(t=0),this.throwIfDisposed(),at.step(this,t)},t.prototype.softmax=function(t){return void 0===t&&(t=-1),this.throwIfDisposed(),at.softmax(this,t)},t.prototype.logSoftmax=function(t){return void 0===t&&(t=-1),this.throwIfDisposed(),at.logSoftmax(this,t)},t.prototype.resizeBilinear=function(t,e){return void 0===e&&(e=!1),this.throwIfDisposed(),at.image.resizeBilinear(this,t,e)},t.prototype.resizeNearestNeighbor=function(t,e){return void 0===e&&(e=!1),this.throwIfDisposed(),at.image.resizeNearestNeighbor(this,t,e)},t.prototype.conv1d=function(t,e,n,r,i,a){return void 0===r&&(r="NWC"),void 0===i&&(i=1),this.throwIfDisposed(),at.conv1d(this,t,e,n,r,i,a)},t.prototype.conv2d=function(t,e,n,r,i,a){return void 0===r&&(r="NHWC"),void 0===i&&(i=[1,1]),this.throwIfDisposed(),at.conv2d(this,t,e,n,r,i,a)},t.prototype.conv2dTranspose=function(t,e,n,r,i){return this.throwIfDisposed(),at.conv2dTranspose(this,t,e,n,r,i)},t.prototype.depthwiseConv2D=function(t,e,n,r,i,a){return void 0===r&&(r="NHWC"),void 0===i&&(i=[1,1]),this.throwIfDisposed(),at.depthwiseConv2d(this,t,e,n,r,i,a)},t.prototype.separableConv2d=function(t,e,n,r,i,a){return void 0===i&&(i=[1,1]),void 0===a&&(a="NHWC"),this.throwIfDisposed(),at.separableConv2d(this,t,e,n,r,i,a)},t.prototype.avgPool=function(t,e,n,r){return this.throwIfDisposed(),at.avgPool(this,t,e,n,r)},t.prototype.maxPool=function(t,e,n,r){return this.throwIfDisposed(),at.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),at.localResponseNormalization(this,t,e,n,r)},t.prototype.pool=function(t,e,n,r,i){return this.throwIfDisposed(),at.pool(this,t,e,n,r,i)},t.prototype.variable=function(t,e,n){return void 0===t&&(t=!0),this.throwIfDisposed(),ut.variable(this,t,e,n)},t.prototype.unsortedSegmentSum=function(t,e){return this.throwIfDisposed(),at.unsortedSegmentSum(this,t,e)},t.prototype.batchToSpaceND=function(t,e){return this.throwIfDisposed(),at.batchToSpaceND(this,t,e)},t.prototype.spaceToBatchND=function(t,e){return this.throwIfDisposed(),at.spaceToBatchND(this,t,e)},t.prototype.topk=function(t,e){return void 0===t&&(t=1),void 0===e&&(e=!0),this.throwIfDisposed(),at.topk(this,t,e)},t.prototype.stridedSlice=function(t,e,n,r,i,a,o,s){return void 0===r&&(r=0),void 0===i&&(i=0),void 0===a&&(a=0),void 0===o&&(o=0),void 0===s&&(s=0),this.throwIfDisposed(),at.stridedSlice(this,t,e,n,r,i,a,o,s)},t.prototype.depthToSpace=function(t,e){return this.throwIfDisposed(),at.depthToSpace(this,t,e)},t.prototype.fft=function(){return this.throwIfDisposed(),at.spectral.fft(this)},t.prototype.ifft=function(){return this.throwIfDisposed(),at.spectral.ifft(this)},t.prototype.rfft=function(){return this.throwIfDisposed(),at.spectral.rfft(this)},t.prototype.irfft=function(){return this.throwIfDisposed(),at.spectral.irfft(this)},t}();Object.defineProperty(st,Symbol.hasInstance,{value:function(t){return!!t&&null!=t.dataId&&null!=t.shape&&null!=t.dtype}});var ut=function(t){function e(e,n,r){void 0===n&&(n=!0);var i=t.call(this,e.shape,e.dtype,null,e.dataId)||this;i.trainable=n,i.name=r,null==i.name&&(i.name=it().nextVariableId().toString());try{it().registerVariable(i)}catch(t){throw it().disposeTensor(i),t}return i}return n(e,t),e.variable=function(t,n,r,i){return void 0===n&&(n=!0),null!=i&&i!==t.dtype&&(t=t.asType(i)),new e(t,n,r)},e.prototype.assign=function(t){if(t.dtype!==this.dtype)throw new Error("dtype of the new value ("+t.dtype+") and previous value ("+this.dtype+") must match");if(!g(t.shape,this.shape))throw new Error("shape of the new value ("+t.shape+") and previous value ("+this.shape+") must match");it().disposeTensor(this),this.dataId=t.dataId,it().registerTensor(this)},e.prototype.dispose=function(){it().disposeVariable(this),this.isDisposedInternal=!0},e}(st);Object.defineProperty(ut,Symbol.hasInstance,{value:function(t){return t instanceof st&&null!=t.assign&&t.assign instanceof Function}});var lt,ct,pt,ht,ft=ut.variable;!function(t){t.R0="R0",t.R1="R1",t.R2="R2",t.R3="R3",t.R4="R4",t.R5="R5",t.R6="R6"}(t.Rank||(t.Rank={})),function(t){t.float32="float32",t.int32="int32",t.bool="int32",t.complex64="complex64"}(lt||(lt={})),function(t){t.float32="float32",t.int32="int32",t.bool="bool",t.complex64="complex64"}(ct||(ct={})),function(t){t.float32="float32",t.int32="float32",t.bool="float32",t.complex64="complex64"}(pt||(pt={})),function(t){t.float32="complex64",t.int32="complex64",t.bool="complex64",t.complex64="complex64"}(ht||(ht={}));var dt={float32:pt,int32:lt,bool:ct,complex64:ht};function mt(t,e){if("string"===t||"string"===e){if("string"===t&&"string"===e)return"string";throw new Error("Can not upcast "+t+" with "+e)}return dt[t][e]}function gt(t){return mt(t,"int32")}function vt(t,e){if(t.dtype===e.dtype)return[t,e];var n=mt(t.dtype,e.dtype);return[t.cast(n),e.cast(n)]}function yt(t,e){p(t.dtype===e.dtype,function(){return"The dtypes of the first("+t.dtype+") and second("+e.dtype+") input must match"})}function bt(t){var e=[];return function t(e,n,r){if(null!=e)if(e instanceof st)n.push(e);else if(i=e,Array.isArray(i)||"object"==typeof i){var i,a=e;for(var o in a){var s=a[o];r.has(s)||(r.add(s),t(s,n,r))}}}(t,e,new Set),e}var xt,wt=Object.freeze({makeTypesMatch:vt,assertTypesMatch:yt,isTensorInList:function(t,e){for(var n=0;n<e.length;n++)if(e[n].id===t.id)return!0;return!1},getTensorsInContainer:bt}),Ct=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}(),Nt=function(){function t(t){this.ENV=t,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Ct}return t.prototype.ready=function(){return r(this,void 0,void 0,function(){var t,e,n;return i(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 i(this,function(i){switch(i.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=i.sent(),[3,3];case 2:r=n,i.label=3;case 3:if(!r)return[2,!1];i.label=4;case 4:return this.backendInstance=this.registry[t],this.profiler=new X(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 i=++this.pendingBackendInitId,a=r.then(function(n){return!(i<e.pendingBackendInitId||(e.registry[t]=n,e.pendingBackendInit=null,0))}).catch(function(n){return!(i<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),i=r.success,a=r.asyncInit;if(a||i)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,i=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");i=t}return this.scopedRun(function(){return r.startScope(i)},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=st.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,i=this,a=[],o=this.isTapeOn(),s=null!=this.state.activeScope?this.state.activeScope.name:"",u=function(t){o&&(a=t.map(function(t){return i.keep(i.clone(t))}))},l=this.state.numBytes,c=this.state.numTensors;if(this.scopedRun(function(){return i.state.kernelDepth++},function(){return i.state.kernelDepth--},function(){r=i.ENV.getBool("DEBUG")?i.profiler.profileKernel(s,e,function(){return t(i.backend,u)}):t(i.backend,u)}),o){var p={id:this.state.nextTapeNodeId++,name:s,inputs:e,outputs:Array.isArray(r)?r:[r],saved:a};null!=n&&(p.gradient=function(t){return n(t,a)}),this.state.activeTape.push(p)}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*D(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 ut||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 i(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 i={id:this.state.nextTapeNodeId++,name:this.state.activeScope.name,inputs:r,outputs:[e],gradient:function(t){var e={};return n(t).forEach(function(t,n){e[n]=function(){return t}}),e}};this.state.activeTape.push(i)},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=bt(t),r=new Set(n.map(function(t){return t.id})),i=0;i<this.state.activeScope.track.length;i++){var a=this.state.activeScope.track[i];a.kept||r.has(a.id)||a.dispose()}var o=this.state.scopeStack.pop();this.state.activeScope=0===this.state.scopeStack.length?null:this.state.scopeStack[this.state.scopeStack.length-1],n.forEach(function(t){t.kept||t.scopeId!==o.id||e.track(t)})},t.prototype.gradients=function(t,e,n,r){var i=this;if(void 0===r&&(r=!1),p(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 i.startTape()},function(){return i.endTape()},function(){return i.tidy("forward",t)});p(a instanceof st,function(){return"The result y returned by f() must be a tensor."});var o=function(t,e,n){for(var r={},i={},a=0;a<e.length;a++)r[e[a].id]=!0;for(a=0;a<t.length;a++){var o=(d=t[a]).inputs;for(var s in o){for(var u=o[s],l=!1,c=0;c<e.length;c++)if(r[u.id]){d.outputs.forEach(function(t){return r[t.id]=!0}),l=!0,i[d.id]=!0;break}if(l)break}}var p={};p[n.id]=!0;var h={};for(a=t.length-1;a>=0;a--)for(o=(d=t[a]).inputs,c=0;c<d.outputs.length;c++)if(p[d.outputs[c].id]){for(var s in o)p[o[s].id]=!0,h[d.id]=!0;break}var f=[];for(a=0;a<t.length;a++){var d;if(i[(d=t[a]).id]&&h[d.id]){var m={};for(var s in d.inputs){var g=d.inputs[s];r[g.id]&&(m[s]=g)}var v=Object.assign({},d);v.inputs=m,v.outputs=d.outputs,f.push(v)}}return f}(this.state.activeTape,e,a);if(!r&&0===o.length&&e.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",function(){var t,r,s={};s[a.id]=null==n?(r=U(m(t=a.shape),"float32"),st.make(t,{values:r})):n,function(t,e,n){for(var r=function(r){var i=e[r],a=[];if(i.outputs.forEach(function(e){var n=t[e.id];if(null!=n)a.push(n);else{var r=st.make(e.shape,{values:j(e.size,e.dtype)},e.dtype);a.push(r)}}),null==i.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+i.name+".");var o=i.gradient(1===i.outputs.length?a[0]:a),s=function(e){if(!(e in o))throw new Error("Cannot backprop through input "+e+". Available gradients found: "+Object.keys(o)+".");var r=n(function(){return o[e]()});if("float32"!==r.dtype)throw new Error("Error in gradient for op "+i.name+". The gradient of input "+e+" must have 'float32' dtype, but has '"+r.dtype+"'");var a=i.inputs[e];if(!g(r.shape,a.shape))throw new Error("Error in gradient for op "+i.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 i.inputs)s(u)},i=e.length-1;i>=0;i--)r(i)}(s,o,function(t){return i.tidy(t)});var u=e.map(function(t){return s[t.id]});return 0===i.state.gradientDepth&&(i.state.activeTape.forEach(function(t){for(var e in t.saved)t.saved[e].dispose()}),i.state.activeTape=null),{value:a,grads:u}})},t.prototype.customGrad=function(t){var e=this;return p(L(t),function(){return"The f passed in customGrad(f) must be a function."}),function(){for(var n,r=[],i=0;i<arguments.length;i++)r[i]=arguments[i];p(r.every(function(t){return t instanceof st}),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,i){return p((n=t.apply(void 0,r.concat([i]))).value instanceof st,function(){return"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"}),p(L(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 i=n.gradFunc(t,e),a=Array.isArray(i)?i:[i];p(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(...)."}),p(a.every(function(t){return t instanceof st}),function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors."});var o={};return a.forEach(function(t,e){o[e]=function(){return t}}),o})}},t.prototype.write=function(t,e,n){var r=this.state.tensorInfo.get(e),i=r.backend;if(t=t||this.backend,"string"===r.dtype){var a=O(n);this.state.numBytes+=a-r.bytes,r.bytes=a}t!==i&&(i.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 i(this,function(r){switch(r.label){case 0:return e=G(),[4,this.backend.time(t)];case 1:return(n=r.sent()).wallMs=G()-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 Ct,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}(),Et=function(){var e=function(){if(null==xt){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}xt=t}return xt}();if(null==e._tfengine){var n=new a(e);e._tfengine=new Nt(n)}return function(e){t.ENV=e}(e._tfengine.ENV),it=function(){return e._tfengine},e._tfengine}();function St(){return"undefined"!=typeof window&&null!=window.document||"undefined"!=typeof WorkerGlobalScope}var kt=o();kt.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.")}),kt.registerFlag("IS_BROWSER",function(){return St()}),kt.registerFlag("IS_NODE",function(){return"undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node}),kt.registerFlag("IS_CHROME",function(){return"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)}),kt.registerFlag("PROD",function(){return!1}),kt.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",function(){return kt.getBool("DEBUG")}),kt.registerFlag("DEPRECATION_WARNINGS_ENABLED",function(){return!0}),kt.registerFlag("IS_TEST",function(){return!1});var It,At,Rt={},Tt={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function Dt(t,e){Rt[t]=e}function Ot(t){t in Rt||(Rt[t]=function(t){if(1!==t&&2!==t)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");var e=_t(t);return e.addEventListener("webglcontextlost",function(e){e.preventDefault(),delete Rt[t]},!1),1===t?e.getContext("webgl",Tt)||e.getContext("experimental-webgl",Tt):e.getContext("webgl2",Tt)}(t));var e=Rt[t];return e.isContextLost()?(delete Rt[t],Ot(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),Rt[t])}function _t(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 Ft(t,e){return[e,t]}function zt(t){var e=m(t);return b(Math.ceil(e/4))}function Mt(t,e){return[Math.max(1,Math.ceil(e/2)),Math.max(1,Math.ceil(t/2))]}function Lt(t,e){var n,r,i,a,s,u,l,c,p,h=t;return 2===o().getNumber("WEBGL_VERSION")?(n=h.R32F,r=h.R16F,i=h.RGBA16F,a=h.RGBA32F,s=h.RED,u=4,l=1,c=h.HALF_FLOAT,p=h.FLOAT):(n=t.RGBA,r=t.RGBA,i=t.RGBA,a=h.RGBA,s=t.RGBA,u=4,l=4,c=null!=e?e.HALF_FLOAT_OES:null,p=t.FLOAT),{internalFormatFloat:n,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:i,internalFormatPackedFloat:a,textureFormatFloat:s,downloadTextureFormat:t.RGBA,downloadUnpackNumChannels:u,defaultNumChannels:l,textureTypeHalfFloat:c,textureTypeFloat:p}}function Pt(t,e,n){var r=n();return e&&function(t){var e=t.getError();if(e!==t.NO_ERROR)throw new Error("WebGL Error: "+Ut(t,e))}(t),r}!function(t){t[t.RENDER=0]="RENDER",t[t.UPLOAD=1]="UPLOAD",t[t.PIXELS=2]="PIXELS",t[t.DOWNLOAD=3]="DOWNLOAD"}(It||(It={})),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"}(At||(At={}));var Bt=5.96e-8,Wt=65504;function Vt(t){return!!(o().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||0===t||Bt<Math.abs(t)&&Math.abs(t)<Wt)}function Ut(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 jt(t,e,n){return he(t,e,function(){return t.getExtension(n)},'Extension "'+n+'" not supported on this browser.')}function Gt(t,e,n){var r=he(t,e,function(){return t.createShader(t.VERTEX_SHADER)},"Unable to create vertex WebGLShader.");if(Pt(t,e,function(){return t.shaderSource(r,n)}),Pt(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 qt(t,e,n){var r=he(t,e,function(){return t.createShader(t.FRAGMENT_SHADER)},"Unable to create fragment WebGLShader.");if(Pt(t,e,function(){return t.shaderSource(r,n)}),Pt(t,e,function(){return t.compileShader(r)}),!1===t.getShaderParameter(r,t.COMPILE_STATUS))throw function(t,e){var n=$t.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],i=t.split("\n"),a=i.length.toString().length+2,o=i.map(function(t,e){return x((e+1).toString(),a)+t}),s=0,u=0;u<o.length;u++)s=Math.max(o[u].length,s);var l=o.slice(0,r-1),c=o.slice(r-1,r),p=o.slice(r);console.log(l.join("\n")),console.log(e.split("\n")[0]),console.log("%c "+x(c[0],s),"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(p.join("\n"))}(n,t.getShaderInfoLog(r)),new Error("Failed to compile fragment shader.");return r}var Ht,Kt,$t=/ERROR: [0-9]+:([0-9]+):/g;function Xt(t,e){return he(t,e,function(){return t.createProgram()},"Unable to create WebGLProgram.")}function Yt(t,e,n){if(Pt(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 Jt(t,e,n){if(Pt(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 Zt(t,e,n){var r=he(t,e,function(){return t.createBuffer()},"Unable to create WebGLBuffer");return Pt(t,e,function(){return t.bindBuffer(t.ARRAY_BUFFER,r)}),Pt(t,e,function(){return t.bufferData(t.ARRAY_BUFFER,n,t.STATIC_DRAW)}),r}function Qt(t,e,n){var r=he(t,e,function(){return t.createBuffer()},"Unable to create WebGLBuffer");return Pt(t,e,function(){return t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,r)}),Pt(t,e,function(){return t.bufferData(t.ELEMENT_ARRAY_BUFFER,n,t.STATIC_DRAW)}),r}function te(t,e){return he(t,e,function(){return t.createTexture()},"Unable to create WebGLTexture.")}function ee(t,e){var n=o().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t<=0||e<=0){var r="["+t+"x"+e+"]";throw new Error("Requested texture size "+r+" is invalid.")}if(t>n||e>n)throw r="["+t+"x"+e+"]",new Error("Requested texture size "+r+" greater than WebGL maximum on this browser / GPU ["+n+"x"+n+"].")}function ne(t,e){return he(t,e,function(){return t.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function re(t,e,n,r,i,a,o,s){var u=t.getAttribLocation(n,r);return-1!==u&&(Pt(t,e,function(){return t.bindBuffer(t.ARRAY_BUFFER,i)}),Pt(t,e,function(){return t.vertexAttribPointer(u,a,t.FLOAT,!1,o,s)}),Pt(t,e,function(){return t.enableVertexAttribArray(u)}),!0)}function ie(t,e,n,r){fe(t,r),Pt(t,e,function(){return t.activeTexture(t.TEXTURE0+r)}),Pt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,n)})}function ae(t,e,n,r){return he(t,e,function(){return t.getUniformLocation(n,r)},'uniform "'+r+'" not present in program.')}function oe(t,e,n){return t.getUniformLocation(e,n)}function se(t,e,n,r,i,a){Pt(t,e,function(){return ie(t,e,r,a)}),Pt(t,e,function(){return t.uniform1i(i,a)})}function ue(t,e,n,r){Pt(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,r)}),Pt(t,e,function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0)})}function le(t,e,n){Pt(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,n)}),Pt(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: "+pe(t,e))}function pe(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 he(t,e,n,r){var i=Pt(t,e,function(){return n()});if(null==i)throw new Error(r);return i}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),m(t.slice(0,t.length-e))}function me(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 ge(t){var e=[1,1,1];return 0===t.length||1===t.length&&1===t[0]||(e=[de(t)].concat(me(t))),e}function ve(t,e){var n;void 0===e&&(e=!1);var r=o().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e&&(r*=2,1===(t=t.map(function(e,n){return n>=t.length-2?l(t[n]):t[n]})).length&&(t=[2,t[0]])),2!==t.length){var i=E(t);t=i.newShape}var a=m(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 s=de(t),u=2,c=2;return t.length&&(u=(n=me(t))[0],c=n[1]),b(a=s*(u/2)*(c/2)).map(function(t){return 2*t})}return b(a)}function ye(t){return t%2==0}function be(t,e){if(g(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 xe(t){if(null==Ht){var e=Ot(t);Ht=e.getParameter(e.MAX_TEXTURE_SIZE)}return Ht}function we(t){if(null==Kt){var e=Ot(t);Kt=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,Kt)}function Ce(t){if(0===t)return 0;var e=Ot(t);return Ne(e,"EXT_disjoint_timer_query_webgl2")&&2===t?2:Ne(e,"EXT_disjoint_timer_query")?1:0}function Ne(t,e){return null!=t.getExtension(e)}function Ee(t){try{if(null!=Ot(t))return!0}catch(t){return!1}return!1}function Se(t){if(0===t)return!1;var e=Ot(t);if(1===t){if(!Ne(e,"OES_texture_float"))return!1}else if(!Ne(e,"EXT_color_buffer_float"))return!1;return Ie(e)}function ke(t){if(0===t)return!1;var e=Ot(t);return 1!==t?Ne(e,"EXT_color_buffer_float")?Ie(e):!!Ne(e,"EXT_color_buffer_half_float")&&function(t,e){var n=Lt(t,e),r=t.createTexture();t.bindTexture(t.TEXTURE_2D,r),t.texImage2D(t.TEXTURE_2D,0,n.internalFormatHalfFloat,1,1,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);var i=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,i),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(i),a}(e,e.getExtension("EXT_color_buffer_half_float")):!!Ne(e,"OES_texture_float")&&!!Ne(e,"WEBGL_color_buffer_float")&&Ie(e)}function Ie(t){var e=Lt(t),n=t.createTexture();t.bindTexture(t.TEXTURE_2D,n),t.texImage2D(t.TEXTURE_2D,0,e.internalFormatFloat,1,1,0,e.textureFormatFloat,e.textureTypeFloat,null);var r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0);var i=t.checkFramebufferStatus(t.FRAMEBUFFER)===t.FRAMEBUFFER_COMPLETE;return t.bindTexture(t.TEXTURE_2D,null),t.bindFramebuffer(t.FRAMEBUFFER,null),t.deleteTexture(n),t.deleteFramebuffer(r),i}function Ae(t){return 2===t&&null!=Ot(t).fenceSync}var Re=Object.freeze({callAndCheck:Pt,canBeRepresented:Vt,getWebGLErrorMessage:Ut,getExtensionOrThrow:jt,createVertexShader:Gt,createFragmentShader:qt,createProgram:Xt,linkProgram:Yt,validateProgram:Jt,createStaticVertexBuffer:Zt,createStaticIndexBuffer:Qt,getNumChannels:function(){return 2===o().getNumber("WEBGL_VERSION")?1:4},createTexture:te,validateTextureSize:ee,createFramebuffer:ne,bindVertexBufferToProgramAttribute:re,bindTextureUnit:ie,unbindTextureUnit:function(t,e,n){fe(t,n),Pt(t,e,function(){return t.activeTexture(t.TEXTURE0+n)}),Pt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)})},getProgramUniformLocationOrThrow:ae,getProgramUniformLocation:oe,bindTextureToProgramUniformSampler:se,bindCanvasToFramebuffer:function(t,e){Pt(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,null)}),Pt(t,e,function(){return t.viewport(0,0,t.canvas.width,t.canvas.height)}),Pt(t,e,function(){return t.scissor(0,0,t.canvas.width,t.canvas.height)})},bindColorTextureToFramebuffer:ue,unbindColorTextureFromFramebuffer:le,validateFramebuffer:ce,getFramebufferErrorMessage:pe,getBatchDim:de,getRowsCols:me,getShapeAs3D:ge,getTextureShapeFromLogicalShape:ve,isReshapeFree:be,getWebGLMaxTextureSize:xe,resetMaxTextureSize:function(){Ht=null},resetMaxTexturesInShader:function(){Kt=null},getMaxTexturesInShader:we,getWebGLDisjointQueryTimerVersion:Ce,hasExtension:Ne,isWebGLVersionEnabled:Ee,isCapableOfRenderingToFloatTexture:Se,isDownloadFloatTextureEnabled:ke,isWebGLFenceEnabled:Ae}),Te=o();function De(t){o().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(t+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function Oe(){return Et.memory()}function _e(t,e){return Et.tidy(t,e)}function Fe(t){bt(t).forEach(function(t){return t.dispose()})}function ze(t){return Et.keep(t)}function Me(){return Et.backend}function Le(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];o().getBool("IS_TEST")||console.warn.apply(console,t)}function Pe(t,e){var n=t;if(T(t))return"string"===e?[]:[t.length];if(!Array.isArray(t))return[];for(var r=[];Array.isArray(n)||T(n)&&"string"!==e;)r.push(n.length),n=n[0];return Array.isArray(t)&&o().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&function t(e,n,r){if(r=r||[],Array.isArray(e)||T(e)){p(n.length>0,function(){return"Element arr["+r.join("][")+"] should be a primitive, but is an array of "+e.length+" elements"}),p(e.length===n[0],function(){return"Element arr["+r.join("][")+"] should have "+n[0]+" elements, but has "+e.length+" elements"});for(var i=n.slice(1),a=0;a<e.length;++a)t(e[a],i,r.concat(a))}else p(0===n.length,function(){return"Element arr["+r.join("][")+"] is a primitive, but should be an array/TypedArray of "+n[0]+" elements"})}(t,r,[]),r}function Be(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 We(t,e,n,r){if(void 0===r&&(r="numeric"),t instanceof st)return Be(r,t.dtype,e,n),t;var i=M(t);if("string"!==i&&["bool","int32","float32"].indexOf(r)>=0&&(i=r),Be(r,i,e,n),null==t||!T(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 s=Pe(t,i);T(t)||Array.isArray(t)||(t=[t]);var u="string"!==i?W(t,i,o().getBool("DEBUG")):d(t,[],!0);return st.make(s,{values:u},i)}function Ve(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 We(t,e+"["+r+"]",n)},r)}function Ue(t,e){for(var n=0;n<t.length;++n)if(t[t.length-n-1]!==e-1-n)return!1;return!0}function je(t,e,n){for(var r=t.length+e.length,i=[],a=0,o=0,s=0;s<r;s++)-1===n.indexOf(s)?i.push(t[a++]):i.push(e[o++]);return i}function Ge(t,e){for(var n=[],r=t.length,i=0;i<r;i++)-1===e.indexOf(i)&&n.push(t[i]);return[n,e.map(function(e){return t[e]})]}function qe(t,e){return je(t,e.map(function(t){return 1}),e)}function He(t,e,n){p(Ue(e,n),function(){return t+" supports only inner-most axes for now. Got axes "+e+" and rank-"+n+" input."})}function Ke(t,e){if(Ue(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 $e(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 Xe(t,e){for(var n=[],r=e-t;r<e;++r)n.push(r);return n}function Ye(t,e){var n=t[0].length;t.forEach(function(t,e){p(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+")"})}),p(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,i){for(var a=0;a<n;a++)p(a===e||t[a]===r[a],function(){return"Error in concat"+n+"D: Shape of tensors["+i+"] ("+t+") does not match the shape of the rest ("+r+") along the non-concatenated axis "+i+"."})})}function Je(t,e){for(var n=t[0].slice(),r=1;r<t.length;r++)n[e]+=t[r][e];return n}function Ze(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 i=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];Et.startScope(n);try{var i=r.apply(void 0,t);return i instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),Et.endScope(i),i}catch(t){throw Et.endScope(null),t}};return Object.defineProperty(i,"name",{value:n,configurable:!0}),i}Te.registerFlag("HAS_WEBGL",function(){return Te.getNumber("WEBGL_VERSION")>0}),Te.registerFlag("WEBGL_VERSION",function(){return Ee(2)?2:Ee(1)?1:0}),Te.registerFlag("WEBGL_BUFFER_SUPPORTED",function(){return 2===Te.get("WEBGL_VERSION")}),Te.registerFlag("WEBGL_CPU_FORWARD",function(){return!0}),Te.registerFlag("WEBGL_FORCE_F16_TEXTURES",function(){return!1}),Te.registerFlag("WEBGL_PACK",function(){return Te.getBool("HAS_WEBGL")}),Te.registerFlag("WEBGL_PACK_NORMALIZATION",function(){return Te.getBool("WEBGL_PACK")}),Te.registerFlag("WEBGL_PACK_CLIP",function(){return Te.getBool("WEBGL_PACK")}),Te.registerFlag("WEBGL_PACK_DEPTHWISECONV",function(){return!1}),Te.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",function(){return Te.getBool("WEBGL_PACK")}),Te.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",function(){return Te.getBool("WEBGL_PACK")}),Te.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",function(){return Te.getBool("WEBGL_PACK")}),Te.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",function(){return Te.getBool("WEBGL_PACK")}),Te.registerFlag("WEBGL_PACK_REDUCE",function(){return Te.getBool("WEBGL_PACK")}),Te.registerFlag("WEBGL_LAZILY_UNPACK",function(){return Te.getBool("WEBGL_PACK")}),Te.registerFlag("WEBGL_CONV_IM2COL",function(){return Te.getBool("WEBGL_PACK")}),Te.registerFlag("WEBGL_MAX_TEXTURE_SIZE",function(){return xe(Te.getNumber("WEBGL_VERSION"))}),Te.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",function(){return we(Te.getNumber("WEBGL_VERSION"))}),Te.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",function(){var t=Te.getNumber("WEBGL_VERSION");return 0===t?0:Ce(t)}),Te.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",function(){return Te.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}),Te.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",function(){return Se(Te.getNumber("WEBGL_VERSION"))}),Te.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",function(){return!Te.getBool("WEBGL_FORCE_F16_TEXTURES")&&Te.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")}),Te.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",function(){return ke(Te.getNumber("WEBGL_VERSION"))}),Te.registerFlag("WEBGL_FENCE_API_ENABLED",function(){return Ae(Te.getNumber("WEBGL_VERSION"))}),Te.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",function(){return Te.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0}),ot=De;var Qe=Ze({complex_:function(t,e){var n=We(t,"real","complex"),r=We(e,"imag","complex");return h(n.shape,r.shape,"real and imag shapes, "+n.shape+" and "+r.shape+", must match in call to tf.complex()."),Et.runKernel(function(t){return t.complex(n,r)},{$real:n,$imag:r})}}),tn=Ze({real_:function(t){var e=We(t,"input","real");return Et.runKernel(function(t){return t.real(e)},{$input:e})}}),en=Ze({imag_:function(t){var e=We(t,"input","imag");return Et.runKernel(function(t){return t.imag(e)},{$input:e})}});function nn(t,e,n){return rn(t,e,Pe(t,n),n)}function rn(t,e,n,r){if(null==r&&(r=M(t)),"complex64"===r)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!T(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){q(e);var i=m(e),a=m(n);p(i===a,function(){return"Based on the provided shape, ["+e+"], the tensor should have "+i+" values but has "+a});for(var s=0;s<n.length;++s){var u=n[s],l=s!==n.length-1||u!==m(e.slice(s));p(n[s]===e[s]||!l,function(){return"Error creating a new Tensor. Inferred shape ("+n+") does not match the provided shape ("+e+"). "})}}return T(t)||Array.isArray(t)||(t=[t]),e=e||n,t="string"!==r?W(t,r,o().getBool("DEBUG")):d(t,[],!0),st.make(e,{values:t},r)}function an(t,e){if((T(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&&T(t)&&!(t instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return rn(t,[],[],e)}function on(t,e){f(t);var n=Pe(t,e);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return rn(t,null,n,e)}function sn(t,e,n){if(f(t),null!=e&&2!==e.length)throw new Error("tensor2d() requires shape to have two numbers");var r=Pe(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 rn(t,e,r,n)}function un(t,e,n){if(f(t),null!=e&&3!==e.length)throw new Error("tensor3d() requires shape to have three numbers");var r=Pe(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 rn(t,e,r,n)}function ln(t,e,n){if(f(t),null!=e&&4!==e.length)throw new Error("tensor4d() requires shape to have four numbers");var r=Pe(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 rn(t,e,r,n)}function cn(t,e,n){if(f(t),null!=e&&5!==e.length)throw new Error("tensor5d() requires shape to have five numbers");var r=Pe(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 rn(t,e,r,n)}function pn(t,e,n){if(f(t),null!=e&&6!==e.length)throw new Error("tensor6d() requires shape to have six numbers");var r=Pe(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 rn(t,e=e||r,r,n)}function hn(t,e){if(void 0===e&&(e="float32"),"complex64"===e){var n=hn(t,"float32"),r=fn(t,"float32");return Qe(n,r)}var i=U(m(t),e);return st.make(t,{values:i},e)}function fn(t,e){if(void 0===e&&(e="float32"),"complex64"===e){var n=fn(t,"float32"),r=fn(t,"float32");return Qe(n,r)}var i=j(m(t),e);return st.make(t,{values:i},e)}function dn(t,e,n){return Et.runKernel(function(r){return r.fill(t,e,n)},{})}function mn(t,e,n){if(n<=0)throw new Error("The number of values should be positive.");return Et.runKernel(function(r){return r.linspace(t,e,n)},{})}function gn(t,e,n,r){if(void 0===n&&(n=1),void 0===r&&(r="float32"),0===n)throw new Error("Cannot have a step of zero");if(t===e||t<e&&n<0||e<t&&n>1)return fn([0],r);var i=j(Math.abs(Math.ceil((e-t)/n)),r);e<t&&1===n&&(n=-1),i[0]=t;for(var a=1;a<i.length;a++)i[a]=i[a-1]+n;return on(i,r)}var vn=Ze({onesLike_:function(t){var e=We(t,"x","onesLike");if("complex64"===e.dtype){var n=vn(tn(e)),r=yn(en(e));return Qe(n,r)}return Et.runKernel(function(t){return t.onesLike(e)},{$x:e},function(t,e){return{$x:function(){return yn(t)}}})}}),yn=Ze({zerosLike_:function(t){var e=We(t,"x","zerosLike");return Et.runKernel(function(t){return t.zerosLike(e)},{$x:e},function(t,e){return{$x:function(){return yn(t)}}})}}),bn=Ze({concat_:function(t,e){void 0===e&&(e=0),p(t.length>=1,function(){return"Pass at least one tensor to concat"});var n=Ve(t,"tensors","concat");"complex64"===n[0].dtype&&n.forEach(function(t){if("complex64"!==t.dtype)throw new Error("Cannot concatenate complex64 tensors with a tensor\n with dtype "+t.dtype+". ")}),e=N(e,n[0].shape)[0];var r=Je(n.map(function(t){return t.shape}),e);if(0===m(r))return nn([],r);if(1===(n=n.filter(function(t){return t.size>0})).length)return n[0];var i=n.map(function(t){return t.shape});Ye(i,e);var a=n;return Et.runKernel(function(t){return t.concat(n,e)},a,function(t){var n=i.map(function(t){return t[e]});return En(t,n,e).map(function(t){return function(){return t}})})}}),xn=Ze({concat1d_:function(t){return bn(t,0)}}),wn=Ze({concat2d_:function(t,e){return bn(t,e)}}),Cn=Ze({concat3d_:function(t,e){return bn(t,e)}}),Nn=Ze({concat4d_:function(t,e){return bn(t,e)}}),En=Ze({split_:function(t,e,n){void 0===n&&(n=0);var r,i=We(t,"x","split");return n=N(n,i.shape)[0],"number"==typeof e?(p(i.shape[n]%e==0,function(){return"Number of splits must evenly divide the axis."}),r=new Array(e).fill(i.shape[n]/e)):(p(i.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),Et.runKernel(function(t){return t.split(i,r,n)},{$x:i},function(t){return{$x:function(){return bn(t,n)}}})}});function Sn(t,e){return t(e={exports:{}},e.exports),e.exports}var kn=Sn(function(t){!function(t,e,n){function r(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}function i(t,e){var n=new function(t){var e,n=this,r=(e=4022871197,function(t){t=t.toString();for(var n=0;n<t.length;n++){var r=.02519603282416938*(e+=t.charCodeAt(n));r-=e=r>>>0,e=(r*=e)>>>0,e+=4294967296*(r-=e)}return 2.3283064365386963e-10*(e>>>0)});n.next=function(){var t=2091639*n.s0+2.3283064365386963e-10*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=t-(n.c=0|t)},n.c=1,n.s0=r(" "),n.s1=r(" "),n.s2=r(" "),n.s0-=r(t),n.s0<0&&(n.s0+=1),n.s1-=r(t),n.s1<0&&(n.s1+=1),n.s2-=r(t),n.s2<0&&(n.s2+=1),r=null}(t),i=e&&e.state,a=n.next;return a.int32=function(){return 4294967296*n.next()|0},a.double=function(){return a()+1.1102230246251565e-16*(2097152*a()|0)},a.quick=a,i&&("object"==typeof i&&r(i,n),a.state=function(){return r(n,{})}),a}e&&e.exports?e.exports=i:this.alea=i}(0,t)}),In=Sn(function(t){!function(t,e,n){function r(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e}function i(t,e){var n=new function(t){var e=this,n="";e.x=0,e.y=0,e.z=0,e.w=0,e.next=function(){var t=e.x^e.x<<11;return e.x=e.y,e.y=e.z,e.z=e.w,e.w^=e.w>>>19^t^t>>>8},t===(0|t)?e.x=t:n+=t;for(var r=0;r<n.length+64;r++)e.x^=0|n.charCodeAt(r),e.next()}(t),i=e&&e.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},a.int32=n.next,a.quick=a,i&&("object"==typeof i&&r(i,n),a.state=function(){return r(n,{})}),a}e&&e.exports?e.exports=i:this.xor128=i}(0,t)}),An=Sn(function(t){!function(t,e,n){function r(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e.v=t.v,e.d=t.d,e}function i(t,e){var n=new function(t){var e=this,n="";e.next=function(){var t=e.x^e.x>>>2;return e.x=e.y,e.y=e.z,e.z=e.w,e.w=e.v,(e.d=e.d+362437|0)+(e.v=e.v^e.v<<4^t^t<<1)|0},e.x=0,e.y=0,e.z=0,e.w=0,e.v=0,t===(0|t)?e.x=t:n+=t;for(var r=0;r<n.length+64;r++)e.x^=0|n.charCodeAt(r),r==n.length&&(e.d=e.x<<10^e.x>>>4),e.next()}(t),i=e&&e.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},a.int32=n.next,a.quick=a,i&&("object"==typeof i&&r(i,n),a.state=function(){return r(n,{})}),a}e&&e.exports?e.exports=i:this.xorwow=i}(0,t)}),Rn=Sn(function(t){!function(t,e,n){function r(t,e){return e.x=t.x.slice(),e.i=t.i,e}function i(t,e){null==t&&(t=+new Date);var n=new function(t){var e=this;e.next=function(){var t,n,r=e.x,i=e.i;return t=r[i],n=(t^=t>>>7)^t<<24,n^=(t=r[i+1&7])^t>>>10,n^=(t=r[i+3&7])^t>>>3,n^=(t=r[i+4&7])^t<<7,t=r[i+7&7],n^=(t^=t<<13)^t<<9,r[i]=n,e.i=i+1&7,n},function(t,e){var n,r=[];if(e===(0|e))r[0]=e;else for(e=""+e,n=0;n<e.length;++n)r[7&n]=r[7&n]<<15^e.charCodeAt(n)+r[n+1&7]<<13;for(;r.length<8;)r.push(0);for(n=0;n<8&&0===r[n];++n);for(8==n?r[7]=-1:r[n],t.x=r,t.i=0,n=256;n>0;--n)t.next()}(e,t)}(t),i=e&&e.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},a.int32=n.next,a.quick=a,i&&(i.x&&r(i,n),a.state=function(){return r(n,{})}),a}e&&e.exports?e.exports=i:this.xorshift7=i}(0,t)}),Tn=Sn(function(t){!function(t,e,n){function r(t,e){return e.i=t.i,e.w=t.w,e.X=t.X.slice(),e}function i(t,e){null==t&&(t=+new Date);var n=new function(t){var e=this;e.next=function(){var t,n,r=e.w,i=e.X,a=e.i;return e.w=r=r+1640531527|0,n=i[a+34&127],t=i[a=a+1&127],n^=n<<13,t^=t<<17,n^=n>>>15,t^=t>>>12,n=i[a]=n^t,e.i=a,n+(r^r>>>16)|0},function(t,e){var n,r,i,a,o,s=[],u=128;for(e===(0|e)?(r=e,e=null):(e+="\0",r=0,u=Math.max(u,e.length)),i=0,a=-32;a<u;++a)e&&(r^=e.charCodeAt((a+32)%e.length)),0===a&&(o=r),r^=r<<10,r^=r>>>15,r^=r<<4,r^=r>>>13,a>=0&&(o=o+1640531527|0,i=0==(n=s[127&a]^=r+o)?i+1:0);for(i>=128&&(s[127&(e&&e.length||0)]=-1),i=127,a=512;a>0;--a)r=s[i+34&127],n=s[i=i+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[i]=r^n;t.w=o,t.X=s,t.i=i}(e,t)}(t),i=e&&e.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},a.int32=n.next,a.quick=a,i&&(i.X&&r(i,n),a.state=function(){return r(n,{})}),a}e&&e.exports?e.exports=i:this.xor4096=i}(0,t)}),Dn=Sn(function(t){!function(t,e,n){function r(t,e){return e.a=t.a,e.b=t.b,e.c=t.c,e.d=t.d,e}function i(t,e){var n=new function(t){var e=this,n="";e.next=function(){var t=e.b,n=e.c,r=e.d,i=e.a;return t=t<<25^t>>>7^n,n=n-r|0,r=r<<24^r>>>8^i,i=i-t|0,e.b=t=t<<20^t>>>12^n,e.c=n=n-r|0,e.d=r<<16^n>>>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):n+=t;for(var r=0;r<n.length+20;r++)e.b^=0|n.charCodeAt(r),e.next()}(t),i=e&&e.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},a.int32=n.next,a.quick=a,i&&("object"==typeof i&&r(i,n),a.state=function(){return r(n,{})}),a}e&&e.exports?e.exports=i:this.tychei=i}(0,t)}),On=Sn(function(t){!function(e,n){var r,i=this,a=256,o=6,s="random",u=n.pow(a,o),l=n.pow(2,52),c=2*l,p=a-1;function h(t,p,h){var v=[],y=m(function t(e,n){var r,i=[],a=typeof e;if(n&&"object"==a)for(r in e)try{i.push(t(e[r],n-1))}catch(t){}return i.length?i:"string"==a?e:e+"\0"}((p=1==p?{entropy:!0}:p||{}).entropy?[t,g(e)]:null==t?function(){try{var t;return r&&(t=r.randomBytes)?t=t(a):(t=new Uint8Array(a),(i.crypto||i.msCrypto).getRandomValues(t)),g(t)}catch(t){var n=i.navigator,o=n&&n.plugins;return[+new Date,i,o,i.screen,g(e)]}}():t,3),v),b=new f(v),x=function(){for(var t=b.g(o),e=u,n=0;t<l;)t=(t+n)*a,e*=a,n=b.g(1);for(;t>=c;)t/=2,e/=2,n>>>=1;return(t+n)/e};return x.int32=function(){return 0|b.g(4)},x.quick=function(){return b.g(4)/4294967296},x.double=x,m(g(b.S),e),(p.pass||h||function(t,e,r,i){return i&&(i.S&&d(i,b),t.state=function(){return d(b,{})}),r?(n[s]=t,e):t})(x,y,"global"in p?p.global:this==n,p.state)}function f(t){var e,n=t.length,r=this,i=0,o=r.i=r.j=0,s=r.S=[];for(n||(t=[n++]);i<a;)s[i]=i++;for(i=0;i<a;i++)s[i]=s[o=p&o+t[i%n]+(e=s[i])],s[o]=e;(r.g=function(t){for(var e,n=0,i=r.i,o=r.j,s=r.S;t--;)e=s[i=p&i+1],n=n*a+s[p&(s[i]=s[o=p&o+e])+(s[o]=e)];return r.i=i,r.j=o,n})(a)}function d(t,e){return e.i=t.i,e.j=t.j,e.S=t.S.slice(),e}function m(t,e){for(var n,r=t+"",i=0;i<r.length;)e[p&i]=p&(n^=19*e[p&i])+r.charCodeAt(i++);return g(e)}function g(t){return String.fromCharCode.apply(0,t)}if(n["seed"+s]=h,m(n.random(),e),t.exports){t.exports=h;try{r=require("crypto")}catch(t){}}}([],Math)});On.alea=kn,On.xor128=In,On.xorwow=An,On.xorshift7=Rn,On.xor4096=Tn,On.tychei=Dn;var _n=On.alea,Fn=function(){function t(t,e,n,r,i){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=i||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 i=void 0,a=void 0,o=void 0;do{o=(i=2*this.random()-1)*i+(a=2*this.random()-1)*a}while(o>=1||0===o);var s=Math.sqrt(-2*Math.log(o)/o);e=this.mean+this.stdDev*i*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}(),zn=function(){function t(t,e,n,r){this.alpha=t,this.beta=1/e,this.dtype=n;var i=r||Math.random();this.randu=_n(i.toString()),this.randn=new Fn(0,1,n,!1,this.randu()),this.d=t<1?t+2/3:t-1/3,this.c=1/Math.sqrt(9*this.d)}return t.prototype.nextValue=function(){for(var t,e,n,r,i,a;;){do{r=this.randn.nextValue(),a=1+this.c*r}while(a<=0);if(a*=a*a,e=1-.331*(t=r*r)*t,n=.5*t+this.d*(1-a+Math.log(a)),(i=this.randu())<e||Math.log(i)<n)break}return a=1/this.beta*this.d*a,this.alpha<1&&(a*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(a)},t.prototype.convertValue=function(t){return"float32"===this.dtype?t:Math.round(t)},t}(),Mn=function(){function t(t,e,n,r){var i=this;if(void 0===t&&(t=0),void 0===e&&(e=1),this.canReturnFloat=function(){return null==i.dtype||"float32"===i.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 Ln(t,e,n){return void 0===e&&(e="float32"),e=e||"float32",q(t),new rt(t,e,n)}function Pn(t,e){void 0===e&&(e=!1),console.log(t.toString(e))}var Bn=Ze({batchToSpaceND_:function(t,e,n){var r=We(t,"x","batchToSpaceND"),i=e.reduce(function(t,e){return t*e});return p(r.rank>=1+e.length,function(){return"input rank is "+r.rank+" but should be > than blockShape.length "+e.length}),p(n.length===e.length,function(){return"crops.length is "+n.length+" but should be equal to blockShape.length "+e.length}),p(r.shape[0]%i==0,function(){return"input tensor batch is "+r.shape[0]+" but is not divisible by the product of the elements of blockShape "+e.join(" * ")+" === "+i}),Et.runKernel(function(t){return t.batchToSpaceND(r,e,n)},{$x:r},function(t){return{$x:function(){return t.spaceToBatchND(e,n)}}})}}),Wn=Ze({cast_:function(t,e){var n=We(t,"x","cast");if(!A(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 Et.runKernel(function(t){return t.cast(n,e)},{$x:n},function(t){return{$x:function(){return t.clone()}}})}}),Vn=Ze({clone_:function(t){var e=We(t,"x","clone",null);return Et.runKernel(function(t){return st.make(e.shape,{dataId:e.dataId},e.dtype)},{$x:e},function(t){return{$x:function(){return t.toFloat()}}})}}),Un=Ze({cumsum_:function(t,e,n,r){void 0===e&&(e=0),void 0===n&&(n=!1),void 0===r&&(r=!1);var i=We(t,"x","cumsum"),a=Ke([e|=0],i.rank),o=i;null!=a&&(o=i.transpose(a));var s=Xe(1,i.rank)[0],u=Et.runKernel(function(t){return t.cumsum(o,s,n,r)},{permutedX:o},function(t){return{permutedX:function(){return t.cumsum(e,n,!r)}}});return null!=a&&(u=u.transpose(a)),u}}),jn=Ze({depthToSpace_:function(t,e,n){void 0===n&&(n="NHWC");var r=We(t,"x","depthToSpace"),i="NHWC"===n?r.shape[1]:r.shape[2],a="NHWC"===n?r.shape[2]:r.shape[3],o="NHWC"===n?r.shape[3]:r.shape[1];return p(i*e>=0,function(){return"Negative dimension size caused by overflow when multiplying\n "+i+" and "+e+" for depthToSpace with input shape\n "+r.shape}),p(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}),p(o%(e*e)==0,function(){return"Dimension size must be evenly divisible by "+e*e+" but is "+o+" for depthToSpace with input shape "+r.shape}),Et.runKernel(function(t){return t.depthToSpace(r,e,n)},{$x:r})}}),Gn=Ze({expandDims_:function(t,e){void 0===e&&(e=0);var n=We(t,"x","expandDims",null);p(e<=n.rank,function(){return"Axis must be <= rank of the tensor"});var r=n.shape.slice();return e<0&&(p(-(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),rr(n,r)}}),qn=Ze({eye_:function(t,e,n,r){void 0===r&&(r="float32"),null==e&&(e=t);for(var i=Ln([t,e],r),a=t<=e?t:e,o=0;o<a;++o)i.set(1,o,o);var s=i.toTensor().as2D(t,e);if(null==n)return s;if(1===n.length)return sr(Gn(s,0),[n[0],1,1]);if(2===n.length)return sr(Gn(Gn(s,0),0),[n[0],n[1],1,1]);if(3===n.length)return sr(Gn(Gn(Gn(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.")}}),Hn=Ze({multinomial_:function(t,e,n,r){void 0===r&&(r=!1);var i=We(t,"logits","multinomial"),a=i.size,o=i.rank;if(a<2)throw new Error("Error in multinomial: you need at least 2 outcomes, but got "+a+".");if(o>2)throw new Error("Rank of probabilities must be 1 or 2, but is "+o);n=n||Math.random();var s=1===o?i.as2D(1,-1):i,u=Et.runKernel(function(t){return t.multinomial(s,r,e,n)},{logits2D:s});return 1===o?u.as1D():u}}),Kn=Ze({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 i=We(t,"indices","oneHot","int32"),a=i.shape.concat([e]);return i=i.flatten(),Et.runKernel(function(t){return t.oneHot(i,e,n,r)},{$indices:i},function(t){return{$indices:function(){return fn(i.shape,"float32")}}}).reshape(a)}}),$n=Ze({pad_:function(t,e,n){void 0===n&&(n=0);var r=We(t,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var i=e.map(function(t){return t[0]});return Et.runKernel(function(t){return t.pad(r,e,n)},{$x:r},function(t){return{$x:function(){return t.slice(i,r.shape)}}})}}),Xn=Ze({pad1d_:function(t,e,n){return void 0===n&&(n=0),p(2===e.length,function(){return"Invalid number of paddings. Must be length of 2."}),$n(t,[e],n)}}),Yn=Ze({pad2d_:function(t,e,n){return void 0===n&&(n=0),p(2===e.length&&2===e[0].length&&2===e[1].length,function(){return"Invalid number of paddings. Must be length of 2 each."}),$n(t,e,n)}}),Jn=Ze({pad3d_:function(t,e,n){return void 0===n&&(n=0),p(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."}),$n(t,e,n)}}),Zn=Ze({pad4d_:function(t,e,n){return void 0===n&&(n=0),p(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."}),$n(t,e,n)}}),Qn=Ze({rand_:function(t,e,n){var r=m(t),i=null;if(null==n||"float32"===n)i=new Float32Array(r);else if("int32"===n)i=new Int32Array(r);else{if("bool"!==n)throw new Error("Unknown data type "+n);i=new Uint8Array(r)}for(var a=0;a<r;a++)i[a]=e();return st.make(t,{values:i},n)}}),tr=Ze({randomNormal_:function(t,e,n,r,i){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 Fn(e,n,r,!1,i),o=Ln(t,r),s=0;s<o.values.length;s++)o.values[s]=a.nextValue();return o.toTensor()}}),er=Ze({randomGamma_:function(t,e,n,r,i){if(void 0===n&&(n=1),void 0===r&&(r="float32"),null==n&&(n=1),null==r&&(r="float32"),"float32"!==r&&"int32"!==r)throw new Error("Unsupported data type "+r);for(var a=new zn(e,n,r,i),o=Ln(t,r),s=0;s<o.values.length;s++)o.values[s]=a.nextValue();return o.toTensor()}}),nr=Ze({randomUniform_:function(t,e,n,r,i){void 0===e&&(e=0),void 0===n&&(n=1),void 0===r&&(r="float32");for(var a=Ln(t,r),o=new Mn(e,n,null,i),s=0;s<a.values.length;s++)a.values[s]=o.nextValue();return a.toTensor()}}),rr=Ze({reshape_:function(t,e){var n=We(t,"x","reshape",null);return e=C(e,n.size),p(n.size===m(e),function(){return"new shape and old shape must have the same number of elements."}),Et.runKernel(function(t){return t.reshape(n,e)},{$x:n},function(t){return{$x:function(){return t.reshape(n.shape)}}})}}),ir=Ze({spaceToBatchND_:function(t,e,n){var r=We(t,"x","spaceToBatchND");return p(r.rank>=1+e.length,function(){return"input rank "+r.rank+" should be > than [blockShape] "+e.length}),p(n.length===e.length,function(){return"paddings.shape[0] "+n.length+" must be equal to [blockShape] "+e.length}),p(r.shape.reduce(function(t,r,i){return i>0&&i<=e.length?t&&(r+n[i-1][0]+n[i-1][1])%e[i-1]==0:t},!0),function(){return"input spatial dimensions "+r.shape.slice(1)+" with paddings "+n.toString()+" must be divisible by blockShapes "+e.toString()}),Et.runKernel(function(t){return t.spaceToBatchND(r,e,n)},{$x:r},function(t){return{$x:function(){return t.batchToSpaceND(e,n)}}})}}),ar=Ze({squeeze_:function(t,e){var n=We(t,"x","squeeze");return rr(n,E(n.shape,e).newShape)}}),or=Ze({stack_:function(t,e){void 0===e&&(e=0);var n=Ve(t,"tensors","stack");if(p(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,i=n[0].shape,a=n[0].dtype;p(e<=r,function(){return"Axis must be <= rank of the tensor"}),n.forEach(function(t){h(i,t.shape,"All tensors passed to stack must have matching shapes")}),n.forEach(function(t){p(a===t.dtype,function(){return"All tensors passed to stack must have matching dtypes"})});var o=n.map(function(t){return t.expandDims(e)});return bn(o,e)}}),sr=Ze({tile_:function(t,e){var n=We(t,"x","tile",null);return p(n.rank===e.length,function(){return"Error in transpose: rank of input "+n.rank+" must match length of reps "+e+"."}),Et.runKernel(function(t,r){var i=t.tile(n,e);return r([n]),i},{$x:n},function(t,n){var r=n[0];return{$x:function(){var n=yn(r);if(1===r.rank)for(var i=0;i<e[0];++i)n=n.add(t.slice([i*r.shape[0]],[r.shape[0]]));else if(2===r.rank)for(i=0;i<e[0];++i)for(var a=0;a<e[1];++a)n=n.add(t.slice([i*r.shape[0],a*r.shape[1]],[r.shape[0],r.shape[1]]));else if(3===r.rank)for(i=0;i<e[0];++i)for(a=0;a<e[1];++a)for(var o=0;o<e[2];++o)n=n.add(t.slice([i*r.shape[0],a*r.shape[1],o*r.shape[2]],[r.shape[0],r.shape[1],r.shape[2]]));else{if(4!==r.rank)throw new Error("Gradient for tile operation is not implemented for rank-"+r.rank+" tensors yet.");for(i=0;i<e[0];++i)for(a=0;a<e[1];++a)for(o=0;o<e[2];++o)for(var s=0;s<e[3];++s)n=n.add(t.slice([i*r.shape[0],a*r.shape[1],o*r.shape[2],s*r.shape[3]],[r.shape[0],r.shape[1],r.shape[2],r.shape[3]]))}return n}}})}}),ur=Ze({truncatedNormal_:function(t,e,n,r,i){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 Fn(e,n,r,!0,i),o=Ln(t,r),s=0;s<o.values.length;s++)o.values[s]=a.nextValue();return o.toTensor()}}),lr=Ze({unstack_:function(t,e){void 0===e&&(e=0),e=e||0;var n=We(t,"x","unstack");return p(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),Et.runKernel(function(t){return t.unstack(n,e)},{$x:n},function(t){return{$x:function(){return or(t,e)}}})}}),cr=function(t,e){return r(this,void 0,void 0,function(){var n,r,a,o,s,u,l,c,h,f;return i(this,function(i){switch(i.label){case 0:return n=We(t,"x","setdiff1d"),r=We(e,"y","setdiff1d"),p(n.dtype===r.dtype,function(){return"x and y should have the same dtype, but got x ("+n.dtype+") and y ("+r.dtype+")."}),p(1===n.rank,function(){return"x should be 1D tensor, but got x ("+n.shape+")."}),p(1===r.rank,function(){return"y should be 1D tensor, but got y ("+r.shape+")."}),[4,n.data()];case 1:return a=i.sent(),[4,r.data()];case 2:for(o=i.sent(),s=new Set(o),u=0,h=0;h<a.length;h++)s.has(a[h])||u++;for(l=new rt([u],n.dtype),c=new rt([u],"int32"),h=0,f=0;h<a.length;h++)s.has(a[h])||(l.values[f]=a[h],c.values[f]=h,f++);return[2,[l.toTensor(),c.toTensor()]]}})})};function pr(t,e,n,r){void 0===r&&(r=!0);var i=[];if(r)(i=i.concat(e.slice(0))).push(t[0]/n),i=i.concat(t.slice(1));else{i=i.concat(t[0]);for(var a=e.length,o=0;o<a;++o)i=i.concat([t[o+1]/e[o],e[o]]);i=i.concat(t.slice(a+1))}return i}function hr(t,e,n){void 0===n&&(n=!0);var r=[];if(n){r.push(e);for(var i=e+1;i<t;++i)i<=2*e?(r.push(i),r.push(i-(e+1))):r.push(i)}else{var a=[],o=[];for(i=1;i<t;++i)i>=2*e+1||i%2==1?o.push(i):a.push(i);r.push.apply(r,a),r.push(0),r.push.apply(r,o)}return r}function fr(t,e,n,r){void 0===r&&(r=!0);var i=[];r?i.push(t[0]/n):i.push(t[0]*n);for(var a=1;a<t.length;++a)a<=e.length?r?i.push(e[a-1]*t[a]):i.push(t[a]/e[a-1]):i.push(t[a]);return i}function dr(t,e){for(var n=[0],r=0;r<e;++r)n.push(t[r][0]);return n}function mr(t,e,n){for(var r=t.slice(0,1),i=0;i<n;++i)r.push(t[i+1]-e[i][0]-e[i][1]);return r}function gr(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],i=1,a=0;a<n.length-1;++a)i*=n[a];var o=t.shape,s=n.slice();s.pop();var u=1;for(a=r;a<t.rank;++a)u*=o[a],s.push(o[a]);var l=B(t.shape).map(function(t){return t/u}).concat([1]).slice(0,r);return[s,i,u,l]}var vr=30;function yr(t){return t<=vr?t:P(t,Math.floor(Math.sqrt(t)))}function br(t,e,n){for(var r=e.rank>1?e.shape[e.rank-1]:1,i=n.length,a=1,o=r;o<i;++o)a*=n[o];var s=r<1?1:r;return{sliceRank:r,numUpdates:e.size/s,sliceSize:a,strides:B(n.slice(0,r)).concat([1]),outputSize:m(n)}}function xr(t){for(var e=[],n=0;t>0;)1&t&&e.push(n),t/=2,n++;return e}function wr(t,e,n){for(var r=[],i=0;i<t.length;i++)r[i]=Math.ceil((e[i]-t[i])/n[i]);return r}function Cr(t,e,n,r,i){var a=e[i],o=n[i]||1;(t&1<<i||null==a)&&(a=o>0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var s=r[i];return a<0&&(a+=s),u(0,a,s-1)}function Nr(t,e,n,r,i){var a=e[i],o=n[i]||1;(t&1<<i||null==a)&&(a=o>0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var s=r[i];return a<0&&(a+=s),o>0?u(0,a,s):u(-1,a,s-1)}function Er(t,e,n){for(var r=n.length,i=0;i<n.length;i++)if(n[i]>1){r=i;break}for(i=r+1;i<n.length;i++)if(e[i]>0||n[i]!==t[i])return!1;return!0}function Sr(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 kr(t,e){p(L(t),function(){return"The f passed in variableGrads(f) must be a function"}),p(null==e||Array.isArray(e)&&e.every(function(t){return t instanceof ut}),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=[],Et.registeredVariables)e.push(Et.registeredVariables[r]);var i=n?e.filter(function(t){return!t.trainable}):null,a=e.length;p((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 o=Et.gradients(t,e,null,!0),s=o.value,u=o.grads;p(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()."}),p(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!=i&&i.forEach(function(t){return l[t.name]=null}),{value:s,grads:l}}function Ir(t){return Et.customGrad(t)}function Ar(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 Rr=Ze({softmax_:function(t,e){void 0===e&&(e=-1);var n=We(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 Ir(function(t,n){var r=t.logSumExp([e],!0),i=t.toFloat().sub(r).exp();return n([i]),{value:i,gradFunc:function(t,n){var r=n[0],i=t.mul(r);return i.sub(i.sum([e],!0).mul(r))}}})(n)}}),Tr=Ze({logSoftmax_:function(t,e){void 0===e&&(e=-1);var n=We(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 Ir(function(t,n){var r=t.max(e,!0),i=t.sub(r),a=i.toFloat().sub(i.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)}}),Dr=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}(),Or=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){throw t.a,t.b,t.transposeA,t.transposeB,t.bias,t.activation,t.preluActivationWeights,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){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.relu6=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.fusedConv2d=function(t){throw t.input,t.filter,t.convInfo,t.bias,t.activation,t.preluActivationWeights,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.fusedDepthwiseConv2D=function(t){throw t.input,t.filter,t.convInfo,t.bias,t.activation,t.preluActivationWeights,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.avgPool3d=function(t,e){throw new Error("Not yet implemented")},t.prototype.avgPool3dBackprop=function(t,e,n){throw new Error("Not yet implemented")},t.prototype.maxPool3d=function(t,e){throw new Error("Not yet implemented")},t.prototype.maxPool3dBackprop=function(t,e,n,r){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,i,a){throw new Error("Not yet implemented")},t.prototype.localResponseNormalization4D=function(t,e,n,r,i){throw new Error("Not yet implemented")},t.prototype.LRNGrad=function(t,e,n,r,i,a,o){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,i){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,i,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.diag=function(t){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 _r(t,e){for(var n=t.length,r=[],i=0;i<n;i++){var a=n-1-i,o=t[a]||1;(e[e.length-1-i]||1)>1&&1===o&&r.unshift(a)}return r}function Fr(t,e){for(var n=[],r=0;r<e.length;r++){var i=t[t.length-r-1],a=e.length-r-1,o=e[a];(null==i||1===i&&o>1)&&n.unshift(a)}return n}function zr(t,e){for(var n=[],r=Math.max(t.length,e.length),i=0;i<r;i++){var a=t[t.length-i-1];null==a&&(a=1);var o=e[e.length-i-1];if(null==o&&(o=1),1===a)n.unshift(o);else if(1===o)n.unshift(a);else{if(a!==o)throw Error("Operands could not be broadcast together with shapes "+t+" and "+e+".");n.unshift(a)}}return n}function Mr(t,e,n,r,i,a,o){void 0===o&&(o="channelsLast");var s,u=Vr(e),l=u[0],c=u[1];if("channelsLast"===o)s=[l,c,t[3],t[3]];else{if("channelsFirst"!==o)throw new Error("Unknown dataFormat "+o);s=[l,c,t[1],t[1]]}return Pr(t,s,n,r,i,a,!1,o)}function Lr(t,e,n,r,i,a,o){void 0===o&&(o="NDHWC");var s,u,l=Ur(e),c=l[0],p=l[1],h=l[2];if("NDHWC"===o)u="channelsLast",s=[c,p,h,t[4],t[4]];else{if("NCDHW"!==o)throw new Error("Unknown dataFormat "+o);u="channelsFirst",s=[c,p,h,t[1],t[1]]}return Br(t,s,n,r,i,!1,u,a)}function Pr(t,e,n,r,i,a,o,s){void 0===o&&(o=!1),void 0===s&&(s="channelsLast");var u=[-1,-1,-1,-1],l=u[0],c=u[1],h=u[2],f=u[3];if("channelsLast"===s)l=t[0],c=t[1],h=t[2],f=t[3];else{if("channelsFirst"!==s)throw new Error("Unknown dataFormat "+s);l=t[0],f=t[1],c=t[2],h=t[3]}var d,m=e[0],g=e[1],y=e[3],b=Vr(n),x=b[0],w=b[1],C=Vr(r),N=C[0],E=C[1],S=jr(m,N),k=jr(g,E),I=function(t,e,n,r,i,a,o,s){var u,l,c;if("number"==typeof t){u={top:t,bottom:t,left:t,right:t,type:0===t?"VALID":"NUMBER"};var h=function(t,e,n,r,i){null==r&&(r=Wr(t,e,n));var a=t[1],o=Gr((t[0]-e+2*r)/n+1,i);p(v(o),function(){return"The output # of rows ("+o+") must be an integer. Change the stride and/or zero pad parameters"});var s=Gr((a-e+2*r)/n+1,i);return p(v(s),function(){return"The output # of columns ("+s+") must be an integer. Change the stride and/or zero pad parameters"}),[o,s]}([e,n],a,r,t,s);l=h[0],c=h[1]}else if("same"===t){l=Math.ceil(e/r),c=Math.ceil(n/i);var f=Math.max(0,(l-1)*r+a-e),d=Math.max(0,(c-1)*i+o-n),m=Math.floor(f/2),g=f-m,y=Math.floor(d/2);u={top:m,bottom:g,left:y,right:d-y,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-o+1)/i)}return{padInfo:u,outHeight:l,outWidth:c}}(i,c,h,x,w,S,k,a),A=I.padInfo,R=I.outHeight,T=I.outWidth,D=o?y*f:y;return"channelsFirst"===s?d=[l,D,R,T]:"channelsLast"===s&&(d=[l,R,T,D]),{batchSize:l,dataFormat:s,inHeight:c,inWidth:h,inChannels:f,outHeight:R,outWidth:T,outChannels:D,padInfo:A,strideHeight:x,strideWidth:w,filterHeight:m,filterWidth:g,effectiveFilterHeight:S,effectiveFilterWidth:k,dilationHeight:N,dilationWidth:E,inShape:t,outShape:d,filterShape:e}}function Br(t,e,n,r,i,a,o,s){void 0===a&&(a=!1),void 0===o&&(o="channelsLast");var u=[-1,-1,-1,-1,-1],l=u[0],c=u[1],h=u[2],f=u[3],d=u[4];if("channelsLast"===o)l=t[0],c=t[1],h=t[2],f=t[3],d=t[4];else{if("channelsFirst"!==o)throw new Error("Unknown dataFormat "+o);l=t[0],d=t[1],c=t[2],h=t[3],f=t[4]}var m,g=e[0],y=e[1],b=e[2],x=e[4],w=Ur(n),C=w[0],N=w[1],E=w[2],S=Ur(r),k=S[0],I=S[1],A=S[2],R=jr(g,k),T=jr(y,I),D=jr(b,A),O=function(t,e,n,r,i,a,o,s,u,l,c){var h,f,d,m;if("number"==typeof t){h={top:t,bottom:t,left:t,right:t,front:t,back:t,type:0===t?"VALID":"NUMBER"};var g=function(t,e,n,r,i,a){null==i&&(i=Wr(t,e,r));var o=t[1],s=t[2],u=Gr((t[0]-e+2*i)/r+1,a);p(v(u),function(){return"The output # of depths ("+u+") must be an integer. Change the stride and/or zero pad parameters"});var l=Gr((o-e+2*i)/r+1,a);p(v(l),function(){return"The output # of rows ("+l+") must be an integer. Change the stride and/or zero pad parameters"});var c=Gr((s-e+2*i)/r+1,a);return p(v(c),function(){return"The output # of columns ("+c+") must be an integer. Change the stride and/or zero pad parameters"}),[u,l,c,1]}([e,n,r,1],s,0,i,t,c);f=g[0],d=g[1],m=g[2]}else if("same"===t){var y=((f=Math.ceil(e/i))-1)*i+s-e,b=((d=Math.ceil(n/a))-1)*a+u-n,x=((m=Math.ceil(r/o))-1)*o+l-r,w=Math.floor(y/2),C=y-w,N=Math.floor(b/2),E=b-N,S=Math.floor(x/2);h={top:N,bottom:E,left:S,right:x-S,front:w,back:C,type:"SAME"}}else{if("valid"!==t)throw Error("Unknown padding parameter: "+t);h={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},f=Math.ceil((e-s+1)/i),d=Math.ceil((n-u+1)/a),m=Math.ceil((r-l+1)/o)}return{padInfo:h,outDepth:f,outHeight:d,outWidth:m}}(i,c,h,f,C,N,E,R,T,D,s),_=O.padInfo,F=O.outDepth,z=O.outHeight,M=O.outWidth,L=a?x*d:x;return"channelsFirst"===o?m=[l,L,F,z,M]:"channelsLast"===o&&(m=[l,F,z,M,L]),{batchSize:l,dataFormat:o,inDepth:c,inHeight:h,inWidth:f,inChannels:d,outDepth:F,outHeight:z,outWidth:M,outChannels:L,padInfo:_,strideDepth:C,strideHeight:N,strideWidth:E,filterDepth:g,filterHeight:y,filterWidth:b,effectiveFilterDepth:R,effectiveFilterHeight:T,effectiveFilterWidth:D,dilationDepth:k,dilationHeight:I,dilationWidth:A,inShape:t,outShape:m,filterShape:e}}function Wr(t,e,n,r){void 0===r&&(r=1);var i=jr(e,r);return Math.floor((t[0]*(n-1)-n+i)/2)}function Vr(t){return"number"==typeof t?[t,t,t]:2===t.length?[t[0],t[1],1]:t}function Ur(t){return"number"==typeof t?[t,t,t]:t}function jr(t,e){return e<=1?t:t+(t-1)*(e-1)}function Gr(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 qr(t){var e=Vr(t),n=e[0],r=e[1],i=e[2];return 1===n&&1===r&&1===i}function Hr(t,e){return qr(t)||qr(e)}function Kr(t){if("NHWC"===t)return"channelsLast";if("NCHW"===t)return"channelsFirst";throw new Error("Unknown dataFormat "+t)}function $r(t,e,n){if("complex64"===e){if("complex64"===t.dtype)return t.clone();var r=fn(t.shape),i=t.toFloat(),a=n.complex(i,r);return r.dispose(),i.dispose(),a}if(!R(t.dtype,e))return st.make(t.shape,{dataId:t.dataId},e);if("complex64"===t.dtype){var o=n.real(t);return a=o.cast(e),o.dispose(),a}if("int32"===e)return n.int(t);if("bool"===e){var s=an(0,t.dtype);return a=n.notEqual(t,s),s.dispose(),a}throw new Error("Error in Cast: failed to cast "+t.dtype+" to "+e)}function Xr(t,e){return st.make(e,{dataId:t.dataId},t.dtype)}function Yr(t,e,n){var r=(e-t)/(n-1),i=j(n,"float32");i[0]=t;for(var a=1;a<i.length;a++)i[a]=i[a-1]+r;return on(i,"float32")}var Jr=Object.freeze({castTensor:$r,reshapeTensor:Xr,linspaceImpl:Yr,upcastType:mt,axesAreInnerMostDims:Ue,combineLocations:je,computeOutAndReduceShapes:Ge,expandShapeToKeepDim:qe,assertAxesAreInnerMostDims:He,getAxesPermutation:Ke,getUndoAxesPermutation:$e,getInnerMostAxes:Xe,getBroadcastDims:_r,getReductionAxes:Fr,assertAndGetBroadcastShape:zr,assertParamsConsistent:Ye,computeOutShape:Je,computePool2DInfo:Mr,computePool3DInfo:Lr,computeConv2DInfo:Pr,computeConv3DInfo:Br,computeDefaultPad:Wr,tupleValuesAreOne:qr,eitherStridesOrDilationsAreOne:Hr,convertConv2DDataFormat:Kr});function Zr(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 Qr(t,e){return{real:t[2*e],imag:t[2*e+1]}}function ti(t,e,n,r){t[2*r]=e,t[2*r+1]=n}function ei(t,e,n){var r=(n?2:-2)*Math.PI*(t/e);return{real:Math.cos(r),imag:Math.sin(r)}}function ni(t,e,n,r,i){for(var a=Array.from(e).map(function(t,e){return{score:t,boxIndex:e}}).filter(function(t){return t.score>i}).sort(function(t,e){return e.score-t.score}),o=[],s=0;s<a.length;s++){var u=a[s],l=u.score,c=u.boxIndex;if(l<i)break;for(var p=!1,h=o.length-1;h>=0;--h)if(ri(t,c,o[h])>=r){p=!0;break}if(!p&&(o.push(c),o.length>=n))break}return on(o,"int32")}function ri(t,e,n){var r=t.subarray(4*e,4*e+4),i=t.subarray(4*n,4*n+4),a=Math.min(r[0],r[2]),o=Math.min(r[1],r[3]),s=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),l=Math.min(i[0],i[2]),c=Math.min(i[1],i[3]),p=Math.max(i[0],i[2]),h=Math.max(i[1],i[3]),f=(s-a)*(u-o),d=(p-l)*(h-c);if(f<=0||d<=0)return 0;var m=Math.max(a,l),g=Math.max(o,c),v=Math.min(s,p),y=Math.min(u,h),b=Math.max(v-m,0)*Math.max(y-g,0);return b/(f+d-b)}function ii(t,e,n){var r=new Array(t.rank).fill(0),i=t.shape.slice();return e.map(function(e){i[n]=e;var a=t.slice(r,i);return r[n]+=e,a})}function ai(t,e){for(var n=new Array(t.rank),r=0;r<n.length;r++)n[r]=t.shape[r]*e[r];var i=Ln(n,t.dtype);for(r=0;r<i.values.length;++r){for(var a=i.indexToLoc(r),o=new Array(t.rank),s=0;s<o.length;s++)o[s]=a[s]%t.shape[s];var u=t.locToIndex(o);i.values[r]=t.values[u]}return i.toTensor()}function oi(t,e,n,r,i){for(var a=e[e.length-1],o=[t.length/a,a],s=o[0],u=o[1],l=S(n,s*r),c=S("int32",s*r),p=0;p<s;p++){for(var h=p*u,f=t.subarray(h,h+u),d=[],m=0;m<f.length;m++)d.push({value:f[m],index:m});d.sort(function(t,e){return e.value-t.value});var g=p*r,v=l.subarray(g,g+r),y=c.subarray(g,g+r);for(m=0;m<r;m++)v[m]=d[m].value,y[m]=d[m].index}var b=e.slice();return b[b.length-1]=r,[nn(l,b,n),nn(c,b,"int32")]}function si(t,e){for(var n=[],r=0;r<e.length;r++)e[r]&&n.push(r);var i=Ln(t,"int32"),a=Ln([n.length,t.length],"int32");for(r=0;r<n.length;r++){var o=i.indexToLoc(n[r]),s=r*t.length;a.values.set(o,s)}return a.toTensor()}var ui=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 "},li=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 "},ci=function(t,e,n){this.variableNames=["A"];var r=t.windowSize,i=t.batchSize,a=t.inSize,o=Math.ceil(a/r);n||this.variableNames.push("bestIndicesA"),this.outputShape=[i,o];var s="max"===e?">":"<",u=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+r+";\n\n int bestIndex = inOffset;\n float bestValue = getA(batch, bestIndex);\n\n for (int i = 0; i < "+r+"; i++) {\n int inIdx = "+u+";\n float candidate = getA(batch, inIdx);\n if (candidate "+s+" bestValue) {\n bestValue = candidate;\n bestIndex = inIdx;\n }\n }\n setOutput(float(bestIndex));\n }\n "};function pi(t,e){return["x","y","z","w","u","v"].slice(0,e).map(function(e){return t+"."+e})}function hi(t,e){return 1===e?[t]:pi(t,e)}function fi(){var t,e,n,r,i,a,s,u,l,c;return 2===o().getNumber("WEBGL_VERSION")?(t="#version 300 es",e="in",n="out",r="in",i="texture",a="outputColor",s="out vec4 outputColor;",u="\n bool isnan_custom(float val) {\n return (val > 0.0 || val < 0.0) ? false : val != 0.0;\n }\n\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan_custom(val.x),\n isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));\n }\n\n #define isnan(value) isnan_custom(value)\n ",l="",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",i="texture2D",a="gl_FragColor",s="",u="\n #define isnan(value) isnan_custom(value)\n bool isnan_custom(float val) {\n return (val > 0. || val < 1. || val == 0.) ? false : true;\n }\n bvec4 isnan_custom(vec4 val) {\n return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\n }\n ",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:i,output:a,defineOutput:s,defineSpecialNaN:u,defineSpecialInf:l,defineRound:c}}function di(t,e,n){void 0===n&&(n="index");var r=B(e);return r.map(function(e,i){return"int "+t[i]+" = "+n+" / "+e+"; "+(i===r.length-1?"int "+t[i+1]+" = "+n+" - "+t[i]+" * "+e:"index -= "+t[i]+" * "+e)+";"}).join("")}function mi(t){var e=B(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 gi="\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 vi(t,e,n,r){var i=[];t.forEach(function(t){var e=m(t.shapeInfo.logicalShape);t.shapeInfo.isUniform?i.push("uniform float "+t.name+(e>1?"["+e+"]":"")+";"):(i.push("uniform sampler2D "+t.name+";"),i.push("uniform int offset"+t.name+";"))});var a,o,s=i.join("\n"),u=t.map(function(t){return function(t,e,n){void 0===n&&(n=!1);var r="";r+=n?function t(e){var n,r,i;switch(e.shapeInfo.logicalShape.length){case 0:return n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),i=fi(),"\n vec4 "+r+"() {\n return "+i.texture2D+"("+n+", 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,i=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],a=fi();return"\n vec4 "+n+"(int index) {\n vec2 uv = packedUVfrom1D(\n "+i[0]+", "+i[1]+", index);\n return "+a.texture2D+"("+e+", uv);\n }\n "}(e);case 2:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),i=t.shapeInfo.texShape,a=i[0],o=i[1],s=fi();if(null!=i&&g(e,i))return"\n vec4 "+r+"(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2("+o+".0, "+a+".0);\n\n return "+s.texture2D+"("+n+", uv);\n }\n ";var u=[Math.ceil(i[0]/2),Math.ceil(i[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 "}(e);case 3:return function(e){var n=e.shapeInfo.logicalShape,r=e.name,i="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape,o=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];if(1===n[0]){var s=n.slice(1),u=Si(e,s);return"\n "+t(u)+"\n vec4 "+i+"(int b, int row, int col) {\n return "+i+"("+ki(["b","row","col"],[1,2])+");\n }\n "}var l=o[0],c=o[1],p=Math.ceil(n[2]/2),h=p*Math.ceil(n[1]/2),f=fi();return"\n vec4 "+i+"(int b, int row, int col) {\n vec2 uv = packedUVfrom3D(\n "+l+", "+c+", "+h+", "+p+", b, row, col);\n return "+f.texture2D+"("+r+", uv);\n }\n "}(e);default:return function(t){for(var e=t.shapeInfo.logicalShape,n=e.length,r=t.name,i="get"+r.charAt(0).toUpperCase()+r.slice(1),a=t.shapeInfo.texShape,o=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],s=o[0],u=o[1],l=Math.ceil(e[n-1]/2),c=l*Math.ceil(e[n-2]/2),p="int b, int row, int col",h="b * "+c+" + (row / 2) * "+l+" + (col / 2)",f=2;f<n-1;f++)p="int b"+f+", "+p,c*=e[n-f-1],h="b"+f+" * "+c+" + "+h;var d=fi();return"\n vec4 "+i+"("+p+") {\n int index = "+h+";\n int texR = index / "+u+";\n int texC = index - texR * "+u+";\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+u+", "+s+");\n return "+d.texture2D+"("+r+", uv);\n }\n "}(e)}}(t):function t(e){var n=e.shapeInfo.logicalShape;switch(n.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,i=r[0],a=r[1];if(1===i&&1===a)return"\n float "+n+"() {\n return sampleTexture("+e+", halfCR);\n }\n ";var o=t.shapeInfo.texShape,s=o[0],u=o[1],l=Ci(e);return"\n float "+n+"() {\n vec2 uv = uvFromFlat("+s+", "+u+", "+l+");\n return sampleTexture("+e+", uv);\n }\n "}(e);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 "+Ni(t)+"\n }\n ";var r=t.shapeInfo.texShape,i=r[0],a=r[1];if(1===a&&1===i)return"\n float "+n+"(int index) {\n return sampleTexture("+e+", halfCR);\n }\n ";var o=Ci(e);return 1===a?"\n float "+n+"(int index) {\n vec2 uv = vec2(0.5, (float(index + "+o+") + 0.5) / "+i+".0);\n return sampleTexture("+e+", uv);\n }\n ":1===i?"\n float "+n+"(int index) {\n vec2 uv = vec2((float(index + "+o+") + 0.5) / "+a+".0, 0.5);\n return sampleTexture("+e+", uv);\n }\n ":"\n float "+n+"(int index) {\n vec2 uv = uvFromFlat("+i+", "+a+", index + "+o+");\n return sampleTexture("+e+", uv);\n }\n "}(e);case 2:return function(e){var n=e.shapeInfo.logicalShape,r=e.name,i="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape;if(null!=a&&g(n,a)){var o=a[0],s=a[1];return"\n float "+i+"(int row, int col) {\n vec2 uv = (vec2(col, row) + halfCR) / vec2("+s+".0, "+o+".0);\n return sampleTexture("+r+", uv);\n }\n "}var u=E(n),l=u.newShape,c=u.keptDims,p=l;if(p.length<n.length){var h=Si(e,p);return"\n "+t(h)+"\n float "+i+"(int row, int col) {\n return "+i+"("+ki(["row","col"],c)+");\n }\n "}if(e.shapeInfo.isUniform)return"\n float "+i+"(int row, int col) {\n int index = round(dot(vec2(row, col), vec2("+n[1]+", 1)));\n "+Ni(e)+"\n }\n ";var f=a[0],d=a[1],m=Ci(r);return 1===d?"\n float "+i+"(int row, int col) {\n float index = dot(vec3(row, col, "+m+"), vec3("+n[1]+", 1, 1));\n vec2 uv = vec2(0.5, (index + 0.5) / "+f+".0);\n return sampleTexture("+r+", uv);\n }\n ":1===f?"\n float "+i+"(int row, int col) {\n float index = dot(vec3(row, col, "+m+"), vec3("+n[1]+", 1, 1));\n vec2 uv = vec2((index + 0.5) / "+d+".0, 0.5);\n return sampleTexture("+r+", uv);\n }\n ":"\n float "+i+"(int row, int col) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * "+n[1]+" + col + "+m+";\n vec2 uv = uvFromFlat("+f+", "+d+", index);\n return sampleTexture("+r+", uv);\n }\n"}(e);case 3:return function(e){var n=e.shapeInfo.logicalShape,r=e.name,i="get"+r.charAt(0).toUpperCase()+r.slice(1),a=n[1]*n[2],o=n[2],s=E(n),u=s.newShape,l=s.keptDims,c=u;if(c.length<n.length){var p=Si(e,c);return"\n "+t(p)+"\n float "+i+"(int row, int col, int depth) {\n return "+i+"("+ki(["row","col","depth"],l)+");\n }\n "}if(e.shapeInfo.isUniform)return"\n float "+i+"(int row, int col, int depth) {\n int index = round(dot(vec3(row, col, depth),\n vec3("+a+", "+o+", 1)));\n "+Ni(e)+"\n }\n ";var h=e.shapeInfo.texShape,f=h[0],d=h[1],m=e.shapeInfo.flatOffset;if(d===a&&null==m)return"\n float "+i+"(int row, int col, int depth) {\n float texR = float(row);\n float texC = dot(vec2(col, depth), vec2("+o+", 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+d+".0, "+f+".0);\n return sampleTexture("+r+", uv);\n }\n ";if(d===o&&null==m)return"\n float "+i+"(int row, int col, int depth) {\n float texR = dot(vec2(row, col), vec2("+n[1]+", 1));\n float texC = float(depth);\n vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+d+".0, "+f+".0);\n return sampleTexture("+r+", uv);\n }\n ";var g=Ci(r);return"\n float "+i+"(int row, int col, int depth) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * "+a+" + col * "+o+" + depth + "+g+";\n vec2 uv = uvFromFlat("+f+", "+d+", index);\n return sampleTexture("+r+", uv);\n }\n "}(e);case 4:return function(e){var n=e.shapeInfo.logicalShape,r=e.name,i="get"+r.charAt(0).toUpperCase()+r.slice(1),a=n[3],o=n[2]*a,s=n[1]*o,u=E(n),l=u.newShape,c=u.keptDims;if(l.length<n.length){var p=Si(e,l);return"\n "+t(p)+"\n float "+i+"(int row, int col, int depth, int depth2) {\n return "+i+"("+ki(["row","col","depth","depth2"],c)+");\n }\n "}if(e.shapeInfo.isUniform)return"\n float "+i+"(int row, int col, int depth, int depth2) {\n int index = round(dot(vec4(row, col, depth, depth2),\n vec4("+s+", "+o+", "+a+", 1)));\n "+Ni(e)+"\n }\n ";var h=e.shapeInfo.flatOffset,f=e.shapeInfo.texShape,d=f[0],m=f[1];if(m===s&&null==h)return"\n float "+i+"(int row, int col, int depth, int depth2) {\n float texR = float(row);\n float texC =\n dot(vec3(col, depth, depth2),\n vec3("+o+", "+a+", 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+m+".0, "+d+".0);\n return sampleTexture("+r+", uv);\n }\n ";if(m===a&&null==h)return"\n float "+i+"(int row, int col, int depth, int depth2) {\n float texR = dot(vec3(row, col, depth),\n vec3("+n[1]*n[2]+", "+n[2]+", 1));\n float texC = float(depth2);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+m+".0, "+d+".0);\n return sampleTexture("+r+", uv);\n }\n ";var g=Ci(r);return"\n float "+i+"(int row, int col, int depth, int depth2) {\n // Explicitly use integer operations as dot() only works on floats.\n int index = row * "+s+" + col * "+o+" +\n depth * "+a+" + depth2;\n vec2 uv = uvFromFlat("+d+", "+m+", index + "+g+");\n return sampleTexture("+r+", uv);\n }\n "}(e);case 5:return function(e){var n=e.shapeInfo.logicalShape,r=e.name,i="get"+r.charAt(0).toUpperCase()+r.slice(1),a=n[4],o=n[3]*a,s=n[2]*o,u=n[1]*s,l=E(n),c=l.newShape,p=l.keptDims;if(c.length<n.length){var h=Si(e,c);return"\n "+t(h)+"\n float "+i+"(int row, int col, int depth, int depth2, int depth3) {\n return "+i+"("+ki(["row","col","depth","depth2","depth3"],p)+");\n }\n "}if(e.shapeInfo.isUniform)return"\n float "+i+"(int row, int col, int depth, int depth2, int depth3) {\n float index = dot(\n vec4(row, col, depth, depth2),\n vec4("+u+", "+s+", "+o+", "+a+")) +\n depth3;\n "+Ni(e)+"\n }\n ";var f=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,m=d[0],g=d[1];if(g===u&&null==f)return"\n float "+i+"(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("+s+", "+o+", "+a+", 1));\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+g+".0, "+m+".0);\n return sampleTexture("+r+", uv);\n }\n ";if(g===a&&null==f)return"\n float "+i+"(int row, int col, int depth, int depth2, int depth3) {\n float texR = dot(\n vec4(row, col, depth, depth2),\n vec4("+n[1]*n[2]*n[3]+",\n "+n[2]*n[3]+", "+n[3]+", 1));\n int texC = depth3;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+g+".0, "+m+".0);\n return sampleTexture("+r+", uv);\n }\n ";var v=Ci(r);return"\n float "+i+"(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 * "+u+" + col * "+s+" + depth * "+o+" +\n depth2 * "+a+" + depth3 + "+v+";\n vec2 uv = uvFromFlat("+m+", "+g+", index);\n return sampleTexture("+r+", uv);\n }\n "}(e);case 6:return function(e){var n=e.shapeInfo.logicalShape,r=e.name,i="get"+r.charAt(0).toUpperCase()+r.slice(1),a=E(n),o=a.newShape,s=a.keptDims;if(o.length<n.length){var u=Si(e,o);return"\n "+t(u)+"\n float "+i+"(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n return "+i+"("+ki(["row","col","depth","depth2","depth3","depth4"],s)+");\n }\n "}var l=n[5],c=n[4]*l,p=n[3]*c,h=n[2]*p,f=n[1]*h;if(e.shapeInfo.isUniform)return"\n float "+i+"(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("+f+", "+h+", "+p+", "+c+")) +\n dot(\n vec2(depth3, depth4),\n vec2("+l+", 1)));\n "+Ni(e)+"\n }\n ";var d=e.shapeInfo.flatOffset,m=e.shapeInfo.texShape,g=m[0],v=m[1];if(v===f&&null==d)return"\n float "+i+"(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+", "+p+", "+c+", "+l+")) +\n float(depth4);\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+v+".0, "+g+".0);\n return sampleTexture("+r+", uv);\n }\n ";if(v===l&&null==d)return"\n float "+i+"(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n float texR = dot(vec4(row, col, depth, depth2),\n vec4("+n[1]*n[2]*n[3]*n[4]+",\n "+n[2]*n[3]*n[4]+",\n "+n[3]*n[4]+",\n "+n[4]+")) + float(depth3);\n int texC = depth4;\n vec2 uv = (vec2(texC, texR) + halfCR) /\n vec2("+v+".0, "+g+".0);\n return sampleTexture("+r+", uv);\n }\n ";var y=Ci(r);return"\n float "+i+"(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 * "+f+" + col * "+h+" + depth * "+p+" +\n depth2 * "+c+" + depth3 * "+l+" + depth4 + "+y+";\n vec2 uv = uvFromFlat("+g+", "+v+", index);\n return sampleTexture("+r+", uv);\n }\n "}(e);default:throw new Error(n.length+"-D input sampling is not yet supported")}}(t);var i=t.shapeInfo.logicalShape,a=e.logicalShape;return i.length<=a.length&&(r+=n?function(t,e){var n,r=t.name,i=r.charAt(0).toUpperCase()+r.slice(1),a="get"+i+"AtOutCoords",o=t.shapeInfo.logicalShape.length,s=e.logicalShape.length,u=_r(t.shapeInfo.logicalShape,e.logicalShape),l=Ei(s),c=s-o,p=["x","y","z","w","u","v"];n=0===o?"":s<2&&u.length>=1?"coords = 0;":u.map(function(t){return"coords."+p[t+c]+" = 0;"}).join("\n");var h;h=s<2&&o>0?"coords":t.shapeInfo.logicalShape.map(function(t,e){return"coords."+p[e+c]}).join(", ");var f="return outputValue;",d=1===m(t.shapeInfo.logicalShape),g=1===m(e.logicalShape);if(1!==o||d||g){if(d&&!g)f=1===s?"\n return vec4(outputValue.x, outputValue.x, 0., 0.);\n ":"\n return vec4(outputValue.x);\n ";else if(u.length){var v=o-2,y=o-1;u.indexOf(v)>-1&&u.indexOf(y)>-1?f="return vec4(outputValue.x);":u.indexOf(v)>-1?f="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":u.indexOf(y)>-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"+i+"("+h+");\n "+f+"\n }\n "}(t,e):function(t,e){var n=t.name,r=n.charAt(0).toUpperCase()+n.slice(1),i="get"+r+"AtOutCoords",a=e.texShape,o=t.shapeInfo.texShape,s=t.shapeInfo.logicalShape.length,u=e.logicalShape.length;if(!t.shapeInfo.isUniform&&s===u&&null==t.shapeInfo.flatOffset&&g(o,a))return"\n float "+i+"() {\n return sampleTexture("+n+", resultUV);\n }\n ";var l=Ei(u),c=_r(t.shapeInfo.logicalShape,e.logicalShape),p=u-s,h=["x","y","z","w","u","v"];return"\n float "+i+"() {\n "+l+" coords = getOutputCoords();\n "+(0===s?"":u<2&&c.length>=1?"coords = 0;":c.map(function(t){return"coords."+h[t+p]+" = 0;"}).join("\n"))+"\n return get"+r+"("+(u<2&&s>0?"coords":t.shapeInfo.logicalShape.map(function(t,e){return"coords."+h[e+p]}).join(", "))+");\n }\n "}(t,e)),r}(t,e,r)}).join("\n"),l=e.texShape,c=fi(),p="\n float sampleTexture(sampler2D textureSampler, vec2 uv) {\n return "+c.texture2D+"(textureSampler, uv).r;\n }\n ",h=function(t){return t.version+"\n precision highp float;\n precision highp int;\n precision highp sampler2D;\n "+t.varyingFs+" vec2 resultUV;\n "+t.defineOutput+"\n const vec2 halfCR = vec2(0.5, 0.5);\n\n struct ivec5\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n };\n\n struct ivec6\n {\n int x;\n int y;\n int z;\n int w;\n int u;\n int v;\n };\n\n uniform float NAN;\n "+t.defineSpecialNaN+"\n "+t.defineSpecialInf+"\n "+t.defineRound+"\n\n int imod(int x, int y) {\n return x - y * (x / y);\n }\n\n int idiv(int a, int b, float sign) {\n int res = a / b;\n int mod = imod(a, b);\n if (sign < 0. && mod != 0) {\n res -= 1;\n }\n return res;\n }\n\n //Based on the work of Dave Hoskins\n //https://www.shadertoy.com/view/4djSRW\n #define HASHSCALE1 443.8975\n float random(float seed){\n vec2 p = resultUV * seed;\n vec3 p3 = fract(vec3(p.xyx) * HASHSCALE1);\n p3 += dot(p3, p3.yzx + 19.19);\n return fract((p3.x + p3.y) * p3.z);\n }\n\n "+yi+"\n "+bi+"\n "+xi+"\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)];return 1===n[0]?"\n int getOutputCoords() {\n return 2 * int(resultUV.x * "+n[1]+".0);\n }\n ":1===n[1]?"\n int getOutputCoords() {\n return 2 * int(resultUV.y * "+n[0]+".0);\n }\n ":"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n return 2 * (resTexRC.x * "+n[1]+" + resTexRC.y);\n }\n "}(0,e);case 2:return function(t,e){var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)];if(g(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,i=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],o=(a=Math.ceil(n[2]/2))*Math.ceil(n[1]/2),"\n ivec3 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+i[0]+", "+i[1]+"));\n int index = resTexRC.x * "+i[1]+" + resTexRC.y;\n\n int b = index / "+o+";\n index -= b * "+o+";\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),i=r*Math.ceil(t[t.length-2]/2),a=i,o="",s="b, r, c",u=2;u<t.length-1;u++)o="\n int b"+u+" = index / "+(a*=t[t.length-u-1])+";\n index -= b"+u+" * "+a+";\n "+o,s="b"+u+", "+s;return"\n ivec"+t.length+" getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+n[0]+", "+n[1]+"));\n int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n\n "+o+"\n\n int b = index / "+i+";\n index -= b * "+i+";\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,i,a,o}(e.logicalShape,l),o="\n void setOutput(vec4 val) {\n "+c.output+" = val;\n }\n "):(a=function(t,e){switch(t.length){case 0:return"\n int getOutputCoords() {\n return 0;\n }\n ";case 1:return function(t,e){return 1===e[0]?"\n int getOutputCoords() {\n return int(resultUV.x * "+e[1]+".0);\n }\n ":1===e[1]?"\n int getOutputCoords() {\n return int(resultUV.y * "+e[0]+".0);\n }\n ":"\n int getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n return resTexRC.x * "+e[1]+" + resTexRC.y;\n }\n "}(0,e);case 2:return function(t,e){return g(t,e)?"\n ivec2 getOutputCoords() {\n return ivec2(resultUV.yx * vec2("+e[0]+", "+e[1]+"));\n }\n ":1===t[1]?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n return ivec2(index, 0);\n }\n ":1===t[0]?"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n return ivec2(0, index);\n }\n ":"\n ivec2 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n int r = index / "+t[1]+";\n int c = index - r * "+t[1]+";\n return ivec2(r, c);\n }\n "}(t,e);case 3:return n=e,r=di(["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=di(["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=di(["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=di(["r","c","d","d2","d3","d4"],t);return"\n ivec6 getOutputCoords() {\n ivec2 resTexRC = ivec2(resultUV.yx *\n vec2("+e[0]+", "+e[1]+"));\n int index = resTexRC.x * "+e[1]+" + resTexRC.y;\n\n "+n+"\n\n ivec6 result = ivec6(r, c, d, d2, d3, d4);\n return result;\n }\n "}(t,e);default:throw new Error(t.length+"-D output sampling is not yet supported")}var n,r}(e.logicalShape,l),o="\n void setOutput(float val) {\n "+c.output+" = vec4(val, 0, 0, 0);\n }\n "),r&&(h+=wi),[h,p,o,s,a,u,n].join("\n")}var yi="\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",bi="\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",xi="\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",wi="\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 Ci(t){return"offset"+t}function Ni(t){var e=t.name,n=m(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 Ei(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 Si(t,e){var n=JSON.parse(JSON.stringify(t));return n.shapeInfo.logicalShape=e,n}function ki(t,e){return e.map(function(e){return t[e]}).join(", ")}var Ii=function(t,e,n,r){this.variableNames=["A"],this.usesPackedTextures=!0,p(t.length>2,function(){return"Packed arg"+(n.charAt(0).toUpperCase()+n.slice(1))+" supports only inputs with rank above 2."});var i=t[t.length-1],a=Math.ceil(i/e);this.outputShape=t.slice(0,-1),a>1&&this.outputShape.push(a),r||this.variableNames.push("bestIndicesA");var o,s,u=this.outputShape,l=u.length,c=Ei(l),h=hi("coords",l);if(1===a){var f=Ei(s=l+1);o="\n "+f+" sourceLocR = "+f+"("+h.join()+", 0);\n ++"+h[l-1]+";\n "+f+" sourceLocG = "+f+"("+h.join()+", 0);\n ++"+h[l-2]+";\n "+f+" sourceLocA = "+f+"("+h.join()+", 0);\n --"+h[l-1]+";\n "+f+" sourceLocB = "+f+"("+h.join()+", 0);\n --"+h[l-2]+";"}else s=l,o="\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 d=["x","y","z","w","u","v"].slice(0,s),m="."+d[s-1],g=d.map(function(t){return"int "+t}),v=hi("sourceLocR",s-1).concat("inIdx.r"),y=hi("sourceLocG",s-1).concat("inIdx.g"),b=hi("sourceLocB",s-1).concat("inIdx.b"),x=hi("sourceLocA",s-1).concat("inIdx.a"),w="max"===n?"greaterThan":"lessThan",C=r?"":"\n inIdx = round(vec4(getBestIndicesAChannel("+v.join()+"),\n getBestIndicesAChannel("+y.join()+"),\n getBestIndicesAChannel("+b.join()+"),\n getBestIndicesAChannel("+x.join()+")));",N="vec4(\n getAChannel("+v.join()+"),\n hasNextCol ? getAChannel("+y.join()+") : 0.,\n hasNextRow ? getAChannel("+b.join()+") : 0.,\n hasNextRow && hasNextCol ? getAChannel("+x.join()+") : 0.)",E=r?"":"\n float getBestIndicesAChannel("+g.join()+") {\n return getChannel(getBestIndicesA("+d.join()+"),\n vec2("+d.slice(-2).join()+"));\n }";this.userCode="\n float getAChannel("+g.join()+") {\n return getChannel(getA("+d.join()+"),\n vec2("+d.slice(-2).join()+"));\n }\n "+E+"\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 "+o+"\n ivec4 srcIdx = ivec4(sourceLocR"+m+", sourceLocG"+m+",\n sourceLocB"+m+", sourceLocA"+m+") * "+e+";\n ivec4 inIdx = srcIdx;\n vec4 bestIndex = vec4(inIdx);\n vec4 bestValue = "+N+";\n\n for (int i = 0; i < "+e+"; i++) {\n inIdx = srcIdx;\n "+C+"\n vec4 candidate = "+N+";\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 "},Ai=function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,i=t.strideWidth,a=t.dilationHeight,o=t.dilationWidth,s=t.effectiveFilterHeight,u=t.effectiveFilterWidth,l=s-1-t.padInfo.top,c=u-1-t.padInfo.left,p=1/(e*n);this.userCode="\n const ivec2 pads = ivec2("+l+", "+c+");\n const float avgMultiplier = float("+p+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+s+";\n wR += "+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+= "+o+") {\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 float dyValue = getDy(b, idyR, idyC, d);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n setOutput(dotProd);\n }\n "},Ri=function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,r=t.filterWidth,i=t.strideDepth,a=t.strideHeight,o=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,l=t.dilationWidth,c=t.effectiveFilterDepth,p=t.effectiveFilterHeight,h=t.effectiveFilterWidth,f=c-1-t.padInfo.front,d=p-1-t.padInfo.top,m=h-1-t.padInfo.left,g=1/(e*n*r);this.userCode="\n const ivec3 pads = ivec3("+f+", "+d+", "+m+");\n const float avgMultiplier = float("+g+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < "+c+";\n wD += "+s+") {\n float dyD = float(dyDCorner + wD) / "+i+".0;\n\n if (dyD < 0.0 || dyD >= "+t.outDepth+".0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < "+p+";\n wR += "+u+") {\n float dyR = float(dyRCorner + wR) / "+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 for (int wC = 0; wC < "+h+";\n wC += "+l+") {\n float dyC = float(dyCCorner + wC) / "+o+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n\n dotProd += dyValue * avgMultiplier;\n }\n }\n }\n setOutput(dotProd);\n }\n "},Ti=function(t,e,n,r,i,a){this.outputShape=[],this.variableNames=["x","mean","variance"],zr(t,e),zr(t,n);var o="0.0";null!=r&&(zr(t,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");var s="1.0";null!=i&&(zr(t,i),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n void main() {\n float x = getXAtOutCoords();\n float mean = getMeanAtOutCoords();\n float variance = getVarianceAtOutCoords();\n float offset = "+o+";\n float scale = "+s+";\n float inv = scale * inversesqrt(variance + float("+a+"));\n setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n }\n "},Di=function(t,e,n,r,i,a){this.usesPackedTextures=!0,this.variableNames=["x","mean","variance"],zr(t,e),zr(t,n);var o="vec4(0.0)";null!=r&&(zr(t,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");var s="vec4(1.0)";null!=i&&(zr(t,i),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n void main() {\n vec4 offset = "+o+";\n vec4 scale = "+s+";\n\n vec4 x = getXAtOutCoords();\n vec4 mean = getMeanAtOutCoords();\n vec4 variance = getVarianceAtOutCoords();\n\n vec4 inv = scale * inversesqrt(variance + vec4("+a+"));\n\n setOutput((x - mean) * inv + offset);\n }\n "},Oi=function(t,e,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=zr(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 "},_i="return a + b;",Fi="return a - b;",zi="return a * b;",Mi="return (a < 0.) ? b * a : a;",Li=function(t,e,n){this.variableNames=["A","B"],this.outputShape=zr(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 "},Pi="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",Bi=function(t,e,n,r){void 0===r&&(r=!1),this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.usesPackedTextures=!0,this.outputShape=zr(e,n);var i=this.outputShape.length,a="";if(r)if(0===i||1===m(this.outputShape))a="\n result.y = 0.;\n result.z = 0.;\n result.w = 0.;\n ";else if(a="\n "+Ei(i)+" coords = getOutputCoords();\n ",1===i)a+="\n result.y = (coords + 1) >= "+this.outputShape[0]+" ? 0. : result.y;\n result.z = 0.;\n result.w = 0.;\n ";else{var o=hi("coords",i);a+="\n bool nextRowOutOfBounds =\n ("+o[i-2]+" + 1) >= "+this.outputShape[i-2]+";\n bool nextColOutOfBounds =\n ("+o[i-1]+" + 1) >= "+this.outputShape[i-1]+";\n result.y = nextColOutOfBounds ? 0. : result.y;\n result.z = nextRowOutOfBounds ? 0. : result.z;\n result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n "}this.userCode="\n vec4 binaryOperation(vec4 a, vec4 b) {\n "+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 "},Wi=function(){function t(t){this.variableNames=["A"],this.outputShape=t,this.userCode="\n uniform float minVal;\n uniform float maxVal;\n\n void main() {\n float value = getAAtOutCoords();\n if (isnan(value)) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, minVal, maxVal));\n }\n "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,i){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(i,"minVal"),n.maxLoc=r.getUniformLocationNoThrow(i,"maxVal")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e)}},t}(),Vi=function(){function t(t){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t,this.userCode="\n uniform float minVal;\n uniform float maxVal;\n\n void main() {\n vec4 value = getAAtOutCoords();\n\n if (any(isnan(value))) {\n setOutput(value);\n return;\n }\n\n setOutput(clamp(value, vec4(minVal), vec4(maxVal)));\n }\n "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,i){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(i,"minVal"),n.maxLoc=r.getUniformLocationNoThrow(i,"maxVal")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e)}},t}(),Ui=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 "},ji=function(t){this.outputShape=[],this.outputShape=Je(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 i=e[n-1];r.push("else if (yC < "+e[n]+") setOutput(getT"+n+"(yR, yC-"+i+"));")}var a=e.length,o=e[e.length-1];r.push("else setOutput(getT"+a+"(yR, yC-"+o+"));"),this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n int yR = coords.x;\n int yC = coords.y;\n\n "+r.join("\n ")+"\n }\n "},Gi=function(t,e){this.usesPackedTextures=!0,this.outputShape=[],this.outputShape=Je(t,e);var n=this.outputShape,r=n.length,i=Ei(r),a=hi("coords",r),o=["x","y","z","w","u","v"].slice(0,r);this.variableNames=t.map(function(t,e){return"T"+e});var s=new Array(t.length-1);s[0]=t[0][e];for(var u=1;u<s.length;u++)s[u]=s[u-1]+t[u][e];var l=o[e],c=o.slice(-2),p=o.join(),h="if ("+l+" < "+s[0]+") {\n return getChannel(\n getT0("+p+"), vec2("+c.join()+"));\n }";for(u=1;u<s.length;u++){var f=s[u-1];h+="\n if ("+l+" < "+s[u]+" && "+l+" >= "+s[u-1]+") {\n return getChannel(\n getT"+u+"("+qi(o,l,f)+"),\n vec2("+qi(c,l,f)+"));\n }"}var d=s.length,m=s[s.length-1];h+="\n return getChannel(\n getT"+d+"("+qi(o,l,m)+"),\n vec2("+qi(c,l,m)+"));",this.userCode="\n float getValue("+o.map(function(t){return"int "+t})+") {\n "+h+"\n }\n\n void main() {\n "+i+" coords = getOutputCoords();\n vec4 result = vec4(getValue("+a+"), 0., 0., 0.);\n\n "+a[r-1]+" = "+a[r-1]+" + 1;\n if ("+a[r-1]+" < "+n[r-1]+") {\n result.g = getValue("+a+");\n }\n\n "+a[r-2]+" = "+a[r-2]+" + 1;\n if ("+a[r-2]+" < "+n[r-2]+") {\n result.a = getValue("+a+");\n }\n\n "+a[r-1]+" = "+a[r-1]+" - 1;\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 "};function qi(t,e,n){var r=t.indexOf(e);return t.map(function(t,e){return e===r?t+" - "+n:t}).join()}var Hi=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,n=t.strideWidth,r=t.padInfo.top,i=t.padInfo.left,a="channelsLast"===t.dataFormat;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int wR = coords.x;\n int wC = coords.y;\n int d1 = coords.z;\n int d2 = coords.w;\n\n // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int b = 0; b < "+t.batchSize+"; b++) {\n for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n int xR = wR + yR * "+e+" - "+r+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+n+" - "+i+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n if ("+a+") {\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n } else {\n float dyValue = getDy(b, d2, yR, yC);\n float xValue = getX(b, d1, xR, xC);\n dotProd += (xValue * dyValue);\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n "},Ki=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,i=t.strideWidth,a="channelsLast"===t.dataFormat,o=e-1-t.padInfo.top,s=n-1-t.padInfo.left,u=a?1:2,l=a?2:3,c=a?3:1;this.userCode="\n const ivec2 pads = ivec2("+o+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords["+c+"];\n\n ivec2 dyCorner = ivec2(coords["+u+"], coords["+l+"]) - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+e+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+e+" - 1 - wR;\n\n for (int wC = 0; wC < "+n+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+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 = "+n+" - 1 - wC;\n\n for (int d2 = 0; d2 < "+t.outChannels+"; d2++) {\n\n if ("+a+") {\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n } else {\n float xValue = getDy(batch, d2, idyR, idyC);\n float wValue = getW(wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n "},$i=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideDepth,n=t.strideHeight,r=t.strideWidth,i=t.padInfo.front,a=t.padInfo.top,o=t.padInfo.left;this.userCode="\n void main() {\n ivec5 coords = getOutputCoords();\n int wF = coords.x;\n int wR = coords.y;\n int wC = coords.z;\n int d1 = coords.w;\n int d2 = coords.u;\n\n float dotProd = 0.0;\n\n for (int b = 0; b < "+t.batchSize+"; b++) {\n for (int yF = 0; yF < "+t.outDepth+"; yF++) {\n int xF = wF + yF * "+e+" - "+i+";\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+" - "+o+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float dyValue = getDy(b, yF, yR, yC, d2);\n float xValue = getX(b, xF, xR, xC, d1);\n dotProd += (xValue * dyValue);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},Xi=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,r=t.filterWidth,i=t.strideDepth,a=t.strideHeight,o=t.strideWidth,s=e-1-t.padInfo.front,u=n-1-t.padInfo.top,l=r-1-t.padInfo.left;this.userCode="\n const ivec3 pads = ivec3("+s+", "+u+", "+l+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d1 = coords.u;\n\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyFCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n float dotProd = 0.0;\n for (int wF = 0; wF < "+e+"; wF++) {\n float dyF = float(dyFCorner + wF) / "+i+".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) / "+o+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n int wCPerm = "+r+" - 1 - wC;\n\n for (int d2 = 0; d2 < "+t.outChannels+"; d2++) {\n float xValue = getDy(batch, idyF, idyR, idyC, d2);\n float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);\n dotProd += xValue * wValue;\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},Yi=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,n=t.strideWidth,r=t.padInfo.top,i=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 // TO DO: Vec4 over the batch size\n for (int b = 0; b < "+t.batchSize+"; b++) {\n for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n int xR = wR + yR * "+e+" - "+r+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n int xC = wC + yC * "+n+" - "+i+";\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 "},Ji=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,i=t.strideWidth,a=e-1-t.padInfo.top,o=n-1-t.padInfo.left,s=t.outChannels/t.inChannels;this.userCode="\n const ivec2 pads = ivec2("+a+", "+o+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d1 = coords[3];\n ivec2 dyCorner = coords.yz - pads;\n int dyRCorner = dyCorner.x;\n int dyCCorner = dyCorner.y;\n\n float dotProd = 0.0;\n\n for (int wR = 0; wR < "+e+"; wR++) {\n float dyR = float(dyRCorner + wR) / "+r+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n int wRPerm = "+e+" - 1 - wR;\n\n for (int wC = 0; wC < "+n+"; wC++) {\n float dyC = float(dyCCorner + wC) / "+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 = "+n+" - 1 - wC;\n\n // TO DO: Vec4 over the channelMul\n for (int dm = 0; dm < "+s+"; dm++) {\n int d2 = d1 * "+s+" + dm;\n float xValue = getDy(batch, idyR, idyC, d2);\n float wValue = getW(wRPerm, wCPerm, d1, dm);\n dotProd += xValue * wValue;\n }\n }\n }\n setOutput(dotProd);\n }\n "},Zi=function(t,e,n,r){void 0===e&&(e=!1),void 0===n&&(n=null),void 0===r&&(r=!1),this.variableNames=["x","W"],this.outputShape=t.outShape;var i=t.padInfo.top,a=t.padInfo.left,o=t.strideHeight,s=t.strideWidth,u=t.dilationHeight,l=t.dilationWidth,c=t.filterHeight,p=t.filterWidth,h=4*Math.floor(t.inChannels/4),f=t.inChannels%4,d="channelsLast"===t.dataFormat,m=d?1:2,g=d?2:3,v=d?3:1,y="",b="";n&&(y=r?"float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n "+n+"\n }":"\n float activation(float x) {\n "+n+"\n }\n ",b="result = activation(result);");var x=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+y+"\n\n const ivec2 strides = ivec2("+o+", "+s+");\n const ivec2 pads = ivec2("+i+", "+a+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d2 = coords["+v+"];\n\n ivec2 xRCCorner =\n ivec2(coords["+m+"], coords["+g+"]) * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+c+"; wR++) {\n int xR = xRCorner + wR * "+u+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+p+"; wC++) {\n int xC = xCCorner + wC * "+l+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+h+"; d1 += 4) {\n vec4 wValues = vec4(\n getW(wR, wC, d1, d2),\n getW(wR, wC, d1 + 1, d2),\n getW(wR, wC, d1 + 2, d2),\n getW(wR, wC, d1 + 3, d2)\n );\n\n if ("+d+") {\n vec4 xValues = vec4(\n getX(batch, xR, xC, d1),\n getX(batch, xR, xC, d1 + 1),\n getX(batch, xR, xC, d1 + 2),\n getX(batch, xR, xC, d1 + 3)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec4 xValues = vec4(\n getX(batch, d1, xR, xC),\n getX(batch, d1 + 1, xR, xC),\n getX(batch, d1 + 2, xR, xC),\n getX(batch, d1 + 3, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n\n if ("+(1===f)+") {\n\n if ("+d+") {\n dotProd +=\n getX(batch, xR, xC, "+h+") *\n getW(wR, wC, "+h+", d2);\n } else {\n dotProd +=\n getX(batch, "+h+", xR, xC) *\n getW(wR, wC, "+h+", d2);\n }\n\n } else if ("+(2===f)+") {\n vec2 wValues = vec2(\n getW(wR, wC, "+h+", d2),\n getW(wR, wC, "+h+" + 1, d2)\n );\n\n if ("+d+") {\n vec2 xValues = vec2(\n getX(batch, xR, xC, "+h+"),\n getX(batch, xR, xC, "+h+" + 1)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec2 xValues = vec2(\n getX(batch, "+h+", xR, xC),\n getX(batch, "+h+" + 1, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n } else if ("+(3===f)+") {\n vec3 wValues = vec3(\n getW(wR, wC, "+h+", d2),\n getW(wR, wC, "+h+" + 1, d2),\n getW(wR, wC, "+h+" + 2, d2)\n );\n\n if ("+d+") {\n vec3 xValues = vec3(\n getX(batch, xR, xC, "+h+"),\n getX(batch, xR, xC, "+h+" + 1),\n getX(batch, xR, xC, "+h+" + 2)\n );\n dotProd += dot(xValues, wValues);\n } else {\n vec3 xValues = vec3(\n getX(batch, "+h+", xR, xC),\n getX(batch, "+h+" + 1, xR, xC),\n getX(batch, "+h+" + 2, xR, xC)\n );\n dotProd += dot(xValues, wValues);\n }\n\n }\n }\n }\n\n float result = dotProd;\n "+x+"\n "+b+"\n setOutput(result);\n }\n "},Qi=function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.padInfo.front,n=t.padInfo.top,r=t.padInfo.left,i=t.strideDepth,a=t.strideHeight,o=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,l=t.dilationWidth,c=t.filterDepth,p=t.filterHeight,h=t.filterWidth,f=4*Math.floor(t.inChannels/4),d=t.inChannels%4;this.userCode="\n const ivec3 strides = ivec3("+i+", "+a+", "+o+");\n const ivec3 pads = ivec3("+e+", "+n+", "+r+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int d2 = coords.u;\n\n ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xFCorner = xFRCCorner.x;\n int xRCorner = xFRCCorner.y;\n int xCCorner = xFRCCorner.z;\n\n // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get\n // y(yF, yR, yC, d2). ? = to be determined. : = across all\n // values in that axis.\n float dotProd = 0.0;\n for (int wF = 0; wF < "+c+"; wF++) {\n int xF = xFCorner + wF * "+s+";\n\n if (xF < 0 || xF >= "+t.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+p+"; wR++) {\n int xR = xRCorner + wR * "+u+";\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+h+"; wC++) {\n int xC = xCCorner + wC * "+l+";\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n for (int d1 = 0; d1 < "+f+"; d1 += 4) {\n vec4 xValues = vec4(\n getX(batch, xF, xR, xC, d1),\n getX(batch, xF, xR, xC, d1 + 1),\n getX(batch, xF, xR, xC, d1 + 2),\n getX(batch, xF, xR, xC, d1 + 3)\n );\n vec4 wValues = vec4(\n getW(wF, wR, wC, d1, d2),\n getW(wF, wR, wC, d1 + 1, d2),\n getW(wF, wR, wC, d1 + 2, d2),\n getW(wF, wR, wC, d1 + 3, d2)\n );\n\n dotProd += dot(xValues, wValues);\n }\n\n if ("+(1===d)+") {\n dotProd +=\n getX(batch, xF, xR, xC, "+f+") *\n getW(wF, wR, wC, "+f+", d2);\n } else if ("+(2===d)+") {\n vec2 xValues = vec2(\n getX(batch, xF, xR, xC, "+f+"),\n getX(batch, xF, xR, xC, "+f+" + 1)\n );\n vec2 wValues = vec2(\n getW(wF, wR, wC, "+f+", d2),\n getW(wF, wR, wC, "+f+" + 1, d2)\n );\n dotProd += dot(xValues, wValues);\n } else if ("+(3===d)+") {\n vec3 xValues = vec3(\n getX(batch, xF, xR, xC, "+f+"),\n getX(batch, xF, xR, xC, "+f+" + 1),\n getX(batch, xF, xR, xC, "+f+" + 2)\n );\n vec3 wValues = vec3(\n getW(wF, wR, wC, "+f+", d2),\n getW(wF, wR, wC, "+f+" + 1, d2),\n getW(wF, wR, wC, "+f+" + 2, d2)\n );\n dotProd += dot(xValues, wValues);\n }\n }\n }\n }\n setOutput(dotProd);\n }\n "},ta=function(t,e,n,r){void 0===e&&(e=!1),void 0===n&&(n=null),void 0===r&&(r=!1),this.variableNames=["x","W"],this.outputShape=t.outShape;var i=t.inHeight,a=t.inWidth,o=t.padInfo.top,s=t.padInfo.left,u=t.strideHeight,l=t.strideWidth,c=t.dilationHeight,p=t.dilationWidth,h=t.filterHeight,f=t.filterWidth,d=t.outChannels/t.inChannels,m="",g="";n&&(m=r?"float activation(float a) {\n float b = getPreluActivationWeightsAtOutCoords();\n "+n+"\n }":"\n float activation(float x) {\n "+n+"\n }\n ",g="result = activation(result);");var v=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+m+"\n\n const ivec2 strides = ivec2("+u+", "+l+");\n const ivec2 pads = ivec2("+o+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2 / "+d+";\n int q = d2 - d1 * "+d+";\n\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.\n for (int wR = 0; wR < "+h+"; wR++) {\n int xR = xRCorner + wR * "+c+";\n\n if (xR < 0 || xR >= "+i+") {\n continue;\n }\n\n for (int wC = 0; wC < "+f+"; wC++) {\n int xC = xCCorner + wC * "+p+";\n\n if (xC < 0 || xC >= "+a+") {\n continue;\n }\n\n float xVal = getX(batch, xR, xC, d1);\n float wVal = getW(wR, wC, d1, q);\n dotProd += xVal * wVal;\n }\n }\n\n float result = dotProd;\n "+v+"\n "+g+"\n setOutput(result);\n }\n "},ea=function(t,e,n,r){void 0===e&&(e=!1),void 0===n&&(n=null),void 0===r&&(r=!1),this.variableNames=["x","W"],this.usesPackedTextures=!0,this.outputShape=t.outShape;for(var i=t.inHeight,a=t.inWidth,o=t.padInfo.top,s=t.padInfo.left,u=t.strideHeight,c=t.strideWidth,p=t.dilationHeight,h=t.dilationWidth,f=t.filterHeight,d=t.filterWidth,m=d,g="int xR; int xC; int xCOffset;",v=0;v<f;v++)for(var y=0;y<d;y++)g+="\n vec4 xTexelR"+v+"C"+2*y+" = vec4(0.);\n vec4 wR"+v+"C"+y+" = vec4(0.);\n vec4 xR"+v+"C"+y+" = vec4(0.);";for(v=0;v<f;v++)for(var b=0;b<m;b++){if(g+="\n xR = xRCorner + "+v*p+";\n xC = xCCorner + "+(y=2*b)*h+";\n ",1===c){if(y<d&&(g+=s%2==1?"\n xCOffset = xC + 1;\n if(xR >= 0 && xR < "+i+" && xCOffset >= 0 && xCOffset < "+a+") {\n xTexelR"+v+"C"+y+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+v+"C"+y+" = vec4(0.);\n }\n\n xCOffset = xC + 1 - 2;\n if(xR >= 0 && xR < "+i+" && xCOffset >= 0 && xCOffset < "+a+") {\n vec4 previous = getX(batch, xR, xCOffset, d1);\n xR"+v+"C"+y+" = vec4(previous.zw, xTexelR"+v+"C"+y+".xy);\n } else {\n xR"+v+"C"+y+" = vec4(0, 0, xTexelR"+v+"C"+y+".xy);\n }\n ":"\n if(xR >= 0 && xR < "+i+" && xC >= 0 && xC < "+a+") {\n xTexelR"+v+"C"+y+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+v+"C"+y+" = vec4(0.);\n }\n\n xR"+v+"C"+y+" = xTexelR"+v+"C"+y+";\n ",y+1<d)){var x=s%2==0?l(h):h;h%2==0&&s%2==1||h%2!=0&&s%2!=1?(g+="\n xCOffset = xC + "+s%2+" + "+x+";\n\n if(xR >= 0 && xR < "+i+" &&\n xCOffset >= 0 && xCOffset < "+a+") {\n xTexelR"+v+"C"+(y+2)+" = getX(batch, xR, xCOffset, d1);\n }\n ",h>1&&(g+="\n xCOffset -= 2;\n if(xR >= 0 && xR < "+i+" &&\n xCOffset >= 0 && xCOffset < "+a+") {\n xTexelR"+v+"C"+y+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+v+"C"+y+" = vec4(0.);\n }\n "),g+="\n xR"+v+"C"+(y+1)+" = vec4(\n xTexelR"+v+"C"+y+".zw, xTexelR"+v+"C"+(y+2)+".xy);\n "):g+="\n xCOffset = xC + "+x+";\n\n if(xR >= 0 && xR < "+i+" &&\n xCOffset >= 0 && xCOffset < "+a+") {\n xTexelR"+v+"C"+(y+2)+" = getX(batch, xR, xCOffset, d1);\n }\n\n xR"+v+"C"+(y+1)+" = xTexelR"+v+"C"+(y+2)+";\n "}}else y<d&&(g+="\n if(xR >= 0 && xR < "+i+") {\n ",s%2==1?(g+="\n xCOffset = xC + 1 - "+c+";\n if(xCOffset >= 0 && xCOffset < "+a+") {\n xTexelR"+v+"C"+y+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+v+"C"+y+" = vec4(0.);\n }\n\n if(xC + 1 >= 0 && xC + 1 < "+a+") {\n xTexelR"+v+"C"+(y+2)+" = getX(batch, xR, xC + 1, d1);\n } else {\n xTexelR"+v+"C"+(y+2)+" = vec4(0.);\n }\n\n xR"+v+"C"+y+" = vec4(\n xTexelR"+v+"C"+y+".zw, xTexelR"+v+"C"+(y+2)+".zw);\n ",y+1<d&&(g+="\n vec4 final = vec4(0.);\n xCOffset = xC + 1 + "+c+";\n if(xCOffset >= 0 && xCOffset < "+a+") {\n final = getX(batch, xR, xCOffset, d1);\n }\n xR"+v+"C"+(y+1)+" = vec4(xTexelR"+v+"C"+(y+2)+".xy, final.xy);\n ")):(g+="\n if(xC >= 0 && xC < "+a+") {\n xTexelR"+v+"C"+y+" = getX(batch, xR, xC, d1);\n } else {\n xTexelR"+v+"C"+y+" = vec4(0.);\n }\n\n xCOffset = xC + "+c+";\n if(xCOffset >= 0 && xCOffset < "+a+") {\n xTexelR"+v+"C"+(y+2)+" = getX(batch, xR, xCOffset, d1);\n } else {\n xTexelR"+v+"C"+(y+2)+" = vec4(0.);\n }\n\n xR"+v+"C"+y+" = vec4(\n xTexelR"+v+"C"+y+".xy, xTexelR"+v+"C"+(y+2)+".xy);\n ",y+1<d&&(g+="\n xR"+v+"C"+(y+1)+" = vec4(\n xTexelR"+v+"C"+y+".zw, xTexelR"+v+"C"+(y+2)+".zw);\n ")),g+="}");y<d&&(g+="\n vec4 wTexelR"+v+"C"+y+" = getW("+v+", "+y+", d1, q);\n wR"+v+"C"+y+" = vec4(wTexelR"+v+"C"+y+".xz, wTexelR"+v+"C"+y+".xz);\n ",y+1<d&&(g+="\n vec4 wTexelR"+v+"C"+(y+1)+" = getW("+v+", "+(y+1)+", d1, q);\n wR"+v+"C"+(y+1)+" =\n vec4(wTexelR"+v+"C"+(y+1)+".xz, wTexelR"+v+"C"+(y+1)+".xz);"))}for(v=0;v<f;v++)for(y=0;y<d;y++)g+="dotProd += xR"+v+"C"+y+" * wR"+v+"C"+y+";";var w="",C="";n&&(w=r?"vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n "+n+"\n }":"vec4 activation(vec4 x) {\n "+n+"\n }",C="result = activation(result);");var N=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+w+"\n\n const ivec2 strides = ivec2("+u+", "+c+");\n const ivec2 pads = ivec2("+o+", "+s+");\n\n void main() {\n\n ivec4 coords = getOutputCoords();\n int batch = coords.x;\n ivec2 xRCCorner = coords.yz * strides - pads;\n int d2 = coords.w;\n int d1 = d2;\n int q = 0;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n vec4 dotProd = vec4(0.);\n\n "+g+"\n\n vec4 result = dotProd;\n "+N+"\n "+C+"\n setOutput(result);\n }\n "},na=function(t,e,n,r,i){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];var a=t[0],o=t[1],s=t[2],u=t[3],l=e[0],c=n[0],p=n[1];this.outputShape=[l,c,p,u];var h="bilinear"===r?1:0,f=[o-1+".0",s-1+".0"],d=f[0],m=f[1],g=c>1?[""+(o-1)/(c-1),"(y2-y1) * height_ratio","y1*"+d+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+d],v=g[0],y=g[1],b=g[2],x=p>1?[""+(s-1)/(p-1),"(x2-x1) * width_ratio","x1*"+m+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+m],w=x[0],C=x[1],N=x[2];this.userCode="\n const float height_ratio = float("+v+");\n const float width_ratio = float("+w+");\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int y = coords[1];\n int x = coords[2];\n int d = coords[3];\n\n // get box vals\n float y1 = getBoxes(b,0);\n float x1 = getBoxes(b,1);\n float y2 = getBoxes(b,2);\n float x2 = getBoxes(b,3);\n\n // get image in batch index\n int bInd = round(getBoxInd(b));\n if(bInd < 0 || bInd >= "+a+") {\n return;\n }\n\n float height_scale = "+y+";\n float width_scale = "+C+";\n\n float in_y = "+b+";\n if( in_y < 0.0 || in_y > "+d+" ) {\n setOutput(float("+i+"));\n return;\n }\n float in_x = "+N+";\n if( in_x < 0.0 || in_x > "+m+" ) {\n setOutput(float("+i+"));\n return;\n }\n\n vec2 sourceFracIndexCR = vec2(in_x,in_y);\n if("+h+" == 1) {\n // Compute the four integer indices.\n ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);\n ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));\n\n float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);\n float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);\n float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);\n float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);\n\n vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);\n\n float top = topLeft + (topRight - topLeft) * fracCR.x;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;\n float newValue = top + (bottom - top) * fracCR.y;\n setOutput(newValue);\n } else {\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestCR = ivec2(floor(\n sourceFracIndexCR + vec2(0.5,0.5)));\n float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);\n setOutput(newValue);\n }\n }\n "},ra=function(t,e,n){this.variableNames=["x"],this.outputShape=t;var r=t.length,i=t[t.length-1],a=n?"<":">";this.userCode="\n int getIndex(int i) {\n "+(n?"return "+i+" -i - 1;":"return i;")+"\n }\n\n void main() {\n "+Ei(r)+" coords = getOutputCoords();\n int end = "+ia(r,"coords")+";\n float val = 0.0;\n for (int i = "+i+" - 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 "+ia(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 ia(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 aa=function(t,e){this.variableNames=["A"];var n=fi();this.outputShape=t,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+di(["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 "},oa=function(t,e){this.variableNames=["A"],this.usesPackedTextures=!0;var n=fi();this.outputShape=t,this.userCode="\n ivec3 outCoordsFromFlatIndex(int index) {\n "+di(["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 "},sa=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}(),ua=function(t){this.variableNames=["X"],this.outputShape=[t,t],this.userCode="\n void main() {\n ivec2 coords = getOutputCoords();\n float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;\n setOutput(val);\n }\n "},la=function(t){this.variableNames=["A"];var e=fi();this.outputShape=t,this.userCode="\n "+gi+"\n\n void main() {\n float x = getAAtOutCoords();\n "+e.output+" = encode_float(x);\n }\n "},ca=function(t){this.variableNames=["A"],this.usesPackedTextures=!0;var e=fi();this.outputShape=t,this.userCode="\n "+gi+"\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 "},pa=function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"];var r=fi(),i=e[0],a=e[1];this.outputShape=t;var o="result";n&&(o="floor(result * 255. + 0.5)"),this.userCode="\n "+mi(t)+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n int flatIndex = getFlatIndex(coords);\n int offset = imod(flatIndex, 4);\n\n flatIndex = idiv(flatIndex, 4, 1.);\n \n int r = flatIndex / "+a+";\n int c = imod(flatIndex, "+a+");\n vec2 uv = (vec2(c, r) + halfCR) / vec2("+a+".0, "+i+".0);\n vec4 values = "+r.texture2D+"(A, uv);\n\n float result;\n\n if(offset == 0) {\n result = values[0];\n } else if(offset == 1) {\n result = values[1];\n } else if(offset == 2) {\n result = values[2];\n } else {\n result = values[3];\n }\n\n "+r.output+" = vec4("+o+", 0., 0., 0.);\n }\n "},ha=function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"];var r=fi(),i=e[0],a=e[1];this.outputShape=t;var o="",s="result";n&&(s="floor(result * 255. + 0.5)");for(var u=0;u<=1;u++)for(var l=0;l<=1;l++){var c=2*u+l;o+="\n localCoords = coords;\n if(localCoords[2] + "+l+" < "+t[2]+") {\n localCoords[2] += "+l+";\n if(localCoords[1] + "+u+" < "+t[1]+") {\n localCoords[1] += "+u+";\n\n flatIndex = getFlatIndex(localCoords);\n offset = imod(flatIndex, 4);\n \n flatIndex = idiv(flatIndex, 4, 1.);\n\n r = flatIndex / "+a+";\n c = imod(flatIndex, "+a+");\n uv = (vec2(c, r) + halfCR) / vec2("+a+".0, "+i+".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 "+mi(t)+"\n\n void main() {\n ivec3 coords = getOutputCoords();\n\n vec4 result = vec4(0.);\n int flatIndex, r, c, offset;\n ivec3 localCoords;\n vec2 uv;\n vec4 values;\n \n "+o+"\n\n "+r.output+" = "+s+";\n }\n "},fa=function(t,e,n){this.variableNames=["real","imag"];var r=e[1];this.outputShape=e;var i=n?"2.0 * "+Math.PI:"-2.0 * "+Math.PI,a=n?r+".0":"1.0";this.userCode="\n const float exponentMultiplier = "+i+";\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 "},da=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}(),ma=function(t){this.variableNames=["A"];var e=fi(),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 "},ga=function(t){this.variableNames=["A"];var e=fi(),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 "},va=function(t,e,n){this.variableNames=["A","indices"];var r=t.slice();r[n]=e,this.outputShape=r,this.rank=r.length;var i=Ei(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"],i=[],a=0;a<t.length;a++)a===e?i.push("int(getIndices("+r[a]+"))"):i.push(""+r[a]);return i.join()}(t,n);this.userCode="\n void main() {\n "+i+" resRC = getOutputCoords();\n setOutput(getA("+a+"));\n }\n "},ya=function(t,e,n){this.sliceDim=t,this.strides=e,this.variableNames=["x","indices"],this.outputShape=n;var r=Ei(e.length),i=Ei(n.length),a=this.sliceDim>1?"strides[j]":"strides";this.userCode="\n "+r+" strides = "+r+"("+this.strides+");\n void main() {\n "+i+" 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){var n=fi();return Gt(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 xa(t,e){return Zt(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 wa(t,e){return Qt(t,e,new Uint16Array([0,1,2,2,1,3]))}function Ca(t,e,n,r,i,a,o){ee(n,r);var s=te(t,e),u=t.TEXTURE_2D;return Pt(t,e,function(){return t.bindTexture(u,s)}),Pt(t,e,function(){return t.texParameteri(u,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE)}),Pt(t,e,function(){return t.texParameteri(u,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)}),Pt(t,e,function(){return t.texParameteri(u,t.TEXTURE_MIN_FILTER,t.NEAREST)}),Pt(t,e,function(){return t.texParameteri(u,t.TEXTURE_MAG_FILTER,t.NEAREST)}),Pt(t,e,function(){return t.texImage2D(u,0,i,n,r,0,a,o,null)}),Pt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)}),s}function Na(t,e,n,r,i){var a=Ft(n,r);return Ca(t,e,a[0],a[1],i.internalFormatFloat,i.textureFormatFloat,t.FLOAT)}function Ea(t,e,n,r,i){var a=Ft(n,r);return Ca(t,e,a[0],a[1],i.internalFormatHalfFloat,i.textureFormatFloat,i.textureTypeHalfFloat)}function Sa(t,e,n,r,i){var a=Ft(n,r);return Ca(t,e,a[0],a[1],t.RGBA,t.RGBA,t.UNSIGNED_BYTE)}function ka(t,e,n,r,i){var a=Mt(n,r);return Ca(t,e,a[0],a[1],i.internalFormatPackedFloat,t.RGBA,t.FLOAT)}function Ia(t,e,n,r,i){var a=Mt(n,r);return Ca(t,e,a[0],a[1],i.internalFormatPackedHalfFloat,t.RGBA,i.textureTypeHalfFloat)}function Aa(t,e,n,r){return Pt(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 Ra(t,e,n,r,i,a,o){var s,u,l;Pt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,n)}),a instanceof Uint8Array?(s=new Uint8Array(r*i*4),u=t.UNSIGNED_BYTE,l=t.RGBA):(s=new Float32Array(r*i*4),u=t.FLOAT,l=o.internalFormatPackedFloat),s.set(a),Pt(t,e,function(){return t.texImage2D(t.TEXTURE_2D,0,l,r,i,0,t.RGBA,u,s)}),Pt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)})}function Ta(t,e,n,r){Pt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,n)}),r.data instanceof Uint8Array?Pt(t,e,function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,r.width,r.height,0,t.RGBA,t.UNSIGNED_BYTE,r.data)}):Pt(t,e,function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r)}),Pt(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)})}function Da(t,e,n,r,i){var a=t.createBuffer();Pt(t,e,function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,a)});var o=16*n*r;return Pt(t,e,function(){return t.bufferData(t.PIXEL_PACK_BUFFER,o,t.STREAM_READ)}),Pt(t,e,function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,0)}),Pt(t,e,function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,null)}),a}function Oa(t,e,n){var r=t,i=new Float32Array(n);return r.bindBuffer(r.PIXEL_PACK_BUFFER,e),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,i),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),i}function _a(t,e,n,r,i){var a=Ft(n,r),o=a[0],s=a[1],u=new Uint8Array(n*r*4);return Pt(t,e,function(){return t.readPixels(0,0,o,s,i.downloadTextureFormat,t.UNSIGNED_BYTE,u)}),new Float32Array(u.buffer)}function Fa(t,e,n,r,i,a,o,s){var u=t,l=new Float32Array(function(t,e){var n=Mt(a,o);return n[0]*n[1]*4}());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 za(t,e,n,r){var i=new Float32Array(n*r*4);return Pt(t,e,function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,i)}),i}var Ma=Object.freeze({createVertexShader:ba,createVertexBuffer:xa,createIndexBuffer:wa,createFloat32MatrixTexture:Na,createFloat16MatrixTexture:Ea,createUnsignedBytesMatrixTexture:Sa,createPackedMatrixTexture:ka,createFloat16PackedMatrixTexture:Ia,bindVertexProgramAttributeStreams:Aa,uploadDenseMatrixToTexture:Ra,uploadPixelDataToTexture:Ta,createBufferFromOutputTexture:Da,downloadFloat32MatrixFromBuffer:Oa,downloadByteEncodedFloatMatrixFromOutputTexture:_a,downloadPackedMatrixFromBuffer:Fa,downloadMatrixFromPackedOutputTexture:za}),La=function(){function t(t){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];var e=o().getNumber("WEBGL_VERSION");if(null!=t?(this.gl=t,Dt(e,t)):this.gl=Ot(e),1===o().getNumber("WEBGL_VERSION"))this.textureFloatExtension=jt(this.gl,this.debug,"OES_texture_float"),this.colorBufferFloatExtension=this.gl.getExtension("WEBGL_color_buffer_float"),this.textureHalfFloatExtension=jt(this.gl,this.debug,"OES_texture_half_float"),this.colorBufferHalfFloatExtension=this.gl.getExtension("EXT_color_buffer_half_float");else if(Ne(this.gl,"EXT_color_buffer_float"))this.colorBufferFloatExtension=this.gl.getExtension("EXT_color_buffer_float");else{if(!Ne(this.gl,"EXT_color_buffer_half_float"))throw new Error("GL context does not support color renderable floats");this.colorBufferHalfFloatExtension=this.gl.getExtension("EXT_color_buffer_half_float")}this.vertexBuffer=xa(this.gl,this.debug),this.indexBuffer=wa(this.gl,this.debug),this.framebuffer=ne(this.gl,this.debug),this.textureConfig=Lt(this.gl,this.textureHalfFloatExtension)}return Object.defineProperty(t.prototype,"debug",{get:function(){return o().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;Pt(e,this.debug,function(){return e.finish()}),Pt(e,this.debug,function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)}),Pt(e,this.debug,function(){return e.deleteFramebuffer(t.framebuffer)}),Pt(e,this.debug,function(){return e.bindBuffer(e.ARRAY_BUFFER,null)}),Pt(e,this.debug,function(){return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)}),Pt(e,this.debug,function(){return e.deleteBuffer(t.indexBuffer)}),this.disposed=!0}},t.prototype.createFloat32MatrixTexture=function(t,e){return this.throwIfDisposed(),Na(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createFloat16MatrixTexture=function(t,e){return this.throwIfDisposed(),Ea(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createUnsignedBytesMatrixTexture=function(t,e){return this.throwIfDisposed(),Sa(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.uploadPixelDataToTexture=function(t,e){this.throwIfDisposed(),Ta(this.gl,this.debug,t,e)},t.prototype.uploadDenseMatrixToTexture=function(t,e,n,r){this.throwIfDisposed(),Ra(this.gl,this.debug,t,e,n,r,this.textureConfig)},t.prototype.createFloat16PackedMatrixTexture=function(t,e){return this.throwIfDisposed(),Ia(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createPackedMatrixTexture=function(t,e){return this.throwIfDisposed(),ka(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),Pt(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 _a(r.gl,r.debug,e,n,r.textureConfig)})},t.prototype.downloadPackedMatrixFromBuffer=function(t,e,n,r,i,a){return Fa(this.gl,t,0,0,0,i,a,this.textureConfig)},t.prototype.downloadFloat32MatrixFromBuffer=function(t,e){return Oa(this.gl,t,e)},t.prototype.createBufferFromTexture=function(t,e,n){this.bindTextureToFrameBuffer(t);var r=Da(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(o().getBool("WEBGL_FENCE_API_ENABLED")){var i=t,a=i.fenceSync(i.SYNC_GPU_COMMANDS_COMPLETE,0);t.flush(),n=function(){var t=i.clientWaitSync(a,0,0);return t===i.ALREADY_SIGNALED||t===i.CONDITION_SATISFIED},e=a}else o().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(e=this.beginQuery(),this.endQuery(),n=function(){return r.isQueryAvailable(e,o().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 za(r.gl,r.debug,e,n)})},t.prototype.createProgram=function(t){this.throwIfDisposed();var e=this.gl,n=qt(e,this.debug,t),r=ba(e,this.debug),i=Xt(e,this.debug);return Pt(e,this.debug,function(){return e.attachShader(i,r)}),Pt(e,this.debug,function(){return e.attachShader(i,n)}),Yt(e,this.debug,i),this.debug&&Jt(e,this.debug,i),this.vertexAttrsAreBound||(this.setProgram(i),this.vertexAttrsAreBound=Aa(e,this.debug,this.program,this.vertexBuffer)),i},t.prototype.deleteProgram=function(t){var e=this;this.throwIfDisposed(),t===this.program&&(this.program=null),null!=t&&Pt(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&&Jt(this.gl,this.debug,this.program),Pt(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):oe(this.gl,t,e)},t.prototype.getAttributeLocation=function(t,e){var n=this;return this.throwIfDisposed(),Pt(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=Mt(e,n),i=r[0],a=r[1];this.setOutputMatrixTextureDriver(t,i,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&&Jt(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(),Pt(t,this.debug,function(){return t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0)})},t.prototype.blockUntilAllProgramsCompleted=function(){var t=this;this.throwIfDisposed(),Pt(this.gl,this.debug,function(){return t.gl.finish()})},t.prototype.getQueryTimerExtension=function(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=jt(this.gl,this.debug,2===o().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===o().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(),i=r.createQueryEXT();return r.beginQueryEXT(r.TIME_ELAPSED_EXT,i),i},t.prototype.endQuery=function(){if(2!==o().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 i(this,function(n){switch(n.label){case 0:return[4,w(function(){return e.disposed||e.isQueryAvailable(t,o().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))})];case 1:return n.sent(),[2,this.getQueryTime(t,o().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(),i=n.getQueryParameter(t,n.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),i&&!this.disjoint}return i=(r=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(t,r.QUERY_RESULT_AVAILABLE_EXT),null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),i&&!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){if(!t[e]())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||w(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,Pt(r,this.debug,function(){return r.viewport(0,0,e,n)}),Pt(r,this.debug,function(){return r.scissor(0,0,e,n)})},t.prototype.setOutputMatrixWriteRegionDriver=function(t,e,n,r){var i=this;this.throwIfDisposed(),Pt(this.gl,this.debug,function(){return i.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 Pa(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,i=e[n],a=i.shape;if(!g(r,a))throw Error("Binary was compiled with different shapes than the current args. Shapes "+r+" and "+a+" must match");if(!t.isUniform||!i.isUniform){var o=t.texShape,s=i.isUniform?null:i.texData.texShape;if(!g(o,s))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+o+" and "+s+" must match")}})}var Ba=function(t,e,n){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t;for(var r=n.filterWidth,i=n.inChannels,a=n.strideWidth,o=n.strideHeight,s=n.padInfo,u=n.outWidth,l=n.dilationWidth,c=n.dilationHeight,p=n.dataFormat,h=s.left,f=s.top,d=i*r,m=fi(),g="channelsLast"===p,v=g?0:1,y=g?1:2,b="",x=0;x<=1;x++)for(var w=0;w<=1;w++)b+="\n blockIndex = rc.y + "+w+";\n pos = rc.x + "+x+";\n\n if(blockIndex < "+t[1]+" && pos < "+t[0]+") {\n offsetY = int(blockIndex / ("+u+")) * "+o+" - "+f+";\n d0 = offsetY + "+c+" * (pos / "+d+");\n\n if(d0 < "+e[v]+" && d0 >= 0) {\n\n offsetX = int(mod(float(blockIndex), "+u+".) * "+a+". - "+h+".);\n d1 = offsetX + "+l+" * (int(mod(float(pos), "+d+".) / "+i+".));\n\n if(d1 < "+e[y]+" && d1 >= 0) {\n\n ch = int(mod(float(pos), "+i+".));\n\n if ("+g+") {\n innerDims = vec2(d1, ch);\n result["+(2*x+w)+"] = getChannel(\n getA(d0, int(innerDims.x),\n int(innerDims.y)), innerDims);\n } else {\n innerDims = vec2(d0, d1);\n result["+(2*x+w)+"] = getChannel(\n getA(ch, int(innerDims.x),\n int(innerDims.y)), innerDims);\n }\n }\n }\n }\n ";this.userCode="\n void main() {\n ivec2 rc = getOutputCoords();\n\n vec4 result = vec4(0);\n\n int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n vec2 innerDims;\n\n "+b+"\n\n "+m.output+" = result;\n }\n "},Wa=function(t,e,n,r,i){this.variableNames=["x"],this.outputShape=[];var a,o=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";a=.5===i?"inversesqrt("+u+")":1===i?"1.0/("+u+")":"exp(log("+u+") * float(-"+i+"));",this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int r = coords[1];\n int c = coords[2];\n int d = coords[3];\n float x = getX(b, r, c, d);\n float sum = 0.0;\n for (int j = -"+o+"; j <= "+o+"; j++) {\n int idx = d + j;\n if (idx >= 0 && idx <= "+s+") {\n float z = getX(b, r, c, idx);\n sum += z * z;\n }\n }\n float val = x * "+a+";\n setOutput(val);\n }\n "},Va=function(t,e,n,r,i){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=i,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("+i+")\n * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)\n / norm;\n if (k == d) {\n dyi += pow(norm, -1.0 * "+i+");\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 "},Ua=function(t,e,n,r,i){this.variableNames=["x"],this.outputShape=[],this.usesPackedTextures=!0;var a,o=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";a=.5===i?"inversesqrt("+u+")":1===i?"1.0/("+u+")":"exp(log("+u+") * float(-"+i+"));",this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords.x;\n int r = coords.y;\n int c = coords.z;\n int d = coords.w;\n\n bool hasNextCol = d < "+this.outputShape[3]+";\n bool hasNextRow = c < "+this.outputShape[2]+";\n\n vec4 sum = vec4(0.);\n vec4 xFragAtOutputCoords = getX(b, r, c, d);\n\n vec4 xAtOutputCoords = vec4(\n getChannel(xFragAtOutputCoords, vec2(c, d)),\n hasNextCol ?\n getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,\n hasNextRow ?\n getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,\n (hasNextRow && hasNextCol) ?\n getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0\n );\n\n int firstChannel = d - "+o+";\n vec2 cache = vec2(0.);\n if(firstChannel >= 0){\n vec4 firstChannelFrag = getX(b, r, c, firstChannel);\n cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));\n if(hasNextRow){\n cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));\n }\n }\n\n ivec2 depth = ivec2(d, d + 1);\n for (int j = - "+o+"; j <= "+o+"; j++) {\n ivec2 idx = depth + j;\n bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\n bvec2 belowUpperBound = lessThanEqual(idx, ivec2("+s+"));\n\n bool depthInRange = aboveLowerBound.x && belowUpperBound.x;\n bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;\n\n if(depthInRange || depthPlusOneInRange){\n vec4 z = vec4(0.);\n vec4 xFragAtCurrentDepth;\n z.xz = cache.xy;\n if(depthPlusOneInRange && hasNextCol){\n xFragAtCurrentDepth = idx.y != d ?\n getX(b, r, c, idx.y) : xFragAtOutputCoords;\n z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));\n if(hasNextRow){\n z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));\n }\n }\n cache.xy = z.yw;\n sum += z * z;\n }\n }\n vec4 result = xAtOutputCoords * "+a+";\n setOutput(result);\n }\n "},ja=function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideHeight,n=t.strideWidth,r=t.dilationHeight,i=t.effectiveFilterHeight,a=t.effectiveFilterWidth,o=i-1-t.padInfo.top,s=a-1-t.padInfo.left,u=i*a-1;this.userCode="\n const ivec2 pads = ivec2("+o+", "+s+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n\n ivec2 dyRCCorner = coords.yz - pads;\n int dyRCorner = dyRCCorner.x;\n int dyCCorner = dyRCCorner.y;\n\n // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n for (int wR = 0; wR < "+i+";\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 "},Ga=function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideDepth,n=t.strideHeight,r=t.strideWidth,i=t.dilationDepth,a=t.dilationHeight,o=t.dilationWidth,s=t.effectiveFilterDepth,u=t.effectiveFilterHeight,l=t.effectiveFilterWidth,c=s-1-t.padInfo.front,p=u-1-t.padInfo.top,h=l-1-t.padInfo.left,f=s*u*l-1;this.userCode="\n const ivec3 pads = ivec3("+c+", "+p+", "+h+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n int dyDCorner = dyCorner.x;\n int dyRCorner = dyCorner.y;\n int dyCCorner = dyCorner.z;\n\n // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get\n // dx(xD, xR, xC, ch).\n // ? = to be determined. : = across all values in that axis.\n float dotProd = 0.0;\n\n for (int wD = 0; wD < "+s+";\n wD += "+i+") {\n float dyD = float(dyDCorner + wD) / "+e+".0;\n\n if (dyD < 0.0 || dyD >= "+t.outDepth+".0 || fract(dyD) > 0.0) {\n continue;\n }\n int idyD = int(dyD);\n\n for (int wR = 0; wR < "+u+";\n wR += "+a+") {\n float dyR = float(dyRCorner + wR) / "+n+".0;\n\n if (dyR < 0.0 || dyR >= "+t.outHeight+".0 ||\n fract(dyR) > 0.0) {\n continue;\n }\n int idyR = int(dyR);\n\n for (int wC = 0; wC < "+l+";\n wC += "+o+") {\n float dyC = float(dyCCorner + wC) / "+r+".0;\n\n if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n fract(dyC) > 0.0) {\n continue;\n }\n int idyC = int(dyC);\n\n float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n int maxPosValue = "+f+" -\n int(getMaxPos(batch, idyD, idyR, idyC, ch));\n\n // Get the current value, check it against the value from the\n // position matrix.\n int curPosValue =\n wD * "+u+" * "+l+" +\n wR * "+l+" + wC;\n float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n dotProd += dyValue * mask;\n }\n }\n }\n setOutput(dotProd);\n }\n "},qa=function(t,e,n,r,i,a,o){void 0===n&&(n=!1),void 0===r&&(r=!1),void 0===i&&(i=!1),void 0===a&&(a=null),void 0===o&&(o=!1),this.variableNames=["matrixA","matrixB"],this.usesPackedTextures=!0,this.outputShape=e;var s=n?t[1]:t[2],u=Math.ceil(s/2),l=n?"i * 2, rc.y":"rc.y, i * 2",c=r?"rc.z, i * 2":"i * 2, rc.z",p=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],h=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],f="",d="";a&&(f=o?"vec4 activation(vec4 a) {\n vec4 b = getPreluActivationWeightsAtOutCoords();\n "+a+"\n }":"vec4 activation(vec4 x) {\n "+a+"\n }",d="result = activation(result);");var m=i?"result += getBiasAtOutCoords();":"";i&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),this.userCode="\n "+f+"\n\n const float sharedDimension = "+u+".0;\n\n vec4 dot2x2ARowBCol(ivec3 rc) {\n vec4 result = vec4(0);\n for (int i = 0; i < "+u+"; i++) {\n vec4 a = getMatrixA(rc.x, "+l+");\n vec4 b = getMatrixB(rc.x, "+c+");\n\n // These swizzled products need to be separately added.\n // See: https://github.com/tensorflow/tfjs/issues/1735\n result += ("+p[0]+" * "+h[0]+");\n result += ("+p[1]+" * "+h[1]+");\n }\n return result;\n }\n\n void main() {\n ivec3 rc = getOutputCoords();\n vec4 result = dot2x2ARowBCol(rc);\n\n "+m+"\n\n "+d+"\n\n setOutput(result);\n }\n "},Ha=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}(),Ka=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 "},$a=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=hi("rc",e),r=Ei(e),i=function(t,e,n){if(1===t)return"rc > "+e[0];for(var r="",i=t-2;i<t;i++)r+=n[i]+" >= "+e[i],i<t-1&&(r+="||");return r}(e,t,n),a=function(t,e,n,r){if(1===t)return"";var i=r.slice(-2);return"\n int r = "+i[0]+";\n int c = "+i[1]+";\n int rp1 = r + 1;\n int cp1 = c + 1;\n\n bool cEdge = cp1 >= "+e+";\n bool rEdge = rp1 >= "+n+";\n "}(e,t[t.length-1],t[t.length-2],n),o=function(t,e){var n=t.length,r=function(t,e){for(var n=[],r=0;r<=1;r++)for(var i=0;i<=1;i++){for(var a=(0===r?"r":"rp1")+", "+(0===i?"c":"cp1"),o=2;o<t;o++)a=e[e.length-1-o]+","+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("+i+") {\n setOutput(vec4(0));\n } else {\n "+a+"\n\n setOutput(vec4("+o+"));\n }\n }\n "}},Xa=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,i=Ei(r),a=e.map(function(t){return t[0]}).join(","),o=e.map(function(e,n){return e[0]+t[n]}).join(","),s=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);this.userCode=1!==r?"\n "+i+" start = "+i+"("+a+");\n "+i+" end = "+i+"("+o+");\n\n void main() {\n "+i+" outC = getOutputCoords();\n if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n setOutput(float("+n+"));\n } else {\n "+i+" coords = outC - start;\n setOutput(getX("+s+"));\n }\n }\n ":"\n int start = "+a+";\n int end = "+o+";\n\n void main() {\n int outC = getOutputCoords();\n if (outC < start || outC >= end) {\n setOutput(float("+n+"));\n } else {\n setOutput(getX(outC - start));\n }\n }\n "},Ya=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,i=Ei(r),a=e.map(function(t){return t[0]}).join(","),o=e.map(function(e,n){return e[0]+t[n]}).join(","),s=hi("rc",r),u=hi("source",r),l=s[r-1]+" < "+this.outputShape[r-1],c=1===r?"source":"vec2("+u.slice(-2).join()+")",p=[i+" rc = outputLoc;",s[r-1]+" += 1;\n if("+l+") {\n ",1===r?"":"}\n rc = outputLoc;\n "+s[r-2]+" += 1;\n if("+s[r-2]+" < "+this.outputShape[r-2]+") {",1===r?"":" "+s[r-1]+" += 1;\n if("+l+") {"],h=1===r?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",f="",d=0,m=1===r?2:4;d<m;d++)f+="\n "+p[d]+"\n if ("+h+") {\n result["+d+"] = float("+n+");\n } else {\n "+i+" source = rc - start;\n result["+d+"] = getChannel(getX("+u.join()+"), "+c+");\n }\n ";f+=1===r?"} ":"}}",this.userCode="\n const "+i+" start = "+i+"("+a+");\n const "+i+" end = "+i+"("+o+");\n\n void main() {\n "+i+" outputLoc = getOutputCoords();\n vec4 result = vec4(0.);\n "+f+"\n setOutput(result);\n }\n "},Ja=function(t,e,n){if(this.variableNames=["x"],"avg"===e&&n)throw new Error("Cannot compute positions for average pool.");var r=t.filterWidth,i=t.strideHeight,a=t.strideWidth,o=t.dilationHeight,s=t.dilationWidth,u=t.effectiveFilterHeight,l=t.effectiveFilterWidth,c=t.padInfo.top,p=t.padInfo.left;this.outputShape=t.outShape;var h="avg"===e,f="0.0";if(h||(f="-1.0 / 1e-20"),n)this.userCode="\n const ivec2 strides = ivec2("+i+", "+a+");\n const ivec2 pads = ivec2("+c+", "+p+");\n\n void main() {\n ivec4 coords = getOutputCoords();\n int batch = coords[0];\n int d = coords[3];\n\n ivec2 xRCCorner = coords.yz * strides - pads;\n int xRCorner = xRCCorner.x;\n int xCCorner = xRCCorner.y;\n\n // max/min x(?, ?, d) to get y(yR, yC, d).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n float avgValue = 0.0;\n\n for (int wR = 0; wR < "+u+";\n wR += "+o+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+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 m=4*Math.floor(r/4),g=r%4,v="\n if ("+h+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec2 strides = ivec2("+i+", "+a+");\n const ivec2 pads = ivec2("+c+", "+p+");\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 += "+o+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+m+"; wC += 4) {\n int xC = xCCorner + wC * "+s+";\n\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n getValue(batch, xR, xC + 2 * "+s+", d),\n getValue(batch, xR, xC + 3 * "+s+", d)\n );\n\n "+v+"\n }\n\n int xC = xCCorner + "+m+";\n if ("+(1===g)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+v+"\n } else if ("+(2===g)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n initializationValue,\n initializationValue\n );\n\n "+v+"\n } else if ("+(3===g)+") {\n vec4 values = vec4(\n getValue(batch, xR, xC, d),\n getValue(batch, xR, xC + "+s+", d),\n getValue(batch, xR, xC + 2 * "+s+", d),\n initializationValue\n );\n\n "+v+"\n }\n }\n setOutput("+d+");\n }\n "}},Za=function(t,e,n){if(this.variableNames=["x"],"avg"===e&&n)throw new Error("Cannot compute positions for average pool.");var r=t.filterWidth,i=t.strideDepth,a=t.strideHeight,o=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,l=t.dilationWidth,c=t.effectiveFilterDepth,p=t.effectiveFilterHeight,h=t.effectiveFilterWidth,f=t.padInfo.front,d=t.padInfo.top,m=t.padInfo.left;this.outputShape=t.outShape;var g="avg"===e,v="0.0";if(g||(v="-1.0 / 1e-20"),n)this.userCode="\n const ivec3 strides =\n ivec3("+i+", "+a+", "+o+");\n const ivec3 pads = ivec3("+f+", "+d+", "+m+");\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).\n // ? = to be determined\n float minMaxValue = 0.0;\n float minMaxValueFound = 0.0;\n int minMaxPosition = 0;\n\n for (int wD = 0; wD < "+c+";\n wD += "+s+") {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= "+t.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+p+";\n wR += "+u+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+h+";\n wC += "+l+") {\n int xC = xCCorner + wC;\n\n if (xC < 0 || xC >= "+t.inWidth+") {\n continue;\n }\n\n float value = getX(batch, xD, xR, xC, ch);\n\n // If a min / max value has already been found, use it. If not,\n // use the current value.\n float currMinMaxValue = mix(\n value, minMaxValue, minMaxValueFound);\n if (value >= currMinMaxValue) {\n minMaxValue = value;\n minMaxValueFound = 1.0;\n minMaxPosition =\n wD * "+p+" * "+h+" +\n wR * "+h+" + wC;;\n }\n }\n }\n }\n setOutput(float(minMaxPosition));\n }\n ";else{var y=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===e&&(y="avgValue / count");var b=4*Math.floor(r/4),x=r%4,w="\n if ("+g+") {\n avgValue += dot(values, ones);\n } else {\n minMaxValue = max(values, minMaxValue);\n }\n ";this.userCode="\n const ivec3 strides =\n ivec3("+i+", "+a+", "+o+");\n const ivec3 pads = ivec3("+f+", "+d+", "+m+");\n const float initializationValue = "+v+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float count = 0.0;\n\n float getValue(int batch, int xD, int xR, int xC, int ch) {\n if (xC < 0 || xC >= "+t.inWidth+") {\n return initializationValue;\n }\n count += 1.0;\n return getX(batch, xD, xR, xC, ch);\n }\n\n void main() {\n ivec5 coords = getOutputCoords();\n int batch = coords.x;\n int ch = coords.u;\n\n ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n int xDCorner = xCorner.x;\n int xRCorner = xCorner.y;\n int xCCorner = xCorner.z;\n\n // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).\n // ? = to be determined\n vec4 minMaxValue = vec4("+v+");\n float avgValue = 0.0;\n count = 0.0;\n\n for (int wD = 0; wD < "+c+";\n wD += "+s+") {\n int xD = xDCorner + wD;\n\n if (xD < 0 || xD >= "+t.inDepth+") {\n continue;\n }\n\n for (int wR = 0; wR < "+p+";\n wR += "+u+") {\n int xR = xRCorner + wR;\n\n if (xR < 0 || xR >= "+t.inHeight+") {\n continue;\n }\n\n for (int wC = 0; wC < "+b+"; wC += 4) {\n int xC = xCCorner + wC * "+l+";\n\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+l+", ch),\n getValue(batch, xD, xR, xC + 2 * "+l+", ch),\n getValue(batch, xD, xR, xC + 3 * "+l+", ch)\n );\n\n "+w+"\n }\n\n int xC = xCCorner + "+b+";\n if ("+(1===x)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+w+"\n } else if ("+(2===x)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+l+", ch),\n initializationValue,\n initializationValue\n );\n\n "+w+"\n } else if ("+(3===x)+") {\n vec4 values = vec4(\n getValue(batch, xD, xR, xC, ch),\n getValue(batch, xD, xR, xC + "+l+", ch),\n getValue(batch, xD, xR, xC + 2 * "+l+", ch),\n initializationValue\n );\n\n "+w+"\n }\n }\n setOutput("+y+");\n }\n }\n "}},Qa=function(t,e){this.variableNames=["x"];var n=t.windowSize,r=t.batchSize,i=t.inSize,a=Math.ceil(i/n);this.outputShape=[r,a];var o="0.0",s="";"prod"===e?o="1.0":"min"===e?(o="1.0 / 1e-20",s="min"):"max"===e&&(o="-1.0 / 1e-20",s="max");var u=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"sum"===e?u="sumValue":"prod"===e?u="prodValue":"all"===e?u="allValue":"any"===e&&(u="anyValue");var l=4*Math.floor(n/4),c=n%4,p="\n if ("+("sum"===e)+") {\n sumValue += dot(values, ones);\n } else if ("+("prod"===e)+") {\n vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n prodValue *= tmp[0] * tmp[1];\n } else {\n minMaxValue = "+s+"(values, minMaxValue);\n }\n ",h="vec4";"all"===e?(o="1.0",p="\n bool reducedAllValue = all(values);\n float floatedReducedAllValue = float(reducedAllValue);\n allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n ",h="bvec4"):"any"===e&&(o="0.0",p="\n bool reducedAnyValue = any(values);\n float floatedReducedAnyValue = float(reducedAnyValue);\n anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n ",h="bvec4");var f="";i%n>0&&(f="\n if (inIdx < 0 || inIdx >= "+i+") {\n return initializationValue;\n }\n "),this.userCode="\n const float initializationValue = "+o+";\n const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n float getValue(int batch, int inIdx) {\n "+f+"\n return getX(batch, inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = outIdx * "+n+";\n\n vec4 minMaxValue = vec4("+o+");\n float prodValue = 1.0;\n float sumValue = 0.0;\n float allValue = 1.0;\n float anyValue = 0.0;\n\n for (int i = 0; i < "+l+"; i += 4) {\n int inIdx = inOffset + i;\n "+h+" values = "+h+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n getValue(batch, inIdx + 3)\n );\n\n "+p+"\n }\n\n int inIdx = inOffset + "+l+";\n if ("+(1===c)+") {\n "+h+" values = "+h+"(\n getValue(batch, inIdx),\n initializationValue,\n initializationValue,\n initializationValue\n );\n\n "+p+"\n } else if ("+(2===c)+") {\n "+h+" values = "+h+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n initializationValue,\n initializationValue\n );\n\n "+p+"\n } else if ("+(3===c)+") {\n "+h+" values = "+h+"(\n getValue(batch, inIdx),\n getValue(batch, inIdx + 1),\n getValue(batch, inIdx + 2),\n initializationValue\n );\n\n "+p+"\n }\n setOutput("+u+");\n }\n "},to=function(t,e){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t;for(var n="",r=0;r<4;r++){var i="thisRC = rc;";r%2==1&&(i+="thisRC.z += 1;"),r>1&&(i+="thisRC.y += 1;"),n+="\n "+i+"\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 "+di(["r","c","d"],e)+"\n return ivec3(r, c, d);\n }\n \n "+mi(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 "},eo=function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,i=r[1],a=r[2],o=t.shape,s=o[1],u=o[2],l=[n&&s>1?i-1:i,n&&u>1?a-1:a],c=[n&&s>1?s-1:s,n&&u>1?u-1:u],p=l[0]/c[0],h=l[1]/c[1],f=1/p,d=1/h,m=2*Math.ceil(f)+2,g=2*Math.ceil(d)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+p+");\n const float widthScale = float("+h+");\n\n const float invHeightScale = float("+f+");\n const float invWidthScale = float("+d+");\n\n const int winHeight = int("+m+");\n const int winWidth = int("+g+");\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(startRLerp - float(winHeight / 2));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(startCLerp - float(winWidth / 2));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= "+s+") {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= "+u+") {\n continue;\n }\n\n float dxR = float(dyR) * heightScale;\n int topDxRIndex = int(floor(dxR));\n int bottomDxRIndex = int(min(ceil(dxR), "+(i-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 "},no=function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var i=t[0],a=t[1],o=t[2],s=t[3];this.outputShape=[i,e,n,s];var u=[r&&e>1?a-1:a,r&&n>1?o-1:o],l=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+");\n const vec2 inputShapeRC = vec2("+a+".0, "+o+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\n ivec2 sourceCeilRC = ivec2(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\n float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\n float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\n float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n float top = topLeft + (topRight - topLeft) * fracRC.y;\n float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n float newValue = top + (bottom - top) * fracRC.x;\n\n setOutput(newValue);\n }\n "},ro=function(t,e,n,r){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=[];var i=t[0],a=t[1],o=t[2],s=t[3];this.outputShape=[i,e,n,s];var u=[r&&e>1?a-1:a,r&&n>1?o-1:o],l=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n const vec3 effectiveInputOverOutputRatioRC = vec3(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+",\n "+u[1]/l[1]+");\n const vec3 inputShapeRC = vec3("+a+".0, "+o+".0,\n "+o+".0);\n\n float getAValue(int b, int r, int c, int d) {\n return getChannel(getA(b, r, c, d), vec2(c, d));\n }\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n // Calculate values for next column in yRC.z.\n ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n // Fractional source index.\n vec3 sourceFracIndexRC = vec3(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the four integer indices.\n ivec3 sourceFloorRC = ivec3(sourceFracIndexRC);\n ivec3 sourceCeilRC = ivec3(\n min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n \n // Should we calculate next column and row elements in 2x2 packed cell.\n bool hasNextCol = d < "+(s-1)+"; \n bool hasNextRow = coords.z < "+(n-1)+";\n\n // In parallel, construct four corners for all four components in\n // packed 2x2 cell.\n vec4 topLeft = vec4(\n getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 bottomLeft = vec4(\n getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n vec4 topRight = vec4(\n getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec4 bottomRight = vec4(\n getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),\n hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)\n : 0.0,\n hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)\n : 0.0,\n (hasNextRow && hasNextCol) ?\n getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);\n\n vec4 top = mix(topLeft, topRight, fracRC.yyzz);\n vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);\n vec4 newValue = mix(top, bottom, fracRC.x);\n\n setOutput(newValue);\n }\n "},io=function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,i=r[1],a=r[2],o=t.shape,s=o[1],u=o[2],l=[n&&s>1?i-1:i,n&&u>1?a-1:a],c=[n&&s>1?s-1:s,n&&u>1?u-1:u],p=l[0]/c[0],h=l[1]/c[1],f=1/p,d=1/h,m=2*Math.ceil(f)+2,g=2*Math.ceil(d)+2;this.userCode="\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n int r = coords[1];\n int c = coords[2];\n\n float accumulator = 0.0;\n\n const float heightScale = float("+p+");\n const float widthScale = float("+h+");\n\n const float invHeightScale = float("+f+");\n const float invWidthScale = float("+d+");\n\n const int winHeight = int("+m+");\n const int winWidth = int("+g+");\n\n // Compute bounds for where in dy we will look\n float startRLerp = floor(float(r) * invHeightScale);\n int startDyR = int(floor(startRLerp - float(winHeight / 2)));\n\n float startCLerp = floor(float(c) * invWidthScale);\n int startDyC = int(floor(startCLerp - float(winWidth / 2)));\n\n // Loop over dy\n for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n int dyR = dyROffset + startDyR;\n\n // Guard against the window exceeding the bounds of dy\n if (dyR < 0 || dyR >= "+s+") {\n continue;\n }\n\n for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n int dyC = dyCOffset + startDyC;\n\n // Guard against the window exceeding the bounds of dy\n if (dyC < 0 || dyC >= "+u+") {\n continue;\n }\n\n float sourceFracRow =\n float("+l[0]+") *\n (float(dyR) / float("+c[0]+"));\n\n float sourceFracCol =\n float("+l[1]+") *\n (float(dyC) / float("+c[1]+"));\n\n int sourceNearestRow = int(min(\n float(int("+i+") - 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 "},ao=function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var i=t[0],a=t[1],o=t[2],s=t[3];this.outputShape=[i,e,n,s];var u=[r&&e>1?a-1:a,r&&n>1?o-1:o],l=[r&&e>1?e-1:e,r&&n>1?n-1:n],c=r?"0.5":"0.0";this.userCode="\n const vec2 effectiveInputOverOutputRatioRC = vec2(\n "+u[0]/l[0]+",\n "+u[1]/l[1]+");\n const vec2 inputShapeRC = vec2("+a+".0, "+o+".0);\n\n void main() {\n ivec4 coords = getOutputCoords();\n int b = coords[0];\n int d = coords[3];\n ivec2 yRC = coords.yz;\n\n // Fractional source index.\n vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n // Compute the coordinators of nearest neighbor point.\n ivec2 sourceNearestRC = ivec2(\n min(inputShapeRC - 1.0, floor(sourceFracIndexRC + "+c+")));\n\n float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n setOutput(newValue);\n }\n "},oo=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(","),i=Ei(n);this.userCode="\n void main() {\n "+i+" 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 "},so=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=hi("rc",n),i=r[n-1]+" + 1 < "+this.outputShape[n-1],a=r[n-2]+" + 1 < "+this.outputShape[n-2],o=Ei(n);function s(n){var r=t.map(function(r,i){return function(n,r){return-1!==e.indexOf(n)&&1!==t[n]?t[n]+" - "+r[n]+" - 1":""+r[n]}(i,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("+i+"){\n result.g = getChannel(getX("+t[0]+" - (rc + 1) - 1),\n "+t[0]+" - (rc + 1) - 1);\n }\n setOutput(result);\n }\n ":"\n void main() {\n "+o+" rc = getOutputCoords();\n vec4 result = vec4(0.);\n result.r = "+s(r.slice())+";\n if("+i+"){\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("+i+") {\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 "},uo=function(t,e,n,r,i,a,o){void 0===o&&(o=!0),this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;var s=Ei(i.length),u=Ei(a.length),l="";1===n?l="i":2===n&&(l="i, j");var c="getIndices("+l+")",p="";1===r?p="i":2===r&&(p="i, coords[1]");var h="getUpdates("+p+")",f=e>1?"strides[j]":"strides";this.userCode="\n "+s+" strides = "+s+"("+i+");\n\n void main() {\n "+u+" coords = getOutputCoords();\n float sum = 0.0;\n bool found = false;\n for (int i = 0; i < "+t+"; i++) {\n int flattenedIndex = 0;\n for (int j = 0; j < "+e+"; j++) {\n int index = round("+c+");\n flattenedIndex += index * "+f+";\n }\n if (flattenedIndex == coords[0]) {\n sum += "+h+";\n found = true;\n }\n }\n setOutput(mix(getDefaultValue(), sum, float(found)));\n }\n "},lo=function(t,e){this.variableNames=["x","segmentIds"];var n=t.windowSize,r=t.batchSize,i=t.inSize,a=t.numSegments,o=a*Math.ceil(i/n);this.outputShape=[r,o];var s=4*Math.floor(n/4),u=n%4,l="\n sumValue += dot(values, segFilter);\n ",c="";i%n>0&&(c="\n if (inIdx < 0 || inIdx >= "+i+") {\n return initializationValue;\n }\n ");var p="";i%n>0&&(p="\n if (inIdx < 0 || inIdx >= "+i+") {\n return -1.0;\n }\n "),this.userCode="\n const float initializationValue = 0.0;\n\n float getValue(int batch, int inIdx) {\n "+c+"\n return getX(batch, inIdx);\n }\n\n float getSegmentIdAtIndex(int inIdx) {\n "+p+"\n return getSegmentIds(inIdx);\n }\n\n void main() {\n ivec2 coords = getOutputCoords();\n int batch = coords[0];\n int outIdx = coords[1];\n int inOffset = int(floor(float(outIdx) / float(\n "+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 "},co=function(t,e,n){var r,i;if(this.variableNames=["c","a","b"],this.outputShape=e,n>4)throw Error("Where for rank "+n+" is not yet supported");if(1===n)i="resRC",r="resRC";else{for(var a=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[],s=[],u=0;u<e.length;u++)s.push(""+a[u]),u<t&&o.push(""+a[u]);r=o.join(),i=s.join()}var l=Ei(n);this.userCode="\n void main() {\n "+l+" resRC = getOutputCoords();\n float cVal = getC("+r+");\n if (cVal >= 1.0) {\n setOutput(getA("+i+"));\n } else {\n setOutput(getB("+i+"));\n }\n }\n "},po=function(){function t(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;var e,n=Ei(this.rank),r="uniform int start["+this.rank+"];",i=function(t){if(1===t)return"sourceLoc";if(t<=6)return ho.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."+ho[e]+" = start["+e+"] + coords."+ho[e]+";"}).join("\n")+"\n ",this.userCode="\n "+r+"\n void main() {\n "+e+"\n setOutput(getSource("+i+"));\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}(),ho=["x","y","z","w","u","v"],fo=function(){function t(t){this.variableNames=["source"],this.usesPackedTextures=!0,this.outputShape=t,this.rank=t.length;var e=Ei(this.rank),n=hi("coords",this.rank),r=hi("sourceLoc",this.rank),i=1===this.rank?"sourceLoc":"vec2("+r.slice(-2).join()+")",a="getChannel(getSource("+r.join()+"), "+i+")",o="\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 "+o+"\n "+s+"\n setOutput(result);\n }\n "}return t.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+t.length+")");return function(n,r){null==e.startLoc&&(e.startLoc=n.getUniformLocationNoThrow(r,"start"),null==e.startLoc)||n.gl.uniform1iv(e.startLoc,t)}},t}(),mo=function(t,e,n){this.variableNames=["x"],this.outputShape=n;var r=n.length,i=Ei(n.length),a=Ei(n.length),o="";if(1===r)o="coords * strides + begin";else{var s=0;o=n.map(function(t,e){return s++,1===n.length?"coords * strides["+e+"] + begin["+e+"]":"coords["+(s-1)+"] * strides["+e+"] + begin["+e+"]"}).join(",")}this.userCode="\n "+i+" begin = "+i+"("+t+");\n "+i+" strides = "+i+"("+e+");\n\n void main() {\n "+a+" coords = getOutputCoords();\n setOutput(getX("+o+"));\n }\n "},go=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,i=vo(e,n),a=yo(t,i,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 o=this.freeTextures[a].shift();return this.usedTextures[a].push(o),o}return this.numUsedTextures++,this.log(),i===At.PACKED_2X2_FLOAT32?r=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):i===At.PACKED_2X2_FLOAT16?r=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):i===At.UNPACKED_FLOAT32?r=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):i===At.UNPACKED_FLOAT16?r=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):i===At.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 i=yo(e,vo(n,r),r);i in this.freeTextures||(this.freeTextures[i]=[]),this.freeTextures[i].push(t),this.numFreeTextures++,this.numUsedTextures--;var a=this.usedTextures[i],o=a.indexOf(t);if(o<0)throw new Error("Cannot release a texture that was never provided by this texture manager");a.splice(o,1),this.log()}},t.prototype.log=function(){if(this.logEnabled){var t=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+t+")")}},t.prototype.getNumUsedTextures=function(){return this.numUsedTextures},t.prototype.getNumFreeTextures=function(){return this.numFreeTextures},t.prototype.dispose=function(){var t=this;if(null!=this.freeTextures){for(var e in this.freeTextures)this.freeTextures[e].forEach(function(e){t.gpgpu.deleteMatrixTexture(e)});for(var e in this.usedTextures)this.usedTextures[e].forEach(function(e){t.gpgpu.deleteMatrixTexture(e)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0}},t}();function vo(t,e){if(t===It.UPLOAD)return At.PACKED_2X2_FLOAT32;if(t===It.RENDER||null==t)return function(t){return o().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?t?At.PACKED_2X2_FLOAT32:At.UNPACKED_FLOAT32:t?At.PACKED_2X2_FLOAT16:At.UNPACKED_FLOAT16}(e);if(t===It.DOWNLOAD||t===It.PIXELS)return At.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+t)}function yo(t,e,n){return t[0]+"_"+t[1]+"_"+e+"_"+n}var bo=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 i=Ei(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=[],i=0;i<t.length;i++)r.push("imod("+n[i]+", "+t[i]+")");return r.join()}(t);this.userCode="\n void main() {\n "+i+" resRC = getOutputCoords();\n setOutput(getA("+a+"));\n }\n "},xo=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 i=Ei(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),i=0;i<t.length;i++)r[t[i]]=n[i];return r.join()}(e);this.userCode="\n void main() {\n "+i+" resRC = getOutputCoords();\n setOutput(getA("+a+"));\n }\n "},wo=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 i=Ei(this.rank),a=pi("rc",this.rank),o=new Array(this.rank);for(r=0;r<e.length;r++)o[e[r]]=a[r];var s="vec2("+o.slice(-2).join()+")",u="++"+a[this.rank-1]+" < "+n[this.rank-1],l="getChannel(getA("+o.join()+"), "+s+")";this.userCode="\n void main() {\n "+i+" 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 "},Co=1.7580993408473768,No=1.0507009873554805,Eo=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 "},So="if (isnan(x)) return x;",ko="return x;",Io="return abs(x);",Ao=So+"\n return (x < 0.0) ? 0.0 : x;\n",Ro=So+"\n return (x < 0.0) ? 0.0 : min(6.0, x);\n",To="return (x >= 0.0) ? x : (exp(x) - 1.0);",Do="return -x;",Oo="return ceil(x);",_o="return floor(x);",Fo="return exp(x);",zo="return exp(x) - 1.0;",Mo="return x;",Lo="return x;",Po="\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",Bo="\n vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n bvec4 isNaN = isnan(x);\n\n result.r = isNaN.r ? x.r : result.r;\n result.g = isNaN.g ? x.g : result.g;\n result.b = isNaN.b ? x.b : result.b;\n result.a = isNaN.a ? x.a : result.a;\n\n return result;\n",Wo="\n vec4 result;\n\n result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n return result;\n",Vo=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 "},Uo=function(t){this.variableNames=["A"],this.usesPackedTextures=!0,this.outputShape=t;var e=t.length,n=hi("rc",e),r=Ei(e),i=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),o=e<=1?"rc":"vec2("+a.join(",")+")";this.userCode="\n void main() {\n "+r+" rc = getOutputCoords();\n vec4 packedInput = getA("+i+");\n\n setOutput(getChannel(packedInput, "+o+"));\n }\n "},jo={};function Go(t,e){if(void 0===e&&(e=!1),"linear"===t)return e?Lo:ko;if("relu"===t)return e?Po:Ao;if("elu"===t)return e?Wo:To;if("relu6"===t)return e?Bo:Ro;if("prelu"===t)return e?Pi:Mi;throw new Error("Activation "+t+" has not been implemented for the WebGL backend.")}var qo=600,Ho=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,!o().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(null==t){var e=Ot(o().getNumber("WEBGL_VERSION"));this.binaryCache=(n=o().getNumber("WEBGL_VERSION"))in jo?jo[n]:(jo[n]={},jo[n]),this.gpgpu=new La(e),this.canvas=e.canvas,this.gpgpuCreatedLocally=!0}else this.binaryCache={},this.gpgpuCreatedLocally=!1,this.canvas=t.gl.canvas;var n;this.textureManager=new go(this.gpgpu),this.numMBBeforeWarning=null==o().global.screen?1024:o().global.screen.height*o().global.screen.width*window.devicePixelRatio*qo/1024/1024,this.texData=new Dr(this,Et)}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="undefined"!=typeof OffscreenCanvas&&t instanceof OffscreenCanvas||"undefined"!=typeof HTMLCanvasElement&&t instanceof HTMLCanvasElement,r=t.data instanceof Uint8Array,i="undefined"!=typeof ImageData&&t instanceof ImageData,a="undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement,s="undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement,u=a?[t.videoWidth,t.videoHeight]:[t.width,t.height],l=u[0],c=u[1],p=[c,l],h=[c,l,e];if(!(n||r||i||a||s))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);(s||a)&&(null==this.fromPixels2DContext&&(this.fromPixels2DContext=_t(o().getNumber("WEBGL_VERSION")).getContext("2d")),this.fromPixels2DContext.canvas.width=l,this.fromPixels2DContext.canvas.height=c,this.fromPixels2DContext.drawImage(t,0,0,l,c),t=this.fromPixels2DContext.canvas);var f,d,m=this.makeTensorHandle(p,"int32");if(this.texData.get(m.dataId).usage=It.PIXELS,this.gpgpu.uploadPixelDataToTexture(this.getTexture(m.dataId),t),o().getBool("WEBGL_PACK")){f=new ga(h);var g=this.makePackedTensor(f.outputShape,m.dtype);d=this.compileAndRun(f,[m],g)}else f=new ma(h),d=this.compileAndRun(f,[m]);return this.disposeData(m.dataId),d},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(o().getBool("DEBUG"))for(var n=0;n<e.length;n++){var r=e[n];if(!Vt(r)){if(o().getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))throw Error("The value "+r+" cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'");throw Error("The value "+r+" cannot be represented on this device.")}}var i=this.texData.get(t);if("complex64"===i.dtype)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.releaseGPUData(t),i.usage=It.UPLOAD,i.values=e},t.prototype.readSync=function(t){var e=this.texData.get(t),n=e.values,r=e.dtype,i=e.complexTensors,a=e.slice,o=e.shape,s=e.isPacked;if(null!=a){var u;u=s?new Vo(o,Mo):new Eo(o,Mo);var l=this.compileAndRun(u,[{dataId:t,shape:o,dtype:r}]),c=this.readSync(l.dataId);return l.dispose(),c}if(null!=n)return this.convertAndCacheOnCPU(t);if("string"===r)return n;var p,h,f=null!=this.activeTimers;return f&&(p=G()),h="complex64"===r?Zr(i.real.dataSync(),i.imag.dataSync()):this.getValuesFromTexture(t),f&&(this.downloadWaitMs+=G()-p),this.convertAndCacheOnCPU(t,h)},t.prototype.read=function(t){return r(this,void 0,void 0,function(){var e,n,r,a,s,u,l,c,p,h,f,d,g,v,y,b,x,w,C,N,E,S;return i(this,function(i){switch(i.label){case 0:if(this.pendingRead.has(t))return e=this.pendingRead.get(t),[2,new Promise(function(t){return e.push(t)})];if(n=this.texData.get(t),r=n.values,a=n.shape,s=n.slice,u=n.dtype,l=n.complexTensors,c=n.isPacked,null!=s)return p=void 0,p=c?new Vo(a,Mo):new Eo(a,Mo),h=this.compileAndRun(p,[{dataId:t,shape:a,dtype:u}]),f=this.read(h.dataId),h.dispose(),[2,f];if(null!=r)return[2,this.convertAndCacheOnCPU(t)];if(!o().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===o().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"!==u&&o().get("WEBGL_BUFFER_SUPPORTED")&&(g=this.decode(t),v=this.texData.get(g.dataId),d=(S=this.gpgpu).createBufferFromTexture.apply(S,[v.texture].concat(zt(a)))),this.pendingRead.set(t,[]),"complex64"===u?[3,2]:[4,this.gpgpu.createAndWaitForFence()];case 1:i.sent(),i.label=2;case 2:return"complex64"!==u?[3,4]:[4,Promise.all([l.real.data(),l.imag.data()])];case 3:return b=i.sent(),x=b[0],w=b[1],y=Zr(x,w),[3,5];case 4:null==d?y=this.getValuesFromTexture(t):(C=m(a),y=this.gpgpu.downloadFloat32MatrixFromBuffer(d,C)),i.label=5;case 5:return null!=g&&this.disposeData(g.dataId),N=this.convertAndCacheOnCPU(t,y),E=this.pendingRead.get(t),this.pendingRead.delete(t),E.forEach(function(t){return t(N)}),this.pendingDisposal.has(t)&&(this.pendingDisposal.delete(t),this.disposeData(t)),[2,N]}})})},t.prototype.getValuesFromTexture=function(t){var e,n=this,r=this.texData.get(t),i=r.shape,a=r.dtype,s=r.isPacked,u=m(i);if(o().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){var l=this.decode(t),c=this.texData.get(l.dataId),p=(e=this.gpgpu).downloadMatrixFromPackedTexture.apply(e,[c.texture].concat(zt(i))).subarray(0,u);return this.disposeData(l.dataId),p}var h=o().getBool("WEBGL_PACK")&&!0===s,f=h?ge(i):i,d=this.makeTensorHandle(f,"float32");d.size=m(i),this.texData.get(d.dataId).usage=It.DOWNLOAD;var g=_e(function(){var e=h?new ca(f):new la(f);return n.compileAndRun(e,[{shape:f,dtype:a,dataId:t}],d,null)}),v=this.texData.get(g.dataId),y=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(v.texture,v.texShape[0],v.texShape[1]).subarray(0,u);return this.disposeData(d.dataId),y},t.prototype.time=function(t){return r(this,void 0,void 0,function(){var e,n,r,a,o,s,u;return i(this,function(i){switch(i.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=d(this.activeTimers.map(function(t){return t.query})).filter(function(t){return null!=t}),o=d(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=i.sent(),u={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:c(s),getExtraProfileInfo:function(){return s.map(function(t,e){return{name:o[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 o().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?this.gpgpu.beginQuery():{startMs:G(),endMs:null}},t.prototype.endTimer=function(t){return o().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(this.gpgpu.endQuery(),t):(t.endMs=G(),t)},t.prototype.getQueryTime=function(t){return r(this,void 0,void 0,function(){var e;return i(this,function(n){return o().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,i=e.texShape,a=e.usage,o=e.isPacked,s=e.slice,u=s&&s.origDataId||t,l=this.dataRefCount.get(u);l>1?this.dataRefCount.set(u,l-1):(this.dataRefCount.delete(u),null!=n&&(this.numBytesInGPU-=this.computeBytes(i,r),this.textureManager.releaseTexture(n,i,a,o)));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.getDataInfo=function(t){return this.texData.get(t)},t.prototype.getCPUBackend=function(){return o().getBool("WEBGL_CPU_FORWARD")?(null==this.cpuBackend&&(this.cpuBackend=Et.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:Et.keep(t.clone()),imag:Et.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===m(n))return nn([],n,t.dtype);var r=this.texData.get(t.dataId).isPacked,i=Er(t.shape,e,n);if(r||!i){var a=o().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new fo(n):new po(n),s=a.getCustomSetupFunc(e);return this.compileAndRun(a,[t],null,s)}return this.uploadToGPU(t.dataId),this.shallowSlice(t,e,n)},t.prototype.shallowSlice=function(t,e,n){var r=this.texData.get(t.dataId),i=st.make(n,{},t.dtype,this),a=this.texData.get(i.dataId);Object.assign(a,r),a.shape=n,a.dtype=t.dtype;var o=Sr(e,t.strides);r.slice&&(o+=r.slice.flatOffset),a.slice={flatOffset:o,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),i},t.prototype.stridedSlice=function(t,e,n,r){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.stridedSlice(t,e,n,r);var i=wr(e,n,r);if(i.some(function(t){return 0===t}))return nn([],i);var a=new mo(e,r,i);return this.compileAndRun(a,[t])},t.prototype.reverse=function(t,e){var n=o().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new so(t.shape,e):new oo(t.shape,e);return this.compileAndRun(n,[t])},t.prototype.concat=function(t,e){if("complex64"===t[0].dtype){var n=t.map(function(t){return tn(t)}),r=t.map(function(t){return en(t)});return Qe(this.concat(n,e),this.concat(r,e))}if(this.shouldExecuteOnCPU(t))return this.cpuBackend.concat(t,e);if(1===t.length)return t[0];if(t.length>o().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var i=Math.floor(t.length/2),a=this.concat(t.slice(0,i),e),s=this.concat(t.slice(i),e);return this.concat([a,s],e)}if(o().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&t[0].rank>1){var u=new Gi(t.map(function(t){return t.shape}),e);return this.compileAndRun(u,t)}var l=Je(t.map(function(t){return t.shape}),e),c=t.map(function(t){return t.as2D(-1,m(t.shape.slice(e)))}),p=new ji(c.map(function(t){return t.shape}));return this.compileAndRun(p,c).reshape(l)},t.prototype.neg=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.neg(t);if(o().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,Do,t.dtype);var e=new Eo(t.shape,Do);return this.compileAndRun(e,[t])},t.prototype.batchMatMul=function(t,e,n,r){var i=n?t.shape[2]:t.shape[1],a=r?e.shape[1]:e.shape[2],o=n?t.shape[1]:t.shape[2],s=t.shape[0];if((1===i||1===a)&&o>1e3){n&&(t=t.transpose([0,2,1])),r&&(e=e.transpose([0,2,1]));var u=1===a?t:t.as3D(s,o,1),l=1===a?2:1,c=1===a?e.as3D(s,1,o):e;return this.multiply(u,c).sum(l,!0)}var p=mt(t.dtype,e.dtype),h=new qa(t.shape,[s,i,a],n,r),f=this.makePackedTensor(h.outputShape,p);return this.compileAndRun(h,[t,e],f)},t.prototype.fusedBatchMatMul=function(t){var e=t.a,n=t.b,r=t.transposeA,i=t.transposeB,a=t.bias,o=t.activation,s=t.preluActivationWeights,u=r?e.shape[2]:e.shape[1],l=i?n.shape[1]:n.shape[2],c=e.shape[0],p=mt(e.dtype,n.dtype),h=null!=a,f=null!=s,d=o?Go(o,!0):null,m=new qa(e.shape,[c,u,l],r,i,h,d,f),g=this.makePackedTensor(m.outputShape,p),v=[e,n];return a&&v.push(a),s&&v.push(s),this.compileAndRun(m,v,g)},t.prototype.multiply=function(t,e){if("complex64"===t.dtype){var n=this.texData.get(t.dataId),r=this.texData.get(e.dataId),i=new Oi("return areal * breal - aimag * bimag;",t.shape,e.shape),a=new Oi("return areal * bimag + aimag * breal;",t.shape,e.shape),s=[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(i,s),l=this.compileAndRun(a,s),c=this.complex(u,l);return u.dispose(),l.dispose(),c}if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.multiply(t,e);if(o().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,zi,t.dtype);var p=new Li(zi,t.shape,e.shape),h=this.makeOutputArray(p.outputShape,t.dtype);return this.compileAndRun(p,[t,e],h)},t.prototype.batchNormalization=function(t,e,n,r,i,a){var s=[t,e,n],u=null;null!=a&&(u=a.shape,s.push(a));var l=null;if(null!=i&&(l=i.shape,s.push(i)),o().getBool("WEBGL_PACK_NORMALIZATION")){var c=new Di(t.shape,e.shape,n.shape,u,l,r);return this.compileAndRun(c,s)}var p=new Ti(t.shape,e.shape,n.shape,u,l,r);return this.compileAndRun(p,s)},t.prototype.localResponseNormalization4D=function(t,e,n,r,i){var a=o().getBool("WEBGL_PACK_NORMALIZATION")?new Ua(t.shape,e,n,r,i):new Wa(t.shape,e,n,r,i);return this.compileAndRun(a,[t])},t.prototype.LRNGrad=function(t,e,n,r,i,a,o){var s=new Va(e.shape,r,i,a,o);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 K(t)});return ai(Ln(t.shape,t.dtype,n),e)}var r=new bo(t.shape,e);return this.compileAndRun(r,[t])},t.prototype.pad=function(t,e,n){var r=o().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Ya(t.shape,e,n):new Xa(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=o().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new wo(t.shape,e):new xo(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 va(t.shape,e.size,n);return this.compileAndRun(r,[t,e])},t.prototype.batchToSpaceND=function(t,e,n){p(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}),i=pr(t.shape,e,r),a=hr(i.length,e.length),o=fr(t.shape,e,r),s=dr(n,e.length),u=mr(o,n,e.length);return t.reshape(i).transpose(a).reshape(o).slice(s,u)},t.prototype.spaceToBatchND=function(t,e,n){p(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}),i=[[0,0]];i.push.apply(i,n);for(var a=1+e.length;a<t.shape.length;++a)i.push([0,0]);var o=t.pad(i),s=pr(o.shape,e,r,!1),u=hr(s.length,e.length,!1),l=fr(o.shape,e,r,!1);return o.reshape(s).transpose(u).reshape(l)},t.prototype.reduce=function(t,e,n){var r=t.shape[0],i=t.shape[1],a=yr(i),o=new Qa({windowSize:a,inSize:i,batchSize:r},e),s=o.outputShape,u=s[0],l=s[1],c=this.makeOutputArray([u,l],n);return this.compileAndRun(o,[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],i=t.shape[1];null!=n&&(r=n.shape[0],i=n.shape[1]);var a=yr(i),o=new ci({windowSize:a,inSize:i,batchSize:r},e,null==n),s=o.outputShape,u=s[0],l=s[1],c=this.makeOutputArray([u,l],"int32"),p=[t];return null!=n&&p.push(n),this.compileAndRun(o,p,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,i=yr(r[r.length-1]),a=new Ii(r,i,e,null==n),o=this.makePackedTensor(a.outputShape,"int32"),s=null==n?[t]:[t,n];return this.compileAndRun(a,s,o),o.rank===t.rank?this.argReducePacked(t,e,o):o},t.prototype.sum=function(t,e){He("sum",e,t.rank);var n=Ge(t.shape,e),r=n[0],i=m(n[1]),a=t.as2D(-1,i),o=gt(t.dtype);return this.reduce(a,"sum",o).reshape(r)},t.prototype.prod=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.prod(t,e);var n=Ge(t.shape,e),r=n[0],i=m(n[1]),a=t.as2D(-1,i),o=gt(t.dtype);return this.reduce(a,"prod",o).reshape(r)},t.prototype.unsortedSegmentSum=function(t,e,n){var r=0,i=Ke([r],t.rank),a=t;null!=i&&(a=t.transpose(i),r=Xe(1,t.rank)[0]);var o=function(t,e,n){for(var r=[],i=t.length,a=0;a<i;a++)a!==e?r.push(t[a]):r.push(n);return r}(a.shape,r,n),s=m([a.shape[r]]),u=a.as2D(-1,s),l=gt(t.dtype),c=this.segOpCompute(u,"unsortedSegmentSum",e,l,n).reshape(o);return null!=i&&(c=c.transpose($e(i))),c},t.prototype.segOpCompute=function(t,e,n,r,i){var a=t.shape[0],o=t.shape[1],s=function(t,e){var n,r=!1;for(t<=vr?(n=t,r=!0):n=P(t,Math.floor(Math.sqrt(t)));!r;)n>e||n===t?r=!0:n=P(t,n+1);return n}(o,i),u=new lo({windowSize:s,inSize:o,batchSize:a,numSegments:i},e),l=u.outputShape,c=l[0],p=l[1],h=this.makeOutputArray([c,p],r);return this.compileAndRun(u,[t,n],h),h.shape[1]===i?h:(n=gn(0,i).tile([o/s]),this.segOpCompute(h,e,n,r,i))},t.prototype.argMinMaxReduce=function(t,e,n){var r=[e];if(He("arg"+n.charAt(0).toUpperCase()+n.slice(1),r,t.rank),!o().getBool("WEBGL_PACK_REDUCE")||t.rank<=2){var i=Ge(t.shape,r),a=i[0],s=m(i[1]),u=t.as2D(-1,s);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 i=new ra(t.shape,n,r);return this.compileAndRun(i,[t])},t.prototype.equal=function(t,e){if(o().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(equal(a, b));\n","bool");var n=new Li("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(o().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(notEqual(a, b));\n","bool");var n=new Li("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(o().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(lessThan(a, b));\n","bool");var n=new Li("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(o().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(lessThanEqual(a, b));\n","bool");var n=new Li("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(o().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(greaterThan(a, b));\n","bool");var n=new Li("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(o().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n return vec4(greaterThanEqual(a, b));\n","bool");var n=new Li("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 Eo(t.shape,"return float(!(x >= 1.0));");return this.compileAndRun(e,[t])},t.prototype.logicalAnd=function(t,e){if(o().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 Li("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(o().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 Li("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 co(t.rank,e.shape,e.rank),i=this.makeOutputArray(r.outputShape,mt(e.dtype,n.dtype));return this.compileAndRun(r,[t,e,n],i)},t.prototype.where=function(t){Le("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var e=t.dataSync();return si(t.shape,e)},t.prototype.topk=function(t,e,n){return oi(t.dataSync(),t.shape,t.dtype,e)},t.prototype.min=function(t,e){He("min",e,t.rank);var n=Ge(t.shape,e),r=n[0],i=m(n[1]),a=t.as2D(-1,i);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=o().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bi("\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 Li("\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=o().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bi("\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 Li("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);He("max",e,t.rank);var n=Ge(t.shape,e),r=n[0],i=m(n[1]),a=t.as2D(-1,i);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=o().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bi("\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 Li("\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){He("all",e,t.rank);var n=Ge(t.shape,e),r=n[0],i=m(n[1]),a=t.as2D(-1,i);return this.reduce(a,"all",a.dtype).reshape(r)},t.prototype.any=function(t,e){He("any",e,t.rank);var n=Ge(t.shape,e),r=n[0],i=m(n[1]),a=t.as2D(-1,i);return this.reduce(a,"any",a.dtype).reshape(r)},t.prototype.squaredDifference=function(t,e){var n=o().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bi("return (a - b) * (a - b);",t.shape,e.shape):new Li("return (a - b) * (a - b);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},t.prototype.realDivide=function(t,e){if(o().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(a.x == b.x) {\n result.x = 1.;\n }\n if(a.y == b.y) {\n result.y = 1.;\n }\n if(a.z == b.z) {\n result.z = 1.;\n }\n if(a.w == b.w) {\n result.w = 1.;\n }\n\n return result;\n","float32",!0);var n=new Li("\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(o().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 Li("\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,_i);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.add(t,e);var n=mt(t.dtype,e.dtype);if(o().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,_i,n);var r=new Li(_i,t.shape,e.shape),i=this.makeOutputArray(r.outputShape,n);return this.compileAndRun(r,[t,e],i)},t.prototype.packedUnaryOp=function(t,e,n){var r=new Vo(t.shape,e),i=this.makePackedTensor(r.outputShape,n);return this.compileAndRun(r,[t],i)},t.prototype.packedBinaryOp=function(t,e,n,r,i){void 0===i&&(i=!1);var a=new Bi(n,t.shape,e.shape,i),o=this.makePackedTensor(a.outputShape,r);return this.compileAndRun(a,[t,e],o)},t.prototype.complexSeparableBinaryOp=function(t,e,n){var r=this,i=this.texData.get(t.dataId),a=this.texData.get(e.dataId),o=[[i.complexTensors.real,a.complexTensors.real],[i.complexTensors.imag,a.complexTensors.imag]].map(function(i){var a=i[0],o=i[1],s=r.makeComplexComponentTensorHandle(t,a),u=r.makeComplexComponentTensorHandle(e,o),l=new Li(n,t.shape,e.shape),c=r.makeOutputArray(l.outputShape,mt(a.dtype,o.dtype));return r.compileAndRun(l,[s,u],c)}),s=o[0],u=o[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>o().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 i=t.map(function(t){return t.dtype}).reduce(function(t,e){return mt(t,e)}),a=t.map(function(t){return t.shape}),s=o().getBool("WEBGL_PACK"),u=s?new li(t[0].shape,a):new ui(t[0].shape,a),l=s?this.makePackedTensor(u.outputShape,i):this.makeOutputArray(u.outputShape,i);return this.compileAndRun(u,t,l)},t.prototype.subtract=function(t,e){if("complex64"===t.dtype&&"complex64"===e.dtype)return this.complexSeparableBinaryOp(t,e,Fi);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.subtract(t,e);var n=mt(t.dtype,e.dtype);if(o().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,Fi,t.dtype);var r=new Li(Fi,t.shape,e.shape),i=this.makeOutputArray(r.outputShape,n);return this.compileAndRun(r,[t,e],i)},t.prototype.pow=function(t,e){var n=o().getBool("WEBGL_PACK_BINARY_OPERATIONS"),r=n?new Bi("\n // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.\n vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));\n vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);\n vec4 result = multiplier * pow(abs(a), b);\n\n // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS\n bvec4 isExpZero = equal(b, vec4(0.0));\n result.r = isExpZero.r ? 1.0 : result.r;\n result.g = isExpZero.g ? 1.0 : result.g;\n result.b = isExpZero.b ? 1.0 : result.b;\n result.a = isExpZero.a ? 1.0 : result.a;\n\n vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));\n \n result.r = isNaN.r > 0. ? NAN : result.r;\n result.g = isNaN.g > 0. ? NAN : result.g;\n result.b = isNaN.b > 0. ? NAN : result.b;\n result.a = isNaN.a > 0. ? NAN : result.a;\n\n return result;\n",t.shape,e.shape):new Li("\nif(a < 0.0 && floor(b) < b){\n return NAN;\n}\nif (b == 0.0) {\n return 1.0;\n}\nreturn (round(mod(b, 2.0)) != 1) ?\n pow(abs(a), b) : sign(a) * pow(abs(a), b);\n",t.shape,e.shape),i=mt(t.dtype,e.dtype),a=n?this.makePackedTensor(r.outputShape,i):this.makeOutputArray(r.outputShape,i);return this.compileAndRun(r,[t,e],a)},t.prototype.ceil=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.ceil(t);if(o().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,Oo,t.dtype);var e=new Eo(t.shape,Oo);return this.compileAndRun(e,[t])},t.prototype.floor=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.floor(t);if(o().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,_o,t.dtype);var e=new Eo(t.shape,_o);return this.compileAndRun(e,[t])},t.prototype.sign=function(t){var e=new Eo(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 Eo(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 Eo(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 Eo(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 Eo(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){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.exp(t);if(o().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,Fo,t.dtype);var e=new Eo(t.shape,Fo);return this.compileAndRun(e,[t])},t.prototype.expm1=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.expm1(t);if(o().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,zo,t.dtype);var e=new Eo(t.shape,zo);return this.compileAndRun(e,[t])},t.prototype.log=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.log(t);if(o().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,"\n vec4 result = log(x);\n vec4 isNaN = vec4(lessThan(x, vec4(0.0)));\n result.r = isNaN.r == 1.0 ? NAN : result.r;\n result.g = isNaN.g == 1.0 ? NAN : result.g;\n result.b = isNaN.b == 1.0 ? NAN : result.b;\n result.a = isNaN.a == 1.0 ? NAN : result.a;\n\n return result;\n",t.dtype);var e=new Eo(t.shape,"if (x < 0.0) return NAN;\n return log(x);");return this.compileAndRun(e,[t])},t.prototype.log1p=function(t){var e=new Eo(t.shape,"return log(1.0 + x);");return this.compileAndRun(e,[t])},t.prototype.sqrt=function(t){var e=new Eo(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 Eo(t.shape,"return inversesqrt(x);");return this.compileAndRun(e,[t])},t.prototype.square=function(t){var e=new Eo(t.shape,"return x * x;");return this.compileAndRun(e,[t])},t.prototype.reciprocal=function(t){var e=new Eo(t.shape,"return 1.0 / x;");return this.compileAndRun(e,[t])},t.prototype.relu=function(t){var e;return e=o().getBool("WEBGL_PACK")?new Vo(t.shape,Po):new Eo(t.shape,Ao),this.compileAndRun(e,[t])},t.prototype.relu6=function(t){var e;return e=o().getBool("WEBGL_PACK")?new Vo(t.shape,Bo):new Eo(t.shape,Ro),this.compileAndRun(e,[t])},t.prototype.prelu=function(t,e){var n=o().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bi(Pi,t.shape,e.shape):new Li(Mi,t.shape,e.shape);return this.compileAndRun(n,[t,e])},t.prototype.elu=function(t){if(o().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,Wo,t.dtype);var e=new Eo(t.shape,To);return this.compileAndRun(e,[t])},t.prototype.eluDer=function(t,e){var n=o().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bi("\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 Li("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 Eo(t.shape,"\n // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n // see: https://arxiv.org/abs/1706.02515\n float scaleAlpha = 1.7580993408473768;\n float scale = 1.0507009873554805;\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n");return this.compileAndRun(e,[t])},t.prototype.int=function(t){var e=new Eo(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,i=(r=o().getBool("WEBGL_PACK_CLIP")?new Vi(t.shape):new Wi(t.shape)).getCustomSetupFunc(e,n);return this.compileAndRun(r,[t],null,i)},t.prototype.abs=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.abs(t);if(o().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,Io,t.dtype);var e=new Eo(t.shape,Io);return this.compileAndRun(e,[t])},t.prototype.complexAbs=function(t){var e=this.texData.get(t.dataId),n=new Ui(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 Eo(t.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(e,[t])},t.prototype.softplus=function(t){var e=new Eo(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 Eo(t.shape,"if (isnan(x)) return x;\n return sin(x);\n");return this.compileAndRun(e,[t])},t.prototype.cos=function(t){var e=new Eo(t.shape,"if (isnan(x)) return x;\n return cos(x);\n");return this.compileAndRun(e,[t])},t.prototype.tan=function(t){var e=new Eo(t.shape,"return tan(x);");return this.compileAndRun(e,[t])},t.prototype.asin=function(t){var e=new Eo(t.shape,"if (isnan(x)) return x;\n if (abs(x) > 1.) {\n return NAN;\n }\n return asin(x);\n");return this.compileAndRun(e,[t])},t.prototype.acos=function(t){var e=new Eo(t.shape,"if (isnan(x)) return x;\n if (abs(x) > 1.) {\n return NAN;\n }\n return acos(x);\n");return this.compileAndRun(e,[t])},t.prototype.atan=function(t){var e=new Eo(t.shape,"if (isnan(x)) return x;\n return atan(x);\n");return this.compileAndRun(e,[t])},t.prototype.atan2=function(t,e){var n=o().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Bi("\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 Li("\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 Eo(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 Eo(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 Eo(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 Eo(t.shape,"if (isnan(x)) return x;return log(x + sqrt(x * x + 1.0));");return this.compileAndRun(e,[t])},t.prototype.acosh=function(t){var e=new Eo(t.shape,"if (isnan(x)) return x;\n if (x < 1.0) return NAN;\n return log(x + sqrt(x * x - 1.0));");return this.compileAndRun(e,[t])},t.prototype.atanh=function(t){var e=new Eo(t.shape,"if (isnan(x)) return x;\n if ((x < -1.0) || (x > 1.0)) return NAN;\n return (log(1.0 + x) - log(1.0 - x)) / 2.0;");return this.compileAndRun(e,[t])},t.prototype.erf=function(t){var e=new Eo(t.shape,'\n // Error function is calculated approximately with elementary function.\n // See "Handbook of Mathematical Functions with Formulas,\n // Graphs, and Mathematical Tables", Abramowitz and Stegun.\n float p = 0.3275911;\n float a1 = 0.254829592;\n float a2 = -0.284496736;\n float a3 = 1.421413741;\n float a4 = -1.453152027;\n float a5 = 1.061405429;\n\n float sign = sign(x);\n x = abs(x);\n float t = 1.0 / (1.0 + p * x);\n return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));\n');return this.compileAndRun(e,[t])},t.prototype.step=function(t,e){var n=new Eo(t.shape,function(t){return void 0===t&&(t=0),So+"\n return x > 0.0 ? 1.0 : float("+t+");\n "}(e));return this.compileAndRun(n,[t])},t.prototype.conv2dByMatMul=function(t,e,n,r,i,a){var s=t.shape,u=this.texData.get(t.dataId),l=n.inChannels,c=s[0]*s[1]*s[2],h=n.outChannels,f="channelsLast"===n.dataFormat,d=(1===c||1===h)&&l>1e3,m=s[2]%2!=0&&!!u.isPacked;if(d||!o().getBool("WEBGL_LAZILY_UNPACK")||!o().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!m){var g=f?s[0]*s[1]*s[2]:s[0]*s[2]*s[3],v=this.reshape(t,[1,g,n.inChannels]),y=this.reshape(e,[1,n.inChannels,n.outChannels]);return this.reshape(this.fusedBatchMatMul({a:v,b:y,transposeA:!1,transposeB:!1,bias:r,activation:i,preluActivationWeights:a}),n.outShape)}var b=f?s[0]*s[1]*(s[2]+1):s[0]*s[2]*(s[3]+1),x=st.make([1,b,n.inChannels],{dataId:t.dataId},t.dtype,this),w=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,p(be(u.shape,x.shape),function(){return"packed reshape "+u.shape+" to "+x.shape+" isn't free"});var C=this.reshape(e,[1,n.inChannels,n.outChannels]),N=this.fusedBatchMatMul({a:x,b:C,transposeA:!1,transposeB:!1,bias:r,activation:i,preluActivationWeights:a}),E=this.texData.get(N.dataId);return p(E.isPacked,function(){return"batchMatMul result is expected to be packed"}),u.shape=w,E.shape=n.outShape,st.make(n.outShape,{dataId:N.dataId},N.dtype,this)},t.prototype.conv2dWithIm2Row=function(t,e,n,r,i,a){var o=n.filterWidth,s=n.filterHeight,u=n.inChannels,l=n.outWidth,c=n.outHeight,p="channelsLast"===n.dataFormat,h=o*s*u,f=c*l,d=[h,f],m=t.squeeze([0]),g=e.reshape([1,h,-1]),v=new Ba(d,m.shape,n),y=this.compileAndRun(v,[m]).reshape([1,d[0],d[1]]),b=null!=r,x=null!=a,w=i?Go(i,!0):null,C=new qa(y.shape,[1,f,n.outChannels],!0,!1,b,w,x),N=[y,g];r&&N.push(r),x&&N.push(a);var E=this.compileAndRun(C,N);return p?E.reshape([1,c,l,n.outChannels]):E.reshape([1,n.outChannels,c,l])},t.prototype.fusedConv2d=function(t){var e=t.input,n=t.filter,r=t.convInfo,i=t.bias,a=t.activation,s=t.preluActivationWeights;if(1===r.filterHeight&&1===r.filterWidth&&1===r.dilationHeight&&1===r.dilationWidth&&1===r.strideHeight&&1===r.strideWidth&&("SAME"===r.padInfo.type||"VALID"===r.padInfo.type))return this.conv2dByMatMul(e,n,r,i,a,s);if(o().getBool("WEBGL_CONV_IM2COL")&&1===e.shape[0])return this.conv2dWithIm2Row(e,n,r,i,a,s);var u=null!=i,l=null!=s,c=a?Go(a,!1):null,p=new Zi(r,u,c,l),h=[e,n];return i&&h.push(i),s&&h.push(s),this.compileAndRun(p,h)},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(o().getBool("WEBGL_CONV_IM2COL")&&1===t.shape[0])return this.conv2dWithIm2Row(t,e,n);var r=new Zi(n);return this.compileAndRun(r,[t,e])},t.prototype.conv2dDerInput=function(t,e,n){var r=new Ki(n);return this.compileAndRun(r,[t,e])},t.prototype.conv2dDerFilter=function(t,e,n){var r=new Hi(n);return this.compileAndRun(r,[t,e])},t.prototype.fusedDepthwiseConv2D=function(t){var e,n=t.input,r=t.filter,i=t.convInfo,a=t.bias,s=t.activation,u=t.preluActivationWeights,l=o().getBool("WEBGL_PACK_DEPTHWISECONV")&&i.strideWidth<=2&&i.outChannels/i.inChannels==1,c=s?Go(s,l):null,p=[n,r],h=null!=a,f=null!=u;return h&&p.push(a),f&&p.push(u),l?(e=new ea(i,h,c,f),this.compileAndRun(e,p,this.makePackedTensor(i.outShape,n.dtype))):(e=new ta(i,h,c,f),this.compileAndRun(e,p))},t.prototype.depthwiseConv2D=function(t,e,n){var r;return o().getBool("WEBGL_PACK_DEPTHWISECONV")&&n.strideWidth<=2&&n.outChannels/n.inChannels==1?(r=new ea(n),this.compileAndRun(r,[t,e],this.makePackedTensor(n.outShape,t.dtype))):(r=new ta(n),this.compileAndRun(r,[t,e]))},t.prototype.depthwiseConv2DDerInput=function(t,e,n){var r=new Ji(n);return this.compileAndRun(r,[t,e])},t.prototype.depthwiseConv2DDerFilter=function(t,e,n){var r=new Yi(n);return this.compileAndRun(r,[t,e])},t.prototype.conv3d=function(t,e,n){var r=new Qi(n);return this.compileAndRun(r,[t,e])},t.prototype.conv3dDerInput=function(t,e,n){var r=new Xi(n);return this.compileAndRun(r,[t,e])},t.prototype.conv3dDerFilter=function(t,e,n){var r=new $i(n);return this.compileAndRun(r,[t,e])},t.prototype.maxPool=function(t,e){var n=new Ja(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 Ja(e,"avg",!1),r=this.makeOutputArray(n.outputShape,"float32");return this.compileAndRun(n,[t],r)},t.prototype.maxPoolBackprop=function(t,e,n,r){var i=new Ja(r,"max",!0),a=this.compileAndRun(i,[e]),o=new ja(r),s=this.makeOutputArray(o.outputShape,e.dtype),u=this.compileAndRun(o,[t,a],s);return a.dispose(),u},t.prototype.avgPoolBackprop=function(t,e,n){var r=new Ai(n),i=this.makeOutputArray(r.outputShape,e.dtype);return this.compileAndRun(r,[t],i)},t.prototype.cast=function(t,e){return $r(t,e,this)},t.prototype.unstack=function(t,e){for(var n=t.shape[e],r=new Array(t.rank-1),i=0,a=0;a<t.rank;a++)a!==e&&(r[i++]=t.shape[a]);var o=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++)o[e]=a,u[a]=this.slice(t,o,s).reshape(r);return u},t.prototype.avgPool3d=function(t,e){var n=new Za(e,"avg",!1),r=this.makeOutputArray(n.outputShape,"float32");return this.compileAndRun(n,[t],r)},t.prototype.avgPool3dBackprop=function(t,e,n){var r=new Ri(n),i=this.makeOutputArray(r.outputShape,e.dtype);return this.compileAndRun(r,[t],i)},t.prototype.maxPool3d=function(t,e){var n=new Za(e,"max",!1),r=this.makeOutputArray(n.outputShape,"float32");return this.compileAndRun(n,[t],r)},t.prototype.maxPool3dBackprop=function(t,e,n,r){var i=new Za(r,"max",!0),a=this.compileAndRun(i,[e]),o=new Ga(r),s=this.makeOutputArray(o.outputShape,e.dtype),u=this.compileAndRun(o,[t,a],s);return a.dispose(),u},t.prototype.reshape=function(t,e){var n=this.texData.get(t.dataId);return!n.isPacked||be(t.shape,e)||null!==n.texture&&be(n.shape,e)?Xr(t,e):this.packedReshape(t,e)},t.prototype.resizeBilinear=function(t,e,n,r){var i=o().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new ro(t.shape,e,n,r):new no(t.shape,e,n,r);return this.compileAndRun(i,[t])},t.prototype.resizeBilinearBackprop=function(t,e,n){var r=new eo(t,e,n);return this.compileAndRun(r,[t])},t.prototype.resizeNearestNeighbor=function(t,e,n,r){var i=new ao(t.shape,e,n,r);return this.compileAndRun(i,[t])},t.prototype.resizeNearestNeighborBackprop=function(t,e,n){var r=new io(t,e,n);return this.compileAndRun(r,[t])},t.prototype.multinomial=function(t,e,n,r){var i=e?t:Rr(t),a=i.shape[0],o=i.shape[1],s=new Ha(a,o,n),u=this.makeOutputArray(s.outputShape,"int32"),l=s.getCustomSetupFunc(r);return this.compileAndRun(s,[i],u,l)},t.prototype.oneHot=function(t,e,n,r){var i=new Ka(t.size,e,n,r);return this.compileAndRun(i,[t])},t.prototype.diag=function(t){var e=new ua(t.size);return this.compileAndRun(e,[t])},t.prototype.nonMaxSuppression=function(t,e,n,r,i){return Le("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead"),ni(t.dataSync(),e.dataSync(),n,r,i)},t.prototype.cropAndResize=function(t,e,n,r,i,a){var o=new na(t.shape,e.shape,r,i,a);return this.compileAndRun(o,[t,e,n])},t.prototype.depthToSpace=function(t,e,n){p(e>1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+e});var r=t.shape[0],i="NHWC"===n?t.shape[1]:t.shape[2],a="NHWC"===n?t.shape[2]:t.shape[3],o="NHWC"===n?t.shape[3]:t.shape[1],s=i*e,u=a*e,l=o/(e*e),c=new sa("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 ii(t,e,n)},t.prototype.scatterND=function(t,e,n){var r=br(0,t,n),i=r.sliceRank,a=r.numUpdates,o=r.sliceSize,s=r.strides,u=r.outputSize,l=[u/o,o],c=t.reshape([a,i]),p=e.reshape([a,o]);if(0===u)return Xr(nn([]),n);var h=an(0),f=new uo(a,i,c.rank,p.rank,s,l);return this.compileAndRun(f,[p,c,h]).reshape(n)},t.prototype.sparseToDense=function(t,e,n,r){var i=br(0,t,n),a=i.sliceRank,o=i.numUpdates,s=i.strides,u=i.outputSize,l=new uo(o,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 fa("return real * expR - imag * expI;",t.shape,e),i=new fa("return real * expI + imag * expR;",t.shape,e),a=[this.makeComplexComponentTensorHandle(t,n.complexTensors.real),this.makeComplexComponentTensorHandle(t,n.complexTensors.imag)],o=this.compileAndRun(r,a),s=this.compileAndRun(i,a),u=this.complex(o,s).as2D(t.shape[0],t.shape[1]);return o.dispose(),s.dispose(),u},t.prototype.gatherND=function(t,e){var n=e.shape,r=n[n.length-1],i=gr(t,e),a=i[0],o=i[1],s=i[2],u=i[3],l=e.reshape([o,r]),c=t.reshape([t.size/s,s]),p=new ya(r,u,[o,s]);return this.compileAndRun(p,[c,l]).reshape(a)},t.prototype.fill=function(t,e,n){if("string"===(n=n||M(e))){var r=k(n,m(t));return r.fill(e),st.make(t,{values:r},n)}var i=new da(t,e),a=i.getCustomSetupFunc(e),o=this.makeOutputArray(t,n);return this.compileAndRun(i,[],o,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 Yr(t,e,n)},t.prototype.makeOutputArray=function(t,e){return st.make(t,{},e,this)},t.prototype.makePackedTensor=function(t,e){var n=st.make(t,{},e,this);return this.texData.get(n.dataId).isPacked=!0,n},t.prototype.unpackTensor=function(t){var e=new Uo(t.shape);return this.compileAndRun(e,[t],st.make(e.outputShape,{},t.dtype,this))},t.prototype.packTensor=function(t){var e=new $a(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(me(t.shape))),r=[de(e)].concat(me(e)),i=new to(r,n.shape);return this.compileAndRun(i,[n],null,null,!0).reshape(e)},t.prototype.decode=function(t){var e,n=this.texData.get(t),r=n.isPacked,i=n.shape,a=n.dtype,o=ge(i),s=zt(i),u=this.makeTensorHandle(i,"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 oa(o,s):new aa(o,s),this.compileAndRun(e,[{shape:o,dtype:a,dataId:t}],u,null,!0),u},t.prototype.compileAndRun=function(t,e,n,r,i){var a=this;if(void 0===i&&(i=!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=S(n.dtype,0),n;var s=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&&m(e.shape)<=o().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&&!be(n.shape,e.shape)){var r=e,i=e.shape;e.shape=n.shape,e=a.packedReshape(e,i),n=a.texData.get(e.dataId),r.shape=i}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="";s.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 i=t.userCode;return t.constructor.name+"_"+r+"_"+i}(t,0,l),p=this.getAndSaveBinary(c,function(){return function(t,e,n,r){var i=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}}),s=a.map(function(t){return t.shapeInfo}),u={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},l=vi(a,u,i,e.usesPackedTextures),c=t.createProgram(l),p=null,h=t.getUniformLocation(c,"NAN",!1);1===o().getNumber("WEBGL_VERSION")&&(p=t.getUniformLocation(c,"INFINITY",!1));for(var f={},d=0;d<e.variableNames.length;d++){var m=e.variableNames[d];f[m]=t.getUniformLocation(c,m,!1),f["offset"+m]=t.getUniformLocation(c,"offset"+m,!1)}return{program:e,source:l,webGLProgram:c,uniformLocations:f,inShapeInfos:s,outShapeInfo:u,infLoc:p,nanLoc:h}}(a.gpgpu,t,s,l)}),h=null!=this.activeTimers;return h&&(u=this.startTimer()),function(t,e,n,r,i){Pa(e.inShapeInfos,n),Pa([e.outShapeInfo],[r]);var a=r.texData.texture,s=r.texData.texShape;r.texData.isPacked?t.setOutputPackedMatrixTexture(a,s[0],s[1]):t.setOutputMatrixTexture(a,s[0],s[1]),t.setProgram(e.webGLProgram),1===o().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 i=e.program.variableNames[r],a=e.uniformLocations[i],o=e.uniformLocations["offset"+i];if(null!=a)if(n.isUniform)if(m(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!=o&&t.gl.uniform1i(o,n.texData.slice.flatOffset),t.setInputMatrixTexture(n.texData.texture,a,r)}),null!=i&&i(t,e.webGLProgram),t.executeProgram()}(this.gpgpu,p,s,l,r),h&&(u=this.endTimer(u),this.activeTimers.push({name:t.constructor.name,query:this.getQueryTime(u)})),!o().getBool("WEBGL_LAZILY_UNPACK")&&this.texData.get(n.dataId).isPacked&&!1===i?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=_e(function(){if(!o().get("WEBGL_RENDER_FLOAT32_ENABLED")){var e=o().getBool("DEBUG");o().set("DEBUG",!1);var n=t.abs(an(1e-8)).dataSync()[0];if(o().set("DEBUG",e),n>0)return 32}return 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,i=n.dtype,a=n.values,o=n.texture,s=n.usage,u=n.isPacked;if(null==o){var l,c=null!=this.activeTimers;c&&(l=G());var p=n.texShape;if(null==p&&(p=ve(r,u),n.texShape=p),null!=a){var h=ge(r),f=void 0,d=p[1],g=p[0],v=a instanceof Uint8Array;u?(d=(e=Mt(p[0],p[1]))[0],g=e[1],f=new ha(h,[g,d],v)):f=new pa(h,[g,d],v);var y=this.makeTensorHandle([g,d],i);this.texData.get(y.dataId).usage=v?It.PIXELS:It.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(y.dataId),d,g,a);var b=this.makeTensorHandle(f.outputShape,y.dtype);b.size=m(f.outputShape),this.texData.get(b.dataId).isPacked=u,this.compileAndRun(f,[y],b);var x=this.texData.get(b.dataId);n.texture=x.texture,n.texShape=x.texShape,n.isPacked=x.isPacked,n.usage=x.usage,this.disposeData(y.dataId),this.texData.delete(b.dataId),n.values=null,c&&(this.uploadWaitMs+=G()-l)}else{var w=this.acquireTexture(p,s,i,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 i=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn("High memory usage in GPU: "+i+" 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]*D(e)},t}();St()&&Et.registerBackend("webgl",function(){return new Ho},2);var Ko=Ze({abs_:function(t){var e=We(t,"x","abs");return"complex64"===e.dtype?Et.runKernel(function(t){return t.complexAbs(e)},{$x:e}):Et.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))}}})}}),$o=Ze({acos_:function(t){var e=We(t,"x","acos");return Et.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(an(1).sub(n.toFloat().square()).sqrt()).neg()}}})}}),Xo=Ze({acosh_:function(t){var e=We(t,"x","acosh");return Et.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())}}})}}),Yo=Ze({asin_:function(t){var e=We(t,"x","asin");return Et.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(an(1).sub(n.toFloat().square()).sqrt())}}})}}),Jo=Ze({asinh_:function(t){var e=We(t,"x","asinh");return Et.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(an(1).add(n.toFloat().square()).sqrt())}}})}}),Zo=Ze({atan_:function(t){var e=We(t,"x","atan");return Et.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))}}})}}),Qo=Ze({atanh_:function(t){var e=We(t,"x","atanh");return Et.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(an(1).sub(n.toFloat().square()))}}})}}),ts=Ze({ceil_:function(t){var e=We(t,"x","ceil");return Et.runKernel(function(t){return t.ceil(e)},{$x:e},function(t){return{$x:function(){return yn(t)}}})}}),es=Ze({clipByValue_:function(t,e,n){var r=We(t,"x","clipByValue");return p(e<=n,function(){return"Error in clip: min ("+e+") must be less than or equal to max ("+n+")."}),Et.runKernel(function(t,i){var a=t.clip(r,e,n);return i([r]),a},{$x:r},function(t,r){var i=r[0];return{$x:function(){return t.where(i.greaterEqual(e).logicalAnd(i.lessEqual(n)),yn(t))}}})}}),ns=Ze({cos_:function(t){var e=We(t,"x","cos");return Et.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)}}})}}),rs=Ze({cosh_:function(t){var e=We(t,"x","cosh");return Et.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)}}})}}),is=Ze({erf_:function(t){var e=We(t,"x","erf");return p("int32"===e.dtype||"float32"===e.dtype,function(){return"Input dtype must be `int32` or `float32`."}),"int32"===e.dtype&&(e=e.toFloat()),Et.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)))}}})}}),as=Ze({exp_:function(t){var e=We(t,"x","exp");return Et.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])}}})}}),os=Ze({expm1_:function(t){var e=We(t,"x","expm1");return Et.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())}}})}}),ss=Ze({floor_:function(t){var e=We(t,"x","floor");return Et.runKernel(function(t){return t.floor(e)},{$x:e},function(t){return{$x:function(){return yn(t)}}})}}),us=Ze({log_:function(t){var e=We(t,"x","log");return Et.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())}}})}}),ls=Ze({log1p_:function(t){var e=We(t,"x","log1p");return Et.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))}}})}}),cs=Ze({logSigmoid_:function(t){var e=We(t,"x","logSigmoid");return Et.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())}}})}}),ps=Ze({neg_:function(t){var e=We(t,"x","neg");return Et.runKernel(function(t){return t.neg(e)},{$x:e},function(t){return{$x:function(){return t.neg()}}})}}),hs=Ze({reciprocal_:function(t){var e=We(t,"x","reciprocal");return Et.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())}}})}}),fs=Ze({round_:function(t){var e=We(t,"x","round");return Et.runKernel(function(t){return t.round(e)},{$x:e},function(t){return{$x:function(){return yn(t)}}})}}),ds=Ze({rsqrt_:function(t){var e=We(t,"x","rsqrt");return Et.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()}}})}}),ms=Ze({sigmoid_:function(t){var e=We(t,"x","sigmoid");return Et.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(an(1).sub(n)))}}})}}),gs=Ze({sign_:function(t){var e=We(t,"x","sign");return Et.runKernel(function(t){return t.sign(e)},{$x:e},function(t){return{$x:function(){return yn(t)}}})}}),vs=Ze({isNaN_:function(t){var e=We(t,"x","isNaN");return Et.runKernel(function(t){return t.isNaN(e)},{$x:e},function(t){return{$x:function(){return yn(t)}}})}}),ys=Ze({isInf_:function(t){var e=We(t,"x","isInf");return Et.runKernel(function(t){return t.isInf(e)},{$x:e},function(t){return{$x:function(){return yn(t)}}})}}),bs=Ze({isFinite_:function(t){var e=We(t,"x","isFinite");return Et.runKernel(function(t){return t.isFinite(e)},{$x:e},function(t){return{$x:function(){return yn(t)}}})}}),xs=Ze({sin_:function(t){var e=We(t,"x","sin");return Et.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)}}})}}),ws=Ze({sinh_:function(t){var e=We(t,"x","sinh");return Et.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)}}})}}),Cs=Ze({softplus_:function(t){var e=We(t,"x","softplus");return Et.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())}}})}}),Ns=Ze({sqrt_:function(t){var e=We(t,"x","sqrt");return Et.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))}}})}}),Es=Ze({square_:function(t){var e=We(t,"x","square");return Et.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))}}})}}),Ss=Ze({step_:function(t,e){void 0===e&&(e=0);var n=We(t,"x","step");return Et.runKernel(function(t){return t.step(n,e)},{$x:n},function(t){return{$x:function(){return yn(t)}}})}}),ks=Ze({tan_:function(t){var e=We(t,"x","tan");return Et.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())}}})}}),Is=Ze({tanh_:function(t){var e=We(t,"x","tanh");return Et.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 an(1).sub(n.square()).mulStrict(t)}}})}});function As(t,e,n,r,i,a){var o,s,u=We(t,"x","batchNorm"),l=We(e,"mean","batchNorm"),c=We(n,"variance","batchNorm");return null!=i&&(o=We(i,"scale","batchNorm")),null!=r&&(s=We(r,"offset","batchNorm")),p(2===u.rank,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."}),p(2===l.rank||1===l.rank,function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank "+l.rank+"."}),p(2===c.rank||1===c.rank,function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank "+c.rank+"."}),null!=o&&p(2===o.rank||1===o.rank,function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank "+o.rank+"."}),null!=s&&p(2===s.rank||1===s.rank,function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank "+s.rank+"."}),Ds(u,l,c,s,o,a)}function Rs(t,e,n,r,i,a){var o,s,u=We(t,"x","batchNorm"),l=We(e,"mean","batchNorm"),c=We(n,"variance","batchNorm");return null!=i&&(o=We(i,"scale","batchNorm")),null!=r&&(s=We(r,"offset","batchNorm")),p(3===u.rank,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."}),p(3===l.rank||1===l.rank,function(){return"Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank "+l.rank+"."}),p(3===c.rank||1===c.rank,function(){return"Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank "+c.rank+"."}),null!=o&&p(3===o.rank||1===o.rank,function(){return"Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank "+o.rank+"."}),null!=s&&p(3===s.rank||1===s.rank,function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank "+s.rank+"."}),Ds(u,l,c,s,o,a)}function Ts(t,e,n,r,i,a){var o,s,u=We(t,"x","batchNorm"),l=We(e,"mean","batchNorm"),c=We(n,"variance","batchNorm");return null!=i&&(o=We(i,"scale","batchNorm")),null!=r&&(s=We(r,"offset","batchNorm")),p(4===u.rank,function(){return"Error in batchNorm4D: x must be rank 4 but got rank "+u.rank+"."}),p(4===l.rank||1===l.rank,function(){return"Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank "+l.rank+"."}),p(4===c.rank||1===c.rank,function(){return"Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank "+c.rank+"."}),null!=o&&p(4===o.rank||1===o.rank,function(){return"Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank "+o.rank+"."}),null!=s&&p(4===s.rank||1===s.rank,function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank "+s.rank+"."}),Ds(u,l,c,s,o,a)}function Ds(t,e,n,r,i,a){null==a&&(a=.001);var o,s,u,l=We(t,"x","batchNorm"),c=We(e,"mean","batchNorm"),h=We(n,"variance","batchNorm");return null!=i&&(o=We(i,"scale","batchNorm")),null!=r&&(s=We(r,"offset","batchNorm")),p(c.rank===h.rank,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."}),p(null==s||c.rank===s.rank,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."}),p(null==o||c.rank===o.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,Et.runKernel(function(t,e){var n=t.batchNormalization(u,Os(c),Os(h),a,Os(o),Os(s));return e([l,c,h,o]),n},{$x:l,$mean:c,$variance:h,$scale:o,$offset:s},function(t,e){var n=e,r=n[0],i=n[1],o=n[2],s=n[3],l=null==s?an(1):s,c=Fr(i.shape,u.shape),p=[];if(1===i.rank){for(var h=0;h<u.shape.length-1;++h)p.push(u.shape[h]);p.push(1)}var f=r.sub(i),d=t.mul(l),m=ds(o.add(an(a))),g=m.mul(m).mul(m).mul(an(-.5));return{$x:function(){return 1===i.rank?t.mul(sr(m.as4D(1,1,1,i.shape[0]),p)).mul(l).reshape(r.shape):t.mul(m).mul(l).reshape(r.shape)},$mean:function(){var t=m.mul(an(-1)).mul(d);return 1===i.rank&&(t=t.sum(c)),t.reshape(i.shape)},$variance:function(){var t=g.mul(f).mul(d);return 1===i.rank&&(t=t.sum(c)),t.reshape(i.shape)},$scale:function(){var e=f.mul(m),n=t.mul(e);return 1===i.rank&&(n=n.sum(c)),n.reshape(i.shape)},$offset:function(){var e=t;return 1===i.rank&&(e=e.sum(c)),e.reshape(i.shape)}}}).reshape(l.shape)}function Os(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(){De("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon")}var Fs=Ze({batchNormalization2d_:function(t,e,n,r,i,a){return void 0===r&&(r=.001),_s(),As(t,e,n,a,i,r)}}),zs=Ze({batchNormalization3d_:function(t,e,n,r,i,a){return void 0===r&&(r=.001),_s(),Rs(t,e,n,a,i,r)}}),Ms=Ze({batchNormalization4d_:function(t,e,n,r,i,a){return void 0===r&&(r=.001),_s(),Ts(t,e,n,a,i,r)}}),Ls=Ze({batchNormalization_:function(t,e,n,r,i,a){return void 0===r&&(r=.001),_s(),Ds(t,e,n,a,i,r)}}),Ps=Ze({batchNorm_:Ds}),Bs=Ze({batchNorm2d_:As}),Ws=Ze({batchNorm3d_:Rs}),Vs=Ze({batchNorm4d_:Ts}),Us=Ze({logicalAnd_:function(t,e){var n=We(t,"a","logicalAnd","bool"),r=We(e,"b","logicalAnd","bool");return zr(n.shape,r.shape),Et.runKernel(function(t){return t.logicalAnd(n,r)},{$a:n,$b:r})}}),js=Ze({logicalNot_:function(t){var e=We(t,"x","logicalNot","bool");return Et.runKernel(function(t){return t.logicalNot(e)},{$x:e})}}),Gs=Ze({logicalOr_:function(t,e){var n=We(t,"a","logicalOr","bool"),r=We(e,"b","logicalOr","bool");return zr(n.shape,r.shape),Et.runKernel(function(t){return t.logicalOr(n,r)},{$a:n,$b:r})}}),qs=Ze({logicalXor_:function(t,e){var n=We(t,"a","logicalXor","bool"),r=We(e,"b","logicalXor","bool");return zr(n.shape,r.shape),Gs(t,e).logicalAnd(Us(t,e).logicalNot())}}),Hs=Ze({where_:function(t,e,n){var r=We(e,"a","where"),i=We(n,"b","where"),a=We(t,"condition","where","bool");return h(r.shape,i.shape,"Error in where: "),1===a.rank?p(a.shape[0]===r.shape[0],function(){return"The first dimension of `a` must match the size of `condition`."}):h(a.shape,i.shape,"Error in where: "),Et.runKernel(function(t,e){var n=t.select(a,r,i);return e([a]),n},{$condition:a,$a:r,$b:i},function(t,e){var n=e[0];return{$condition:function(){return yn(n).toFloat()},$a:function(){return t.mul(n.cast(t.dtype))},$b:function(){return t.mul(n.logicalNot().cast(t.dtype))}}})}}),Ks=function(t){return r(this,void 0,void 0,function(){var e,n,r;return i(this,function(i){switch(i.label){case 0:return[4,(e=We(t,"condition","whereAsync","bool")).data()];case 1:return n=i.sent(),r=si(e.shape,n),t!==e&&e.dispose(),[2,r]}})})},$s=Ze({add_:function(t,e){var n,r=We(t,"a","add"),i=We(e,"b","add");n=vt(r,i),r=n[0],i=n[1];var a=zr(r.shape,i.shape);return Et.runKernel(function(t){return t.add(r,i)},{$a:r,$b:i},function(t){return{$a:function(){var e=t,n=Fr(r.shape,a);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)},$b:function(){var e=t,n=Fr(i.shape,a);return n.length>0&&(e=e.sum(n)),e.reshape(i.shape)}}})}}),Xs=Ze({addN_:function(t){p(Array.isArray(t),function(){return"The argument passed to tf.addN() must be a list of tensors"}),p(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 We(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(!g(t.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});var r=e;return Et.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})}}),Ys=Ze({addStrict_:function(t,e){var n=We(t,"a","addStrict"),r=We(e,"b","addStrict");return h(n.shape,r.shape,"Error in addStrict: "),n.add(r)}}),Js=Ze({atan2_:function(t,e){var n,r=We(t,"a","atan2"),i=We(e,"b","atan2");n=vt(r,i),r=n[0],i=n[1];var a=zr(r.shape,i.shape);return Et.runKernel(function(t,e){var n=t.atan2(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=$s(n.square(),r.square()),i=t.mul(r.div(e)),o=Fr(n.shape,a);return o.length>0&&(i=i.sum(o)),i.reshape(n.shape)},$b:function(){var e=$s(n.square(),r.square()),i=ps(t.mul(n.div(e))),o=Fr(r.shape,a);return o.length>0&&(i=i.sum(o)),i.reshape(r.shape)}}})}}),Zs=Ze({div_:function(t,e){var n,r=We(t,"a","div"),i=We(e,"b","div");if(n=vt(r,i),r=n[0],i=n[1],"int32"===r.dtype&&"int32"===i.dtype)return tu(r,i);var a=zr(r.shape,i.shape);return Et.runKernel(function(t,e){var n=t.realDivide(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=t.div(r.toFloat()),i=Fr(n.shape,a);return i.length>0?e.sum(i).reshape(n.shape):e},$b:function(){var e=t.mul(n.toFloat()),i=Fr(r.shape,a);i.length>0&&(e=e.sum(i).reshape(r.shape));var o=r.square();return e.div(o.toFloat()).neg()}}})}}),Qs=Ze({divStrict_:function(t,e){var n=We(t,"a","div"),r=We(e,"b","div");return h(n.shape,r.shape,"Error in divideStrict: "),n.div(r)}}),tu=Ze({floorDiv_:function(t,e){var n,r=We(t,"a","floorDiv"),i=We(e,"b","floorDiv");n=vt(r,i),r=n[0],i=n[1];var a=zr(r.shape,i.shape);return Et.runKernel(function(t,e){var n=t.floorDiv(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=t.div(r.toFloat()),i=Fr(n.shape,a);return i.length>0?e.sum(i).reshape(n.shape):e},$b:function(){var e=t.mul(n.toFloat()),i=Fr(r.shape,a);i.length>0&&(e=e.sum(i).reshape(r.shape));var o=r.square();return e.div(o.toFloat()).neg()}}})}}),eu=Ze({maximum_:function(t,e){var n,r=We(t,"a","maximum"),i=We(e,"b","maximum");return n=vt(r,i),r=n[0],i=n[1],"bool"===r.dtype&&(r=r.toInt(),i=i.toInt()),zr(r.shape,i.shape),Et.runKernel(function(t,e){var n=t.maximum(r,i);return e([r,i]),n},{$a:r,$b:i},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())}}})}}),nu=Ze({maximumStrict_:function(t,e){var n=We(t,"a","maximumStrict"),r=We(e,"b","maximumStrict");return h(n.shape,r.shape,"Error in maximumStrict: "),n.maximum(r)}}),ru=Ze({minimum_:function(t,e){var n,r=We(t,"a","minimum"),i=We(e,"b","minimum");return n=vt(r,i),r=n[0],i=n[1],"bool"===r.dtype&&(r=r.toInt(),i=i.toInt()),zr(r.shape,i.shape),Et.runKernel(function(t,e){var n=t.minimum(r,i);return e([r,i]),n},{$a:r,$b:i},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())}}})}}),iu=Ze({minimumStrict_:function(t,e){var n=We(t,"a","minimumStrict"),r=We(e,"b","minimumStrict");return h(n.shape,r.shape,"Error in minimumStrict: "),n.minimum(r)}}),au=Ze({mod_:function(t,e){var n,r=We(t,"a","mod"),i=We(e,"b","mod");n=vt(r,i),r=n[0],i=n[1];var a=zr(r.shape,i.shape);return Et.runKernel(function(t,e){var n=t.mod(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=Fr(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()),i=Fr(r.shape,a);return i.length>0?e.sum(i).reshape(r.shape):e}}})}}),ou=Ze({modStrict_:function(t,e){var n=We(t,"a","modStrict"),r=We(e,"b","modStrict");return h(n.shape,r.shape,"Error in modStrict: "),n.mod(r)}}),su=Ze({mul_:function(t,e){var n,r=We(t,"a","mul"),i=We(e,"b","mul");n=vt(r,i),r=n[0],i=n[1];var a=zr(r.shape,i.shape);return Et.runKernel(function(t,e){var n=t.multiply(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=t.mul(r.toFloat()),i=Fr(n.shape,a);return i.length>0?e.sum(i).reshape(n.shape):e},$b:function(){var e=t.mul(n.toFloat()),i=Fr(r.shape,a);return i.length>0?e.sum(i).reshape(r.shape):e}}})}}),uu=Ze({mulStrict_:function(t,e){var n=We(t,"a","mul"),r=We(e,"b","mul");return h(n.shape,r.shape,"Error in multiplyStrict: "),n.mul(r)}}),lu=Ze({pow_:function(t,e){var n=We(t,"base","pow"),r=We(e,"exp","pow"),i=zr(n.shape,r.shape);return t=n.cast(mt(n.dtype,r.dtype)),e=r.cast(mt(n.dtype,r.dtype)),Et.runKernel(function(t,e){var i=t.pow(n,r);return e([n,r,i]),i},{$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(an(1))))),o=Fr(n.shape,i);return o.length>0&&(a=a.sum(o)),a.reshape(n.shape)},$exp:function(){var e=n.greater(0),o=n.log().where(e,yn(n)),s=t.mul(a.mul(o)),u=Fr(r.shape,i);return u.length>0&&(s=s.sum(u)),s.reshape(r.shape)}}})}}),cu=Ze({powStrict_:function(t,e){return h(t.shape,e.shape,"Error in powStrict: "),t.pow(e)}}),pu=Ze({squaredDifference_:function(t,e){var n,r=We(t,"a","squaredDifference"),i=We(e,"b","squaredDifference");return n=vt(r,i),r=n[0],i=n[1],zr(r.shape,i.shape),Et.runKernel(function(t,e){var n=t.squaredDifference(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1],i=an(2);return{$a:function(){return t.mul(n.sub(r).mul(i))},$b:function(){return t.mul(r.sub(n).mul(i))}}})}}),hu=Ze({squaredDifferenceStrict_:function(t,e){var n=We(t,"a","squaredDifferenceStrict"),r=We(e,"b","squaredDifferenceStrict");return h(n.shape,r.shape,"Error in squaredDifferenceStrict: "),n.squaredDifference(r)}}),fu=Ze({sub_:function(t,e){var n,r=We(t,"a","sub"),i=We(e,"b","sub");n=vt(r,i),r=n[0],i=n[1];var a=zr(r.shape,i.shape);return Et.runKernel(function(t){return t.subtract(r,i)},{$a:r,$b:i},function(t){return{$a:function(){var e=t,n=Fr(r.shape,a);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)},$b:function(){var e=t,n=Fr(i.shape,a);return n.length>0&&(e=e.sum(n)),e.neg().reshape(i.shape)}}})}}),du=Ze({subStrict_:function(t,e){var n=We(t,"a","subStrict"),r=We(e,"b","subStrict");return h(n.shape,r.shape,"Error in subStrict: "),n.sub(r)}}),mu=Ze({equal_:function(t,e){var n,r=We(t,"a","equal"),i=We(e,"b","equal");return n=vt(r,i),r=n[0],i=n[1],zr(r.shape,i.shape),Et.runKernel(function(t){return t.equal(r,i)},{$a:r,$b:i})}}),gu=Ze({equalStrict_:function(t,e){var n=We(t,"a","equalStrict"),r=We(e,"b","equalStrict");return h(n.shape,r.shape,"Error in equalStrict: "),n.equal(r)}}),vu=Ze({greater_:function(t,e){var n,r=We(t,"a","greater"),i=We(e,"b","greater");return n=vt(r,i),r=n[0],i=n[1],zr(r.shape,i.shape),Et.runKernel(function(t){return t.greater(r,i)},{$a:r,$b:i})}}),yu=Ze({greaterEqual_:function(t,e){var n,r=We(t,"a","greaterEqual"),i=We(e,"b","greaterEqual");return n=vt(r,i),r=n[0],i=n[1],zr(r.shape,i.shape),Et.runKernel(function(t,e){var n=t.greaterEqual(r,i);return e([r,i]),n},{$a:r,$b:i},function(t,e){var n=e[0],r=e[1];return{$a:function(){return yn(n)},$b:function(){return yn(r)}}})}}),bu=Ze({greaterEqualStrict_:function(t,e){var n=We(t,"a","greaterEqualStrict"),r=We(e,"b","greaterEqualStrict");return h(n.shape,r.shape,"Error in greaterEqualStrict: "),n.greaterEqual(r)}}),xu=Ze({greaterStrict_:function(t,e){var n=We(t,"a","greaterStrict"),r=We(e,"b","greaterStrict");return h(n.shape,r.shape,"Error in greaterStrict: "),n.greater(r)}}),wu=Ze({less_:function(t,e){var n,r=We(t,"a","less"),i=We(e,"b","less");return n=vt(r,i),r=n[0],i=n[1],zr(r.shape,i.shape),Et.runKernel(function(t){return t.less(r,i)},{$a:r,$b:i})}}),Cu=Ze({lessEqual_:function(t,e){var n,r=We(t,"a","lessEqual"),i=We(e,"b","lessEqual");return n=vt(r,i),r=n[0],i=n[1],zr(r.shape,i.shape),Et.runKernel(function(t){return t.lessEqual(r,i)},{$a:r,$b:i})}}),Nu=Ze({lessEqualStrict_:function(t,e){var n=We(t,"a","lessEqualStrict"),r=We(e,"b","lessEqualStrict");return h(n.shape,r.shape,"Error in lessEqualStrict: "),n.lessEqual(r)}}),Eu=Ze({lessStrict_:function(t,e){var n=We(t,"a","lessStrict"),r=We(e,"b","lessStrict");return h(n.shape,r.shape,"Error in lessStrict: "),n.less(r)}}),Su=Ze({notEqual_:function(t,e){var n,r=We(t,"a","notEqual"),i=We(e,"b","notEqual");return n=vt(r,i),r=n[0],i=n[1],zr(r.shape,i.shape),Et.runKernel(function(t){return t.notEqual(r,i)},{$a:r,$b:i})}}),ku=Ze({notEqualStrict_:function(t,e){var n=We(t,"a","notEqualStrict"),r=We(e,"b","notEqualStrict");return h(n.shape,r.shape,"Error in notEqualStrict: "),n.notEqual(r)}});function Iu(t,e){for(var n=[],r=t;r<e;++r)n.push(r);return n}function Au(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 Ru=Ze({gather_:function(t,e,n){void 0===n&&(n=0);var r=We(t,"x","gather"),i=We(e,"indices","gather","int32");n=N(n,r.shape)[0];var a=function(t,e,n){for(var r=t.shape[n],i=[],a=1,o=1,s=0;s<n;s++)i.push(t.shape[s]),a*=t.shape[s];for(s=0;s<e.rank;s++)i.push(e.shape[s]);for(s=n+1;s<t.rank;s++)i.push(t.shape[s]),o*=t.shape[s];return{batchSize:a,sliceSize:o,dimSize:r,outputShape:i}}(r,i,n);return Et.runKernel(function(t,e){var a=t.gather(r,i.flatten(),n);return e([i]),a},{$x:r},function(t,e){var i=e[0];return{$x:function(){var e=r.shape,a=i.size,o=e.slice(0,n),s=o.length,u=e.slice(n,e.length).slice(1),l=u.length,c=Iu(0,s),p=Iu(s+1,s+1+l),h=Au([o,[a],u]),f=t.reshape(h),d=i.reshape([a]),m=Au([[s],c,p]),g=f.transpose(m),v=Tu(g,d,r.shape[n]),y=$e(m);return v.transpose(y)}}}).reshape(a.outputShape)}}),Tu=Ze({unsortedSegmentSum_:function(t,e,n){var r=We(t,"x","unsortedSegmentSum"),i=We(e,"segmentIds","unsortedSegmentSum","int32");return p(v(n),function(){return"numSegments must be of dtype int"}),Et.runKernel(function(t,e){var a=t.unsortedSegmentSum(r,i,n);return e([i]),a},{$x:r},function(t,e){var n=e[0];return{$x:function(){return function(t,e){for(var n=eu(e,yn(e)),r=Ru(t,n),i=yu(e,an(0,"int32")),a=r.rank-i.rank,o=0;o<a;++o)i=Gn(i,o+1);i=Us(i,hn(r.shape,"bool"));var s=yn(r);return Hs(i,r,s)}(t,n)}}})}}),Du=function(t,e,n){return r(this,void 0,void 0,function(){var r,a,o,s,u,l,c,f,d,m,g,v,y;return i(this,function(i){switch(i.label){case 0:for(r=We(t,"tensor","boolMask"),a=We(e,"mask","boolMask","bool"),o=null==n?0:n,s=a.rank,u=r.shape,p(s>0,function(){return"mask cannot be scalar"}),h(u.slice(o,o+s),a.shape,"mask's shape must match the first K dimensions of tensor's shape,"),l=1,c=o;c<o+s;c++)l*=u[c];return f=u.slice(0,o).concat([l],u.slice(o+s)),d=r.reshape(f),m=a.reshape([-1]),[4,Ks(m)];case 1:return g=i.sent(),v=g.squeeze([1]),y=Ru(d,v,o),t!==r&&r.dispose(),e!==a&&a.dispose(),v.dispose(),d.dispose(),m.dispose(),g.dispose(),[2,y]}})})};function Ou(t,e,n,r,i,a,o){void 0===a&&(a="NHWC"),p(t.length===e.rank,function(){return"Length of inShape ("+t.length+") and rank of dy ("+e.rank+") must match"});var s=t,u=e,l=!1;3===e.rank&&(l=!0,u=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]),s=[1,t[0],t[1],t[2]]),p(4===s.length,function(){return"Error in conv2dDerInput: inShape must be length 4, but got length "+s.length+"."}),p(4===u.rank,function(){return"Error in conv2dDerInput: dy must be rank 4, but got rank "+u.rank}),p(4===n.rank,function(){return"Error in conv2dDerInput: filter must be rank 4, but got rank "+n.rank});var c="NHWC"===a?s[3]:s[1],h="NHWC"===a?u.shape[3]:u.shape[1];p(c===n.shape[2],function(){return"Error in conv2dDerInput: depth of input ("+c+") must match input depth for filter "+n.shape[2]+"."}),p(h===n.shape[3],function(){return"Error in conv2dDerInput: depth of output ("+h+") must match output depth for filter "+n.shape[3]+"."}),null!=o&&p(v(i),function(){return"Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+i+"."});var f=Kr(a),d=Pr(s,n.shape,r,1,i,o,!1,f),m=Et.runKernel(function(t,e){var r=t.conv2dDerInput(u,n,d);return e([n,u]),r},{dy4D:u,filter:n},function(t,e){var n=e[0],s=e[1];return{dy4D:function(){return Mu(t,n,r,i,a,1,o)},filter:function(){return Pu(t,s,n.shape,r,i,a,o)}}});return l?m.as3D(m.shape[1],m.shape[2],m.shape[3]):m}function _u(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],i=e[2];return 1===n&&1===r&&1===i}function Fu(t,e,n,r,i){p(t.length===e.rank,function(){return"Length of inShape ("+t.length+") and rank of dy ("+e.rank+") must match"});var a=t,o=e,s=!1;4===e.rank&&(s=!0,o=e.as5D(1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]),a=[1,t[0],t[1],t[2],t[3]]);var u=a[4],l=o.shape[4];p(5===a.length,function(){return"Error in conv3dDerInput: inShape must be length 5, but got length "+a.length+"."}),p(5===o.rank,function(){return"Error in conv3dDerInput: dy must be rank 5, but got rank "+o.rank}),p(5===n.rank,function(){return"Error in conv3dDerInput: filter must be rank 5, but got rank "+n.rank}),p(u===n.shape[3],function(){return"Error in conv3dDerInput: depth of input ("+u+") must match input depth for filter "+n.shape[3]+"."}),p(l===n.shape[4],function(){return"Error in conv3dDerInput: depth of output ("+l+") must match output depth for filter "+n.shape[4]+"."});var c=Br(a,n.shape,r,1,i),h=Et.runKernel(function(t){return t.conv3dDerInput(o,n,c)},{dy5D:o});return s?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}var zu=Ze({conv1d_:function(t,e,n,r,i,a,o){void 0===i&&(i="NWC"),void 0===a&&(a=1);var s=We(t,"x","conv1d"),u=We(e,"filter","conv1d"),l=s,c=!1;2===s.rank&&(c=!0,l=s.as3D(1,s.shape[0],s.shape[1])),p(3===l.rank,function(){return"Error in conv1d: input must be rank 3, but got rank "+l.rank+"."}),p(3===u.rank,function(){return"Error in conv1d: filter must be rank 3, but got rank "+u.rank+"."}),null!=o&&p(v(r),function(){return"Error in conv1d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+"."}),p(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]+"."}),p(Hr(n,a),function(){return"Error in conv1D: Either stride or dilation must be 1. Got stride "+n+" and dilation '"+a+"'"}),p("NWC"===i,function(){return"Error in conv1d: got dataFormat of "+i+" but only NWC is currently supported."});var h=u.as4D(1,u.shape[0],u.shape[1],u.shape[2]),f=l.as4D(l.shape[0],1,l.shape[1],l.shape[2]),d=Mu(f,h,[1,n],r,"NHWC",[1,a],o);return c?d.as2D(d.shape[2],d.shape[3]):d.as3D(d.shape[0],d.shape[2],d.shape[3])}}),Mu=Ze({conv2d_:function(t,e,n,r,i,a,o){void 0===i&&(i="NHWC"),void 0===a&&(a=[1,1]);var s=We(t,"x","conv2d"),u=We(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])),p(4===l.rank,function(){return"Error in conv2d: input must be rank 4, but got rank "+l.rank+"."}),p(4===u.rank,function(){return"Error in conv2d: filter must be rank 4, but got rank "+u.rank+"."}),null!=o&&p(v(r),function(){return"Error in conv2d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+"."});var h="NHWC"===i?l.shape[3]:l.shape[1];p(h===u.shape[2],function(){return"Error in conv2d: depth of input ("+h+") must match input depth for filter "+u.shape[2]+"."}),p(Hr(n,a),function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+a+"'"});var f=Kr(i),d=Pr(l.shape,u.shape,n,a,r,o,!1,f),m=Et.runKernel(function(t,e){var n=t.conv2d(l,u,d);return e([u,l]),n},{x:l,$filter:u},function(t,e){var o=e,s=o[0],u=o[1];return p(qr(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 Bu(u.shape,t,s,n,r,i)},$filter:function(){return Pu(u,t,s.shape,n,r,i)}}});return c?m.as3D(m.shape[1],m.shape[2],m.shape[3]):m}}),Lu=Ze({conv3d_:function(t,e,n,r,i,a){void 0===i&&(i="NDHWC"),void 0===a&&(a=[1,1,1]);var o=We(t,"x","conv3d"),s=We(e,"filter","conv3d"),u=o,l=!1;4===o.rank&&(l=!0,u=o.as5D(1,o.shape[0],o.shape[1],o.shape[2],o.shape[3])),p(5===u.rank,function(){return"Error in conv3d: input must be rank 5, but got rank "+u.rank+"."}),p(5===s.rank,function(){return"Error in conv3d: filter must be rank 5, but got rank "+s.rank+"."}),p(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]+"."}),p(function(t,e){return _u(n)||_u(e)}(0,a),function(){return"Error in conv3D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+a+"'"}),p("NDHWC"===i,function(){return"Error in conv3d: got dataFormat of "+i+" but only NDHWC is currently supported."});var c=Br(u.shape,s.shape,n,a,r),h=Et.runKernel(function(t,e){var n=t.conv3d(u,s,c);return e([u,s]),n},{x:u,$filter:s},function(t,e){p(_u(a),function(){return"Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+a+"'"});var i=e[0],o=e[1];return{x:function(){return Fu(i.shape,t,o,n,r)},$filter:function(){return function(t,e,n,r,i){var a=t;4===t.rank&&(a=t.as5D(1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]));var o=e;4===o.rank&&(o=e.as5D(1,e.shape[0],e.shape[1],e.shape[2],e.shape[3])),p(5===a.rank,function(){return"Error in conv3dDerFilter: input must be rank 5, but got shape "+a.shape+"."}),p(5===o.rank,function(){return"Error in conv3dDerFilter: dy must be rank 5, but got shape "+o.shape+"."}),p(5===n.length,function(){return"Error in conv3dDerFilter: filterShape must be length 5, but got "+n+"."}),p(a.shape[4]===n[3],function(){return"Error in conv3dDerFilter: depth of input "+a.shape[4]+") must match input depth in filter ("+n[3]+"."}),p(o.shape[4]===n[4],function(){return"Error in conv3dDerFilter: depth of dy ("+o.shape[4]+") must match output depth for filter ("+n[4]+")."});var s=Br(a.shape,n,r,1,i);return Et.runKernel(function(t){return t.conv3dDerFilter(a,o,s)},{x5D:a,dy5D:o})}(i,t,o.shape,n,r)}}});return l?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}}),Pu=Ze({conv2dDerFilter_:function(t,e,n,r,i,a,o){void 0===a&&(a="NHWC");var s=t;3===t.rank&&(s=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var u=e;3===u.rank&&(u=e.as4D(1,e.shape[0],e.shape[1],e.shape[2])),p(4===s.rank,function(){return"Error in conv2dDerFilter: input must be rank 4, but got shape "+s.shape+"."}),p(4===u.rank,function(){return"Error in conv2dDerFilter: dy must be rank 4, but got shape "+u.shape+"."}),p(4===n.length,function(){return"Error in conv2dDerFilter: filterShape must be length 4, but got "+n+"."});var l="NHWC"===a?s.shape[3]:s.shape[1],c="NHWC"===a?u.shape[3]:u.shape[1];p(l===n[2],function(){return"Error in conv2dDerFilter: depth of input "+l+") must match input depth in filter ("+n[2]+"."}),p(c===n[3],function(){return"Error in conv2dDerFilter: depth of dy ("+c+") must match output depth for filter ("+n[3]+")."}),null!=o&&p(v(i),function(){return"Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+i+"."});var h=Kr(a),f=Pr(s.shape,n,r,1,i,o,!1,h);return Et.runKernel(function(t){return t.conv2dDerFilter(s,u,f)},{x4D:s,dy4D:u})}}),Bu=Ze({conv2dDerInput_:Ou}),Wu=Ze({depthwiseConv2d_:function(t,e,n,r,i,a,o){void 0===i&&(i="NHWC"),void 0===a&&(a=[1,1]);var s=We(t,"x","depthwiseConv2d"),u=We(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])),p(4===l.rank,function(){return"Error in depthwiseConv2d: input must be rank 4, but got rank "+l.rank+"."}),p(4===u.rank,function(){return"Error in depthwiseConv2d: filter must be rank 4, but got rank "+u.rank+"."}),p(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]),p(Hr(n,a),function(){return"Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+a+"'"}),null!=o&&p(v(r),function(){return"Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+"."});var h=Pr(l.shape,u.shape,n,a,r,o,!0),f=Et.runKernel(function(t,e){var n=t.depthwiseConv2D(l,u,h);return e([l,u]),n},{x:l,$filter:u},function(t,e){p(qr(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 Vu(n.shape,t,r,h)},$filter:function(){return Uu(n,t,r.shape,h)}}});return c?f.as3D(f.shape[1],f.shape[2],f.shape[3]):f}}),Vu=Ze({depthwiseConv2dDerInput_:function(t,e,n,r){var i=e,a=!1;3===e.rank&&(a=!0,i=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var o=Et.runKernel(function(t){return t.depthwiseConv2DDerInput(i,n,r)},{dy4D:i});return a?o.as3D(o.shape[1],o.shape[2],o.shape[3]):o}}),Uu=Ze({depthwiseConv2dDerFilter_:function(t,e,n,r){var i=t;3===t.rank&&(i=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])),Et.runKernel(function(t){return t.depthwiseConv2DDerFilter(i,a,r)},{x4D:i,dy4D:a})}}),ju=Ze({separableConv2d_:function(t,e,n,r,i,a,o){void 0===a&&(a=[1,1]),void 0===o&&(o="NHWC");var s=We(t,"x","separableConv2d"),u=We(e,"depthwiseFilter","separableConv2d"),l=We(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"===o)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");p(4===c.rank,function(){return"Error in separableConv2d: input must be rank 4, but got rank "+c.rank+"."}),p(4===u.rank,function(){return"Error in separableConv2d: depthwise filter must be rank 4, but got rank "+u.rank+"."}),p(4===l.rank,function(){return"Error in separableConv2d: pointwise filter must be rank 4, but got rank "+u.rank+"."}),p(1===l.shape[0],function(){return"Error in separableConv2d: the first dimension of pointwise filter must be 1, but got "+l.shape[0]+"."}),p(1===l.shape[1],function(){return"Error in separableConv2d: the second dimension of pointwise filter must be 1, but got "+l.shape[1]+"."});var f=u.shape[2],d=u.shape[3];p(l.shape[2]===f*d,function(){return"Error in separableConv2d: the third dimension of pointwise filter must be "+f*d+", but got "+l.shape[2]+"."});var m=Wu(c,u,r,i,o,a),g=Mu(m,l,1,"valid",o);return h?g.as3D(g.shape[1],g.shape[2],g.shape[3]):g}}),Gu=Ze({conv2dTranspose_:function(t,e,n,r,i,a){return Ou(n,We(t,"x","conv2dTranspose"),We(e,"filter","conv2dTranspose"),r,i,"NHWC",a)}}),qu=Ze({conv3dTranspose_:function(t,e,n,r,i){return Fu(n,We(t,"x","conv3dTranspose"),We(e,"filter","conv3dTranspose"),r,i)}}),Hu=Ze({matMul_:function(t,e,n,r){var i;void 0===n&&(n=!1),void 0===r&&(r=!1);var a=We(t,"a","matMul"),o=We(e,"b","matMul");i=vt(a,o),a=i[0],o=i[1];var s=n?a.shape[a.rank-2]:a.shape[a.rank-1],u=r?o.shape[o.rank-1]:o.shape[o.rank-2],l=n?a.shape[a.rank-1]:a.shape[a.rank-2],c=r?o.shape[o.rank-2]:o.shape[o.rank-1],h=a.shape.slice(0,-2),f=o.shape.slice(0,-2),d=m(h),v=m(f);p(a.rank>=2&&o.rank>=2&&a.rank===o.rank,function(){return"Error in matMul: inputs must have the same rank of at least 2, got ranks "+a.rank+" and "+o.rank+"."}),p(g(h,f),function(){return"Error in matMul: outer dimensions ("+h+") and ("+f+") of Tensors with shapes "+a.shape+" and "+o.shape+" must match."}),p(s===u,function(){return"Error in matMul: inner shapes ("+s+") and ("+u+") of Tensors with shapes "+a.shape+" and "+o.shape+" and transposeA="+n+" and transposeB="+r+" must match."});var y=a.shape.slice(0,-2).concat([l,c]),b=n?a.as3D(d,s,l):a.as3D(d,l,s),x=r?o.as3D(v,c,u):o.as3D(v,u,c);return Et.runKernel(function(t,e){var i=t.batchMatMul(b,x,n,r);return e([b,x]),i},{$a:b,$b:x},function(t,e){var i=e,a=i[0],o=i[1];return n||r?!n&&r?{$a:function(){return t.matMul(o,!1,!1)},$b:function(){return t.matMul(a,!0,!1)}}:n&&!r?{$a:function(){return o.matMul(t,!1,!0)},$b:function(){return a.matMul(t,!1,!1)}}:{$a:function(){return o.matMul(t,!0,!0)},$b:function(){return t.matMul(a,!0,!0)}}:{$a:function(){return t.matMul(o,!1,!0)},$b:function(){return a.matMul(t,!0,!1)}}}).reshape(y)}}),Ku=Ze({dot_:function(t,e){var n=We(t,"t1","dot"),r=We(e,"t2","dot");p(!(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 i=1===n.rank?n.size:n.shape[1],a=1===r.rank?r.size:r.shape[0];return p(i===a,function(){return"Error in dot: inner dimensions of inputs must match, but got "+i+" 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]))}}),$u=Ze({outerProduct_:function(t,e){var n=We(t,"v1","outerProduct"),r=We(e,"v2","outerProduct");return p(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))}}),Xu=Ze({reverse_:function(t,e){var n=We(t,"x","reverse");if(0===n.rank)return n.clone();var r=N(e,n.shape);return Et.runKernel(function(t){return t.reverse(n,r)},{$x:n},function(t){return{$x:function(){return t.reverse(r)}}}).reshapeAs(n)}}),Yu=Ze({reverse1d_:function(t){var e=We(t,"x","reverse");return p(1===e.rank,function(){return"Error in reverse1D: x must be rank 1 but got rank "+e.rank+"."}),Xu(e,0)}}),Ju=Ze({reverse2d_:function(t,e){var n=We(t,"x","reverse");return p(2===n.rank,function(){return"Error in reverse2D: x must be rank 2 but got rank "+n.rank+"."}),Xu(n,e)}}),Zu=Ze({reverse3d_:function(t,e){var n=We(t,"x","reverse");return p(3===n.rank,function(){return"Error in reverse3D: x must be rank 3 but got rank "+n.rank+"."}),Xu(n,e)}}),Qu=Ze({reverse4d_:function(t,e){var n=We(t,"x","reverse");return p(4===n.rank,function(){return"Error in reverse4D: x must be rank 4 but got rank "+n.rank+"."}),Xu(n,e)}});function tl(t,e,n,r,i,a){var o=We(t,"x","maxPool"),s=o,u=!1;3===o.rank&&(u=!0,s=o.as4D(1,o.shape[0],o.shape[1],o.shape[2])),null==r&&(r=[1,1]),p(4===s.rank,function(){return"Error in maxPool: input must be rank 4 but got rank "+s.rank+"."}),p(Hr(n,r),function(){return"Error in maxPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"}),null!=a&&p(v(i),function(){return"Error in maxPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+i+"."});var l=Mr(s.shape,e,n,r,i,a),c=Et.runKernel(function(t,e){var n=t.maxPool(s,l);return e([s,n]),n},{x:s},function(t,a){var o=a[0],s=a[1];return{x:function(){return function(t,e,n,r,i,a,o,s){var u=We(t,"dy","maxPoolBackprop"),l=We(e,"input","maxPoolBackprop"),c=We(n,"output","maxPoolBackprop");p(l.rank===u.rank,function(){return"Rank of input ("+l.rank+") does not match rank of dy ("+u.rank+")"}),null==a&&(a=[1,1]),p(Hr(i,a),function(){return"Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+i+" and dilations '"+a+"'"}),p(4===u.rank,function(){return"Error in maxPoolBackprop: dy must be rank 4 but got rank "+u.rank+"."}),p(4===l.rank,function(){return"Error in maxPoolBackprop: input must be rank 4 but got rank "+l.rank+"."});var h=Mr(l.shape,r,i,a,o,s);return Et.runKernel(function(t){return t.maxPoolBackprop(u,l,c,h)},{$dy:u,$input:l})}(t,o,s,e,n,r,i)}}});return u?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}function el(t,e,n,r,i,a){var o=We(t,"x","avgPool","float32");null==r&&(r=[1,1]),p(Hr(n,r),function(){return"Error in avgPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"});var s=o,u=!1;3===o.rank&&(u=!0,s=o.as4D(1,o.shape[0],o.shape[1],o.shape[2])),p(4===s.rank,function(){return"Error in avgPool: x must be rank 4 but got rank "+s.rank+"."}),null!=a&&p(v(i),function(){return"Error in avgPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+i+"."});var l=Mr(s.shape,e,n,r,i,a),c=Et.runKernel(function(t){return t.avgPool(s,l)},{x:s},function(t){return{x:function(){return function(t,e,n,r,i,a){var o=We(t,"dy","avgPoolBackprop"),s=We(e,"input","avgPoolBackprop");p(s.rank===o.rank,function(){return"Rank of input ("+s.rank+") does not match rank of dy ("+o.rank+")"}),null==i&&(i=[1,1]),p(Hr(r,i),function(){return"Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+i+"'"});var u=s,l=o,c=!1;3===s.rank&&(c=!0,u=s.as4D(1,s.shape[0],s.shape[1],s.shape[2]),l=o.as4D(1,o.shape[0],o.shape[1],o.shape[2])),p(4===l.rank,function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+l.rank+"."}),p(4===u.rank,function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+u.rank+"."});var h=Mr(u.shape,n,r,i,a),f=Et.runKernel(function(t){return t.avgPoolBackprop(l,u,h)},{dy4D:l,input4D:u});return c?f.as3D(f.shape[1],f.shape[2],f.shape[3]):f}(t,s,e,n,r,i)}}});return c=c.cast(o.dtype),u?c.as3D(c.shape[1],c.shape[2],c.shape[3]):c}var nl=Ze({maxPool_:function(t,e,n,r,i){return tl(t,e,n,1,r,i)}}),rl=Ze({avgPool_:function(t,e,n,r,i){return el(t,e,n,1,r,i)}}),il=Ze({pool_:function(t,e,n,r,i,a){null==i&&(i=[1,1]),null==a&&(a=1),0===r&&(r="valid");var o=We(t,"x","maxPool"),s=o,u=!1;3===o.rank&&(u=!0,s=o.as4D(1,o.shape[0],o.shape[1],o.shape[2])),p(Hr(a,i),function(){return"Error in pool: Either strides or dilations must be 1. Got strides "+a+" and dilations '"+i+"'"});var l,c=Mr(s.shape,e,a,i,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)}),i=n.map(function(t,e){return t-r[e]});return n.map(function(t,e){return[r[e],i[e]]})}([c.filterHeight,c.filterWidth],h):[[0,0],[0,0]];var f=1===h[0]&&1===h[1],d=function(t,e,n){var r=n.map(function(t){return t[0]}),i=n.map(function(t){return t[1]}),a=t.concat(r,i),o=e.map(function(t,e){return(t-a[e]%t)%t}),s=i.map(function(t,e){return t+o[e]});return[e.map(function(t,e){return[r[e],s[e]]}),e.map(function(t,e){return[0,o[e]]})]}([c.inHeight,c.inWidth],h,l),m=d[0],g=d[1],v=f?r:"valid",y=f?s:ir(s,h,m),b=("avg"===n?function(){return el(y,e,a,1,v)}:function(){return tl(y,e,a,1,v)})(),x=f?b:Bn(b,h,g);return u?x.as3D(x.shape[1],x.shape[2],x.shape[3]):x}}),al=Ze({maxPool3d_:function(t,e,n,r,i,a,o){void 0===a&&(a="NDHWC");var s=We(t,"x","maxPool3d"),u=s,l=!1;4===s.rank&&(l=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),null==o&&(o=[1,1,1]),p(5===u.rank,function(){return"Error in maxPool3d: x must be rank 5 but got rank "+u.rank+"."}),p("NDHWC"===a,function(){return"Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of "+a}),p(Hr(n,o),function(){return"Error in maxPool3d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+o+"'"}),null!=i&&p(v(r),function(){return"Error in maxPool3d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+r+"."});var c=Lr(u.shape,e,n,o,r,i,a),h=Et.runKernel(function(t,e){var n=t.maxPool3d(u,c);return e([u,n]),n},{x:u},function(t,a){var s=a[0],u=a[1];return{x:function(){return function(t,e,n,r,i,a,o,s){var u=We(t,"dy","maxPool3dBackprop"),l=We(e,"input","maxPool3dBackprop"),c=We(n,"output","maxPool3dBackprop"),h=u,f=l,d=c,m=!1;4===l.rank&&(m=!0,h=u.as5D(1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]),f=l.as5D(1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]),d=c.as5D(1,c.shape[0],c.shape[1],c.shape[2],c.shape[3])),p(5===h.rank,function(){return"Error in maxPool3dBackprop: dy must be rank 5 but got rank "+h.rank+"."}),p(5===f.rank,function(){return"Error in maxPool3dBackprop: input must be rank 5 but got rank "+f.rank+"."}),p(5===d.rank,function(){return"Error in maxPool3dBackprop: output must be rank 5 but got rank "+d.rank+"."}),null==a&&(a=[1,1,1]),p(Hr(i,a),function(){return"Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides "+i+" and dilations '"+a+"'"}),null!=s&&p(v(o),function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+o+"."});var g=Lr(f.shape,r,i,a,o,s),y=Et.runKernel(function(t){return t.maxPool3dBackprop(h,f,d,g)},{dy5D:h,input5D:f});return m?y.as4D(y.shape[1],y.shape[2],y.shape[3],y.shape[4]):y}(t,s,u,e,n,o,r,i)}}});return l?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}}),ol=Ze({avgPool3d_:function(t,e,n,r,i,a,o){void 0===a&&(a="NDHWC");var s=We(t,"x","avgPool3d","float32"),u=s,l=!1;4===s.rank&&(l=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),null==o&&(o=[1,1,1]),p(5===u.rank,function(){return"Error in avgPool3d: x must be rank 5 but got rank "+u.rank+"."}),p("NDHWC"===a,function(){return"Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of "+a}),p(Hr(n,o),function(){return"Error in avgPool3d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+o+"'"}),null!=i&&p(v(r),function(){return"Error in avgPool3d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+r+"."});var c=Lr(u.shape,e,n,o,r,i,a),h=Et.runKernel(function(t){return t.avgPool3d(u,c)},{x:u},function(t){return{x:function(){return function(t,e,n,r,i,a,o){var s=We(t,"dy","avgPool3dBackprop"),u=We(e,"input","avgPool3dBackprop"),l=s,c=u,h=!1;4===u.rank&&(h=!0,l=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]),c=u.as5D(1,u.shape[0],u.shape[1],u.shape[2],u.shape[3])),p(5===l.rank,function(){return"Error in avgPool3dBackprop: dy must be rank 5 but got rank "+l.rank+"."}),p(5===c.rank,function(){return"Error in avgPool3dBackprop: input must be rank 5 but got rank "+c.rank+"."}),null==i&&(i=[1,1,1]),p(Hr(r,i),function(){return"Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+i+"'"}),null!=o&&p(v(a),function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+a+"."});var f=Lr(c.shape,n,r,i,a,o),d=Et.runKernel(function(t){return t.avgPool3dBackprop(l,c,f)},{dy5D:l,input5D:c});return h?d.as4D(d.shape[1],d.shape[2],d.shape[3],d.shape[4]):d}(t,u,e,n,o,r,i)}}});return h=h.cast(u.dtype),l?h.as4D(h.shape[1],h.shape[2],h.shape[3],h.shape[4]):h}}),sl=Ze({slice_:function(t,e,n){var r,i,a=We(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()).forEach(function(t){p(-1!==t,function(){return"slice() does not support negative begin indexing."})}),i=(i=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:(p(-1===t,function(){return"Negative size values should be exactly -1 but got "+t+" for the slice() size at index "+e+"."}),a.shape[e]-r[e])}),function(t,e,n){p(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+")."}),p(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){p(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]+")"})},i=0;i<t.rank;++i)r(i)}(a,r,i);var o=a.shape;return Et.runKernel(function(t){return t.slice(a,r,i)},{$x:a},function(t){for(var e=[],n=0;n<t.rank;n++)e.push([r[n],o[n]-r[n]-i[n]]);return{$x:function(){return t.pad(e)}}})}}),ul=Ze({slice1d_:function(t,e,n){var r=We(t,"x","slice1d");return p(1===r.rank,function(){return"slice1d expects a rank-1 tensor, but got a rank-"+r.rank+" tensor"}),sl(r,[e],[n])}}),ll=Ze({slice2d_:function(t,e,n){var r=We(t,"x","slice2d");return p(2===r.rank,function(){return"slice2d expects a rank-2 tensor, but got a rank-"+r.rank+" tensor"}),sl(r,e,n)}}),cl=Ze({slice3d_:function(t,e,n){var r=We(t,"x","slice3d");return p(3===r.rank,function(){return"slice3d expects a rank-3 tensor, but got a rank-"+r.rank+" tensor"}),sl(r,e,n)}}),pl=Ze({slice4d_:function(t,e,n){var r=We(t,"x","slice4d");return p(4===r.rank,function(){return"slice4d expects a rank-4 tensor, but got a rank-"+r.rank+" tensor"}),sl(r,e,n)}});function hl(t,e,n,r,i){return e.rank<n.rank&&(e=e.reshape(qe(e.shape,r))),t.rank<n.rank&&(t=t.reshape(qe(t.shape,r))),{$x:function(){var r=t.mul(n.equal(e).cast(t.dtype));return null==i?r:r.transpose(i)}}}var fl=Ze({all_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=We(t,"x","all","bool"),i=N(e,r.shape),a=i,o=Ke(a,r.rank);null!=o&&(r=r.transpose(o),a=Xe(a.length,r.rank));var s=Et.runKernel(function(t){return t.all(r,a)},{$x:r});if(n){var u=qe(s.shape,i);return s.reshape(u)}return s}}),dl=Ze({any_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=We(t,"x","any","bool"),i=N(e,r.shape),a=i,o=Ke(a,r.rank);null!=o&&(r=r.transpose(o),a=Xe(a.length,r.rank));var s=Et.runKernel(function(t){return t.any(r,a)},{$x:r});if(n){var u=qe(s.shape,i);return s.reshape(u)}return s}}),ml=Ze({argMax_:function(t,e){void 0===e&&(e=0);var n=We(t,"x","argMax");null==e&&(e=0);var r=N(e,n.shape),i=Ke(r,n.rank);return null!=i&&(n=n.transpose(i),r=Xe(r.length,n.rank)),Et.runKernel(function(t,e){var i=t.argMax(n,r[0]);return e([n]),i},{$x:n},function(t,e){var n=e[0];return{$x:function(){return yn(n)}}})}}),gl=Ze({argMin_:function(t,e){void 0===e&&(e=0);var n=We(t,"x","argMin");null==e&&(e=0);var r=N(e,n.shape),i=Ke(r,n.rank);return null!=i&&(n=n.transpose(i),r=Xe(r.length,n.rank)),Et.runKernel(function(t,e){var i=t.argMin(n,r[0]);return e([n]),i},{$x:n},function(t,e){var n=e[0];return{$x:function(){return yn(n)}}})}}),vl=Ze({logSumExp_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=We(t,"x","logSumExp"),i=N(e,r.shape),a=r.max(i,!0),o=r.sub(a).exp().sum(i).log(),s=a.reshape(o.shape).add(o);if(n){var u=qe(s.shape,i);return s.reshape(u)}return s}}),yl=Ze({max_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=We(t,"x","max"),i=r,a=N(e,r.shape),o=a,s=Ke(o,r.rank);null!=s&&(r=r.transpose(s),o=Xe(o.length,r.rank));var u=Et.runKernel(function(t,e){var n=t.max(r,o);return e([i,n]),n},{$x:r},function(t,e){return hl(t,e[1],e[0],a,s)});if(n){var l=qe(u.shape,a);u=u.reshape(l)}return u}}),bl=Ze({mean_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=We(t,"x","mean"),i=N(e,r.shape),a=m(Ge(r.shape,i)[1]);return Ir(function(t){var r=an(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 i.forEach(function(t){n[t]=1}),e.reshape(n).mul(hn(t.shape,"float32")).div(a)}}})(r)}}),xl=Ze({min_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=We(t,"x","min"),i=r,a=N(e,r.shape),o=a,s=Ke(o,r.rank);null!=s&&(r=r.transpose(s),o=Xe(o.length,r.rank));var u=Et.runKernel(function(t,e){var n=t.min(r,o);return e([i,n]),n},{$x:r},function(t,e){return hl(t,e[1],e[0],a,s)});if(n){var l=qe(u.shape,a);u=u.reshape(l)}return u}}),wl=Ze({moments_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=N(e,(t=We(t,"x","moments")).shape),i=t.mean(r,n),a=i.shape;return n||(a=qe(i.shape,r)),{mean:i,variance:t.toFloat().sub(i.reshape(a)).square().mean(r,n)}}}),Cl=Ze({sum_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=We(t,"x","sum");"bool"===r.dtype&&(r=r.toInt());var i=N(e,r.shape);return Ir(function(t){var e=Ke(i,t.rank),r=i,a=t;null!=e&&(a=t.transpose(e),r=Xe(r.length,t.rank));var o=Et.runKernel(function(t){return t.sum(a,r)},{permutedX:a});if(n){var s=qe(o.shape,i);o=o.reshape(s)}return{value:o,gradFunc:function(e){var n=t.shape.slice();return i.forEach(function(t){n[t]=1}),e.reshape(n).mul(hn(t.shape,"float32"))}}})(r)}}),Nl=Ze({prod_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=We(t,"x","prod");"bool"===r.dtype&&(r=r.toInt());var i=N(e,r.shape),a=Ke(i,r.rank),o=i,s=r;null!=a&&(s=r.transpose(a),o=Xe(o.length,r.rank));var u=Et.runKernel(function(t){return t.prod(s,o)},{permutedX:s});if(n){var l=qe(u.shape,i);u=u.reshape(l)}return u}}),El=Ze({elu_:function(t){var e=We(t,"x","elu");return Et.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 Et.runKernel(function(e){return e.eluDer(t,n)},{dy:t,y:n})}}})}}),Sl=Ze({leakyRelu_:function(t,e){void 0===e&&(e=.2);var n=We(t,"x","leakyRelu");return eu(an(e).mul(n),n)}}),kl=Ze({prelu_:function(t,e){var n=We(t,"x","prelu"),r=We(e,"alpha","prelu");return Et.runKernel(function(t,e){var i=t.prelu(n,r);return e([n,r]),i},{$x:n,$alpha:r},function(t,e){var n=e[0],r=e[1],i=n.greater(0);return{$x:function(){return Hs(i,t,t.mul(r))},$alpha:function(){var e=Hs(i,yn(t),t.mul(n)),a=Fr(r.shape,t.shape);return a.length>0&&(e=e.sum(a)),e.reshape(r.shape)}}})}}),Il=Ze({relu_:function(t){var e=We(t,"x","relu");return"bool"===e.dtype?e.toInt():Et.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())}}})}}),Al=Ze({relu6_:function(t){var e=We(t,"x","relu6");return"bool"===e.dtype?e.toInt():Et.runKernel(function(t,n){var r=t.relu6(e);return n([e]),r},{$x:e},function(t,e){var n=e[0],r=n.lessEqual(6).mul(n.step());return{$x:function(){return t.mulStrict(r.toFloat())}}})}}),Rl=Ze({selu_:function(t){var e=We(t,"x","selu");return Et.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(an(0)),r=an(Co),i=an(No),a=t.mul(i),o=t.mul(r).mul(n.toFloat().exp());return Hs(e,a,o)}}})}}),Tl=Ze({transpose_:function(t,e){var n=We(t,"x","transpose");return null==e&&(e=n.shape.map(function(t,e){return e}).reverse()),p(n.rank===e.length,function(){return"Error in transpose: rank of input "+n.rank+" must match length of perm "+e+"."}),e.forEach(function(t){p(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():Et.runKernel(function(t){return t.transpose(n,e)},{$x:n},function(t){var n=$e(e);return{$x:function(){return t.transpose(n)}}})}}),Dl=Ze({localResponseNormalization_:function(t,e,n,r,i){void 0===e&&(e=5),void 0===n&&(n=1),void 0===r&&(r=1),void 0===i&&(i=.5);var a=We(t,"x","localResponseNormalization");p(4===a.rank||3===a.rank,function(){return"Error in localResponseNormalization: x must be rank 3 or 4 but got\n rank "+a.rank+"."}),p(v(e),function(){return"Error in localResponseNormalization: depthRadius must be an integer but got depthRadius "+e+"."});var o=a,s=!1;3===a.rank&&(s=!0,o=a.as4D(1,a.shape[0],a.shape[1],a.shape[2]));var u=Et.runKernel(function(t,a){var s=t.localResponseNormalization4D(o,e,n,r,i);return a([o,s]),s},{x4D:o},function(t,a){var o=a[0],s=a[1];return{x4D:function(){return Et.runKernel(function(a){return a.LRNGrad(t,o,s,e,n,r,i)},{})}}});return s?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),Ol=Ze({norm_:function(t,e,n,r){void 0===e&&(e="euclidean"),void 0===n&&(n=null),void 0===r&&(r=!1);var i=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(an(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=We(t,"x","norm"),e,n),a=i.shape;if(r){var o=N(n,t.shape);a=qe(i.shape,o)}return i.reshape(a)}}),_l=Ze({basicLSTMCell_:function(t,e,n,r,i,a){var o=We(t,"forgetBias","basicLSTMCell"),s=We(e,"lstmKernel","basicLSTMCell"),u=We(n,"lstmBias","basicLSTMCell"),l=We(r,"data","basicLSTMCell"),c=We(i,"c","basicLSTMCell"),p=We(a,"h","basicLSTMCell"),h=l.concat(p,1).matMul(s).add(u),f=h.shape[0],d=h.shape[1]/4,m=[f,d],g=h.slice([0,0],m),v=h.slice([0,d],m),y=h.slice([0,2*d],m),b=h.slice([0,3*d],m),x=g.sigmoid().mulStrict(v.tanh()).addStrict(c.mulStrict(o.add(y).sigmoid()));return[x,x.tanh().mulStrict(b.sigmoid())]}}),Fl=Ze({multiRNNCell_:function(t,e,n,r){for(var i=We(e,"data","multiRNNCell"),a=Ve(n,"c","multiRNNCell"),o=Ve(r,"h","multiRNNCell"),s=i,u=[],l=0;l<t.length;l++){var c=t[l](s,a[l],o[l]);u.push(c[0]),u.push(c[1]),s=c[1]}var p=[],h=[];for(l=0;l<u.length;l+=2)p.push(u[l]),h.push(u[l+1]);return[p,h]}}),zl=Ze({movingAverage_:function(t,e,n,r,i){void 0===i&&(i=!0);var a=We(t,"v","movingAverage"),o=We(e,"x","movingAverage"),s=We(n,"decay","movingAverage");yt(a,o),p(g(a.shape,o.shape),function(){return"Shape mismatch in v and x"});var u=an(1),l=u.sub(s),c=o.sub(a).mul(l);if(i){p(null!=r,function(){return"When using zeroDebias: true, step is required."});var h=We(r,"step","movingAverage");c=c.div(u.sub(lu(s,h)))}return a.add(c)}}),Ml=Ze({stridedSlice_:function(t,e,n,r,i,a,o,s,u){if(void 0===i&&(i=0),void 0===a&&(a=0),void 0===o&&(o=0),void 0===s&&(s=0),void 0===u&&(u=0),null==r&&(r=new Array(e.length)),0!==o)throw new Error("ellipsis mask is not yet supported");var l=We(t,"x","stridedSlice"),c=xr(s),p=l.shape.slice();c.forEach(function(t){e[t]=0,n[t]=1,p.splice(t,0,1)}),l=l.reshape(p);for(var h=0;h<l.rank;h++)e[h]=Cr(i,e,r,l.shape,h),n[h]=Nr(a,n,r,l.shape,h),r[h]=r[h]||1;var f=xr(u);f.forEach(function(t){n[t]=e[t]+1,r[t]=1});var d=wr(e,n,r),m=d.filter(function(t,e){return-1===f.indexOf(e)});return r.every(function(t){return 1===t})?sl(l,e,d).reshape(m):Et.runKernel(function(t){return t.stridedSlice(l,e,n,r)},{$x:l}).reshape(m)}}),Ll=Ze({topk_:function(t,e,n){void 0===e&&(e=1),void 0===n&&(n=!0);var r=We(t,"x","topk");if(0===r.rank)throw new Error("topk() expects the input to be of rank 1 or higher");var i=r.shape[r.shape.length-1];if(e>i)throw new Error("'k' passed to topk() must be <= the last dimension ("+i+") but got "+e);var a=Et.runKernel(function(t){return t.topk(r,e,n)},{$x:r});return{values:a[0],indices:a[1]}}}),Pl=Ze({scatterND_:function(t,e,n){var r=We(t,"indices","scatterND","int32"),i=We(e,"updates","scatterND");return function(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,i=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: "+i+".";if(n.rank<i)throw new Error(a+" update.rank < "+i+". ");if(t.length<r+(n.rank-i))throw new Error(a+" Output shape length < "+(r+(n.rank-i)));if(n.rank!==i+t.length-r)throw new Error(a+" update.rank != "+(i+t.length-r));for(var o=0;o<i;++o)if(n.shape[o]!==e.shape[o])throw new Error(a+" updates.shape["+o+"] ("+n.shape[o]+") != indices.shape["+o+"] ("+e.shape[o]+").");for(o=0;o<n.rank-i;++o)if(n.shape[o+i]!==t[o+r])throw new Error(a+" updates.shape["+(o+i)+"] ("+n.shape[o+i]+") != shape["+(o+i)+"] ("+t[o+i]+")")}(n,e,t)}(i,r,n),Et.runKernel(function(t){return t.scatterND(r,i,n)},{$indices:r,$updates:i})}}),Bl=Ze({fft_:function(t){p("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 Et.runKernel(function(t){return t.fft(r)},{input:t}).reshape(t.shape)}}),Wl=Ze({ifft_:function(t){p("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 Et.runKernel(function(t){return t.ifft(r)},{input:t}).reshape(t.shape)}}),Vl=Ze({rfft_:function(t,e){p("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],i=t.size/r;if(null!=e&&e<r){var a=t.shape.map(function(t){return 0}),o=t.shape.map(function(t){return t});o[t.shape.length-1]=e,n=t.slice(a,o),r=e}else if(null!=e&&e>r){var s=t.shape.map(function(t){return t});s[t.shape.length-1]=e-r,n=t.concat(fn(s),t.shape.length-1),r=e}else n=t;var u=n.zerosLike(),l=Qe(n,u).as2D(i,r),c=Bl(l),h=Math.floor(r/2)+1,f=tn(c),d=en(c),m=f.split([h,r-h],f.shape.length-1),g=d.split([h,r-h],d.shape.length-1),v=n.shape.slice();return v[n.shape.length-1]=h,Qe(m[0],g[0]).reshape(v)}}),Ul=Ze({irfft_:function(t){var e=t.shape[t.shape.length-1],n=t.size/e;if(e<=2){var r=t.as2D(n,e),i=Wl(r);return tn(i)}var a=[n,2*(e-1)],o=tn(t).as2D(n,e),s=en(t).as2D(n,e),u=o.slice([0,1],[n,e-2]).reverse(1),l=s.slice([0,1],[n,e-2]).reverse(1).mul(an(-1)),c=o.concat(u,1),p=s.concat(l,1);return r=Qe(c,p).as2D(a[0],a[1]),i=Wl(r),tn(i)}}),jl=Object.freeze({fft:Bl,ifft:Wl,rfft:Vl,irfft:Ul}),Gl=Ze({sparseToDense_:function(t,e,n,r){void 0===r&&(r=0);var i=We(t,"sparseIndices","sparseToDense","int32"),a=We(e,"sparseValues","sparseToDense"),o=We(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 i=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 o=e.size;if(0!==e.rank&&(1!==e.rank||o!==i))throw new Error("sparseValues has incorrect shape "+e.shape+", should be [] or ["+i+"]");if(e.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(i,a,n,o),Et.runKernel(function(t){return t.sparseToDense(i,a,n,o)},{$sparseIndices:i,$sparseValues:a,$defaultValue:o})}}),ql=Ze({gatherND_:function(t,e){var n=We(e,"indices","gatherND","int32"),r=We(t,"x","gatherND");return Et.runKernel(function(t){return t.gatherND(r,n)},{$x:r,$indices:n})}}),Hl=Ze({diag_:function(t){var e=We(t,"x","diag").flatten(),n=t.shape.concat(t.shape);return Et.runKernel(function(t){return t.diag(e)},{$x:e}).reshape(n)}}),Kl=Ze({dropout_:function(t,e,n,r){var i=We(t,"x","dropout");if(p("float32"===i.dtype,function(){return"x has to be a floating point tensor since it's going to be scaled, but got a "+i.dtype+" tensor instead."}),p(e>=0&&e<1,function(){return"rate must be a float in the range [0, 1), but got "+e+"."}),0===e)return t instanceof st?i.clone():i;var a=function(t,e){if(null==e)return t.shape.slice();if(g(t.shape,e))return e;if(t.shape.length===e.length){for(var n=[],r=0;r<t.shape.length;r++)null==e[r]&&null!=t.shape[r]?n.push(t.shape[r]):n.push(e[r]);return n}return e}(i,n),o=1-e,s=nr(a,0,1,"float32",r).add(o).floor().div(o);return i.mul(s)}});function $l(t,e,n){for(var r=1-t%2,i=new Float32Array(t),a=0;a<t;++a){var o=2*Math.PI*a/(t+r-1);i[a]=e-n*Math.cos(o)}return on(i,"float32")}var Xl=Ze({hannWindow_:function(t){return $l(t,.5,.5)}}),Yl=Ze({hammingWindow_:function(t){return $l(t,.54,.46)}}),Jl=Ze({frame_:function(t,e,n,r,i){void 0===r&&(r=!1),void 0===i&&(i=0);for(var a=0,o=[];a+e<=t.size;)o.push(sl(t,a,e)),a+=n;if(r)for(;a<t.size;){var s=a+e-t.size,u=bn([sl(t,a,e-s),dn([s],i)]);o.push(u),a+=n}return 0===o.length?sn([],[0,e]):bn(o).as2D(o.length,e)}}),Zl=Ze({stft_:function(t,e,n,r,i){var a;void 0===i&&(i=Xl),null==r&&(a=e,r=Math.floor(Math.pow(2,Math.ceil(Math.log(a)/Math.log(2)))));for(var o=Jl(t,e,n),s=su(o,i(e)),u=[],l=0;l<o.shape[0];l++)u.push(Vl(s.slice([l,0],[1,e]),r));return bn(u)}}),Ql=Object.freeze({hannWindow:Xl,hammingWindow:Yl,frame:Jl,stft:Zl}),tc=function(t,e,n){return void 0===n&&(n=1),r(this,void 0,void 0,function(){var r,a,o,s,u,l,c,f,d,m,g,v,y,b;return i(this,function(i){switch(i.label){case 0:return r=We(t,"predictions","inTopK"),a=We(e,"targets","inTopK"),p(r.rank>1,function(){return"inTopK() expects the predictions to be of rank 2 or higher, but got "+r.rank}),p(r.rank-1===a.rank,function(){return"predictions rank should be 1 larger than targets rank, but got predictions rank "+r.rank+" and targets rank "+a.rank}),h(r.shape.slice(0,r.shape.length-1),a.shape,"predictions's shape should be align with the targets' shape, except the last dimension."),o=r.shape[r.shape.length-1],p(n>0&&n<=o,function(){return"'k' passed to inTopK() must be > 0 && <= the predictions last dimension ("+o+"), but got "+n}),[4,r.data()];case 1:return s=i.sent(),[4,a.data()];case 2:for(u=i.sent(),l=[s.length/o,o],f=l[1],d=S("bool",c=l[0]),m=0;m<c;m++){for(g=m*f,v=s.subarray(g,g+f),y=[],b=0;b<v.length;b++)y.push({value:v[b],index:b});for(y.sort(function(t,e){return e.value-t.value}),d[m]=0,b=0;b<n;b++)if(y[b].index===u[m]){d[m]=1;break}}return t!==r&&r.dispose(),e!==a&&a.dispose(),[2,nn(d,a.shape,"bool")]}})})};!function(t){t[t.NONE=0]="NONE",t[t.MEAN=1]="MEAN",t[t.SUM=2]="SUM",t[t.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"}(t.Reduction||(t.Reduction={}));var ec=Ze({absoluteDifference_:function(e,n,r,i){void 0===i&&(i=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=We(e,"labels","absoluteDifference"),o=We(n,"predictions","absoluteDifference"),s=null;null!=r&&(s=We(r,"weights","absoluteDifference")),h(a.shape,o.shape,"Error in absoluteDifference: ");var u=a.sub(o).abs();return nc(u,s,i)}}),nc=Ze({computeWeightedLoss_:function(e,n,r){void 0===r&&(r=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var i=We(e,"losses","computeWeightedLoss"),a=null;null!=n&&(a=We(n,"weights","computeWeightedLoss"));var o=null==a?i:i.mul(a);if(r===t.Reduction.NONE)return o;if(r===t.Reduction.SUM)return o.sum();if(r===t.Reduction.MEAN){if(null==a)return o.mean();var s=i.size/a.size,u=o.sum().div(a.sum());return s>1?u.div(an(s)):u}if(r===t.Reduction.SUM_BY_NONZERO_WEIGHTS){if(null==a)return o.sum().div(an(i.size));var l=a.mul(hn(i.shape)).notEqual(an(0)).sum().toFloat();return o.sum().div(l)}throw Error("Unknown reduction: "+r)}}),rc=Ze({cosineDistance_:function(e,n,r,i,a){void 0===a&&(a=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=We(e,"labels","cosineDistance"),s=We(n,"predictions","cosineDistance"),u=null;null!=i&&(u=We(i,"weights","cosineDistance")),h(o.shape,s.shape,"Error in cosineDistance: ");var l=an(1).sub(o.mul(s).sum(r,!0));return nc(l,u,a)}}),ic=Ze({hingeLoss_:function(e,n,r,i){void 0===i&&(i=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=We(e,"labels","hingeLoss"),o=We(n,"predictions","hingeLoss"),s=null;null!=r&&(s=We(r,"weights","hingeLoss")),h(a.shape,o.shape,"Error in hingeLoss: ");var u=an(1);a=an(2).mul(a).sub(u);var l=u.sub(a.mul(o)).relu();return nc(l,s,i)}}),ac=Ze({huberLoss_:function(e,n,r,i,a){void 0===i&&(i=1),void 0===a&&(a=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=We(e,"labels","huberLoss"),s=We(n,"predictions","huberLoss"),u=null;null!=r&&(u=We(r,"weights","huberLoss")),h(o.shape,s.shape,"Error in huberLoss: ");var l=an(i),c=s.sub(o).abs(),p=ru(c,l),f=c.sub(p),d=an(.5).mul(p.square()).add(l.mul(f));return nc(d,u,a)}}),oc=Ze({logLoss_:function(e,n,r,i,a){void 0===i&&(i=1e-7),void 0===a&&(a=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=We(e,"labels","logLoss"),s=We(n,"predictions","logLoss"),u=null;null!=r&&(u=We(r,"weights","logLoss")),h(o.shape,s.shape,"Error in logLoss: ");var l=an(1),c=an(i),p=o.mul(s.add(c).log()).neg().sub(l.sub(o).mul(l.sub(s).add(c).log()));return nc(p,u,a)}}),sc=Ze({meanSquaredError_:function(e,n,r,i){void 0===i&&(i=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var a=We(e,"labels","meanSquaredError"),o=We(n,"predictions","meanSquaredError"),s=null;null!=r&&(s=We(r,"weights","meanSquaredError")),h(a.shape,o.shape,"Error in meanSquaredError: ");var u=a.squaredDifference(o);return nc(u,s,i)}}),uc=Ze({sigmoidCrossEntropy_:function(e,n,r,i,a){void 0===i&&(i=0),void 0===a&&(a=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=We(e,"multiClassLabels","sigmoidCrossEntropy"),s=We(n,"logits","sigmoidCrossEntropy"),u=null;if(null!=r&&(u=We(r,"weights","sigmoidCrossEntropy")),h(o.shape,s.shape,"Error in sigmoidCrossEntropy: "),i>0){var l=an(i),c=an(1),p=an(.5);o=o.mul(c.sub(l)).add(p.mul(l))}var f=function(t,e){var n=We(t,"labels","sigmoidCrossEntropyWithLogits"),r=We(e,"logits","sigmoidCrossEntropyWithLogits");h(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");var i=r.relu(),a=r.mul(n),o=r.abs().neg().exp().log1p();return i.sub(a).add(o)}(o,s);return nc(f,u,a)}}),lc=Ze({softmaxCrossEntropy_:function(e,n,r,i,a){void 0===i&&(i=0),void 0===a&&(a=t.Reduction.SUM_BY_NONZERO_WEIGHTS);var o=We(e,"onehotLabels","softmaxCrossEntropy"),s=We(n,"logits","softmaxCrossEntropy"),u=null;if(null!=r&&(u=We(r,"weights","softmaxCrossEntropy")),h(o.shape,s.shape,"Error in softmaxCrossEntropy: "),i>0){var l=an(i),c=an(1),p=an(o.shape[1]);o=o.mul(c.sub(l)).add(l.div(p))}var f=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 Ir(function(t,e,r){var i=e.logSumExp([n],!0),a=e.toFloat().sub(i);return r([t,a]),{value:a.mul(t).neg().sum([n]),gradFunc:function(t,e){var r=e[0],i=e[1],a=qe(t.shape,[n]);return[t.reshape(a).mul(r.toFloat().sub(i.exp())),t.reshape(a).mul(i.exp().sub(r.toFloat()))]}}})(t,e)}(o,s);return nc(f,u,a)}}),cc=Object.freeze({get Reduction(){return t.Reduction},absoluteDifference:ec,computeWeightedLoss:nc,cosineDistance:rc,hingeLoss:ic,huberLoss:ac,logLoss:oc,meanSquaredError:sc,sigmoidCrossEntropy:uc,softmaxCrossEntropy:lc});function pc(t,e){return void 0===e&&(e=!1),Et.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],i=qn(n),a=t.clone(),o=sn([[1]],[1,1]),s=o.clone(),u=n>=r?r:n,l=function(t){var e,u=a,l=s,c=i;e=Et.tidy(function(){var e=a.slice([t,t],[n-t,1]),u=e.norm(),l=a.slice([t,t],[1,1]),c=sn([[-1]]).where(l.greater(0),sn([[1]])),p=l.sub(c.mul(u)),h=e.div(p);s=1===h.shape[0]?o.clone():o.concat(h.slice([1,0],[h.shape[0]-1,h.shape[1]]),0);var f=c.matMul(p).div(u).neg(),d=a.slice([t,0],[n-t,r]),m=f.mul(s);if(0===t)a=d.sub(m.matMul(s.transpose().matMul(d)));else{var g=d.sub(m.matMul(s.transpose().matMul(d)));a=a.slice([0,0],[t,r]).concat(g,0)}var v=i.slice([0,t],[n,i.shape[1]-t]);if(0===t)i=v.sub(v.matMul(s).matMul(m.transpose()));else{var y=v.sub(v.matMul(s).matMul(m.transpose()));i=i.slice([0,0],[n,t]).concat(y,1)}return[s,a,i]}),s=e[0],a=e[1],i=e[2],Fe([u,l,c])},c=0;c<u;++c)l(c);return!e&&n>r&&(i=i.slice([0,0],[n,r]),a=a.slice([0,0],[r,r])),[i,a]})}var hc=Ze({gramSchmidt_:function(t){var e;if(Array.isArray(t)){e=!1,p(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){p(t[e].shape[0]===n,function(){return"Gram-Schmidt: Non-unique lengths found in the input vectors: ("+t[e].shape[0]+" vs. "+n+")"})},i=1;i<t.length;++i)r(i)}else e=!0,t=En(t,t.shape[0],0).map(function(t){return ar(t,[0])});p(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=[],o=t,s=function(t){a.push(Et.tidy(function(){var e=o[t];if(t>0)for(var n=0;n<t;++n){var r=Cl(a[n].mulStrict(e)).mul(a[n]);e=e.sub(r)}return e.div(Ol(e,"euclidean"))}))};for(i=0;i<t.length;++i)s(i);return e?or(a,0):a}}),fc=Ze({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 pc(t,e);var n=t.shape.slice(0,t.shape.length-2).reduce(function(t,e){return t*e}),r=[],i=[];return lr(t.reshape([n,t.shape[t.shape.length-2],t.shape[t.shape.length-1]]),0).forEach(function(t){var n=pc(t,e),a=n[0],o=n[1];r.push(a),i.push(o)}),[or(r,0).reshape(t.shape),or(i,0).reshape(t.shape)]}}),dc=Object.freeze({gramSchmidt:hc,qr:fc});function mc(t,e,n,r,i){null==r&&(r=.5),null==i&&(i=Number.NEGATIVE_INFINITY);var a=t.shape[0];return n=Math.min(n,a),p(0<=r&&r<=1,function(){return"iouThreshold must be in [0, 1], but was '"+r+"'"}),p(2===t.rank,function(){return"boxes must be a 2D tensor, but was of rank '"+t.rank+"'"}),p(4===t.shape[1],function(){return"boxes must have 4 columns, but 2nd dimension was "+t.shape[1]}),p(1===e.rank,function(){return"scores must be a 1D tensor"}),p(e.shape[0]===a,function(){return"scores has incompatible shape with boxes. Expected "+a+", but was "+e.shape[0]}),{maxOutputSize:n,iouThreshold:r,scoreThreshold:i}}var gc=Ze({resizeBilinear_:function(t,e,n){void 0===n&&(n=!1);var r=We(t,"images","resizeBilinear");p(3===r.rank||4===r.rank,function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+r.rank+"."}),p(2===e.length,function(){return"Error in resizeBilinear: new shape must 2D, but got shape "+e+"."});var i=r,a=!1;3===r.rank&&(a=!0,i=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var o=e[0],s=e[1],u=Et.runKernel(function(t,e){return e([i]),t.resizeBilinear(i,o,s,n)},{batchImages:i},function(t,e){return{batchImages:function(){return Et.runKernel(function(r){return r.resizeBilinearBackprop(t,e[0],n)},{})}}});return a?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),vc=Ze({resizeNearestNeighbor_:function(t,e,n){void 0===n&&(n=!1);var r=We(t,"images","resizeNearestNeighbor");p(3===r.rank||4===r.rank,function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+r.rank+"."}),p(2===e.length,function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+e+"."}),p("float32"===r.dtype||"int32"===r.dtype,function(){return"`images` must have `int32` or `float32` as dtype"});var i=r,a=!1;3===r.rank&&(a=!0,i=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var o=e[0],s=e[1],u=Et.runKernel(function(t,e){return e([i]),t.resizeNearestNeighbor(i,o,s,n)},{batchImages:i},function(t,e){return{batchImages:function(){return Et.runKernel(function(r){return r.resizeNearestNeighborBackprop(t,e[0],n)},{})}}});return a?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),yc=Ze({nonMaxSuppression_:function(t,e,n,r,i){void 0===r&&(r=.5),void 0===i&&(i=Number.NEGATIVE_INFINITY);var a=We(t,"boxes","nonMaxSuppression"),o=We(e,"scores","nonMaxSuppression"),s=mc(a,o,n,r,i);return n=s.maxOutputSize,r=s.iouThreshold,i=s.scoreThreshold,Et.runKernel(function(t){return t.nonMaxSuppression(a,o,n,r,i)},{$boxes:a})}}),bc=Ze({cropAndResize_:function(t,e,n,r,i,a){var o=We(t,"image","cropAndResize","float32"),s=We(e,"boxes","cropAndResize","float32"),u=We(n,"boxInd","cropAndResize","int32");i=i||"bilinear",a=a||0;var l=s.shape[0];return p(4===o.rank,function(){return"Error in cropAndResize: image must be rank 4,but got rank "+o.rank+"."}),p(2===s.rank&&4===s.shape[1],function(){return"Error in cropAndResize: boxes must be have size ["+l+",4] but had shape "+s.shape+"."}),p(1===u.rank&&u.shape[0]===l,function(){return"Error in cropAndResize: boxInd must be have size ["+l+"] but had shape "+s.shape+"."}),p(2===r.length,function(){return"Error in cropAndResize: cropSize must be of length 2, but got length "+r.length+"."}),p(r[0]>=1&&r[1]>=1,function(){return"cropSize must be atleast [1,1], but was "+r}),p("bilinear"===i||"nearest"===i,function(){return"method must be bilinear or nearest, but was "+i}),Et.runKernel(function(t,e){return t.cropAndResize(o,s,u,r,i,a)},{$image:o,$boxes:s})}}),xc=Object.freeze({resizeBilinear:gc,resizeNearestNeighbor:vc,nonMaxSuppression:yc,nonMaxSuppressionAsync:function(t,e,n,a,o){return void 0===a&&(a=.5),void 0===o&&(o=Number.NEGATIVE_INFINITY),r(this,void 0,void 0,function(){var r,s,u,l,c,p,h;return i(this,function(i){switch(i.label){case 0:return r=We(t,"boxes","nonMaxSuppressionAsync"),s=We(e,"scores","nonMaxSuppressionAsync"),u=mc(r,s,n,a,o),n=u.maxOutputSize,a=u.iouThreshold,o=u.scoreThreshold,[4,Promise.all([r.data(),s.data()])];case 1:return l=i.sent(),c=l[0],p=l[1],h=ni(c,p,n,a,o),r!==t&&r.dispose(),s!==e&&s.dispose(),[2,h]}})})},cropAndResize:bc}),wc=Ze({matMul_:function(t){var e,n=t.a,r=t.b,i=t.transposeA,a=void 0!==i&&i,o=t.transposeB,s=void 0!==o&&o,u=t.bias,l=t.activation,c=void 0===l?"linear":l,h=t.preluActivationWeights,f=We(n,"a","fused matMul"),d=We(r,"b","fused matMul");e=vt(f,d),f=e[0],d=e[1];var v=a?f.shape[f.rank-2]:f.shape[f.rank-1],y=s?d.shape[d.rank-1]:d.shape[d.rank-2],b=a?f.shape[f.rank-1]:f.shape[f.rank-2],x=s?d.shape[d.rank-2]:d.shape[d.rank-1],w=f.shape.slice(0,-2),C=d.shape.slice(0,-2),N=m(w),E=m(C);p(f.rank>=2&&d.rank>=2&&f.rank===d.rank,function(){return"Error in fused matMul: inputs must have the same rank of at least 2, got ranks "+f.rank+" and "+d.rank+"."}),p(g(w,C),function(){return"Error in fused matMul: outer dimensions ("+w+") and ("+C+") of Tensors with shapes "+f.shape+" and "+d.shape+" must match."}),p(v===y,function(){return"Error in fused matMul: inner shapes ("+v+") and ("+y+") of Tensors with shapes "+f.shape+" and "+d.shape+" and transposeA="+a+" and transposeB="+s+" must match."});var S,k,I=f.shape.slice(0,-2).concat([b,x]),A=a?f.as3D(N,v,b):f.as3D(N,b,v),R=s?d.as3D(E,x,y):d.as3D(E,y,x);null!=u&&zr(I,(S=vt(S=We(u,"bias","fused matMul"),f)[0]).shape),null!=h&&(k=We(h,"prelu weights","fused matMul"));var T={$a:A,$b:R};return null!=u&&(T.$bias=S),null!=h&&(T.$preluActivationWeights=k),Et.runKernel(function(t,e){var n=t.fusedBatchMatMul({a:A,b:R,transposeA:a,transposeB:s,bias:S,activation:c,preluActivationWeights:k});return e([A,R,n]),n},T,function(t,e){var n,r=e[0],i=e[1],o=e[2];if(null==c||"linear"===c)n=t;else{if("relu"!==c)throw new Error("Gradient for activation "+c+" has not been implemented yet.");n=t.mul(o.step())}var l={};return null!=u&&(l={$bias:function(){var t=n,e=Fr(S.shape,n.shape);return e.length>0&&(t=t.sum(e)),t.reshape(S.shape)}}),a||s?!a&&s?Object.assign({$a:function(){return n.matMul(i,!1,!1)},$b:function(){return n.matMul(r,!0,!1)}},l):a&&!s?Object.assign({$a:function(){return i.matMul(n,!1,!0)},$b:function(){return r.matMul(n,!1,!1)}},l):Object.assign({$a:function(){return i.matMul(n,!0,!0)},$b:function(){return n.matMul(r,!0,!0)}},l):Object.assign({$a:function(){return n.matMul(i,!1,!0)},$b:function(){return r.matMul(n,!0,!1)}},l)}).reshape(I)}}),Cc=Ze({conv2d_:function(t){var e=t.x,n=t.filter,r=t.strides,i=t.pad,a=t.dataFormat,o=void 0===a?"NHWC":a,s=t.dilations,u=void 0===s?[1,1]:s,l=t.dimRoundingMode,c=t.bias,h=t.activation,f=void 0===h?"linear":h,d=t.preluActivationWeights,m=We(e,"x","conv2d"),g=We(n,"filter","conv2d"),y=m,b=!1;3===m.rank&&(b=!0,y=m.as4D(1,m.shape[0],m.shape[1],m.shape[2])),p(4===y.rank,function(){return"Error in fused conv2d: input must be rank 4, but got rank "+y.rank+"."}),p(4===g.rank,function(){return"Error in fused conv2d: filter must be rank 4, but got rank "+g.rank+"."}),null!=l&&p(v(i),function(){return"Error in fused conv2d: pad must be an integer when using, dimRoundingMode "+l+" but got pad "+i+"."}),p(y.shape[3]===g.shape[2],function(){return"Error in conv2d: depth of input ("+y.shape[3]+") must match input depth for filter "+g.shape[2]+"."}),p(Hr(r,u),function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+u+"'"}),p("NHWC"===o,function(){return"Error in conv2d: got dataFormat of "+o+" but only NHWC is currently supported."});var x,w,C=Pr(y.shape,g.shape,r,u,i,l);null!=c&&(x=vt(x=We(c,"bias","fused conv2d"),m)[0],zr(C.outShape,x.shape)),null!=d&&(w=We(d,"prelu weights","fused conv2d"));var N={x:y,$filter:g};null!=c&&(N.$bias=x),null!=d&&(N.$preluActivationWeights=w);var E=Et.runKernel(function(t,e){var n=t.fusedConv2d({input:y,filter:g,convInfo:C,bias:x,activation:f,preluActivationWeights:w});return e([g,y,n]),n},N,function(t,e){var n,a=e,o=a[0],s=a[1],l=a[2];if(null==f||"linear"===f)n=t;else{if("relu"!==f)throw new Error("Gradient for activation "+f+" has not been implemented yet.");n=t.mul(l.step())}p(qr(u),function(){return"Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+u+"'"});var h={};return null!=c&&(h={$bias:function(){var t=n,e=Fr(x.shape,n.shape);return e.length>0&&(t=t.sum(e)),t.reshape(x.shape)}}),Object.assign({x:function(){return Bu(s.shape,n,o,r,i)},$filter:function(){return Pu(s,n,o.shape,r,i)}},h)});return b?E.as3D(E.shape[1],E.shape[2],E.shape[3]):E}}),Nc=Ze({depthwiseConv2d_:function(t){var e=t.x,n=t.filter,r=t.strides,i=t.pad,a=(t.dataFormat,t.dilations),o=void 0===a?[1,1]:a,s=t.dimRoundingMode,u=t.bias,l=t.activation,c=void 0===l?"linear":l,h=t.preluActivationWeights,f=We(e,"x","depthwiseConv2d"),d=We(n,"filter","depthwiseConv2d"),m=f,g=!1;3===f.rank&&(g=!0,m=f.as4D(1,f.shape[0],f.shape[1],f.shape[2])),p(4===m.rank,function(){return"Error in fused depthwiseConv2d: input must be rank 4, but got rank "+m.rank+"."}),p(4===d.rank,function(){return"Error in fused depthwiseConv2d: filter must be rank 4, but got rank "+d.rank+"."}),p(m.shape[3]===d.shape[2],function(){return"Error in fused depthwiseConv2d: number of input channels ("+m.shape[3]+") must match the inChannels dimension in filter "+d.shape[2]+"."}),null==o&&(o=[1,1]),p(Hr(r,o),function(){return"Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+o+"'"}),null!=s&&p(v(i),function(){return"Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode "+s+" but got pad "+i+"."});var y,b,x=Pr(m.shape,d.shape,r,o,i,s,!0);null!=u&&(y=vt(y=We(u,"bias","fused conv2d"),f)[0],zr(x.outShape,y.shape)),null!=h&&(b=We(h,"prelu weights","fused depthwiseConv2d"));var w={x:m,$filter:d};null!=u&&(w.$bias=y),null!=h&&(w.$preluActivationWeights=b);var C=Et.runKernel(function(t,e){var n=t.fusedDepthwiseConv2D({input:m,filter:d,convInfo:x,bias:y,activation:c,preluActivationWeights:b});return e([m,d,n]),n},w,function(t,e){p(qr(o),function(){return"Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+o+"'"});var n,r=e[0],i=e[1],a=e[2];if(null==c||"linear"===c)n=t;else{if("relu"!==c)throw new Error("Gradient for activation "+c+" has not been implemented yet.");n=t.mul(a.step())}var s={};return null!=u&&(s={$bias:function(){var t=n,e=Fr(y.shape,n.shape);return e.length>0&&(t=t.sum(e)),t.reshape(y.shape)}}),Object.assign({x:function(){return Vu(r.shape,n,i,x)},$filter:function(){return Uu(r,n,i.shape,x)}},s)});return g?C.as3D(C.shape[1],C.shape[2],C.shape[3]):C}}),Ec=Object.freeze({matMul:wc,conv2d:Cc,depthwiseConv2d:Nc}),Sc=Object.freeze({image:xc,linalg:dc,losses:cc,spectral:jl,fused:Ec,signal:Ql,conv1d:zu,conv2d:Mu,conv3d:Lu,depthwiseConv2d:Wu,separableConv2d:ju,conv2dTranspose:Gu,conv3dTranspose:qu,op:Ze,batchNormalization2d:Fs,batchNormalization3d:zs,batchNormalization4d:Ms,batchNormalization:Ls,batchNorm:Ps,batchNorm2d:Bs,batchNorm3d:Ws,batchNorm4d:Vs,booleanMaskAsync:Du,complex:Qe,real:tn,imag:en,concat:bn,concat1d:xn,concat2d:wn,concat3d:Cn,concat4d:Nn,split:En,matMul:Hu,dot:Ku,outerProduct:$u,reverse:Xu,reverse1d:Yu,reverse2d:Ju,reverse3d:Zu,reverse4d:Qu,maxPool:nl,avgPool:rl,pool:il,maxPool3d:al,avgPool3d:ol,slice:sl,slice1d:ul,slice2d:ll,slice3d:cl,slice4d:pl,abs:Ko,acos:$o,acosh:Xo,asin:Yo,asinh:Jo,atan:Zo,atanh:Qo,ceil:ts,clipByValue:es,cos:ns,cosh:rs,erf:is,exp:as,expm1:os,floor:ss,log:us,log1p:ls,logSigmoid:cs,neg:ps,reciprocal:hs,round:fs,rsqrt:ds,sigmoid:ms,sign:gs,isNaN:vs,isInf:ys,isFinite:bs,sin:xs,sinh:ws,softplus:Cs,sqrt:Ns,square:Es,step:Ss,tan:ks,tanh:Is,all:fl,any:dl,argMax:ml,argMin:gl,logSumExp:vl,max:yl,mean:bl,min:xl,moments:wl,sum:Cl,prod:Nl,equal:mu,equalStrict:gu,greater:vu,greaterEqual:yu,greaterEqualStrict:bu,greaterStrict:xu,less:wu,lessEqual:Cu,lessEqualStrict:Nu,lessStrict:Eu,notEqual:Su,notEqualStrict:ku,add:$s,addN:Xs,addStrict:Ys,atan2:Js,div:Zs,divStrict:Qs,floorDiv:tu,maximum:eu,maximumStrict:nu,minimum:ru,minimumStrict:iu,mod:au,modStrict:ou,mul:su,mulStrict:uu,pow:lu,powStrict:cu,squaredDifference:pu,squaredDifferenceStrict:hu,sub:fu,subStrict:du,elu:El,leakyRelu:Sl,prelu:kl,relu:Il,relu6:Al,selu:Rl,logicalAnd:Us,logicalNot:js,logicalOr:Gs,logicalXor:qs,where:Hs,whereAsync:Ks,buffer:Ln,print:Pn,batchToSpaceND:Bn,cast:Wn,clone:Vn,cumsum:Un,depthToSpace:jn,expandDims:Gn,eye:qn,multinomial:Hn,oneHot:Kn,pad:$n,pad1d:Xn,pad2d:Yn,pad3d:Jn,pad4d:Zn,rand:Qn,randomNormal:tr,randomGamma:er,randomUniform:nr,reshape:rr,spaceToBatchND:ir,squeeze:ar,stack:or,tile:sr,truncatedNormal:ur,unstack:lr,setdiff1dAsync:cr,fill:dn,linspace:mn,ones:hn,range:gn,scalar:an,tensor:nn,tensor1d:on,tensor2d:sn,tensor3d:un,tensor4d:ln,tensor5d:cn,tensor6d:pn,zeros:fn,onesLike:vn,zerosLike:yn,transpose:Tl,softmax:Rr,logSoftmax:Tr,localResponseNormalization:Dl,norm:Ol,gather:Ru,unsortedSegmentSum:Tu,basicLSTMCell:_l,multiRNNCell:Fl,movingAverage:zl,stridedSlice:Ml,topk:Ll,scatterND:Pl,fft:Bl,ifft:Wl,rfft:Vl,irfft:Ul,sparseToDense:Gl,gatherND:ql,diag:Hl,dropout:Kl,hannWindow:Xl,hammingWindow:Yl,frame:Jl,stft:Zl,inTopKAsync:tc});function kc(t,e,n,r){if("linear"===n)return t.linear(e);if("relu"===n)return t.relu(e);if("elu"===n)return t.elu(e);if("relu6"===n)return t.relu6(e);if("prelu"===n)return t.prelu(e,r);throw new Error("Activation "+n+" has not been implemented for the CPU backend.")}var Ic=function(){function t(){if(this.blockSize=48,this.firstUse=!0,o().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 Dr(this,Et)}return t.prototype.register=function(t,e,n){if(this.firstUse&&(this.firstUse=!1,o().get("IS_NODE")&&Le("\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,i=t.data instanceof Uint8Array,a="undefined"!=typeof ImageData&&t instanceof ImageData,s="undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement,u="undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement,l=s?[t.videoWidth,t.videoHeight]:[t.width,t.height],c=l[0],p=l[1];if(o().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,c,p).data;else if(a||i)n=t.data;else{if(!u&&!s)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=c,this.fromPixels2DContext.canvas.height=p,this.fromPixels2DContext.drawImage(t,0,0,c,p),n=this.fromPixels2DContext.getImageData(0,0,c,p).data}if(4===e)r=new Int32Array(n);else{var h=c*p;r=new Int32Array(h*e);for(var f=0;f<h;f++)for(var d=0;d<e;++d)r[f*e+d]=n[4*f+d]}return un(r,[p,c,e],"int32")},t.prototype.read=function(t){return r(this,void 0,void 0,function(){return i(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?Zr(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 K(t)})}catch(t){throw new Error("Failed to decode encoded string bytes into utf-8")}return Ln(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 i(this,function(n){return e=G(),t(),[2,{kernelMs:G()-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=st.make(t.shape,{},"complex64");return this.data.get(n.dataId).complexTensors={real:Et.keep(t.clone()),imag:Et.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&&p("complex64"!==t.dtype,function(){return e+" does not support complex64 tensors."})})},t.prototype.slice=function(t,e,n){if(this.assertNotComplex(t,"slice"),Er(t.shape,e,n)){var r=Sr(e,t.strides),i=m(n);return nn(this.readSync(t.dataId).subarray(r,r+i),n,t.dtype)}for(var a=Ln(n,t.dtype),o=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]=o.get.apply(o,u)}return a.toTensor()},t.prototype.stridedSlice=function(t,e,n,r){this.assertNotComplex(t,"stridedSlice");var i=wr(e,n,r);if(i.some(function(t){return 0===t}))return nn([],i);for(var a=Ln(i,t.dtype),o=this.bufferSync(t),s=0;s<a.size;s++){for(var u=a.indexToLoc(s),l=new Array(u.length),c=0;c<l.length;c++)l[c]=u[c]*r[c]+e[c];a.set.apply(a,[o.get.apply(o,l)].concat(u))}return a.toTensor()},t.prototype.diag=function(t){for(var e=this.readSync(t.dataId),n=Ln([t.size,t.size],t.dtype),r=n.values,i=0;i<e.length;i++)r[i*t.size+i]=e[i];return n.toTensor()},t.prototype.unstack=function(t,e){for(var n=t.shape[e],r=new Array(t.rank-1),i=0,a=0;a<t.rank;a++)a!==e&&(r[i++]=t.shape[a]);var o=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++)o[e]=a,u[a]=this.slice(t,o,s).reshape(r);return u},t.prototype.reverse=function(t,e){this.assertNotComplex(t,"reverse");for(var n=Ln(t.shape,t.dtype),r=this.bufferSync(t),i=function(i){var a=n.indexToLoc(i),o=a.slice();e.forEach(function(e){return o[e]=t.shape[e]-1-o[e]}),n.set.apply(n,[r.get.apply(r,o)].concat(a))},a=0;a<n.size;a++)i(a);return n.toTensor()},t.prototype.concat=function(t,e){var n=this;if("complex64"===t[0].dtype){var r=t.map(function(t){return tn(t)}),i=t.map(function(t){return en(t)});return Qe(this.concat(r,e),this.concat(i,e))}var a=t.map(function(t){var n=m(t.shape.slice(e));return t.as2D(-1,n)}),o=Je(a.map(function(t){return t.shape}),1),s=Ln(o,t[0].dtype).values;if(1===a[0].shape[0]){var u=0;a.forEach(function(t){s.set(n.readSync(t.dataId),u),u+=t.size})}else{var l=0;a.forEach(function(t){for(var e=n.readSync(t.dataId),r=0,i=0;i<t.shape[0];++i)for(var a=i*o[1]+l,u=0;u<t.shape[1];++u)s[a+u]=e[r++];l+=t.shape[1]})}var c=Je(t.map(function(t){return t.shape}),e);return nn(s,c,t[0].dtype)},t.prototype.neg=function(t){return this.assertNotComplex(t,"neg"),this.multiply(an(-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,mt(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=Ln(t[0].shape,t[0].dtype),i=r.values,a=0;a<t.length;a++)for(var o=n[a],s=0;s<i.length;s++)i[s]+=o[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,mt(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 i=n?t.shape[1]:t.shape[2],a=n?t.shape[2]:t.shape[1],o=r?e.shape[1]:e.shape[2],s=t.shape[0],u=this.readSync(t.dataId),l=this.readSync(e.dataId),c=n?[t.strides[0],1,t.strides[1]]:[t.strides[0],t.strides[1],1],p=c[0],h=c[1],f=c[2],d=r?[1,e.strides[1],e.strides[0]]:[e.strides[1],1,e.strides[0]],m=d[0],g=d[1],v=d[2],y=a*o,b=Ln([s,a,o],t.dtype),x=b.values,w=this.blockSize,C=0;C<s;C++)for(var N=0;N<a;N+=w)for(var E=0;E<o;E+=w)for(var S=0;S<i;S+=w)for(var k=Math.min(N+w,a),I=Math.min(E+w,o),A=Math.min(S+w,i),R=N;R<k;R++)for(var T=E;T<I;T++){for(var D=0,O=S;O<A;O++)D+=u[C*p+R*h+O*f]*l[O*m+T*g+C*v];x[C*y+(R*o+T)]+=D}return b.toTensor()},t.prototype.fusedBatchMatMul=function(t){var e=t.a,n=t.b,r=t.transposeA,i=t.transposeB,a=t.bias,o=t.activation,s=t.preluActivationWeights,u=this.batchMatMul(e,n,r,i);return a&&(u=this.add(u,a)),o&&(u=kc(this,u,o,s)),u},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,mt(t.dtype,e.dtype),function(t,e){return t*e})},t.prototype.realDivide=function(t,e){return this.assertNotComplex([t,e],"realDivide"),this.broadcastedBinaryOp(t,e,"float32",function(t,e){return t/e})},t.prototype.floorDiv=function(t,e){return this.assertNotComplex([t,e],"floorDiv"),this.broadcastedBinaryOp(t,e,"int32",function(t,e){return Math.floor(t/e)})},t.prototype.sum=function(t,e){this.assertNotComplex(t,"sum"),He("sum",e,t.rank);for(var n=Ge(t.shape,e),r=n[0],i=n[1],a=fn(r,mt(t.dtype,"int32")),o=m(i),s=this.readSync(a.dataId),u=this.readSync(t.dataId),l=0;l<s.length;++l){for(var c=l*o,p=0,h=0;h<o;++h)p+=u[c+h];s[l]=p}return a},t.prototype.prod=function(t,e){this.assertNotComplex(t,"sum");for(var n=Ge(t.shape,e),r=n[0],i=n[1],a=fn(r,mt(t.dtype,"int32")),o=m(i),s=this.readSync(a.dataId),u=this.readSync(t.dataId),l=0;l<s.length;++l){for(var c=l*o,p=1,h=0;h<o;++h)p*=u[c+h];s[l]=p}return a},t.prototype.unsortedSegmentSum=function(t,e,n){this.assertNotComplex(t,"unsortedSegmentSum");for(var r=[],i=t.rank-e.rank,a=0;a<i;++a)e=e.expandDims(a+1);for(a=0;a<n;++a){var o=an(a,"int32"),s=mu(o,e).asType("float32").mul(t).sum(0);r.push(s)}return or(r)},t.prototype.argMin=function(t,e){this.assertNotComplex(t,"argMin");var n=[e];He("argMin",n,t.rank);for(var r=Ge(t.shape,n),i=r[0],a=r[1],o=fn(i,"int32"),s=m(a),u=this.readSync(o.dataId),l=this.readSync(t.dataId),c=0;c<u.length;++c){for(var p=c*s,h=l[p],f=0,d=0;d<s;++d){var g=l[p+d];g<h&&(h=g,f=d)}u[c]=f}return o},t.prototype.argMax=function(t,e){this.assertNotComplex(t,"argMax");var n=[e];He("argMax",n,t.rank);for(var r=Ge(t.shape,n),i=r[0],a=r[1],o=fn(i,"int32"),s=m(a),u=this.readSync(o.dataId),l=this.readSync(t.dataId),c=0;c<u.length;++c){for(var p=c*s,h=l[p],f=0,d=0;d<s;++d){var g=l[p+d];g>h&&(h=g,f=d)}u[c]=f}return o},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 i=mt(t.dtype,"int32"),a=fn(t.shape,i),o=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 p=0;p<u;p++){var h=l(c,p);if(0===p)o[h]=n?0:s[h];else{var f=l(c,p-1);o[h]=n?s[f]+o[f]:s[h]+o[f]}}return 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 st.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),i=this.readSync(e.dataId),a=this.readSync(n.dataId),o=fn(e.shape,mt(e.dtype,n.dtype)),s=this.readSync(o.dataId),u=0,l=0===t.rank||t.rank>1||1===e.rank?1:m(e.shape.slice(1)),c=0;c<r.length;c++)for(var p=0;p<l;p++)1===r[c]?s[u++]=i[c]:s[u++]=a[c];return o},t.prototype.where=function(t){this.assertNotComplex([t],"where");var e=this.readSync(t.dataId);return si(t.shape,e)},t.prototype.topk=function(t,e,n){return this.assertNotComplex(t,"topk"),oi(this.readSync(t.dataId),t.shape,t.dtype,e)},t.prototype.min=function(t,e){this.assertNotComplex(t,"min"),He("min",e,t.rank);for(var n=Ge(t.shape,e),r=n[0],i=n[1],a=fn(r,t.dtype),o=m(i),s=this.readSync(a.dataId),u=this.readSync(t.dataId),l=0;l<s.length;++l){for(var c=l*o,p=u[c],h=0;h<o;++h){var f=u[c+h];f<p&&(p=f)}s[l]=p}return 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"),He("max",e,t.rank);for(var n=Ge(t.shape,e),r=n[0],i=n[1],a=fn(r,t.dtype),o=m(i),s=this.readSync(a.dataId),u=this.readSync(t.dataId),l=0;l<s.length;++l){for(var c=l*o,p=u[c],h=0;h<o;++h){var f=u[c+h];f>p&&(p=f)}s[l]=p}return 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"),He("all",e,t.rank);for(var n=Ge(t.shape,e),r=n[0],i=n[1],a=fn(r,t.dtype),o=m(i),s=this.readSync(a.dataId),u=this.readSync(t.dataId),l=0;l<s.length;++l){for(var c=l*o,p=u[c],h=0;h<o;++h){var f=u[c+h];p=p&&f}s[l]=p}return a},t.prototype.any=function(t,e){this.assertNotComplex(t,"any"),He("any",e,t.rank);for(var n=Ge(t.shape,e),r=n[0],i=n[1],a=fn(r,t.dtype),o=m(i),s=this.readSync(a.dataId),u=this.readSync(t.dataId),l=0;l<s.length;++l){for(var c=l*o,p=u[c],h=0;h<o;++h){var f=u[c+h];p=p||f}s[l]=p}return 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 st.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 st.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 st.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 st.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 st.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 st.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 i=Math.floor(e[r]);e[r]-i<.5?n[r]=Math.floor(e[r]):e[r]-i>.5?n[r]=Math.ceil(e[r]):n[r]=i%2==0?i:i+1}return st.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 st.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 st.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 i=e[r];n[r]=Math.log(i)}return st.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 i=e[r];n[r]=Math.log1p(i)}return st.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 i=e[r];n[r]=Math.sqrt(i)}return st.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 i=e[r];n[r]=1/Math.sqrt(i)}return st.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 i=e[r];n[r]=i*i}return st.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 st.make(t.shape,{values:n})},t.prototype.linear=function(t){return t},t.prototype.relu=function(t){this.assertNotComplex(t,"relu");for(var e=fn(t.shape,t.dtype),n=this.readSync(e.dataId),r=this.readSync(t.dataId),i=0;i<r.length;++i)n[i]=Math.max(0,r[i]);return e},t.prototype.relu6=function(t){this.assertNotComplex(t,"relu");for(var e=fn(t.shape,t.dtype),n=this.readSync(e.dataId),r=this.readSync(t.dataId),i=0;i<r.length;++i)n[i]=Math.min(Math.max(0,r[i]),6);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 i=n[r];e[r]=i>=0?i:Math.exp(i)-1}return st.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),i=this.readSync(t.dataId),a=0;a<r.length;++a){var o=r[a];n[a]=o>=1?i[a]:i[a]*(o+1)}return st.make(e.shape,{values:n})},t.prototype.selu=function(t){this.assertNotComplex(t,"selu");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r){var i=n[r];e[r]=i>=0?1.0507009873554805*i:1.7580993408473768*(Math.exp(i)-1)}return st.make(t.shape,{values:e})},t.prototype.clip=function(t,e,n){this.assertNotComplex(t,"clip");for(var r=new Float32Array(t.size),i=this.readSync(t.dataId),a=0;a<i.length;++a){var o=i[a];r[a]=o>n?n:o<e?e:o}return st.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 st.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 i=n[2*r],a=n[2*r+1];e[r]=Math.hypot(i,a)}return st.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 st.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 st.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),i=0;i<r.length;++i){var a,o=r[i]>-e,s=r[i]<e,u=Math.exp(r[i]);a=s?u:o?r[i]:Math.log(1+u),n[i]=a}return st.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 st.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 st.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 st.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 st.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 st.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 st.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 st.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 st.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]=y(n[r]);return st.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 st.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 st.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 st.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 i=Math.sign(n[r]),a=Math.abs(n[r]),o=1/(1+.3275911*a);e[r]=i*(1-((((1.061405429*o-1.453152027)*o+1.421413741)*o-.284496736)*o+.254829592)*o*Math.exp(-a*a))}return st.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),i=0;i<r.length;++i){var a=r[i];isNaN(a)?n[i]=NaN:n[i]=a>0?1:e}return st.make(t.shape,{values:n})},t.prototype.fusedConv2d=function(t){var e=t.input,n=t.filter,r=t.convInfo,i=t.bias,a=t.activation,o=t.preluActivationWeights,s=this.conv2d(e,n,r);return i&&(s=this.add(s,i)),a&&(s=kc(this,s,a,o)),s},t.prototype.conv2d=function(t,e,n){this.assertNotComplex([t,e],"conv2d");for(var r=n.filterHeight,i=n.filterWidth,a=n.dilationHeight,o=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,l="channelsLast"===n.dataFormat,c=Ln(n.outShape,t.dtype),p=t.strides[0],h=l?t.strides[1]:t.strides[2],f=l?t.strides[2]:1,d=l?1:t.strides[1],m=c.strides[0],g=l?c.strides[1]:c.strides[2],v=l?c.strides[2]:1,y=l?1:c.strides[1],b=this.readSync(t.dataId),x=this.readSync(e.dataId),w=c.values,C=0;C<n.batchSize;++C)for(var N=C*p,E=C*m,S=0;S<n.outHeight;++S)for(var k=E+S*g,I=S*n.strideHeight-u,A=0;A<r;A++){var R=I+A*a;if(!(R<0||R>=n.inHeight))for(var T=A*e.strides[0],D=N+R*h,O=0;O<n.outWidth;++O)for(var _=k+O*v,F=O*n.strideWidth-s,z=0;z<i;z++){var M=F+z*o;if(!(M<0||M>=n.inWidth))for(var L=D+M*f,P=T+z*e.strides[1],B=0;B<n.inChannels;++B){for(var W=b[L+B*d],V=0;V<n.outChannels;++V)w[_+V*y]+=W*x[P+V];P+=n.outChannels}}}return c.toTensor()},t.prototype.conv3d=function(t,e,n){for(var r=n.filterDepth,i=n.filterHeight,a=n.filterWidth,o=n.dilationDepth,s=n.dilationHeight,u=n.dilationWidth,l=n.padInfo.front,c=n.padInfo.left,p=n.padInfo.top,h=Ln(n.outShape,t.dtype),f=this.readSync(t.dataId),d=this.readSync(e.dataId),m=h.values,g=0;g<n.batchSize;++g)for(var v=g*t.strides[0],y=g*h.strides[0],b=0;b<n.outDepth;++b)for(var x=y+b*h.strides[1],w=b*n.strideDepth-l,C=0;C<r;C++){var N=w+C*o;if(!(N<0||N>=n.inDepth))for(var E=C*e.strides[0],S=v+N*t.strides[1],k=0;k<n.outHeight;++k)for(var I=x+k*h.strides[2],A=k*n.strideHeight-p,R=0;R<i;R++){var T=A+R*s;if(!(T<0||T>=n.inHeight))for(var D=E+R*e.strides[1],O=S+T*t.strides[2],_=0;_<n.outWidth;++_)for(var F=I+_*n.outChannels,z=_*n.strideWidth-c,M=0;M<a;M++){var L=z+M*u;if(!(L<0||L>=n.inWidth))for(var P=D+M*e.strides[2],B=O+L*n.inChannels,W=P,V=0;V<n.inChannels;++V){for(var U=f[B+V],j=0;j<n.outChannels;++j)m[F+j]+=U*d[W+j];W+=n.outChannels}}}}return h.toTensor()},t.prototype.conv2dDerInput=function(t,e,n){this.assertNotComplex([t,e],"conv2dDerInput");for(var r=Ln(n.inShape,"float32"),i=r.values,a=this.readSync(t.dataId),o=this.readSync(e.dataId),s=e.strides,u=s[0],l=s[1],c=s[2],p=n.batchSize,h=n.filterHeight,f=n.filterWidth,d=n.inChannels,m=n.inHeight,g=n.inWidth,v=n.outChannels,y=n.outHeight,b=n.outWidth,x=n.strideHeight,w=n.strideWidth,C=n.dataFormat,N=h-1-n.padInfo.top,E=f-1-n.padInfo.left,S="channelsLast"===C,k=r.strides[0],I=S?r.strides[1]:r.strides[2],A=S?r.strides[2]:1,R=S?1:r.strides[1],T=t.strides[0],D=S?t.strides[1]:t.strides[2],O=S?t.strides[2]:1,_=S?1:t.strides[1],F=0;F<p;++F)for(var z=0;z<d;++z)for(var M=0;M<m;++M)for(var L=M-N,P=Math.max(0,Math.ceil(L/x)),B=Math.min(y,(h+L)/x),W=0;W<g;++W){for(var V=W-E,U=Math.max(0,Math.ceil(V/w)),j=Math.min(b,(f+V)/w),G=0,q=P;q<B;++q)for(var H=q*x-L,K=U;K<j;++K)for(var $=T*F+D*q+O*K,X=u*(h-1-H)+l*(f-1-(K*w-V))+c*z,Y=0;Y<v;++Y)G+=a[$+_*Y]*o[X+Y];i[k*F+I*M+A*W+R*z]=G}return r.toTensor()},t.prototype.conv3dDerInput=function(t,e,n){for(var r=Ln(n.inShape,"float32"),i=r.values,a=r.strides,o=a[0],s=a[1],u=a[2],l=a[3],c=this.readSync(t.dataId),p=t.strides,h=p[0],f=p[1],d=p[2],m=p[3],g=this.readSync(e.dataId),v=e.strides,y=v[0],b=v[1],x=v[2],w=v[3],C=n.batchSize,N=n.filterDepth,E=n.filterHeight,S=n.filterWidth,k=n.inChannels,I=n.inDepth,A=n.inHeight,R=n.inWidth,T=n.outChannels,D=n.outDepth,O=n.outHeight,_=n.outWidth,F=n.strideDepth,z=n.strideHeight,M=n.strideWidth,L=N-1-n.padInfo.front,P=E-1-n.padInfo.top,B=S-1-n.padInfo.left,W=0;W<C;++W)for(var V=0;V<k;++V)for(var U=0;U<I;++U)for(var j=U-L,G=Math.max(0,Math.ceil(j/F)),q=Math.min(D,(N+j)/F),H=0;H<A;++H)for(var K=H-P,$=Math.max(0,Math.ceil(K/z)),X=Math.min(O,(E+K)/z),Y=0;Y<R;++Y){for(var J=Y-B,Z=Math.max(0,Math.ceil(J/M)),Q=Math.min(_,(S+J)/M),tt=0,et=G;et<q;++et)for(var nt=et*F-j,rt=$;rt<X;++rt)for(var it=rt*z-K,at=Z;at<Q;++at)for(var ot=h*W+f*et+d*rt+m*at,st=y*(N-1-nt)+b*(E-1-it)+x*(S-1-(at*M-J))+w*V,ut=0;ut<T;++ut)tt+=c[ot+ut]*g[st+ut];i[o*W+s*U+u*H+l*Y+V]=tt}return r.toTensor()},t.prototype.conv2dDerFilter=function(t,e,n){this.assertNotComplex([t,e],"conv2dDerFilter");for(var r=n.strideHeight,i=n.strideWidth,a=n.filterHeight,o=n.filterWidth,s="channelsLast"===n.dataFormat,u=Ln(n.filterShape,"float32"),l=n.padInfo.left,c=n.padInfo.top,p=this.bufferSync(t),h=this.bufferSync(e),f=0;f<a;++f)for(var d=Math.max(0,Math.ceil((c-f)/r)),m=Math.min(n.outHeight,(n.inHeight+c-f)/r),g=0;g<o;++g)for(var v=Math.max(0,Math.ceil((l-g)/i)),y=Math.min(n.outWidth,(n.inWidth+l-g)/i),b=0;b<n.inChannels;++b)for(var x=0;x<n.outChannels;++x){for(var w=0,C=0;C<n.batchSize;++C)for(var N=d;N<m;++N)for(var E=f+N*r-c,S=v;S<y;++S){var k=g+S*i-l;w+=s?p.get(C,E,k,b)*h.get(C,N,S,x):p.get(C,b,E,k)*h.get(C,x,N,S)}u.set(w,f,g,b,x)}return u.toTensor()},t.prototype.conv3dDerFilter=function(t,e,n){for(var r=n.strideDepth,i=n.strideHeight,a=n.strideWidth,o=n.filterDepth,s=n.filterHeight,u=n.filterWidth,l=Ln(n.filterShape,"float32"),c=l.values,p=l.strides,h=p[0],f=p[1],d=p[2],m=p[3],g=this.readSync(e.dataId),v=e.strides,y=v[0],b=v[1],x=v[2],w=v[3],C=this.readSync(t.dataId),N=t.strides,E=N[0],S=N[1],k=N[2],I=N[3],A=n.padInfo.front,R=n.padInfo.left,T=n.padInfo.top,D=0;D<o;++D)for(var O=Math.max(0,Math.ceil((A-D)/r)),_=Math.min(n.outDepth,(n.inDepth+A-D)/r),F=D*h,z=0;z<s;++z)for(var M=Math.max(0,Math.ceil((T-z)/i)),L=Math.min(n.outHeight,(n.inHeight+T-z)/i),P=z*f+F,B=0;B<u;++B)for(var W=Math.max(0,Math.ceil((R-B)/a)),V=Math.min(n.outWidth,(n.inWidth+R-B)/a),U=B*d+P,j=0;j<n.inChannels;++j)for(var G=j*m+U,q=0;q<n.outChannels;++q){for(var H=0,K=0;K<n.batchSize;++K)for(var $=K*E,X=K*y,Y=O;Y<_;++Y)for(var J=(D+Y*r-A)*S+$,Z=Y*b+X,Q=M;Q<L;++Q)for(var tt=(z+Q*i-T)*k+J,et=Q*x+Z,nt=W;nt<V;++nt){var rt=nt*w+et;H+=C[(B+nt*a-R)*I+tt+j]*g[rt+q]}c[G+q]=H}return l.toTensor()},t.prototype.fusedDepthwiseConv2D=function(t){var e=t.input,n=t.filter,r=t.convInfo,i=t.bias,a=t.activation,o=t.preluActivationWeights,s=this.depthwiseConv2D(e,n,r);return i&&(s=this.add(s,i)),a&&(s=kc(this,s,a,o)),s},t.prototype.depthwiseConv2D=function(t,e,n){this.assertNotComplex([t,e],"depthwiseConv2D");for(var r=n.filterHeight,i=n.filterWidth,a=n.dilationHeight,o=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,l=n.outChannels/n.inChannels,c=Ln(n.outShape,t.dtype),p=this.readSync(t.dataId),h=this.readSync(e.dataId),f=c.values,d=0;d<n.batchSize;++d)for(var m=d*t.strides[0],g=d*c.strides[0],v=0;v<n.outHeight;++v)for(var y=g+v*c.strides[1],b=v*n.strideHeight-s,x=0;x<r;++x){var w=b+x*a;if(!(w<0||w>=n.inHeight))for(var C=x*e.strides[0],N=m+w*t.strides[1],E=0;E<n.outWidth;++E)for(var S=y+E*c.strides[2],k=E*n.strideWidth-u,I=0;I<i;++I){var A=k+I*o;if(!(A<0||A>=n.inWidth))for(var R=C+I*e.strides[1],T=N+A*n.inChannels,D=S,O=R,_=0;_<n.inChannels;++_){for(var F=p[T+_],z=0;z<l;++z)f[D+z]+=F*h[O+z];D+=l,O+=l}}}return c.toTensor()},t.prototype.depthwiseConv2DDerInput=function(t,e,n){this.assertNotComplex([t,e],"depthwiseConv2DDerInput");for(var r=Ln(n.inShape,"float32"),i=r.values,a=r.strides,o=a[0],s=a[1],u=a[2],l=this.readSync(t.dataId),c=t.strides,p=c[0],h=c[1],f=c[2],d=this.readSync(e.dataId),m=e.strides,g=m[0],v=m[1],y=m[2],b=n.batchSize,x=n.filterHeight,w=n.filterWidth,C=n.inChannels,N=n.inHeight,E=n.inWidth,S=n.outChannels,k=n.outHeight,I=n.outWidth,A=n.strideHeight,R=n.strideWidth,T=x-1-n.padInfo.top,D=w-1-n.padInfo.left,O=S/C,_=0;_<b;++_)for(var F=0;F<C;++F)for(var z=0;z<N;++z)for(var M=z-T,L=Math.max(0,Math.ceil(M/A)),P=Math.min(k,(x+M)/A),B=0;B<E;++B){for(var W=B-D,V=Math.max(0,Math.ceil(W/R)),U=Math.min(I,(w+W)/R),j=0,G=L;G<P;++G)for(var q=G*A-M,H=V;H<U;++H)for(var K=p*_+h*G+f*H,$=g*(x-1-q)+v*(w-1-(H*R-W))+y*F,X=0;X<O;++X)j+=l[K+(F*O+X)]*d[$+X];i[o*_+s*z+u*B+F]=j}return r.toTensor()},t.prototype.depthwiseConv2DDerFilter=function(t,e,n){this.assertNotComplex([t,e],"depthwiseConv2DDerFilter");for(var r=n.strideHeight,i=n.strideWidth,a=n.filterHeight,o=n.filterWidth,s=Ln(n.filterShape,"float32"),u=n.padInfo.left,l=n.padInfo.top,c=n.outChannels/n.inChannels,p=this.bufferSync(t),h=this.bufferSync(e),f=0;f<a;++f)for(var d=Math.max(0,Math.ceil((l-f)/r)),m=Math.min(n.outHeight,(n.inHeight+l-f)/r),g=0;g<o;++g)for(var v=Math.max(0,Math.ceil((u-g)/i)),y=Math.min(n.outWidth,(n.inWidth+u-g)/i),b=0;b<n.outChannels;++b){for(var x=Math.trunc(b/c),w=b%c,C=0,N=0;N<n.batchSize;++N)for(var E=d;E<m;++E)for(var S=f+E*r-l,k=v;k<y;++k){var I=g+k*i-u;C+=p.get(N,S,I,x)*h.get(N,E,k,b)}s.set(C,f,g,x,w)}return s.toTensor()},t.prototype.tile=function(t,e){return this.assertNotComplex(t,"tile"),ai(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]}),i=e.map(function(t){return t[0]}),a=this.bufferSync(t),o=Ln(r,t.dtype);0!==n&&o.values.fill(n);for(var s=0;s<t.size;s++){var u=a.indexToLoc(s),l=u.map(function(t,e){return t+i[e]});o.set.apply(o,[a.get.apply(a,u)].concat(l))}return o.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 i=this.readSync(t.dataId),a=Ln(n,t.dtype),o=this.bufferSync(t);for(r=0;r<t.size;++r){for(var s=o.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]=i[r]}return a.toTensor()},t.prototype.gather=function(t,e,n){this.assertNotComplex([t,e],"gather");var r=t.shape.slice(),i=this.readSync(e.dataId);r[n]=i.length;for(var a=Ln(r,t.dtype),o=this.bufferSync(t),s=0;s<a.size;++s){var u=a.indexToLoc(s),l=u.slice();l[n]=i[u[n]];var c=o.locToIndex(l);a.values[s]=o.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}),i=pr(t.shape,e,r),a=hr(i.length,e.length),o=fr(t.shape,e,r),s=dr(n,e.length),u=mr(o,n,e.length);return t.reshape(i).transpose(a).reshape(o).slice(s,u)},t.prototype.spaceToBatchND=function(t,e,n){this.assertNotComplex([t],"spaceToBatchND");var r=e.reduce(function(t,e){return t*e}),i=[[0,0]];i.push.apply(i,n);for(var a=1+e.length;a<t.shape.length;++a)i.push([0,0]);var o=t.pad(i),s=pr(o.shape,e,r,!1),u=hr(s.length,e.length,!1),l=fr(o.shape,e,r,!1);return o.reshape(s).transpose(u).reshape(l)},t.prototype.pool=function(t,e,n){this.assertNotComplex(t,"pool");for(var r=e.strideHeight,i=e.strideWidth,a=e.dilationHeight,o=e.dilationWidth,s=e.effectiveFilterHeight,u=e.effectiveFilterWidth,l=e.padInfo.top,c=e.padInfo.left,p="max"===n?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,h=this.readSync(t.dataId),f=Ln(e.outShape,t.dtype),d=f.values,m=e.outShape[1]*e.outShape[2]*e.outShape[3],g=e.outShape[2]*e.outShape[3],v=e.outShape[3],y=0;y<e.batchSize;++y)for(var b=y*m,x=y*t.strides[0],w=0;w<e.inChannels;++w)for(var C=0;C<e.outHeight;++C)for(var N=C*r-l,E=Math.max(0,N),S=Math.min(e.inHeight,s+N),k=b+C*g,I=0;I<e.outWidth;++I){for(var A=I*i-c,R=Math.max(0,A),T=Math.min(e.inWidth,u+A),D=p,O=0,_=0,F=E;F<S;F+=a){for(var z=x+F*t.strides[1],M=R;M<T;M+=o){var L=h[z+M*t.strides[2]+w];"max"===n&&L>D?D=L:"avg"===n&&(O+=L,_++)}if(isNaN(D))break}d[k+I*v+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=Ln(e.outShape,"int32"),r=e.strideHeight,i=e.strideWidth,a=e.dilationHeight,o=e.dilationWidth,s=e.effectiveFilterHeight,u=e.effectiveFilterWidth,l=e.padInfo.top,c=e.padInfo.left,p=this.bufferSync(t),h=0;h<e.batchSize;++h)for(var f=0;f<e.inChannels;++f)for(var d=0;d<e.outHeight;++d){for(var m=d*r-l,g=m;g<0;)g+=a;for(var v=Math.min(e.inHeight,s+m),y=0;y<e.outWidth;++y){for(var b=y*i-c,x=b;x<0;)x+=o;for(var w=Math.min(e.inWidth,u+b),C=Number.NEGATIVE_INFINITY,N=-1,E=g;E<v;E+=a)for(var S=E-m,k=x;k<w;k+=o){var I=k-b,A=p.get(h,E,k,f);A>C&&(C=A,N=S*u+I)}n.set(N,h,d,y,f)}}return n.toTensor()},t.prototype.maxPoolBackprop=function(t,e,n,r){this.assertNotComplex([e,n],"maxPoolBackprop");for(var i=this.maxPoolPositions(e,r),a=r.strideHeight,o=r.strideWidth,s=r.dilationHeight,u=r.dilationWidth,l=r.effectiveFilterHeight,c=r.effectiveFilterWidth,p=c-1-r.padInfo.left,h=l-1-r.padInfo.top,f=Ln(e.shape,"float32"),d=this.bufferSync(i),m=this.bufferSync(t),g=0;g<r.batchSize;++g)for(var v=0;v<r.inChannels;++v)for(var y=0;y<r.inHeight;++y)for(var b=0;b<r.inWidth;++b){for(var x=y-h,w=b-p,C=0,N=0;N<l;N+=s){var E=(x+N)/a;if(!(E<0||E>=r.outHeight||Math.floor(E)!==E))for(var S=0;S<c;S+=u){var k=(w+S)/o;if(!(k<0||k>=r.outWidth||Math.floor(k)!==k)){var I=l*c-1-d.get(g,E,k,v)===N*c+S?1:0;0!==I&&(C+=m.get(g,E,k,v)*I)}}}f.set(C,g,y,b,v)}return f.toTensor()},t.prototype.avgPoolBackprop=function(t,e,n){this.assertNotComplex([t,e],"avgPoolBackprop");for(var r=n.strideHeight,i=n.strideWidth,a=n.filterHeight,o=n.filterWidth,s=n.dilationHeight,u=n.dilationWidth,l=n.effectiveFilterHeight,c=n.effectiveFilterWidth,p=c-1-n.padInfo.left,h=l-1-n.padInfo.top,f=Ln(e.shape,"float32"),d=1/(a*o),m=this.bufferSync(t),g=0;g<n.batchSize;++g)for(var v=0;v<n.inChannels;++v)for(var y=0;y<n.inHeight;++y)for(var b=0;b<n.inWidth;++b){for(var x=y-h,w=b-p,C=0,N=0;N<l;N+=s){var E=(x+N)/r;if(!(E<0||E>=n.outHeight||Math.floor(E)!==E))for(var S=0;S<c;S+=u){var k=(w+S)/i;k<0||k>=n.outWidth||Math.floor(k)!==k||(C+=m.get(g,E,k,v))}}f.set(C*d,g,y,b,v)}return f.toTensor()},t.prototype.pool3d=function(t,e,n){this.assertNotComplex(t,"pool3d");for(var r=e.strideDepth,i=e.strideHeight,a=e.strideWidth,o=e.dilationDepth,s=e.dilationHeight,u=e.dilationWidth,l=e.effectiveFilterDepth,c=e.effectiveFilterHeight,p=e.effectiveFilterWidth,h=e.padInfo.front,f=e.padInfo.top,d=e.padInfo.left,m="max"===n?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,g=this.readSync(t.dataId),v=Ln(e.outShape,t.dtype),y=v.values,b=e.outShape[1]*e.outShape[2]*e.outShape[3]*e.outShape[4],x=e.outShape[2]*e.outShape[3]*e.outShape[4],w=e.outShape[3]*e.outShape[4],C=e.outShape[4],N=0;N<e.batchSize;++N)for(var E=N*b,S=N*t.strides[0],k=0;k<e.inChannels;++k)for(var I=0;I<e.outDepth;++I){for(var A=I*r-h,R=A;R<0;)R+=o;for(var T=Math.min(e.inDepth,l+A),D=E+I*x,O=0;O<e.outHeight;++O){for(var _=O*i-f,F=_;F<0;)F+=s;for(var z=Math.min(e.inHeight,c+_),M=D+O*w,L=0;L<e.outWidth;++L){for(var P=L*a-d,B=P;B<0;)B+=u;for(var W=Math.min(e.inWidth,p+P),V=M+L*C,U=m,j=0,G=0,q=R;q<T;q+=o){for(var H=S+q*t.strides[1],K=F;K<z;K+=s){for(var $=H+K*t.strides[2],X=B;X<W;X+=u){var Y=g[$+X*t.strides[3]+k];if("max"===n&&Y>U?U=Y:"avg"===n&&(j+=Y,G++),isNaN(U))break}if(isNaN(U))break}if(isNaN(U))break}y[V+k]="avg"===n?j/G:U}}}return v.toTensor()},t.prototype.avgPool3d=function(t,e){return this.assertNotComplex(t,"avgPool3d"),this.pool3d(t,e,"avg").toFloat()},t.prototype.avgPool3dBackprop=function(t,e,n){this.assertNotComplex([t,e],"avgPool3dBackprop");for(var r=n.strideDepth,i=n.strideHeight,a=n.strideWidth,o=n.filterDepth,s=n.filterHeight,u=n.filterWidth,l=n.dilationDepth,c=n.dilationHeight,p=n.dilationWidth,h=n.effectiveFilterDepth,f=n.effectiveFilterHeight,d=n.effectiveFilterWidth,m=h-1-n.padInfo.front,g=d-1-n.padInfo.left,v=f-1-n.padInfo.top,y=Ln(e.shape,"float32"),b=1/(o*s*u),x=this.bufferSync(t),w=0;w<n.batchSize;++w)for(var C=0;C<n.inChannels;++C)for(var N=0;N<n.inDepth;++N)for(var E=0;E<n.inHeight;++E)for(var S=0;S<n.inWidth;++S){for(var k=N-m,I=E-v,A=S-g,R=0,T=0;T<h;T+=l){var D=(k+T)/r;if(!(D<0||D>=n.outDepth||Math.floor(D)!==D))for(var O=0;O<f;O+=c){var _=(I+O)/i;if(!(_<0||_>=n.outHeight||Math.floor(_)!==_))for(var F=0;F<d;F+=p){var z=(A+F)/a;z<0||z>=n.outWidth||Math.floor(z)!==z||(R+=x.get(w,D,_,z,C))}}}y.set(R*b,w,N,E,S,C)}return y.toTensor()},t.prototype.maxPool3d=function(t,e){return this.assertNotComplex(t,"maxPool3d"),this.pool3d(t,e,"max").toFloat()},t.prototype.maxPool3dPositions=function(t,e){for(var n=Ln(e.outShape,"int32"),r=e.strideDepth,i=e.strideHeight,a=e.strideWidth,o=e.dilationDepth,s=e.dilationHeight,u=e.dilationWidth,l=e.effectiveFilterDepth,c=e.effectiveFilterHeight,p=e.effectiveFilterWidth,h=e.padInfo.front,f=e.padInfo.top,d=e.padInfo.left,m=this.bufferSync(t),g=0;g<e.batchSize;++g)for(var v=0;v<e.inChannels;++v)for(var y=0;y<e.outDepth;++y){for(var b=y*r-h,x=b;x<0;)x+=o;for(var w=Math.min(e.inDepth,l+b),C=0;C<e.outHeight;++C){for(var N=C*i-f,E=N;E<0;)E+=s;for(var S=Math.min(e.inHeight,c+N),k=0;k<e.outWidth;++k){for(var I=k*a-d,A=I;A<0;)A+=u;for(var R=Math.min(e.inWidth,p+I),T=Number.NEGATIVE_INFINITY,D=-1,O=x;O<w;O+=o)for(var _=O-b,F=E;F<S;F+=s)for(var z=F-N,M=A;M<R;M+=u){var L=M-I,P=m.get(g,O,F,M,v);P>=T&&(T=P,D=_*c*p+z*c+L)}n.set(D,g,y,C,k,v)}}}return n.toTensor()},t.prototype.maxPool3dBackprop=function(t,e,n,r){this.assertNotComplex([e,n],"maxPool3dBackprop");for(var i=this.maxPool3dPositions(e,r),a=r.strideDepth,o=r.strideHeight,s=r.strideWidth,u=r.dilationDepth,l=r.dilationHeight,c=r.dilationWidth,p=r.effectiveFilterDepth,h=r.effectiveFilterHeight,f=r.effectiveFilterWidth,d=p-1-r.padInfo.front,m=f-1-r.padInfo.left,g=h-1-r.padInfo.top,v=Ln(e.shape,"float32"),y=this.bufferSync(i),b=this.bufferSync(t),x=0;x<r.batchSize;++x)for(var w=0;w<r.inChannels;++w)for(var C=0;C<r.inDepth;++C)for(var N=0;N<r.inHeight;++N)for(var E=0;E<r.inWidth;++E){for(var S=C-d,k=N-g,I=E-m,A=0,R=0;R<p;R+=u){var T=(S+R)/a;if(!(T<0||T>=r.outDepth||Math.floor(T)!==T))for(var D=0;D<h;D+=l){var O=(k+D)/o;if(!(O<0||O>=r.outHeight||Math.floor(O)!==O))for(var _=0;_<f;_+=c){var F=(I+_)/s;if(!(F<0||F>=r.outWidth||Math.floor(F)!==F)){var z=p*h*f-1-y.get(x,T,O,F,w)===R*h*f+D*f+_?1:0;0!==z&&(A+=b.get(x,T,O,F,w)*z)}}}}v.set(A,x,C,N,E,w)}return v.toTensor()},t.prototype.cast=function(t,e){return $r(t,e,this)},t.prototype.reshape=function(t,e){return Xr(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 i=t.shape,a=i[0],o=i[1],s=i[2],u=i[3],l=this.readSync(t.dataId),c=new Float32Array(m([a,e,n,u])),p=[r&&e>1?o-1:o,r&&n>1?s-1:s],h=[r&&e>1?e-1:e,r&&n>1?n-1:n],f=0,d=p[0]/h[0],g=p[1]/h[1],v=0;v<a;v++)for(var y=0;y<e;y++)for(var b=d*y,x=Math.floor(b),w=b-x,C=Math.min(o-1,Math.ceil(b)),N=v*t.strides[0]+x*t.strides[1],E=v*t.strides[0]+C*t.strides[1],S=0;S<n;S++)for(var k=g*S,I=Math.floor(k),A=k-I,R=Math.min(s-1,Math.ceil(k)),T=N+I*t.strides[2],D=E+I*t.strides[2],O=N+ +R*t.strides[2],_=E+R*t.strides[2],F=0;F<u;F++){var z=l[T+F],M=l[D+F],L=z+(l[O+F]-z)*A,P=L+(M+(l[_+F]-M)*A-L)*w;c[f++]=P}return nn(c,[a,e,n,u])},t.prototype.resizeBilinearBackprop=function(t,e,n){this.assertNotComplex([t,e],"resizeBilinearBackprop");for(var r=e.shape,i=r[0],a=r[1],o=r[2],s=r[3],u=t.shape,l=u[1],c=u[2],p=new Float32Array(i*a*o*s),h=[n&&l>1?a-1:a,n&&c>1?o-1:o],f=[n&&l>1?l-1:l,n&&c>1?c-1:c],d=h[0]/f[0],m=h[1]/f[1],g=this.readSync(t.dataId),v=0,y=0;y<i;y++)for(var b=y*e.strides[0],x=0;x<l;x++)for(var w=x*d,C=Math.floor(w),N=Math.min(Math.ceil(w),a-1),E=b+C*e.strides[1],S=b+N*e.strides[1],k=w-C,I=1-k,A=0;A<c;A++)for(var R=A*m,T=Math.floor(R),D=Math.min(Math.ceil(R),o-1),O=R-T,_=1-O,F=E+T*e.strides[2],z=E+D*e.strides[2],M=S+T*e.strides[2],L=S+D*e.strides[2],P=I*_,B=I*O,W=k*_,V=k*O,U=0;U<s;U++){var j=g[v++];p[F+U]+=j*P,p[z+U]+=j*B,p[M+U]+=j*W,p[L+U]+=j*V}return ln(p,[i,o,a,s],e.dtype)},t.prototype.resizeNearestNeighbor=function(t,e,n,r){this.assertNotComplex(t,"resizeNearestNeighbor");for(var i=t.shape,a=i[0],o=i[1],s=i[2],u=i[3],l=this.readSync(t.dataId),c=new Float32Array(a*e*n*u),p=[r&&e>1?o-1:o,r&&n>1?s-1:s],h=[r&&e>1?e-1:e,r&&n>1?n-1:n],f=p[0]/h[0],d=p[1]/h[1],m=0,g=0;g<a;g++)for(var v=g*t.strides[0],y=0;y<e;y++)for(var b=f*y,x=v+Math.min(o-1,r?Math.round(b):Math.floor(b))*t.strides[1],w=0;w<n;w++)for(var C=d*w,N=x+Math.min(s-1,r?Math.round(C):Math.floor(C))*t.strides[2],E=0;E<u;E++){var S=l[N+E];c[m++]=S}return nn(c,[a,e,n,u],t.dtype)},t.prototype.resizeNearestNeighborBackprop=function(t,e,n){this.assertNotComplex([t,e],"resizeNearestNeighborBackprop");for(var r=e.shape,i=r[0],a=r[1],o=r[2],s=r[3],u=t.shape,l=u[1],c=u[2],p=new Float32Array(i*a*o*s),h=this.readSync(t.dataId),f=[n&&l>1?a-1:a,n&&c>1?o-1:o],d=[n&&l>1?l-1:l,n&&c>1?c-1:c],m=f[0]/d[0],g=f[1]/d[1],v=1/m,y=1/g,b=2*Math.ceil(v)+2,x=2*Math.ceil(y)+2,w=0;w<i;w++)for(var C=w*e.strides[0],N=0;N<a;N++)for(var E=C+N*e.strides[1],S=Math.floor(N*v),k=Math.floor(S-b/2),I=0;I<o;I++)for(var A=E+I*e.strides[2],R=Math.floor(I*y),T=Math.floor(R-x/2),D=0;D<s;D++){for(var O=0,_=0;_<b;_++){var F=_+k;if(!(F<0||F>=l)){var z=C+F*t.strides[1],M=F*m;if(N===Math.min(a-1,n?Math.round(M):Math.floor(M)))for(var L=0;L<x;L++){var P=L+T;if(!(P<0||P>=c)){var B=z+P*t.strides[2],W=P*g;I===Math.min(o-1,n?Math.round(W):Math.floor(W))&&(O+=h[B+D])}}}}p[A+D]=O}return ln(p,e.shape,e.dtype)},t.prototype.batchNormalization=function(t,e,n,r,i,a){this.assertNotComplex([t,e,n,i,a],"batchNorm");for(var o=this.readSync(t.dataId),s=this.readSync(e.dataId),u=this.readSync(n.dataId),l=i?this.readSync(i.dataId):new Float32Array([1]),c=a?this.readSync(a.dataId):new Float32Array([0]),p=new Float32Array(o.length),h=c.length,f=l.length,d=u.length,m=s.length,g=0,v=0,y=0,b=0,x=0;x<o.length;++x)p[x]=c[g++]+(o[x]-s[v++])*l[y++]/Math.sqrt(u[b++]+r),g>=h&&(g=0),v>=m&&(v=0),y>=f&&(y=0),b>=d&&(b=0);return ln(p,t.shape)},t.prototype.localResponseNormalization4D=function(t,e,n,r,i){this.assertNotComplex(t,"localResponseNormalization4D");var a=t.shape[3],o=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),i=t-n+Math.min(n+e,o),u=0;r<=i;r++){var l=s[r];u+=l*l}return u}for(var p=0;p<u;p++){var h=c(p),f=s[p]*Math.pow(n+r*h,-i);l[p]=f}return ln(l,t.shape)},t.prototype.LRNGrad=function(t,e,n,r,i,a,o){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),p=new Float32Array(t.size),h=t.size,f=0;f<h;f++){for(var d=f%s,m=f-d+Math.max(0,d-r),g=f-d+Math.min(s,d+r+1),v=0,y=m;y<g;y++)v+=Math.pow(l[y],2);for(v=a*v+i,y=m;y<g;y++){var b=-2*a*o*l[y]*c[f]/v;f===y&&(b+=Math.pow(v,-o)),b*=u[f],p[y]+=b}}return ln(p,t.shape)},t.prototype.multinomial=function(t,e,n,r){this.assertNotComplex(t,"multinomial");for(var i=e?t:Rr(t),a=i.shape[0],o=i.shape[1],s=fn([a,n],"int32"),u=this.readSync(s.dataId),l=this.readSync(i.dataId),c=0;c<a;++c){var p=c*o,h=new Float32Array(o-1);h[0]=l[p];for(var f=1;f<h.length;++f)h[f]=h[f-1]+l[p+f];for(var d=_n(r.toString()),m=c*n,g=0;g<n;++g){var v=d();u[m+g]=h.length;for(var y=0;y<h.length;y++)if(v<h[y]){u[m+g]=y;break}}}return s},t.prototype.oneHot=function(t,e,n,r){this.assertNotComplex(t,"oneHot");var i=new Float32Array(t.size*e);i.fill(r);for(var a=this.readSync(t.dataId),o=0;o<t.size;++o)a[o]>=0&&a[o]<e&&(i[o*e+a[o]]=n);return sn(i,[t.size,e],"int32")},t.prototype.nonMaxSuppression=function(t,e,n,r,i){return this.assertNotComplex(t,"nonMaxSuppression"),ni(this.readSync(t.dataId),this.readSync(e.dataId),n,r,i)},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],i=Ln(t.shape,"float32"),a=Ln(t.shape,"float32"),o=tn(t).as2D(n,r),s=en(t).as2D(n,r),u=0;u<n;u++)for(var l=o.slice([u,0],[1,r]),c=s.slice([u,0],[1,r]),p=Qe(l,c),h=this.readSync(this.fftImpl(p,e).dataId),f=0;f<r;f++){var d=Qr(h,f);i.values[u*r+f]=d.real,a.values[u*r+f]=d.imag}return Qe(i.toTensor(),a.toTensor()).as2D(n,r)},t.prototype.fftImpl=function(t,e){var n=t.as1D(),r=n.size;if(this.isExponentOf2(r)){var i=this.fftRadix2(n,r,e).as2D(t.shape[0],t.shape[1]);return e&&(i=Qe(tn(i).div(an(r)),en(i).div(an(r)))),i}var a=this.readSync(t.dataId),o=function(t){for(var e=new Float32Array(t.length/2),n=new Float32Array(t.length/2),r=0;r<t.length;r+=2)e[r/2]=t[r],n[r/2]=t[r+1];return{real:e,imag:n}}(this.fourierTransformByMatmul(a,r,e));return Qe(o.real,o.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),i=e/2,a=function(t){for(var e=Math.ceil(t.length/4),n=new Float32Array(e),r=new Float32Array(e),i=0;i<t.length;i+=4)n[Math.floor(i/4)]=t[i],r[Math.floor(i/4)]=t[i+1];return{real:n,imag:r}}(r),o=Qe(a.real,a.imag).as1D(),s=function(t){for(var e=Math.floor(t.length/4),n=new Float32Array(e),r=new Float32Array(e),i=2;i<t.length;i+=4)n[Math.floor(i/4)]=t[i],r[Math.floor(i/4)]=t[i+1];return{real:n,imag:r}}(r),u=Qe(s.real,s.imag).as1D();o=this.fftRadix2(o,i,n),u=this.fftRadix2(u,i,n);var l=function(t,e){for(var n=new Float32Array(t/2),r=new Float32Array(t/2),i=0;i<Math.ceil(t/2);i++){var a=(e?2:-2)*Math.PI*(i/t);n[i]=Math.cos(a),r[i]=Math.sin(a)}return{real:n,imag:r}}(e,n),c=Qe(l.real,l.imag).mul(u),p=o.add(c),h=o.sub(c),f=tn(p).concat(tn(h)),d=en(p).concat(en(h));return Qe(f,d).as1D()},t.prototype.fourierTransformByMatmul=function(t,e,n){for(var r=new Float32Array(2*e),i=0;i<e;i++){for(var a=0,o=0,s=0;s<e;s++){var u=ei(i*s,e,n),l=Qr(t,s);a+=l.real*u.real-l.imag*u.imag,o+=l.real*u.imag+l.imag*u.real}n&&(a/=e,o/=e),ti(r,a,o,i)}return r},t.prototype.depthToSpace=function(t,e,n){p("NHWC"===n,function(){return"Only NHWC dataFormat supported on CPU for depthToSpace. Got "+n}),p(e>1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+e});for(var r=t.shape[0],i=t.shape[1],a=t.shape[2],o=t.shape[3],s=i*e,u=a*e,l=o/(e*e),c=this.readSync(t.dataId),h=new Float32Array(r*s*u*l),f=0,d=0;d<r;++d)for(var m=0;m<s;++m)for(var g=Math.floor(m/e),v=m%e,y=0;y<u;++y)for(var b=Math.floor(y/e),x=(v*e+y%e)*l,w=0;w<l;++w){var C=w+x+o*(b+a*(g+i*d));h[f++]=c[C]}return ln(h,[r,s,u,l])},t.prototype.broadcastedBinaryOp=function(t,e,n,r){var i=zr(t.shape,e.shape),a=Ln(i,n),o=this.readSync(t.dataId),s=this.readSync(e.dataId),u=_r(t.shape,i),l=_r(e.shape,i),c=a.values;if(u.length+l.length===0)for(var p=0;p<c.length;++p)c[p]=r(o[p%o.length],s[p%s.length]);else{var h=this.bufferSync(t),f=this.bufferSync(e),d=function(n){var i=a.indexToLoc(n),p=i.slice(-t.rank);u.forEach(function(t){return p[t]=0});var d=h.locToIndex(p),m=i.slice(-e.rank);l.forEach(function(t){return m[t]=0});var g=f.locToIndex(m);c[n]=r(o[d],s[g])};for(p=0;p<c.length;++p)d(p)}return a.toTensor()},t.prototype.broadcastedBinaryComplexOp=function(t,e,n){var r=zr(t.shape,e.shape),i=Ln(r,"float32"),a=Ln(r,"float32"),o=this.readSync(t.dataId),s=this.readSync(e.dataId),u=_r(t.shape,r),l=_r(e.shape,r),c=i.values,p=a.values;if(u.length+l.length===0)for(var h=0;h<c.length;h++){var f=h%o.length,d=h%s.length,m=n(o[2*f],o[2*f+1],s[2*d],s[2*d+1]);c[h]=m.real,p[h]=m.imag}else{var g=this.bufferSync(this.data.get(t.dataId).complexTensors.real),v=this.bufferSync(this.data.get(e.dataId).complexTensors.real),y=function(r){var a=i.indexToLoc(r),h=a.slice(-t.rank);u.forEach(function(t){return h[t]=0});var f=g.locToIndex(h),d=a.slice(-e.rank);l.forEach(function(t){return d[t]=0});var m=v.locToIndex(d),y=n(o[2*f],o[2*f+1],s[2*m],s[2*m+1]);c[r]=y.real,p[r]=y.imag};for(h=0;h<c.length;h++)y(h)}return this.complex(i.toTensor(),a.toTensor())},t.prototype.split=function(t,e,n){return ii(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,i,a){for(var o=t.shape,s=o[0],u=o[1],l=o[2],c=o[3],p=e.shape[0],h=r[0],f=r[1],d=Ln([p,h,f,c],t.dtype),m=this.readSync(e.dataId),g=this.readSync(n.dataId),v=this.readSync(t.dataId),y=t.strides,b=d.strides,x=0;x<p;x++){var w=4*x,C=m[w],N=m[w+1],E=m[w+2],S=m[w+3],k=g[x];if(!(k>=s))for(var I=h>1?(E-C)*(u-1)/(h-1):0,A=f>1?(S-N)*(l-1)/(f-1):0,R=0;R<h;R++){var T=h>1?C*(u-1)+R*I:.5*(C+E)*(u-1);if(T<0||T>u-1)for(var D=0;D<f;D++)for(var O=0;O<c;O++){var _=O+D*b[2]+R*b[1]+x*b[0];d.values[_]=a}else if("bilinear"===i){var F=Math.floor(T),z=Math.ceil(T),M=T-F;for(D=0;D<f;D++)if((q=f>1?N*(l-1)+D*A:.5*(N+S)*(l-1))<0||q>l-1)for(O=0;O<c;O++)_=O+D*b[2]+R*b[1]+x*b[0],d.values[_]=a;else{var L=Math.floor(q),P=Math.ceil(q),B=q-L;for(O=0;O<c;O++){var W=v[_=O+L*y[2]+F*y[1]+k*y[0]],V=v[_=O+P*y[2]+F*y[1]+k*y[0]],U=v[_=O+L*y[2]+z*y[1]+k*y[0]],j=W+(V-W)*B,G=U+(v[_=O+P*y[2]+z*y[1]+k*y[0]]-U)*B;_=O+D*b[2]+R*b[1]+x*b[0],d.values[_]=j+(G-j)*M}}}else for(D=0;D<f;++D){var q;if((q=f>1?N*(l-1)+D*A:.5*(N+S)*(l-1))<0||q>l-1)for(O=0;O<c;O++)_=O+D*b[2]+R*b[1]+x*b[0],d.values[_]=a;else{var H=Math.round(q),K=Math.round(T);for(O=0;O<c;O++){var $=O+H*y[2]+K*y[1]+k*y[0],X=O+D*b[2]+R*b[1]+x*b[0];d.values[X]=v[$]}}}}}return d.toTensor()},t.prototype.sparseToDense=function(t,e,n,r){var i=br(0,t,n),a=i.sliceRank,o=i.numUpdates,s=i.sliceSize,u=i.strides,l=i.outputSize;return this.scatter(t,e,n,l,s,o,a,u,r,!1)},t.prototype.gatherND=function(t,e){var n=e.shape,r=n[n.length-1],i=gr(t,e),a=i[0],o=i[1],s=i[2],u=i[3];if(0===o)return nn([],a,t.dtype);for(var l=new rt([o,s],t.dtype),c=this.readSync(e.dataId),p=this.readSync(t.dataId),h=0;h<o;h++){for(var f=[],d=0,m=0;m<r;m++){var g=c[h*r+m];d+=g*u[m],f.push(g)}if(d<0||d>=t.size/s)throw new Error("Invalid indices: "+f+" does not index into "+t.shape);for(var v=0;v<s;v++)l.values[h*s+v]=p[d*s+v]}return l.toTensor().reshape(a)},t.prototype.scatterND=function(t,e,n){var r=br(0,t,n),i=r.sliceRank,a=r.numUpdates,o=r.sliceSize,s=r.strides,u=r.outputSize,l=an(0);return this.scatter(t,e,n,u,o,a,i,s,l,!0)},t.prototype.fill=function(t,e,n){var r=k(n=n||M(e),m(t));return r.fill(e),st.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=k(t.dtype,m(t.shape));return st.make(t.shape,{values:e},t.dtype)},t.prototype.linspace=function(t,e,n){return Yr(t,e,n)},t.prototype.scatter=function(t,e,n,r,i,a,o,s,u,l){var c=[r/i,i],p=this.readSync(t.dataId),h=this.readSync(e.dataId);if(0===r)return nn([],n,e.dtype);var f=new rt(c,e.dtype);f.values.fill(this.readSync(u.dataId)[0]);for(var d=0;d<a;d++){for(var m=[],g=0,v=0;v<o;v++){var y=p[d*o+v];m.push(y),g+=y*s[v]}if(g<0||g>=r/i)throw new Error("Invalid indices: "+m+" does not index into "+n);for(var b=0;b<i;b++)l?f.values[g*i+b]+=h[d*i+b]:f.values[g*i+b]=0===e.rank?h[0]:h[d*i+b]}return f.toTensor().reshape(n)},t}();Et.registerBackend("cpu",function(){return new Ic},1);var Ac=function(){function t(){}return t.prototype.fetch=function(t,e){return fetch(t,e)},t.prototype.now=function(){return performance.now()},t.prototype.encode=function(t,e){if("utf-8"!==e&&"utf8"!==e)throw new Error("Browser's encoder only supports utf-8, but got "+e);return null==this.textEncoder&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(t)},t.prototype.decode=function(t,e){return new TextDecoder(e).decode(t)},t}();o().get("IS_BROWSER")&&o().setPlatform("browser",new Ac);var Rc,Tc=function(){function t(){this.util=require("util"),this.textEncoder=new this.util.TextEncoder}return t.prototype.fetch=function(t,e){return null!=o().global.fetch?o().global.fetch(t,e):(null==Rc&&(Rc=require("node-fetch")),Rc(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}();o().get("IS_NODE")&&o().setPlatform("node",new Tc);var Dc={float32:4,int32:4,uint16:2,uint8:1,bool:1},Oc=4;function _c(t,e){for(var n={},r=0,i=function(e){var i=e.name,a=e.dtype,o=e.shape,s=m(o),u=void 0;if("quantization"in e){var l=e.quantization;if("uint8"!==l.dtype&&"uint16"!==l.dtype)throw new Error("Weight "+e.name+" has unknown quantization dtype "+l.dtype+". Supported quantization dtypes are: 'uint8' and 'uint16'.");var c=Dc[l.dtype],p=t.slice(r,r+s*c),h="uint8"===l.dtype?new Uint8Array(p):new Uint16Array(p);if("float32"===a)u=Float32Array.from(h,function(t){return t*l.scale+l.min});else{if("int32"!==a)throw new Error("Unsupported dtype in weight '"+i+"': "+a);u=Int32Array.from(h,function(t){return Math.round(t*l.scale+l.min)})}r+=s*c}else if("string"===a){var f=m(e.shape);u=[];for(var d=0;d<f;d++){var g=new Uint32Array(t.slice(r,r+Oc))[0];r+=Oc;var v=new Uint8Array(t.slice(r,r+g));u.push(v),r+=g}}else{var y=Dc[a];if(p=t.slice(r,r+s*y),"float32"===a)u=new Float32Array(p);else if("int32"===a)u=new Int32Array(p);else{if("bool"!==a)throw new Error("Unsupported dtype in weight '"+i+"': "+a);u=new Uint8Array(p)}r+=s*y}n[i]=nn(u,o,a)},a=0,o=e;a<o.length;a++)i(o[a]);return n}var Fc="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function zc(t){return Fc?Buffer.byteLength(t):new Blob([t]).size}function Mc(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 Lc(t){for(t=t.trim();t.endsWith("/");)t=t.slice(0,t.length-1);var e=t.split("/");return e[e.length-1]}function Pc(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:zc(JSON.stringify(t.modelTopology)),weightSpecsBytes:null==t.weightSpecs?0:zc(JSON.stringify(t.weightSpecs)),weightDataBytes:null==t.weightData?0:t.weightData.byteLength}}var Bc=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 i=[];return("load"===n?t.getInstance().loadRouters:t.getInstance().saveRouters).forEach(function(t){var n=t(e,r);null!==n&&i.push(n)}),i},t}(),Wc="://",Vc=function(){function t(){this.managers={}}return t.getInstance=function(){return null==t.instance&&(t.instance=new t),t.instance},t.registerManager=function(e,n){p(null!=e,function(){return"scheme must not be undefined or null."}),e.endsWith(Wc)&&(e=e.slice(0,e.indexOf(Wc))),p(e.length>0,function(){return"scheme must not be an empty string."});var r=t.getInstance();p(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 Uc(t){if(-1===t.indexOf(Wc))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+Vc.getSchemes().join(","));return{scheme:t.split(Wc)[0],path:t.split(Wc)[1]}}function jc(t,e,n){return void 0===n&&(n=!1),r(this,void 0,void 0,function(){var r,a,o,s,u,l,c,h,f;return i(this,function(i){switch(i.label){case 0:return p(t!==e,function(){return"Old path and new path are the same: '"+t+"'"}),p((r=Bc.getLoadHandlers(t)).length>0,function(){return"Copying failed because no load handler is found for source URL "+t+"."}),p(r.length<2,function(){return"Copying failed because more than one ("+r.length+") load handlers for source URL "+t+"."}),a=r[0],p((o=Bc.getSaveHandlers(e)).length>0,function(){return"Copying failed because no save handler is found for destination URL "+e+"."}),p(o.length<2,function(){return"Copying failed because more than one ("+r.length+") save handlers for destination URL "+e+"."}),s=o[0],u=Uc(t).scheme,l=Uc(t).path,c=u===Uc(t).scheme,[4,a.load()];case 1:return h=i.sent(),n&&c?[4,Vc.getManager(u).removeModel(l)]:[3,3];case 2:i.sent(),i.label=3;case 3:return[4,s.save(h)];case 4:return f=i.sent(),!n||c?[3,6]:[4,Vc.getManager(u).removeModel(l)];case 5:i.sent(),i.label=6;case 6:return[2,f.modelArtifactsInfo]}})})}var Gc="models_store",qc="model_info_store";function Hc(){if(!o().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 Kc(t){var e=t.result;e.createObjectStore(Gc,{keyPath:"modelPath"}),e.createObjectStore(qc,{keyPath:"modelPath"})}var $c=function(){function t(t){if(this.indexedDB=Hc(),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 i(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 i(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 i=n.indexedDB.open("tensorflowjs",1);i.onupgradeneeded=function(){return Kc(i)},i.onsuccess=function(){var a=i.result;if(null==e){var o=a.transaction(Gc,"readonly"),s=o.objectStore(Gc).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)},o.oncomplete=function(){return a.close()}}else{var u,l=Pc(e),c=a.transaction(qc,"readwrite"),p=c.objectStore(qc),h=p.put({modelPath:n.modelPath,modelArtifactsInfo:l});h.onsuccess=function(){var i=(u=a.transaction(Gc,"readwrite")).objectStore(Gc).put({modelPath:n.modelPath,modelArtifacts:e,modelArtifactsInfo:l});i.onsuccess=function(){return t({modelArtifactsInfo:l})},i.onerror=function(t){var e=(p=c.objectStore(qc)).delete(n.modelPath);e.onsuccess=function(){return a.close(),r(i.error)},e.onerror=function(t){return a.close(),r(i.error)}}},h.onerror=function(t){return a.close(),r(h.error)},c.oncomplete=function(){null==u?a.close():u.oncomplete=function(){return a.close()}}}},i.onerror=function(t){return r(i.error)}})},t.URL_SCHEME="indexeddb://",t}(),Xc=function(t){return o().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith($c.URL_SCHEME)?(e=t.slice($c.URL_SCHEME.length),new $c(e)):null;var e};Bc.registerSaveRouter(Xc),Bc.registerLoadRouter(Xc);var Yc=function(){function t(){this.indexedDB=Hc()}return t.prototype.listModels=function(){return r(this,void 0,void 0,function(){var t=this;return i(this,function(e){return[2,new Promise(function(e,n){var r=t.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=function(){return Kc(r)},r.onsuccess=function(){var t=r.result,i=t.transaction(qc,"readonly"),a=i.objectStore(qc).getAll();a.onsuccess=function(){for(var t={},n=0,r=a.result;n<r.length;n++){var i=r[n];t[i.modelPath]=i.modelArtifactsInfo}e(t)},a.onerror=function(e){return t.close(),n(a.error)},i.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 i(this,function(n){var r;return t=(r=t).startsWith($c.URL_SCHEME)?r.slice($c.URL_SCHEME.length):r,[2,new Promise(function(n,r){var i=e.indexedDB.open("tensorflowjs",1);i.onupgradeneeded=function(){return Kc(i)},i.onsuccess=function(){var e,a=i.result,o=a.transaction(qc,"readwrite"),s=o.objectStore(qc),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 i=s.delete(t),o=function(){var i=(e=a.transaction(Gc,"readwrite")).objectStore(Gc).delete(t);i.onsuccess=function(){return n(u.result.modelArtifactsInfo)},i.onerror=function(t){return r(u.error)}};i.onsuccess=o,i.onerror=function(t){return o(),a.close(),r(u.error)}},u.onerror=function(t){return a.close(),r(u.error)},o.oncomplete=function(){null==e?a.close():e.oncomplete=function(){return a.close()}}},i.onerror=function(t){return r(i.error)}})]})})},t}();if(o().getBool("IS_BROWSER"))try{Vc.registerManager($c.URL_SCHEME,new Yc)}catch(e){}var Jc="/",Zc="tensorflowjs_models",Qc="info",tp="model_topology",ep="weight_specs",np="weight_data",rp="model_metadata";function ip(t){return{info:[Zc,t,Qc].join(Jc),topology:[Zc,t,tp].join(Jc),weightSpecs:[Zc,t,ep].join(Jc),weightData:[Zc,t,np].join(Jc),modelMetadata:[Zc,t,rp].join(Jc)}}function ap(t){var e=t.split(Jc);if(e.length<3)throw new Error("Invalid key format: "+t);return e.slice(1,e.length-1).join(Jc)}var op=function(){function t(t){if(!o().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=ip(this.modelPath)}return t.prototype.save=function(t){return r(this,void 0,void 0,function(){var e,n,r;return i(this,function(i){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=Pc(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,Fc?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,o,s;return i(this,function(i){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))&&(o=JSON.parse(a),e.format=o.format,e.generatedBy=o.generatedBy,e.convertedBy=o.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(Fc){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),i=0;i<n.length;++i)r.set([n.charCodeAt(i)],i);return r.buffer}(s),[2,e]})})},t.URL_SCHEME="localstorage://",t}(),sp=function(t){return o().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(op.URL_SCHEME)?(e=t.slice(op.URL_SCHEME.length),new op(e)):null;var e};Bc.registerSaveRouter(sp),Bc.registerLoadRouter(sp);var up=function(){function t(){p(o().getBool("IS_BROWSER"),function(){return"Current environment is not a web browser"}),p(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,o;return i(this,function(i){for(t={},e=Zc+Jc,n=Jc+Qc,r=0;r<this.LS.length;++r)(a=this.LS.key(r)).startsWith(e)&&a.endsWith(n)&&(o=ap(a),t[o]=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 i(this,function(r){var i;if(t=(i=t).startsWith(op.URL_SCHEME)?i.slice(op.URL_SCHEME.length):i,e=ip(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(o().getBool("IS_BROWSER"))try{Vc.registerManager(op.URL_SCHEME,new up)}catch(e){}var lp="model",cp=".json",pp=".weights.bin";function hp(t){return new Promise(function(t){return setTimeout(t)}).then(t)}var fp=function(){function t(e){if(!o().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=lp),this.modelTopologyFileName=e+cp,this.weightDataFileName=e+pp}return t.prototype.save=function(t){return r(this,void 0,void 0,function(){var e,n,r,a,o,s;return i(this,function(i){switch(i.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"})),(o=null==this.jsonAnchor?document.createElement("a"):this.jsonAnchor).download=this.modelTopologyFileName,o.href=a,[4,hp(function(){return o.dispatchEvent(new MouseEvent("click"))})];case 2:return i.sent(),null==t.weightData?[3,4]:((s=null==this.weightDataAnchor?document.createElement("a"):this.weightDataAnchor).download=this.weightDataFileName,s.href=e,[4,hp(function(){return s.dispatchEvent(new MouseEvent("click"))})]);case 3:i.sent(),i.label=4;case 4:return[2,{modelArtifactsInfo:Pc(t)}]}})})},t.URL_SCHEME="downloads://",t}(),dp=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 i(this,function(r){return t=this.files[0],e=this.files.slice(1),[2,new Promise(function(r,i){var a=new FileReader;a.onload=function(a){var o=JSON.parse(a.target.result),s=o.modelTopology;if(null!=s){0===e.length&&r({modelTopology:s});var u=o.weightsManifest;if(null!=u){var l;try{l=n.checkManifestAndWeightFiles(u,e)}catch(t){return void i(t)}var c=[],p=[],h=[];u.forEach(function(t){t.paths.forEach(function(t){p.push(t),h.push(null)}),c.push.apply(c,t.weights)}),u.forEach(function(t){t.paths.forEach(function(t){var e=new FileReader;e.onload=function(e){var n=e.target.result,i=p.indexOf(t);h[i]=n,-1===h.indexOf(null)&&r({modelTopology:s,weightSpecs:c,weightData:Mc(h)})},e.onerror=function(e){return i("Failed to weights data from file of path '"+t+"'.")},e.readAsArrayBuffer(l[t])})})}else i(new Error("weightManifest field is missing from file "+t.name))}else i(new Error("modelTopology field is missing from file "+t.name))},a.onerror=function(e){return i("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 Lc(t.name)}),i={},a=0,o=t;a<o.length;a++)o[a].paths.forEach(function(t){var a=Lc(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.");i[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 i},t}();function mp(t,e,n,r){!function(t){p(null!=t&&Array.isArray(t)&&t.length>0,function(){return"promises must be a none empty array"})}(t),function(t,e){p(t>=0&&t<=1,function(){return"Progress fraction must be in range [0, 1], but got startFraction "+t}),p(e>=0&&e<=1,function(){return"Progress fraction must be in range [0, 1], but got endFraction "+e}),p(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 i=0;return Promise.all(t.map(function(a){return a.then(function(a){var o=n+ ++i/t.length*(r-n);return e(o),a}),a}))}function gp(t,e){return r(this,void 0,void 0,function(){var n,r,a,s,u,l,c,p,h;return i(this,function(i){switch(i.label){case 0:return null==e&&(e={}),n=null==e.fetchFunc?o().platform.fetch:e.fetchFunc,r=t.map(function(t){return n(t,e.requestInit,{isBinary:!0})}),a=0,s=.5,null!=e.onProgress?[3,2]:[4,Promise.all(r)];case 1:return u=i.sent(),[3,4];case 2:return[4,mp(r,e.onProgress,a,s)];case 3:u=i.sent(),i.label=4;case 4:return l=u.map(function(t){return t.arrayBuffer()}),c=.5,p=1,null!=e.onProgress?[3,6]:[4,Promise.all(l)];case 5:return h=i.sent(),[3,8];case 6:return[4,mp(l,e.onProgress,c,p)];case 7:h=i.sent(),i.label=8;case 8:return[2,h]}})})}function vp(t){var e=this;return function(n,a,o){return void 0===a&&(a=""),r(e,void 0,void 0,function(){var e,r,s,u,l,c,p,h,f,d;return i(this,function(i){switch(i.label){case 0:if(e=n.map(function(){return!1}),r={},s=null!=o?o.map(function(){return!1}):[],u=[],n.forEach(function(t,n){var i=0;t.weights.forEach(function(t){var a="quantization"in t?t.quantization.dtype:t.dtype,l=Dc[a]*m(t.shape),c=function(){e[n]=!0,null==r[n]&&(r[n]=[]),r[n].push({manifestEntry:t,groupOffset:i,sizeBytes:l})};null!=o?o.forEach(function(e,n){e===t.name&&(c(),s[n]=!0)}):c(),u.push(t.name),i+=l})}),!s.every(function(t){return t}))throw l=o.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},[]),p=[],c.forEach(function(t){n[t].paths.forEach(function(t){var e=a+(a.endsWith("/")?"":"/")+t;p.push(e)})}),[4,t(p)];case 1:return h=i.sent(),f={},d=0,c.forEach(function(t){for(var e=n[t].paths.length,i=0,a=0;a<e;a++)i+=h[d+a].byteLength;for(var o=new ArrayBuffer(i),s=new Uint8Array(o),u=0,l=0;l<e;l++){var c=new Uint8Array(h[d+l]);s.set(c,u),u+=c.byteLength}r[t].forEach(function(t){var e=_c(o.slice(t.groupOffset,t.groupOffset+t.sizeBytes),[t.manifestEntry]);for(var n in e)f[n]=e[n]}),d+=e}),[2,f]}})})}}Bc.registerSaveRouter(function(t){return o().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(fp.URL_SCHEME)?(void 0===(e=t.slice(fp.URL_SCHEME.length))&&(e="model"),new fp(e)):null;var e});var yp=function(){function t(t,e){if(this.DEFAULT_METHOD="POST",null==e&&(e={}),this.weightPathPrefix=e.weightPathPrefix,this.onProgress=e.onProgress,null!=e.fetchFunc?(p("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=o().platform.fetch,p(null!=t&&t.length>0,function(){return"URL path for http must not be null, undefined or empty."}),Array.isArray(t)&&p(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 i(this,function(i){switch(i.label){case 0:if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");return(e=Object.assign({method:this.DEFAULT_METHOD},this.requestInit)).body=new FormData,n=[{paths:["./model.weights.bin"],weights:t.weightSpecs}],r={modelTopology:t.modelTopology,format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy,userDefinedMetadata:t.userDefinedMetadata,weightsManifest:n},e.body.append("model.json",new Blob([JSON.stringify(r)],{type:"application/json"}),"model.json"),null!=t.weightData&&e.body.append("model.weights.bin",new Blob([t.weightData],{type:"application/octet-stream"}),"model.weights.bin"),[4,this.fetch(this.path,e)];case 1:if((a=i.sent()).ok)return[2,{modelArtifactsInfo:Pc(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,o,s,u;return i(this,function(i){switch(i.label){case 0:return[4,this.fetch(this.path,this.requestInit)];case 1:if(!(t=i.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.");i.label=2;case 2:return i.trys.push([2,4,,5]),[4,t.json()];case 3:return e=i.sent(),[3,5];case 4:throw i.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=i.sent(),o=u[0],s=u[1],i.label=7;case 7:return[2,{modelTopology:r,weightSpecs:o,weightData:s}]}})})},t.prototype.loadWeights=function(t){return r(this,void 0,void 0,function(){var e,n,r,a,o,s,u,l,c,p,h;return i(this,function(i){switch(i.label){case 0:for(e=Array.isArray(this.path)?this.path[1]:this.path,n=function(t){var e=t.lastIndexOf("/"),n=t.lastIndexOf("?");return[t.substring(0,e)+"/",n>e?t.substring(n):""]}(e),r=n[0],a=n[1],o=this.weightPathPrefix||r,s=[],u=0,l=t;u<l.length;u++)c=l[u],s.push.apply(s,c.weights);return p=[],t.forEach(function(t){t.paths.forEach(function(t){p.push(o+t+a)})}),[4,gp(p,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress})];case 1:return h=i.sent(),[2,[s,Mc(h)]]}})})},t.URL_SCHEME_REGEX=/^https?:\/\//,t}();function bp(t){return null!=t.match(yp.URL_SCHEME_REGEX)}var xp=function(t,e){return"undefined"==typeof fetch?null:(Array.isArray(t)?t.every(function(t){return bp(t)}):bp(t))?wp(t,{onProgress:e}):null};function wp(t,e){return new yp(t,e)}Bc.registerSaveRouter(xp),Bc.registerLoadRouter(xp);var Cp=function(){function t(t){this.modelArtifacts=t}return t.prototype.load=function(){return r(this,void 0,void 0,function(){return i(this,function(t){return[2,this.modelArtifacts]})})},t}(),Np=function(){function t(t){this.saveHandler=t}return t.prototype.save=function(t){return r(this,void 0,void 0,function(){return i(this,function(e){return[2,this.saveHandler(t)]})})},t}(),Ep=Object.freeze({browserFiles:function(t){return new dp(t)},browserHTTPRequest:function(t,e){return wp(t,e)},concatenateArrayBuffers:Mc,decodeWeights:_c,encodeWeights:function(t,e){return r(this,void 0,void 0,function(){var n,a,o,s,u,l=this;return i(this,function(c){switch(c.label){case 0:for(n=[],a=[],o=Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t),s=function(s){var u=o[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 p={name:u,shape:c.shape,dtype:c.dtype};if("string"===c.dtype){var h=new Promise(function(t){return r(l,void 0,void 0,function(){var e,n,r,a,o,s,u;return i(this,function(i){switch(i.label){case 0:return[4,c.bytes()];case 1:for(e=i.sent(),n=e.reduce(function(t,e){return t+e.length},0)+Oc*e.length,r=new Uint8Array(n),a=0,o=0;o<e.length;o++)s=e[o],u=new Uint8Array(new Uint32Array([s.length]).buffer),r.set(u,a),a+=Oc,r.set(s,a),a+=s.length;return t(r),[2]}})})});a.push(h)}else a.push(c.data());null!=e&&(p.group=e),n.push(p)},u=0;u<o.length;++u)s(u);return[4,Promise.all(a)];case 1:return[2,{data:function(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),i=0;return n.forEach(function(t){r.set(new Uint8Array(t.buffer),i),i+=t.byteLength}),r.buffer}(c.sent()),specs:n}]}})})},fromMemory:function(t,e,n,r){return 1===arguments.length?null!=t.modelTopology||null!=t.weightSpecs?new Cp(t):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new Cp({modelTopology:t})):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new Cp({modelTopology:t,weightSpecs:e,weightData:n,trainingConfig:r}))},getLoadHandlers:function(t,e){return Bc.getLoadHandlers(t,e)},getModelArtifactsInfoForJSON:Pc,getSaveHandlers:function(t){return Bc.getSaveHandlers(t)},http:wp,isHTTPScheme:bp,loadWeights:function(t,e,n,a){return void 0===e&&(e=""),r(this,void 0,void 0,function(){return i(this,function(r){return[2,vp(function(t){return gp(t,{requestInit:a})})(t,e,n)]})})},registerLoadRouter:function(t){return Bc.registerLoadRouter(t)},registerSaveRouter:function(t){return Bc.registerSaveRouter(t)},weightsLoaderFactory:vp,withSaveHandler:function(t){return new Np(t)},copyModel:function(t,e){return r(this,void 0,void 0,function(){return i(this,function(n){return[2,jc(t,e,!1)]})})},listModels:function(){return r(this,void 0,void 0,function(){var t,e,n,r,a,o,s;return i(this,function(i){switch(i.label){case 0:t=Vc.getSchemes(),e={},n=0,r=t,i.label=1;case 1:return n<r.length?(a=r[n],[4,Vc.getManager(a).listModels()]):[3,4];case 2:for(s in o=i.sent())e[a+Wc+s]=o[s];i.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 i(this,function(n){return[2,jc(t,e,!0)]})})},removeModel:function(t){return r(this,void 0,void 0,function(){var e;return i(this,function(n){return e=Uc(t),[2,Vc.getManager(e.scheme).removeModel(e.path)]})})}}),Sp=Ze({confusionMatrix_:function(t,e,n){var r=We(t,"labels","confusionMatrix"),i=We(e,"predictions","confusionMatrix");p(null==n||n>0&&Number.isInteger(n),function(){return"If provided, numClasses must be a positive integer, but got "+n}),p(1===r.rank,function(){return"Expected the rank of labels to be 1, but got "+r.rank}),p(1===i.rank,function(){return"Expected the rank of predictions to be 1, but got "+i.rank}),p(r.shape[0]===i.shape[0],function(){return"Mismatch in the number of examples: "+r.shape[0]+" vs. "+i.shape[0]+". Labels and predictions should have the same number of elements."}),p(n>0&&Number.isInteger(n),function(){return"numClasses is required to be a positive integer, but got "+n});var a=Kn(r.asType("int32"),n),o=Kn(i.asType("int32"),n);return a.transpose().matMul(o).asType("int32")}}),kp=Object.freeze({confusionMatrix:Sp}),Ip=Ze({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.");var n="undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement;if(n&&n&&t.readyState<2)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.");return Et.fromPixels(t,e)}}),Ap=Object.freeze({toPixels:function(t,e){return r(this,void 0,void 0,function(){var n,r,a,o,s,u,l,c,p,h,f,d,m,g,v,y,b,x,w,C,N,E,S;return i(this,function(i){switch(i.label){case 0:if(n=We(t,"img","toPixels"),t instanceof st||(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],o=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=i.sent(),l=n.min(),c=n.max(),[4,Promise.all([l.data(),c.data()])];case 2:if(p=i.sent(),h=p[0],f=p[1],d=h[0],m=f[0],l.dispose(),c.dispose(),"float32"===n.dtype){if(d<0||m>1)throw new Error("Tensor values for a float32 Tensor must be in the range [0 - 1] but got range ["+d+" - "+m+"].")}else{if("int32"!==n.dtype)throw new Error("Unsupported type for toPixels: "+n.dtype+". Please use float32 or int32 tensors.");if(d<0||m>255)throw new Error("Tensor values for a int32 Tensor must be in the range [0 - 255] but got range ["+d+" - "+m+"].")}for(g="float32"===n.dtype?255:1,v=new Uint8ClampedArray(o*a*4),y=0;y<a*o;++y)b=void 0,x=void 0,w=void 0,C=void 0,1===s?(b=u[y]*g,x=u[y]*g,w=u[y]*g,C=255):3===s?(b=u[3*y]*g,x=u[3*y+1]*g,w=u[3*y+2]*g,C=255):4===s&&(b=u[4*y]*g,x=u[4*y+1]*g,w=u[4*y+2]*g,C=u[4*y+3]*g),v[0+(N=4*y)]=Math.round(b),v[N+1]=Math.round(x),v[N+2]=Math.round(w),v[N+3]=Math.round(C);return null!=e&&(e.width=o,e.height=a,E=e.getContext("2d"),S=new ImageData(v,o,a),E.putImageData(S,0,0)),n!==t&&n.dispose(),[2,v]}})})},fromPixels:Ip}),Rp=function(){function t(){}return t.prototype.getClassName=function(){return this.constructor.className},t.fromConfig=function(t,e){return new t(e)},t}(),Tp=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 Dp(t){p(null!=t.className,function(){return"Class being registered does not have the static className property defined."}),p("string"==typeof t.className,function(){return"className is required to be a string, but got type "+typeof t.className}),p(t.className.length>0,function(){return"Class being registered has an empty-string as its className, which is disallowed."}),Tp.register(t)}var Op=Object.freeze({Serializable:Rp,SerializationMap:Tp,registerClass:Dp}),_p=.001,Fp=.1;function zp(){return 32===Et.backend.floatPrecision()?_p:Fp}function Mp(t,e,n){var r=!0;if((T(t)||T(e))&&(r=!1),T(t)&&T(e)&&(r=!0),r){var i=t.constructor.name,a=e.constructor.name;if(i!==a)throw new Error("Arrays are of different type. Actual: "+i+". Expected: "+a)}if(Array.isArray(t)&&Array.isArray(e)){var o=Pe(t),s=Pe(e);if(!g(o,s))throw new Error("Arrays have different shapes. Actual: ["+o+"]. Expected: ["+s+"]")}var u=T(t)?t:d(t),l=T(e)?e:d(e);if(u.length!==l.length)throw new Error("Arrays have different lengths actual: "+u.length+" vs expected: "+l.length+".\nActual: "+u+".\nExpected: "+l+".");for(var c=0;c<l.length;++c){var p=u[c],h=l[c];if(!n(p,h))throw new Error("Arrays differ: actual["+c+"] = "+p+", expected["+c+"] = "+h+".\nActual: "+u+".\nExpected: "+l+".")}}function Lp(t,e,n){return!isFinite(t)&&!isFinite(e)||!(isNaN(t)||isNaN(e)||Math.abs(t-e)>n)}var Pp=Object.freeze({TEST_EPSILON_FLOAT16:Fp,expectArraysClose:function(t,e,n){return null==n&&(n=zp()),Mp(t,e,function(t,e){return Lp(t,e,n)})},testEpsilon:zp,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 _(t)||_(t[0])||_(e)||_(e[0])?Mp(t,n,function(t,e){return t==e}):Mp(t,e,function(t,e){return Lp(t,e,0)})},expectNumbersClose:function(t,e,n){if(null==n&&(n=zp()),!Lp(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))}}),Bp=Object.freeze({gpgpu_util:Ma,webgl_util:Re,forceHalfFloat:function(){o().set("WEBGL_FORCE_F16_TEXTURES",!0)},MathBackendWebGL:Ho,setWebGLContext:Dt,GPGPUContext:La}),Wp=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.minimize=function(t,e,n){void 0===e&&(e=!1);var r=this.computeGradients(t,n),i=r.value,a=r.grads;if(null!=n){var o=n.map(function(t){return{name:t.name,tensor:a[t.name]}});this.applyGradients(o)}else this.applyGradients(a);return Fe(a),e?i:(i.dispose(),null)},Object.defineProperty(e.prototype,"iterations",{get:function(){return null==this.iterations_&&(this.iterations_=0),this.iterations_},enumerable:!0,configurable:!0}),e.prototype.incrementIterations=function(){this.iterations_=this.iterations+1},e.prototype.computeGradients=function(t,e){return kr(t,e)},e.prototype.dispose=function(){null!=this.iterations_&&Fe(this.iterations_)},e.prototype.saveIterations=function(){return r(this,void 0,void 0,function(){return i(this,function(t){return null==this.iterations_&&(this.iterations_=0),[2,{name:"iter",tensor:an(this.iterations_,"int32")}]})})},e.prototype.getWeights=function(){return r(this,void 0,void 0,function(){return i(this,function(t){throw new Error("getWeights() is not implemented for this optimizer yet.")})})},e.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){return i(this,function(t){throw new Error("setWeights() is not implemented for this optimizer class "+this.getClassName())})})},e.prototype.extractIterations=function(t){return r(this,void 0,void 0,function(){var e;return i(this,function(n){switch(n.label){case 0:return e=this,[4,t[0].tensor.data()];case 1:return e.iterations_=n.sent()[0],[2,t.slice(1)]}})})},e}(Rp);Object.defineProperty(Wp,Symbol.hasInstance,{value:function(t){return null!=t.minimize&&null!=t.computeGradients&&null!=t.applyGradients}});var Vp=function(t){function e(e,n,r){void 0===r&&(r=null);var i=t.call(this)||this;return i.learningRate=e,i.rho=n,i.epsilon=r,i.accumulatedGrads=[],i.accumulatedUpdates=[],null==r&&(i.epsilon=Et.backend.epsilon()),i}return n(e,t),e.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t)).forEach(function(n,r){var i=Et.registeredVariables[n];null==e.accumulatedGrads[r]&&(e.accumulatedGrads[r]={originalName:n+"/accum_grad",variable:_e(function(){return yn(i).variable(!1)})}),null==e.accumulatedUpdates[r]&&(e.accumulatedUpdates[r]={originalName:n+"/accum_var",variable:_e(function(){return yn(i).variable(!1)})});var a=Array.isArray(t)?t[r].tensor:t[n];if(null!=a){var o=e.accumulatedGrads[r].variable,s=e.accumulatedUpdates[r].variable;_e(function(){var t=o.mul(e.rho).add(a.square().mul(1-e.rho)),n=s.add(e.epsilon).sqrt().div(o.add(e.epsilon).sqrt()).mul(a),r=s.mul(e.rho).add(n.square().mul(1-e.rho));o.assign(t),s.assign(r);var u=n.mul(-e.learningRate).add(i);i.assign(u)})}}),this.incrementIterations()},e.prototype.dispose=function(){null!=this.accumulatedUpdates&&(Fe(this.accumulatedGrads.map(function(t){return t.variable})),Fe(this.accumulatedUpdates.map(function(t){return t.variable})))},e.prototype.getWeights=function(){return r(this,void 0,void 0,function(){var t;return i(this,function(e){switch(e.label){case 0:return t=this.accumulatedGrads.concat(this.accumulatedUpdates),[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(t.map(function(t){return{name:t.originalName,tensor:t.variable}}))]}})})},e.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){var e;return i(this,function(n){switch(n.label){case 0:return[4,this.extractIterations(t)];case 1:return t=n.sent(),e=t.length/2,this.accumulatedGrads=t.slice(0,e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),this.accumulatedUpdates=t.slice(e,2*e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),[2]}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}},e.fromConfig=function(t,e){return new t(e.learningRate,e.rho,e.epsilon)},e.className="Adadelta",e}(Wp);Dp(Vp);var Up=function(t){function e(e,n){void 0===n&&(n=.1);var r=t.call(this)||this;return r.learningRate=e,r.initialAccumulatorValue=n,r.accumulatedGrads=[],r}return n(e,t),e.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t)).forEach(function(n,r){var i=Et.registeredVariables[n];null==e.accumulatedGrads[r]&&(e.accumulatedGrads[r]={originalName:n+"/accumulator",variable:_e(function(){return dn(i.shape,e.initialAccumulatorValue).variable(!1)})});var a=Array.isArray(t)?t[r].tensor:t[n];if(null!=a){var o=e.accumulatedGrads[r].variable;_e(function(){var t=o.add(a.square());o.assign(t);var n=a.div(t.add(Et.backend.epsilon()).sqrt()).mul(-e.learningRate).add(i);i.assign(n)})}}),this.incrementIterations()},e.prototype.dispose=function(){null!=this.accumulatedGrads&&Fe(this.accumulatedGrads.map(function(t){return t.variable}))},e.prototype.getWeights=function(){return r(this,void 0,void 0,function(){return i(this,function(t){switch(t.label){case 0:return[4,this.saveIterations()];case 1:return[2,[t.sent()].concat(this.accumulatedGrads.map(function(t){return{name:t.originalName,tensor:t.variable}}))]}})})},e.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){return i(this,function(e){switch(e.label){case 0:return[4,this.extractIterations(t)];case 1:return t=e.sent(),this.accumulatedGrads=t.map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),[2]}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}},e.fromConfig=function(t,e){return new t(e.learningRate,e.initialAccumulatorValue)},e.className="Adagrad",e}(Wp);Dp(Up);var jp=function(t){function e(e,n,r,i){void 0===i&&(i=null);var a=t.call(this)||this;return a.learningRate=e,a.beta1=n,a.beta2=r,a.epsilon=i,a.accumulatedFirstMoment=[],a.accumulatedSecondMoment=[],_e(function(){a.accBeta1=an(n).variable(),a.accBeta2=an(r).variable()}),null==i&&(a.epsilon=Et.backend.epsilon()),a}return n(e,t),e.prototype.applyGradients=function(t){var e=this,n=Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t);_e(function(){var r=fu(1,e.accBeta1),i=fu(1,e.accBeta2);n.forEach(function(n,a){var o=Et.registeredVariables[n];null==e.accumulatedFirstMoment[a]&&(e.accumulatedFirstMoment[a]={originalName:n+"/m",variable:_e(function(){return yn(o).variable(!1)})}),null==e.accumulatedSecondMoment[a]&&(e.accumulatedSecondMoment[a]={originalName:n+"/v",variable:_e(function(){return yn(o).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)),p=l.mul(e.beta2).add(s.square().mul(1-e.beta2)),h=c.div(r),f=p.div(i);u.assign(c),l.assign(p);var d=h.div(f.sqrt().add(e.epsilon)).mul(-e.learningRate).add(o);o.assign(d)}}),e.accBeta1.assign(e.accBeta1.mul(e.beta1)),e.accBeta2.assign(e.accBeta2.mul(e.beta2))}),this.incrementIterations()},e.prototype.dispose=function(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&Fe(this.accumulatedFirstMoment.map(function(t){return t.variable})),null!=this.accumulatedSecondMoment&&Fe(this.accumulatedSecondMoment.map(function(t){return t.variable}))},e.prototype.getWeights=function(){return r(this,void 0,void 0,function(){var t;return i(this,function(e){switch(e.label){case 0:return t=this.accumulatedFirstMoment.concat(this.accumulatedSecondMoment),[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(t.map(function(t){return{name:t.originalName,tensor:t.variable}}))]}})})},e.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){var e,n=this;return i(this,function(r){switch(r.label){case 0:return[4,this.extractIterations(t)];case 1:return t=r.sent(),_e(function(){n.accBeta1.assign(lu(n.beta1,n.iterations_+1)),n.accBeta2.assign(lu(n.beta2,n.iterations_+1))}),e=t.length/2,this.accumulatedFirstMoment=t.slice(0,e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),this.accumulatedSecondMoment=t.slice(e,2*e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),[2]}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}},e.fromConfig=function(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon)},e.className="Adam",e}(Wp);Dp(jp);var Gp=function(t){function e(e,n,r,i,a){void 0===i&&(i=null),void 0===a&&(a=0);var o=t.call(this)||this;return o.learningRate=e,o.beta1=n,o.beta2=r,o.epsilon=i,o.decay=a,o.accumulatedFirstMoment=[],o.accumulatedWeightedInfNorm=[],_e(function(){o.iteration=an(0).variable(),o.accBeta1=an(n).variable()}),null==i&&(o.epsilon=Et.backend.epsilon()),o}return n(e,t),e.prototype.applyGradients=function(t){var e=this,n=Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t);_e(function(){var r=fu(1,e.accBeta1),i=Zs(-e.learningRate,e.iteration.mul(e.decay).add(1));n.forEach(function(n,a){var o=Et.registeredVariables[n];null==e.accumulatedFirstMoment[a]&&(e.accumulatedFirstMoment[a]={originalName:n+"/m",variable:yn(o).variable(!1)}),null==e.accumulatedWeightedInfNorm[a]&&(e.accumulatedWeightedInfNorm[a]={originalName:n+"/v",variable:yn(o).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)),p=l.mul(e.beta2),h=s.abs(),f=p.maximum(h);u.assign(c),l.assign(f);var d=i.div(r).mul(c.div(f.add(e.epsilon))).add(o);o.assign(d)}}),e.iteration.assign(e.iteration.add(1)),e.accBeta1.assign(e.accBeta1.mul(e.beta1))}),this.incrementIterations()},e.prototype.dispose=function(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&Fe(this.accumulatedFirstMoment.map(function(t){return t.variable})),null!=this.accumulatedWeightedInfNorm&&Fe(this.accumulatedWeightedInfNorm.map(function(t){return t.variable}))},e.prototype.getWeights=function(){return r(this,void 0,void 0,function(){return i(this,function(t){throw new Error("getWeights() is not implemented for Adamax yet.")})})},e.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){return i(this,function(t){throw new Error("setWeights() is not implemented for Adamax yet.")})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}},e.fromConfig=function(t,e){return new t(e.learningRate,e.beta1,e.beta2,e.epsilon,e.decay)},e.className="Adamax",e}(Wp);Dp(Gp);var qp=function(t){function e(e){var n=t.call(this)||this;return n.learningRate=e,n.setLearningRate(e),n}return n(e,t),e.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t)).forEach(function(n,r){var i=Array.isArray(t)?t[r].tensor:t[n];if(null!=i){var a=Et.registeredVariables[n];_e(function(){var t=e.c.mul(i).add(a);a.assign(t)})}}),this.incrementIterations()},e.prototype.setLearningRate=function(t){this.learningRate=t,null!=this.c&&this.c.dispose(),this.c=ze(an(-t))},e.prototype.dispose=function(){this.c.dispose()},e.prototype.getWeights=function(){return r(this,void 0,void 0,function(){return i(this,function(t){switch(t.label){case 0:return[4,this.saveIterations()];case 1:return[2,[t.sent()]]}})})},e.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){return i(this,function(e){switch(e.label){case 0:return[4,this.extractIterations(t)];case 1:if(0!==(t=e.sent()).length)throw new Error("SGD optimizer does not have settable weights.");return[2]}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate}},e.fromConfig=function(t,e){return new t(e.learningRate)},e.className="SGD",e}(Wp);Dp(qp);var Hp=function(t){function e(e,n,r){void 0===r&&(r=!1);var i=t.call(this,e)||this;return i.learningRate=e,i.momentum=n,i.useNesterov=r,i.accumulations=[],i.m=an(i.momentum),i}return n(e,t),e.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t)).forEach(function(n,r){var i=Et.registeredVariables[n];null==e.accumulations[r]&&(e.accumulations[r]={originalName:n+"/momentum",variable:_e(function(){return yn(i).variable(!1)})});var a=e.accumulations[r].variable,o=Array.isArray(t)?t[r].tensor:t[n];null!=o&&_e(function(){var t,n=e.m.mul(a).add(o);t=e.useNesterov?e.c.mul(o.add(n.mul(e.m))).add(i):e.c.mul(n).add(i),a.assign(n),i.assign(t)})}),this.incrementIterations()},e.prototype.dispose=function(){this.m.dispose(),null!=this.accumulations&&Fe(this.accumulations.map(function(t){return t.variable}))},e.prototype.setMomentum=function(t){this.momentum=t},e.prototype.getWeights=function(){return r(this,void 0,void 0,function(){return i(this,function(t){switch(t.label){case 0:return[4,this.saveIterations()];case 1:return[2,[t.sent()].concat(this.accumulations.map(function(t){return{name:t.originalName,tensor:t.variable}}))]}})})},e.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){return i(this,function(e){switch(e.label){case 0:return[4,this.extractIterations(t)];case 1:return t=e.sent(),this.accumulations=t.map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),[2]}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}},e.fromConfig=function(t,e){return new t(e.learningRate,e.momentum,e.useNesterov)},e.className="Momentum",e}(qp);Dp(Hp);var Kp=function(t){function e(e,n,r,i,a){void 0===n&&(n=.9),void 0===r&&(r=0),void 0===i&&(i=null),void 0===a&&(a=!1);var o=t.call(this)||this;return o.learningRate=e,o.decay=n,o.momentum=r,o.epsilon=i,o.accumulatedMeanSquares=[],o.accumulatedMoments=[],o.accumulatedMeanGrads=[],o.centered=a,null==i&&(o.epsilon=Et.backend.epsilon()),o}return n(e,t),e.prototype.applyGradients=function(t){var e=this;(Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t)).forEach(function(n,r){var i=Et.registeredVariables[n];null==e.accumulatedMeanSquares[r]&&(e.accumulatedMeanSquares[r]={originalName:n+"/rms",variable:_e(function(){return yn(i).variable(!1)})}),null==e.accumulatedMoments[r]&&(e.accumulatedMoments[r]={originalName:n+"/momentum",variable:_e(function(){return yn(i).variable(!1)})}),null==e.accumulatedMeanGrads[r]&&e.centered&&(e.accumulatedMeanGrads[r]={originalName:n+"/mg",variable:_e(function(){return yn(i).variable(!1)})});var a=Array.isArray(t)?t[r].tensor:t[n];if(null!=a){var o=e.accumulatedMeanSquares[r].variable,s=e.accumulatedMoments[r].variable;_e(function(){var t=o.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()));o.assign(t),n.assign(u),s.assign(l);var c=i.sub(l);i.assign(c)}else{var p=o.mul(e.decay).add(a.square().mul(1-e.decay));l=s.mul(e.momentum).add(a.mul(e.learningRate).div(p.add(e.epsilon).sqrt())),o.assign(p),s.assign(l),c=i.sub(l),i.assign(c)}})}}),this.incrementIterations()},e.prototype.dispose=function(){null!=this.accumulatedMeanSquares&&Fe(this.accumulatedMeanSquares.map(function(t){return t.variable})),null!=this.accumulatedMeanGrads&&this.centered&&Fe(this.accumulatedMeanGrads.map(function(t){return t.variable})),null!=this.accumulatedMoments&&Fe(this.accumulatedMoments.map(function(t){return t.variable}))},e.prototype.getWeights=function(){return r(this,void 0,void 0,function(){var t;return i(this,function(e){switch(e.label){case 0:return t=this.accumulatedMeanSquares.concat(this.accumulatedMoments),this.centered&&t.push.apply(t,this.accumulatedMeanGrads),[4,this.saveIterations()];case 1:return[2,[e.sent()].concat(t.map(function(t){return{name:t.originalName,tensor:t.variable}}))]}})})},e.prototype.setWeights=function(t){return r(this,void 0,void 0,function(){var e;return i(this,function(n){switch(n.label){case 0:return[4,this.extractIterations(t)];case 1:return t=n.sent(),e=this.centered?t.length/3:t.length/2,this.accumulatedMeanSquares=t.slice(0,e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),this.accumulatedMoments=t.slice(e,2*e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}}),this.centered&&(this.accumulatedMeanGrads=t.slice(2*e,3*e).map(function(t){return{originalName:t.name,variable:t.tensor.variable(!1)}})),[2]}})})},e.prototype.getConfig=function(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}},e.fromConfig=function(t,e){return new t(e.learningRate,e.decay,e.momentum,e.epsilon,e.centered)},e.className="RMSProp",e}(Wp);Dp(Kp);var $p=function(){function t(){}return t.sgd=function(t){return new qp(t)},t.momentum=function(t,e,n){return void 0===n&&(n=!1),new Hp(t,e,n)},t.rmsprop=function(t,e,n,r,i){return void 0===e&&(e=.9),void 0===n&&(n=0),void 0===r&&(r=null),void 0===i&&(i=!1),new Kp(t,e,n,r,i)},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 jp(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 Vp(t,e,n)},t.adamax=function(t,e,n,r,i){return void 0===t&&(t=.002),void 0===e&&(e=.9),void 0===n&&(n=.999),void 0===r&&(r=null),void 0===i&&(i=0),new Gp(t,e,n,r,i)},t.adagrad=function(t,e){return void 0===e&&(e=.1),new Up(t,e)},t}(),Xp={sgd:$p.sgd,momentum:$p.momentum,adadelta:$p.adadelta,adagrad:$p.adagrad,rmsprop:$p.rmsprop,adamax:$p.adamax,adam:$p.adam},Yp="undefined"!=typeof requestAnimationFrame?requestAnimationFrame:"undefined"!=typeof setImmediate?setImmediate:function(t){return t()};function Jp(){return new Promise(function(t){return Yp(function(){return t()})})}at=Sc;var Zp=function(t,e){return(Zp=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,e)};function Qp(t,e){function n(){this.constructor=t}Zp(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}var th,eh=function(){return(eh=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var i in e=arguments[n])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)};function nh(t,e,n,r){return new(n||(n=Promise))(function(i,a){function o(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?i(t.value):new n(function(e){e(t.value)}).then(o,s)}u((r=r.apply(t,e||[])).next())})}function rh(t,e){var n,r,i,a,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[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(;o;)try{if(n=1,r&&(i=2&a[0]?r.return:a[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,a[1])).done)return i;switch(r=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,r=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!(i=(i=o.trys).length>0&&i[i.length-1])&&(6===a[0]||2===a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){o.label=a[1];break}if(6===a[0]&&o.label<i[1]){o.label=i[1],i=a;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(a);break}i[2]&&o.ops.pop(),o.trys.pop();continue}a=e.call(t,o)}catch(t){a=[6,t],r=0}finally{n=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,s])}}}function ih(){return null==th&&(th=Me().epsilon()),th}var ah=function(t){function e(n){var r=t.call(this,n)||this;return Object.setPrototypeOf(r,e.prototype),r}return Qp(e,t),e}(Error),oh=function(t){function e(n){var r=t.call(this,n)||this;return Object.setPrototypeOf(r,e.prototype),r}return Qp(e,t),e}(Error),sh=function(t){function e(n){var r=t.call(this,n)||this;return Object.setPrototypeOf(r,e.prototype),r}return Qp(e,t),e}(Error),uh=function(t){function e(n){var r=t.call(this,n)||this;return Object.setPrototypeOf(r,e.prototype),r}return Qp(e,t),e}(Error),lh=function(t){function e(n){var r=t.call(this,n)||this;return Object.setPrototypeOf(r,e.prototype),r}return Qp(e,t),e}(Error);!function(t){function e(n){var r=t.call(this,n)||this;return Object.setPrototypeOf(r,e.prototype),r}Qp(e,t)}(Error);function ch(t,e){if(Array.isArray(t)){for(var n=[],r=0;r<e;r++)n=n.concat(t);return n}return(n=new Array(e)).fill(t),n}function ph(t,e){if(!t)throw new lh(e)}function hh(t,e){for(var n=0,r=0,i=t;r<i.length;r++)i[r]===e&&n++;return n}function fh(t){return 1===t.length?t[0]:t}function dh(t){return Array.isArray(t)?t:[t]}function mh(t){var e=t.replace(/(.)([A-Z][a-z0-9]+)/g,"$1_$2").replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();return"_"!==e[0]?e:"private"+e}function gh(t){return t.length<=1?t:-1===t.indexOf("_")?t:t.replace(/[_]+(\w|$)/g,function(t,e){return e.toUpperCase()})}var vh={};function yh(t){if(null===t||void 0===t)return null;var e={};return e.className=t.getClassName(),e.config=t.getConfig(),e}function bh(t,e,n,r,i){var a,o,s;if(void 0===e&&(e={}),void 0===n&&(n={}),void 0===r&&(r="object"),void 0===i&&(i=!1),"string"==typeof t){var u=t,l=void 0;if(u in n)l=n[u];else if(u in vh)l=vh[u];else if(null==(l=e[u]))throw new sh("Unknown "+r+": "+t+". This may be due to one of the following reasons:\n1. The "+r+" is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom "+r+" is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().");return l}var c=t;if(null==c.className||null==c.config)throw new sh(r+": Improper config format: "+JSON.stringify(c)+".\n'className' and 'config' must set.");var p=c.className,h=void 0,f=void 0;if(p in n?(h=(a=n[p])[0],f=a[1]):p in vh?(h=(o=vh.className)[0],f=o[1]):p in e&&(h=(s=e[p])[0],f=s[1]),null==h)throw new sh("Unknown "+r+": "+p+". This may be due to one of the following reasons:\n1. The "+r+" is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom "+r+" is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().");if(null!=f){for(var d={},m=0,g=Object.keys(vh);m<g.length;m++)d[C=g[m]]=vh[C];for(var v=0,y=Object.keys(n);v<y.length;v++)d[C=y[v]]=n[C];c.config.customObjects=d;for(var b=eh({},vh),x=0,w=Object.keys(n);x<w.length;x++){var C=w[x];vh[C]=n[C]}!function t(e){if(null!=e&&"object"==typeof e)if(Array.isArray(e))e.forEach(function(e){return t(e)});else for(var n=0,r=Object.keys(e);n<r.length;n++){var i=r[n],a=e[i];null!=a&&"object"==typeof a&&(Array.isArray(a)||"ndarray"!==a.type||"number"!=typeof a.value?t(a):e[i]=a.value)}}(c.config);var N=f(h,c.config,n,i);return vh=eh({},b),N}b=eh({},vh);for(var E=0,S=Object.keys(n);E<S.length;E++)C=S[E],vh[C]=n[C];return N=new h(c.config),vh=eh({},b),N}function xh(t,e){return-1*function(t,e){return t<e?-1:t>e?1:0}(t,e)}function wh(t){if(null==t)return t;for(var e=[],n=0,r=t;n<r.length;n++){var i=r[n];-1===e.indexOf(i)&&e.push(i)}return e}function Ch(t){if(null==t)throw new sh("Invalid value in obj: "+JSON.stringify(t));for(var e in t)if(t.hasOwnProperty(e))return!1;return!0}function Nh(t,e,n){if(null!=n&&t.indexOf(n)<0)throw new sh(n+" is not a valid "+e+". Valid values are "+t+" or null/undefined.")}function Eh(t,e,n,r){return void 0===n&&(n=0),void 0===r&&(r=1/0),ph(n>=0),ph(r>=n),Array.isArray(t)&&t.length>=n&&t.length<=r&&t.every(function(t){return typeof t===e})}function Sh(t,e){Array.isArray(t)?($.assert(t.length>0,function(){return e+" is unexpectedly an empty array."}),t.forEach(function(t,n){return Sh(t,"element "+(n+1)+" of "+e)})):$.assert(Number.isInteger(t)&&t>0,function(){return"Expected "+e+" to be a positive integer, but got "+function t(e){return null===e?"null":Array.isArray(e)?"["+e.map(function(e){return t(e)}).join(",")+"]":"string"==typeof e?'"'+e+'"':""+e}(t)+"."})}function kh(t){return"relu"===t?"relu":"linear"===t?"linear":"elu"===t?"elu":null}function Ih(t,e){return _e(function(){return Ns(Cl(uu(t,t),e,!0))})}var Ah=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Qp(e,t),e.prototype.getConfig=function(){return{}},e}(Op.Serializable),Rh=function(t){function e(e){var n=t.call(this)||this;return n.defaultMaxValue=2,n.defaultAxis=0,n.maxValue=null!=e.maxValue?e.maxValue:n.defaultMaxValue,n.axis=null!=e.axis?e.axis:n.defaultAxis,n}return Qp(e,t),e.prototype.apply=function(t){var e=this;return _e(function(){var n=Ih(t,e.axis),r=es(n,0,e.maxValue);return su(t,Zs(r,$s(ih(),n)))})},e.prototype.getConfig=function(){return{maxValue:this.maxValue,axis:this.axis}},e.className="MaxNorm",e}(Ah);Op.registerClass(Rh);var Th=function(t){function e(e){var n=t.call(this)||this;return n.defaultAxis=0,n.axis=null!=e.axis?e.axis:n.defaultAxis,n}return Qp(e,t),e.prototype.apply=function(t){var e=this;return _e(function(){return Zs(t,$s(ih(),Ih(t,e.axis)))})},e.prototype.getConfig=function(){return{axis:this.axis}},e.className="UnitNorm",e}(Ah);Op.registerClass(Th);var Dh=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Qp(e,t),e.prototype.apply=function(t){return Il(t)},e.className="NonNeg",e}(Ah);Op.registerClass(Dh);var Oh=function(t){function e(e){var n=t.call(this)||this;return n.defaultMinValue=0,n.defaultMaxValue=1,n.defaultRate=1,n.defaultAxis=0,n.minValue=null!=e.minValue?e.minValue:n.defaultMinValue,n.maxValue=null!=e.maxValue?e.maxValue:n.defaultMaxValue,n.rate=null!=e.rate?e.rate:n.defaultRate,n.axis=null!=e.axis?e.axis:n.defaultAxis,n}return Qp(e,t),e.prototype.apply=function(t){var e=this;return _e(function(){var n=Ih(t,e.axis),r=$s(su(e.rate,es(n,e.minValue,e.maxValue)),su(1-e.rate,n));return su(t,Zs(r,$s(ih(),n)))})},e.prototype.getConfig=function(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}},e.className="MinMaxNorm",e}(Ah);Op.registerClass(Oh);var _h={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function Fh(t){return yh(t)}function zh(t,e){return void 0===e&&(e={}),bh(t,Op.SerializationMap.getMap().classNameMap,e,"constraint")}function Mh(t){return null==t?null:"string"==typeof t?zh({className:t in _h?_h[t]:t,config:{}}):t instanceof Ah?t:zh(t)}var Lh=Object.freeze({maxNorm:function(t){return new Rh(t)},unitNorm:function(t){return new Th(t)},nonNeg:function(){return new Dh},minMaxNorm:function(t){return new Oh(t)}}),Ph=["channelsFirst","channelsLast"],Bh=["valid","same","causal"],Wh=["max","avg"],Vh=["sum","mul","concat","ave"],Uh=new Map;function jh(t){Nh(Ph,"DataFormat",t)}function Gh(t){Nh(Bh,"PaddingMode",t)}function qh(t){Nh(Wh,"PoolMode",t)}var Hh=[],Kh="/";function $h(t,e){Hh.push(t);try{var n=e();return Hh.pop(),n}catch(t){throw Hh.pop(),t}}function Xh(t){if(!Zh(t))throw new Error("Not a valid tensor name: '"+t+"'");return(0===Hh.length?"":Hh.join(Kh)+Kh)+t}function Yh(t){if(!Zh(t))throw new Error("Not a valid tensor name: '"+t+"'");Uh.has(t)||Uh.set(t,0);var e=Uh.get(t);if(Uh.set(t,Uh.get(t)+1),e>0){var n=t+"_"+e;return Uh.set(n,1),n}return t}var Jh=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function Zh(t){return!!t.match(Jh)}function Qh(t){return t===parseInt(t.toString(),10)}function tf(t,e,n){null==e&&(e=0),null==n&&(n=t.length);for(var r=1,i=e;i<n;++i)r*=t[i];return r}function ef(t){return on(t=Array.isArray(t)?new Float32Array(t):t)}function nf(t){return xl(ef(t)).dataSync()[0]}function rf(t){return yl(ef(t)).dataSync()[0]}function af(t,e){if(e<t)throw new sh("end ("+e+") < begin ("+t+") is forbidden.");for(var n=[],r=t;r<e;++r)n.push(r);return n}function of(t,e){return t.asType(e)}function sf(t,e){void 0===e&&(e=-1);var n=t.shape.slice();return e<0&&(e=n.length+e+1),n.splice(e,0,1),t.reshape(n)}function uf(t,e,n){return _e(function(){switch(t.rank){case 1:return ul(t,e,n);case 2:return ll(t,[e,0],[n,t.shape[1]]);case 3:return cl(t,[e,0,0],[n,t.shape[1],t.shape[2]]);case 4:return pl(t,[e,0,0,0],[n,t.shape[1],t.shape[2],t.shape[3]]);default:throw new sh("sliceAlongFirstAxis() received an unsupported tensor rank: "+t.rank)}})}function lf(t,e,n){return _e(function(){switch(t.rank){case 1:return ul(t,e,n);case 2:return ll(t,[0,e],[t.shape[0],n]);case 3:return cl(t,[0,0,e],[t.shape[0],t.shape[1],n]);case 4:return pl(t,[0,0,0,e],[t.shape[0],t.shape[1],t.shape[2],n]);default:throw new sh("sliceAlongLastAxis() received an unsupported tensor rank: "+t.rank)}})}function cf(t,e,n,r){return _e(function(){switch(t.rank){case 1:return ul(t,e,n);case 2:switch(r){case 1:return uf(t,e,n);case 2:return lf(t,e,n);default:throw new sh("The axis is not within the rank of the tensor "+r)}case 3:switch(r){case 1:return uf(t,e,n);case 2:return cl(t,[0,e,0],[t.shape[0],n,t.shape[2]]);case 3:return lf(t,e,n);default:throw new sh("The axis is not within the rank of the tensor "+r)}case 4:switch(r){case 1:return uf(t,e,n);case 2:return pl(t,[0,e,0,0],[t.shape[0],n,t.shape[2],t.shape[3]]);case 3:return pl(t,[0,0,e,0],[t.shape[0],t.shape[1],n,t.shape[3]]);case 4:return lf(t,e,n);default:throw new sh("The axis is not within the rank of the tensor "+r)}default:throw new sh("sliceAlongLastAxis() received an unsupported tensor rank: "+t.rank)}})}function pf(t,e){var n;return void 0===e&&(e=-1),e<0&&(e=0!==(n=t[0].rank)?n:0),e===t[0].rank&&(e=-1),bn(t,e)}function hf(t,e){switch(t.rank){case 1:return xn([t,e]);case 2:return wn([t,e],0);case 3:return Cn([t,e],0);case 4:return Nn([t,e],0);default:throw new sh("concatAlongFirstAxis() received an unsupported tensor rank: "+t.rank)}}function ff(t,e){if(Array.isArray(e)||(e=[e]),t.rank!==e.length)throw new sh("The length of input n ("+e.length+") does not match the number of dimensions in input x ("+t.rank+")");return sr(t,e)}function df(t,e,n,r,i){return void 0===e&&(e=0),void 0===n&&(n=1),tr(t,e,n,r,i)}function mf(t,e,n,r){if(t.rank<2||e.rank<2)throw new uh("dot requires both inputs to be rank >= 2 but got x shape = "+t.shape+" and y shape = "+e.shape);if(e.rank>=3&&t.shape.slice(-1)[0]!==(c=e.shape.slice(-2)[0]))throw new uh("If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = "+t.shape+" and y shape = "+e.shape);if(2===t.rank&&2===e.rank){var i=!1,a=!1;return Ec.matMul({a:t,b:e,transposeA:i,transposeB:a,bias:r?yf(t.rank,r,"channelsLast"):null,activation:n})}var o=t.shape.slice(),s=o.pop();t=t.reshape([-1,s]);var u=e.shape.slice(),l=u.pop(),c=u.pop(),p=u.concat([l]),h=Array.from({length:e.rank},function(t,n){return 0===n?e.rank-2:n<=e.rank-2?n-1:n});e=e.transpose(h).reshape([c,-1]);var f=o.concat(p);return i=!1,a=!1,Ec.matMul({a:t,b:e,transposeA:i,transposeB:a,bias:r?yf(t.rank,r,"channelsLast"):null,activation:n}).reshape(f)}function gf(t,e,n){return _e(function(){return e=Array.isArray(e)?on(e,"int32"):e.toInt(),Ru(t,e,n)})}function vf(t){return uu(t,t)}function yf(t,e,n){var r=e.shape;if(1!==e.rank&&e.rank!==t)throw new sh("Unexpected bias dimensions: "+e.rank+"; expected it to be 1 or "+t);if(5===t){if("channelsFirst"===n)return 1===r.length?e.reshape([1,r[0],1,1,1]):e.reshape([1,r[3],r[0],r[1],r[2]]);if("channelsLast"===n)return 1===r.length?e.reshape([1,1,1,1,r[0]]):e.reshape([1].concat(r))}else if(4===t){if("channelsFirst"===n)return 1===r.length?e.reshape([1,r[0],1,1]):e.reshape([1,r[2],r[0],r[1]]);if("channelsLast"===n)return 1===r.length?e.reshape([1,1,1,r[0]]):e.reshape([1].concat(r))}else if(3===t){if("channelsFirst"===n)return 1===r.length?e.reshape([1,r[0],1]):e.reshape([1,r[1],r[0]]);if("channelsLast"===n)return 1===r.length?e.reshape([1,1,r[0]]):e.reshape([1].concat(r))}else if(t<3)return e;throw new sh("Unsupported input rank by biasAdd: "+e.rank)}function bf(t,e,n){return _e(function(){return null==n&&(n="channelsLast"),jh(n),t.add(yf(t.rank,e,n))})}function xf(t,e,n,r){return _e(function(){return Kl(t,e,n,r)})}function wf(t,e,n){return void 0===n&&(n=!1),n?t():e()}var Cf=["fanIn","fanOut","fanAvg"],Nf=["normal","uniform","truncatedNormal"];var Ef=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Qp(e,t),e.prototype.fromConfigUsesCustomObjects=function(){return!1},e.prototype.getConfig=function(){return{}},e}(Op.Serializable),Sf=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Qp(e,t),e.prototype.apply=function(t,e){return fn(t,e)},e.className="Zeros",e}(Ef);Op.registerClass(Sf);var kf=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Qp(e,t),e.prototype.apply=function(t,e){return hn(t,e)},e.className="Ones",e}(Ef);Op.registerClass(kf);var If=function(t){function e(e){var n=t.call(this)||this;if("object"!=typeof e)throw new sh("Expected argument of type ConstantConfig but got "+e);if(void 0===e.value)throw new sh("config must have value set but got "+e);return n.value=e.value,n}return Qp(e,t),e.prototype.apply=function(t,e){var n=this;return _e(function(){return su(an(n.value),hn(t,e))})},e.prototype.getConfig=function(){return{value:this.value}},e.className="Constant",e}(Ef);Op.registerClass(If);var Af=function(t){function e(e){var n=t.call(this)||this;return n.DEFAULT_MINVAL=-.05,n.DEFAULT_MAXVAL=.05,n.minval=e.minval||n.DEFAULT_MINVAL,n.maxval=e.maxval||n.DEFAULT_MAXVAL,n.seed=e.seed,n}return Qp(e,t),e.prototype.apply=function(t,e){return nr(t,this.minval,this.maxval,e)},e.prototype.getConfig=function(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}},e.className="RandomUniform",e}(Ef);Op.registerClass(Af);var Rf=function(t){function e(e){var n=t.call(this)||this;return n.DEFAULT_MEAN=0,n.DEFAULT_STDDEV=.05,n.mean=e.mean||n.DEFAULT_MEAN,n.stddev=e.stddev||n.DEFAULT_STDDEV,n.seed=e.seed,n}return Qp(e,t),e.prototype.apply=function(t,e){if("float32"!==(e=e||"float32")&&"int32"!==e)throw new uh("randomNormal does not support dType "+e+".");return df(t,this.mean,this.stddev,e,this.seed)},e.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}},e.className="RandomNormal",e}(Ef);Op.registerClass(Rf);var Tf=function(t){function e(e){var n=t.call(this)||this;return n.DEFAULT_MEAN=0,n.DEFAULT_STDDEV=.05,n.mean=e.mean||n.DEFAULT_MEAN,n.stddev=e.stddev||n.DEFAULT_STDDEV,n.seed=e.seed,n}return Qp(e,t),e.prototype.apply=function(t,e){if("float32"!==(e=e||"float32")&&"int32"!==e)throw new uh("truncatedNormal does not support dType "+e+".");return ur(t,this.mean,this.stddev,e,this.seed)},e.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}},e.className="TruncatedNormal",e}(Ef);Op.registerClass(Tf);var Df=function(t){function e(e){var n=t.call(this)||this;return n.gain=null!=e.gain?e.gain:1,n}return Qp(e,t),e.prototype.apply=function(t,e){var n=this;return _e(function(){if(2!==t.length||t[0]!==t[1])throw new sh("Identity matrix initializer can only be used for 2D square matrices.");return su(n.gain,qn(t[0]))})},e.prototype.getConfig=function(){return{gain:this.gain}},e.className="Identity",e}(Ef);Op.registerClass(Df);var Of=function(t){function e(e){var n=t.call(this)||this;if(e.scale<0)throw new sh("scale must be a positive float. Got: "+e.scale);return n.scale=null==e.scale?1:e.scale,n.mode=null==e.mode?"fanIn":e.mode,function(t){Nh(Cf,"FanMode",t)}(n.mode),n.distribution=null==e.distribution?"normal":e.distribution,function(t){Nh(Nf,"Distribution",t)}(n.distribution),n.seed=e.seed,n}return Qp(e,t),e.prototype.apply=function(t,e){var n=function(t,e){var n,r;if(void 0===e&&(e="channelsLast"),jh(e),2===t.length)n=t[0],r=t[1];else if(-1!==[3,4,5].indexOf(t.length))if("channelsFirst"===e){var i=tf(t,2);n=t[1]*i,r=t[0]*i}else"channelsLast"===e&&(i=tf(t,0,t.length-2),n=t[t.length-2]*i,r=t[t.length-1]*i);else{var a=tf(t);n=Math.sqrt(a),r=Math.sqrt(a)}return[n,r]}(t),r=n[0],i=n[1],a=this.scale;if("fanIn"===this.mode?a/=Math.max(1,r):"fanOut"===this.mode?a/=Math.max(1,i):a/=Math.max(1,(r+i)/2),"normal"===this.distribution){var o=Math.sqrt(a);if("float32"!==(e=e||"float32")&&"int32"!==e)throw new uh(this.getClassName()+" does not support dType "+e+".");return ur(t,0,o,e,this.seed)}var s=Math.sqrt(3*a);return nr(t,-s,s,e)},e.prototype.getConfig=function(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}},e.className="VarianceScaling",e}(Ef);Op.registerClass(Of);var _f=function(t){function e(e){return t.call(this,{scale:1,mode:"fanAvg",distribution:"uniform",seed:null==e?null:e.seed})||this}return Qp(e,t),e.prototype.getClassName=function(){return Of.className},e.className="GlorotUniform",e}(Of);Op.registerClass(_f);var Ff=function(t){function e(e){return t.call(this,{scale:1,mode:"fanAvg",distribution:"normal",seed:null==e?null:e.seed})||this}return Qp(e,t),e.prototype.getClassName=function(){return Of.className},e.className="GlorotNormal",e}(Of);Op.registerClass(Ff);var zf=function(t){function e(e){return t.call(this,{scale:2,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})||this}return Qp(e,t),e.prototype.getClassName=function(){return Of.className},e.className="HeNormal",e}(Of);Op.registerClass(zf);var Mf=function(t){function e(e){return t.call(this,{scale:2,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})||this}return Qp(e,t),e.prototype.getClassName=function(){return Of.className},e.className="HeUniform",e}(Of);Op.registerClass(Mf);var Lf=function(t){function e(e){return t.call(this,{scale:1,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})||this}return Qp(e,t),e.prototype.getClassName=function(){return Of.className},e.className="LeCunNormal",e}(Of);Op.registerClass(Lf);var Pf=function(t){function e(e){return t.call(this,{scale:1,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})||this}return Qp(e,t),e.prototype.getClassName=function(){return Of.className},e.className="LeCunNormal",e}(Of);Op.registerClass(Pf);var Bf=function(t){function e(e){var n=t.call(this)||this;if(n.DEFAULT_GAIN=1,n.gain=null==e.gain?n.DEFAULT_GAIN:e.gain,n.seed=e.seed,null!=n.seed)throw new uh("Random seed is not implemented for Orthogonal Initializer yet.");return n}return Qp(e,t),e.prototype.apply=function(t,e){var n=this;return _e(function(){if(2!==t.length)throw new uh("The Orthogonal Initializer does not support non-2D shapes yet.");t[0]*t[1]>2e3&&console.warn("Orthogonal initializer is being called on a matrix with more than 2000 ("+t[0]*t[1]+") elements: Slowness may result.");var e=df(t[0]>t[1]?[t[1],t[0]]:t,0,1,"float32"),r=dc.gramSchmidt(e);return t[0]>t[1]&&(r=r.transpose()),su(n.gain,r)})},e.prototype.getConfig=function(){return{gain:this.gain,seed:this.seed}},e.className="Orthogonal",e}(Ef);Op.registerClass(Bf);var Wf={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 Vf(t,e){return void 0===e&&(e={}),bh(t,Op.SerializationMap.getMap().classNameMap,e,"initializer")}function Uf(t){return yh(t)}function jf(t){if("string"==typeof t){var e=t in Wf?Wf[t]:t;if("GlorotNormal"===e)return new Ff;if("GlorotUniform"===e)return new _f;if("HeNormal"===e)return new zf;if("HeUniform"===e)return new Mf;if("LeCunNormal"===e)return new Lf;if("LeCunUniform"===e)return new Pf;var n={};return n.className=e,n.config={},Vf(n)}return t instanceof Ef?t:Vf(t)}var Gf=Object.freeze({zeros:function(){return new Sf},ones:function(){return new kf},constant:function(t){return new If(t)},randomUniform:function(t){return new Af(t)},randomNormal:function(t){return new Rf(t)},truncatedNormal:function(t){return new Tf(t)},identity:function(t){return new Df(t)},varianceScaling:function(t){return new Of(t)},glorotUniform:function(t){return new _f(t)},glorotNormal:function(t){return new Ff(t)},heNormal:function(t){return new zf(t)},heUniform:function(t){return new Mf(t)},leCunNormal:function(t){return new Lf(t)},leCunUniform:function(t){return new Pf(t)},orthogonal:function(t){return new Bf(t)}}),qf=0;function Hf(){return qf++}var Kf={};function $f(t){return void 0===t&&(t=""),t in Kf||(Kf[t]=0),Kf[t]+=1,t+Kf[t].toString()}function Xf(t){return Array.isArray(t)&&Array.isArray(t[0])}function Yf(t){return 0===t.length?[]:Array.isArray(t[0])?t:[t]}function Jf(t){var e;if(Array.isArray(t)){if(1!==t.length)throw new sh("Expected Tensor length to be 1; got "+t.length);e=t[0]}else e=t;return e}function Zf(t){if(Array.isArray(t)&&Array.isArray(t[0])){if(1===t.length)return(t=t)[0];throw new sh("Expected exactly 1 Shape; got "+t.length)}return t}function Qf(t){for(var e=0,n=0,r=t;n<r.length;n++){var i=r[n];0===i.shape.length?e+=1:e+=i.shape.reduce(function(t,e){return t*e})}return e}var td="Variable",ed=function(){function t(t,e,n,r,i){void 0===e&&(e="float32"),void 0===n&&(n=td),void 0===r&&(r=!0),void 0===i&&(i=null),this.dtype=null==e?"float32":e,this.shape=t.shape,this.id=Hf(),n=null==n?td:n,this.originalName=Xh(n),this.name=Yh(this.originalName),this.trainable_=r,this.constraint=i,this.val=ft(t,this.trainable_,this.name,this.dtype)}return t.prototype.read=function(){return this.assertNotDisposed(),this.val},t.prototype.write=function(t){return this.assertNotDisposed(),function(t,e){if(t.shape.toString()!==e.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(t.shape)+" vs. "+JSON.stringify(e.shape))}(this.val,t),this.val.id!==t.id&&(this.val.assign(t),null!=this.constraint&&this.val.assign(this.constraint.apply(this.val))),this},t.prototype.dispose=function(){this.assertNotDisposed(),this.val.dispose()},t.prototype.assertNotDisposed=function(){if(this.val.isDisposed)throw new Error("LayersVariable "+this.name+" is already disposed.")},Object.defineProperty(t.prototype,"trainable",{get:function(){return this.trainable_},set:function(t){this.trainable_=t,this.val.trainable=t},enumerable:!0,configurable:!0}),t}();function nd(t){return t.map(function(t){return t.read()})}function rd(t){t.forEach(function(t){t[0].write(t[1])})}var id=function(t){this.dtype=t.dtype,this.shape=t.shape,null!=t.shape?this.ndim=t.shape.length:this.ndim=t.ndim,this.maxNDim=t.maxNDim,this.minNDim=t.minNDim,this.axes=t.axes||{}},ad=function(t,e,n,r,i,a,o){this.dtype=t,this.shape=e,this.sourceLayer=n,this.inputs=r,this.callArgs=i,this.outputTensorIndex=o,this.id=Hf(),null!=a&&(this.originalName=Xh(a),this.name=Yh(this.originalName)),this.rank=e.length},od=0,sd=function(){function t(t,e){this.callArgs=e,this.id=od++,this.outboundLayer=t.outboundLayer,this.inboundLayers=t.inboundLayers,this.nodeIndices=t.nodeIndices,this.tensorIndices=t.tensorIndices,this.inputTensors=t.inputTensors,this.outputTensors=t.outputTensors,this.inputMasks=t.inputMasks,this.outputMasks=t.outputMasks,this.inputShapes=t.inputShapes,this.outputShapes=t.outputShapes;for(var n=0,r=t.inboundLayers;n<r.length;n++){var i=r[n];null!=i&&i.outboundNodes.push(this)}t.outboundLayer.inboundNodes.push(this)}return t.prototype.getConfig=function(){for(var t=[],e=0,n=this.inboundLayers;e<n.length;e++){var r=n[e];null!=r?t.push(r.name):t.push(null)}return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:t,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}},t}(),ud=0,ld=function(t){function e(e){var n=t.call(this)||this;n._callHook=null,n._addedWeightNames=[],n._stateful=!1,n.id=ud++,n.activityRegularizer=null,n.inputSpec=null,n.supportsMasking=!1,n._trainableWeights=[],n._nonTrainableWeights=[],n._losses=[],n._updates=[],n._built=!1,n.inboundNodes=[],n.outboundNodes=[];var r=e.name;if(!r){var i=n.getClassName();r=mh(i)+"_"+$f(i)}if(n.name=r,n.trainable_=null==e.trainable||e.trainable,null!=e.inputShape||null!=e.batchInputShape){var a=void 0;if(null!=e.batchInputShape)a=e.batchInputShape;else if(null!=e.inputShape){var o=null;null!=e.batchSize&&(o=e.batchSize),a=[o].concat(e.inputShape)}n.batchInputShape=a;var s=e.dtype;null==s&&(s=e.inputDType),null==s&&(s="float32"),n.dtype=s}return null!=e.weights?n.initialWeights=e.weights:n.initialWeights=null,n._refCount=null,n.fastWeightInitDuringBuild=!1,n}return Qp(e,t),e.nodeKey=function(t,e){return t.name+"_ib-"+e.toString()},e.prototype.getNodeAtIndex=function(t,e){if(0===this.inboundNodes.length)throw new oh("The layer has never been called and thus has no defined "+e+".");if(this.inboundNodes.length<=t)throw new sh("Asked to get "+e+" at node "+t+", but the layer has only "+this.inboundNodes.length+" inbound nodes.");return this.inboundNodes[t]},e.prototype.getInputAt=function(t){return fh(this.getNodeAtIndex(t,"input").inputTensors)},e.prototype.getOutputAt=function(t){return fh(this.getNodeAtIndex(t,"output").outputTensors)},Object.defineProperty(e.prototype,"input",{get:function(){if(this.inboundNodes.length>1)throw new ah("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 ah("Layer "+this.name+" is not connected, no input to return.");return fh(this.getNodeAtIndex(0,"input").inputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"output",{get:function(){if(0===this.inboundNodes.length)throw new ah("Layer "+this.name+" has no inbound nodes.");if(this.inboundNodes.length>1)throw new ah("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use `getOutputAt(nodeIndex)` instead.');return fh(this.getNodeAtIndex(0,"output").outputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"losses",{get:function(){return this._losses},enumerable:!0,configurable:!0}),e.prototype.calculateLosses=function(){return this.losses.map(function(t){return t()})},Object.defineProperty(e.prototype,"updates",{get:function(){return this._updates},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"built",{get:function(){return this._built},set:function(t){this._built=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"trainable",{get:function(){return this.trainable_},set:function(t){this._trainableWeights.forEach(function(e){return e.trainable=t}),this.trainable_=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"trainableWeights",{get:function(){return this.trainable_?this._trainableWeights.filter(function(t){return t.trainable}):[]},set:function(t){this._trainableWeights=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"nonTrainableWeights",{get:function(){return this.trainable?this._trainableWeights.filter(function(t){return!t.trainable}).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)},set:function(t){this._nonTrainableWeights=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"weights",{get:function(){return this.trainableWeights.concat(this.nonTrainableWeights)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"stateful",{get:function(){return this._stateful},enumerable:!0,configurable:!0}),e.prototype.resetStates=function(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")},e.prototype.assertInputCompatibility=function(t){if(t=dh(t),null!=this.inputSpec&&0!==this.inputSpec.length){var e=dh(this.inputSpec);if(t.length!==e.length)throw new sh("Layer "+this.name+" expects "+e.length+" inputs, but it received "+t.length+" input tensors. Input received: "+t);for(var n=0;n<t.length;n++){var r=t[n],i=e[n];if(null!=i){var a=r.rank;if(null!=i.ndim&&a!==i.ndim)throw new sh("Input "+n+" is incompatible with layer "+this.name+": expected ndim="+i.ndim+", found ndim="+a);if(null!=i.maxNDim&&a>i.maxNDim)throw new sh("Input "+n+" is incompatible with layer "+this.name+": expected max_ndim="+i.maxNDim+", found ndim="+a);if(null!=i.minNDim&&a<i.minNDim)throw new sh("Input "+n+" is incompatible with layer "+this.name+": expected min_ndim="+i.minNDim+", found ndim="+a+".");if(null!=i.dtype&&r.dtype!==i.dtype)throw new sh("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 u=Number(s),l=i.axes[s],c=u>=0?o[u]:o[o.length+u];if(null!=l&&-1===[l,null].indexOf(c))throw new sh("Input "+n+" is incompatible with layer "+this.name+": expected axis "+u+" of input shape to have value "+l+" but got shape "+o+".")}}if(null!=i.shape)for(var p=0;p<i.shape.length;++p){var h=i.shape[p],f=r.shape[p];if(null!=h&&null!=f&&h!==f)throw new sh("Input "+n+" is incompatible with layer "+this.name+": expected shape="+i.shape+", found shape="+r.shape+".")}}}}},e.prototype.call=function(t,e){return t},e.prototype.invokeCallHook=function(t,e){null!=this._callHook&&this._callHook(t,e)},e.prototype.setCallHook=function(t){this._callHook=t},e.prototype.clearCallHook=function(){this._callHook=null},e.prototype.apply=function(t,e){var n=this;e=e||{},this.assertNotDisposed();for(var r=dh(t),i=!0,a=0,o=r;a<o.length;a++)if(!(o[a]instanceof ad)){i=!1;break}for(var s=!0,u=0,l=r;u<l.length;u++)if(l[u]instanceof ad){s=!1;break}if(i===s)throw new sh("Arguments to apply() must be all SymbolicTensors or all Tensors");return $h(this.name,function(){if(!n.built){n.assertInputCompatibility(t);for(var i=[],a=0,o=dh(t);a<o.length;a++){var u=o[a];i.push(u.shape)}n.build(fh(i)),n.built=!0,n.initialWeights&&n.setWeights(n.initialWeights),null===n._refCount&&s&&(n._refCount=1)}if(n.assertInputCompatibility(t),s){for(var l=[],c=0,p=dh(m=n.call(t,e));c<p.length;c++){var h=p[c];-1!==r.indexOf(h)&&(h=h.clone()),l.push(h)}if(m=fh(l),null!=n.activityRegularizer)throw new uh("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return m}var f=function(t){for(var e=[],n=0,r=t=dh(t);n<r.length;n++){var i=r[n];e.push(i.shape)}return fh(e)}(t),d=n.computeOutputShape(f),m=void 0,g="float32";if(n.warnOnIncompatibleInputShape(Array.isArray(t)?f[0]:f),m=null!=d&&d.length>0&&Array.isArray(d[0])?d.map(function(r,i){return new ad(g,r,n,dh(t),e,n.name,i)}):new ad(g,d,n,dh(t),e,n.name),n.addInboundNode(t,m,null,null,f,d,e),n._refCount++,null!=n.activityRegularizer)throw new uh("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return m})},e.prototype.warnOnIncompatibleInputShape=function(t){if(null!=this.batchInputShape)if(t.length!==this.batchInputShape.length)console.warn("The rank of the input tensor provided (shape: "+JSON.stringify(t)+") does not match that of the batchInputShape ("+JSON.stringify(this.batchInputShape)+") of the layer "+this.name);else{var e=!1;this.batchInputShape.forEach(function(n,r){null!=n&&null!=t[r]&&t[r]!==n&&(e=!0)}),e&&console.warn("The shape of the input tensor ("+JSON.stringify(t)+") does not match the expectation of layer "+this.name+": "+JSON.stringify(this.batchInputShape))}},Object.defineProperty(e.prototype,"outputShape",{get:function(){if(null==this.inboundNodes||0===this.inboundNodes.length)throw new ah("The layer "+this.name+" has never been called and thus has no defined output shape.");for(var t=[],e=0,n=this.inboundNodes;e<n.length;e++){var r=n[e],i=JSON.stringify(r.outputShapes);-1===t.indexOf(i)&&t.push(i)}if(1===t.length){var a=this.inboundNodes[0].outputShapes;return Array.isArray(a)&&Array.isArray(a[0])&&1===a.length?a[0]:a}throw new ah("The layer "+this.name+' has multiple inbound nodes with different output shapes. Hence the notion of "outut shape" is ill-defined for the layer.')},enumerable:!0,configurable:!0}),e.prototype.countParams=function(){if(!this.built)throw new oh("You tried to call countParams() on "+this.name+", but the layer is not built yet. Build it first by calling build(batchInputShape).");return Qf(this.weights)},e.prototype.build=function(t){this.built=!0},e.prototype.getWeights=function(t){return void 0===t&&(t=!1),nd(t?this.trainableWeights:this.weights)},e.prototype.setWeights=function(t){var e=this;_e(function(){var n=e.weights;if(n.length!==t.length)throw new sh('You called setWeights(weights) on layer "'+e.name+'" with a weight list of length '+t.length+", but the layer was expecting "+n.length+" weights. Provided weights: "+t+"...");if(0!==n.length){for(var r=[],i=nd(n),a=0;a<i.length;++a){var o=i[a],s=n[a],u=t[a];if(!$.arraysEqual(o.shape,u.shape))throw new sh("Layer weight shape "+o.shape+" not compatible with provided weight shape "+u.shape);r.push([s,u])}rd(r)}})},e.prototype.addWeight=function(t,e,n,r,i,a,o){if(-1!==this._addedWeightNames.indexOf(t))throw new sh("Duplicate weight name "+t+" for layer "+this.name);this._addedWeightNames.push(t),null==n&&(n="float32"),this.fastWeightInitDuringBuild&&(r=jf("zeros"));var s=r.apply(e,n),u=new ed(s,n,t,a,o);return s.dispose(),null!=i&&this.addLoss(function(){return i.apply(u.read())}),null==a&&(a=!0),a?this._trainableWeights.push(u):this._nonTrainableWeights.push(u),u},e.prototype.setFastWeightInitDuringBuild=function(t){this.fastWeightInitDuringBuild=t},e.prototype.addLoss=function(t){var e;null==t||Array.isArray(t)&&0===t.length||(t=dh(t),void 0!==this._losses&&null!==this._losses&&(e=this.losses).push.apply(e,t))},e.prototype.computeOutputShape=function(t){return t},e.prototype.computeMask=function(t,e){var n=this;if(!this.supportsMasking){if(null!=e){if(!Array.isArray(e))throw new TypeError("Layer "+this.name+" does not support masking, but was passed an inputMask.");e.forEach(function(t){if(null!=t)throw new TypeError("Layer "+n.name+" does not support masking, but was passed an inputMask.")})}return null}return e},e.prototype.addInboundNode=function(t,e,n,r,i,a,o){void 0===o&&(o=null);var s=dh(t);e=dh(e),n=dh(n),r=dh(r),i=Yf(i),a=Yf(a);for(var u=[],l=[],c=[],p=0,h=s;p<h.length;p++){var f=h[p];u.push(f.sourceLayer),l.push(f.nodeIndex),c.push(f.tensorIndex)}new sd({outboundLayer:this,inboundLayers:u,nodeIndices:l,tensorIndices:c,inputTensors:s,outputTensors:e,inputMasks:n,outputMasks:r,inputShapes:i,outputShapes:a},o);for(var d=0;d<e.length;d++)e[d].sourceLayer=this,e[d].nodeIndex=this.inboundNodes.length-1,e[d].tensorIndex=d},e.prototype.getConfig=function(){var t={name:this.name,trainable:this.trainable};return null!=this.batchInputShape&&(t.batchInputShape=this.batchInputShape),null!=this.dtype&&(t.dtype=this.dtype),t},e.prototype.disposeWeights=function(){return this.weights.forEach(function(t){return t.dispose()}),this.weights.length},e.prototype.assertNotDisposed=function(){if(0===this._refCount)throw new Error("Layer '"+this.name+"' is already disposed.")},e.prototype.dispose=function(){if(!this.built)throw new Error("Cannot dispose Layer "+this.name+" because it has not been built yet.");if(null===this._refCount)throw new Error("Cannot dispose Layer "+this.name+" because it has not been used yet.");this.assertNotDisposed();var t=0;return 0==--this._refCount&&(t=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:t}},e}(Op.Serializable);var cd,pd=function(t){function e(e){var n=t.call(this,{dtype:e.dtype,name:null!=e.name?e.name:$f("input").toString()})||this;if(null==e.batchSize&&(e.batchSize=null),null==e.sparse&&(e.sparse=!1),n.trainable=!1,n.built=!0,n.sparse=e.sparse,null!=e.inputShape&&null!=e.batchInputShape)throw new sh("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");var r=e.batchInputShape;if(null==r){if(null==e.inputShape)throw new sh("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");r=[e.batchSize].concat(e.inputShape)}else if(null!=e.batchSize)throw new sh("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");var i=e.dtype||"float32";n.batchInputShape=r,n.dtype=i,n.inputSpec=[{shape:r}];var a=new ad(n.dtype,n.batchInputShape,n,[],{},n.name);return a.nodeIndex=0,a.tensorIndex=0,new sd({outboundLayer:n,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[a],outputTensors:[a],inputMasks:[null],outputMasks:[null],inputShapes:[r],outputShapes:[r]}),n}return Qp(e,t),e.prototype.apply=function(t,e){throw new sh("Cannot pass any input to an InputLayer's apply() method. InputLayer name: "+this.name)},e.prototype.dispose=function(){return{refCountAfterDispose:this._refCount,numDisposedVariables:0}},e.prototype.getConfig=function(){return{batchInputShape:this.batchInputShape,dtype:this.dtype,sparse:this.sparse,name:this.name}},e.className="InputLayer",e}(ld);function hd(t){if(null==t.batchShape&&null==t.shape)throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");if(null!=t.batchShape&&null!=t.shape)throw new sh("Please provide either a `shape` or `batchShape` argument to Input, but not both.");var e=t.batchShape;null!=t.shape&&null==e&&(e=[null].concat(t.shape));var n=t.dtype;return null==n&&(n="float32"),new pd({batchInputShape:e,name:t.name,dtype:n,sparse:t.sparse}).inboundNodes[0].outputTensors[0]}function fd(t){return nh(this,void 0,void 0,function(){var e,n,r,i,a,o,s,u;return rh(this,function(l){switch(l.label){case 0:if(null==t)return[2];for(i in e=[],n=[],r=[],t)"number"!=typeof(a=t[i])&&(o=a,e.push(o.data()),n.push(i),r.push(o));return e.length>0?[4,Promise.all(e)]:[3,2];case 1:for(s=l.sent(),u=0;u<s.length;++u)t[n[u]]=s[u][0];Fe(r),l.label=2;case 2:return[2]}})})}function dd(t){if(null!=t)for(var e in t){var n=t[e];"number"!=typeof n&&n.dispose()}}Op.registerClass(pd),function(t){t[t.SILENT=0]="SILENT",t[t.VERBOSE=1]="VERBOSE"}(cd||(cd={}));var md=125,gd=function(){function t(){this.validationData=null}return t.prototype.setParams=function(t){this.params=t},t.prototype.onEpochBegin=function(t,e){return nh(this,void 0,void 0,function(){return rh(this,function(t){return[2]})})},t.prototype.onEpochEnd=function(t,e){return nh(this,void 0,void 0,function(){return rh(this,function(t){return[2]})})},t.prototype.onBatchBegin=function(t,e){return nh(this,void 0,void 0,function(){return rh(this,function(t){return[2]})})},t.prototype.onBatchEnd=function(t,e){return nh(this,void 0,void 0,function(){return rh(this,function(t){return[2]})})},t.prototype.onTrainBegin=function(t){return nh(this,void 0,void 0,function(){return rh(this,function(t){return[2]})})},t.prototype.onTrainEnd=function(t){return nh(this,void 0,void 0,function(){return rh(this,function(t){return[2]})})},t.prototype.setModel=function(t){},t}(),vd=function(){function t(t,e){void 0===e&&(e=10),null==t&&(t=[]),this.callbacks=t,this.queueLength=e}return t.prototype.append=function(t){this.callbacks.push(t)},t.prototype.setParams=function(t){for(var e=0,n=this.callbacks;e<n.length;e++)n[e].setParams(t)},t.prototype.setModel=function(t){for(var e=0,n=this.callbacks;e<n.length;e++)n[e].setModel(t)},t.prototype.onEpochBegin=function(t,e){return nh(this,void 0,void 0,function(){var n,r;return rh(this,function(i){switch(i.label){case 0:null==e&&(e={}),n=0,r=this.callbacks,i.label=1;case 1:return n<r.length?[4,r[n].onEpochBegin(t,e)]:[3,4];case 2:i.sent(),i.label=3;case 3:return n++,[3,1];case 4:return[2]}})})},t.prototype.onEpochEnd=function(t,e){return nh(this,void 0,void 0,function(){var n,r;return rh(this,function(i){switch(i.label){case 0:null==e&&(e={}),n=0,r=this.callbacks,i.label=1;case 1:return n<r.length?[4,r[n].onEpochEnd(t,e)]:[3,4];case 2:i.sent(),i.label=3;case 3:return n++,[3,1];case 4:return[2]}})})},t.prototype.onBatchBegin=function(t,e){return nh(this,void 0,void 0,function(){var n,r;return rh(this,function(i){switch(i.label){case 0:null==e&&(e={}),n=0,r=this.callbacks,i.label=1;case 1:return n<r.length?[4,r[n].onBatchBegin(t,e)]:[3,4];case 2:i.sent(),i.label=3;case 3:return n++,[3,1];case 4:return[2]}})})},t.prototype.onBatchEnd=function(t,e){return nh(this,void 0,void 0,function(){var n,r;return rh(this,function(i){switch(i.label){case 0:null==e&&(e={}),n=0,r=this.callbacks,i.label=1;case 1:return n<r.length?[4,r[n].onBatchEnd(t,e)]:[3,4];case 2:i.sent(),i.label=3;case 3:return n++,[3,1];case 4:return[2]}})})},t.prototype.onTrainBegin=function(t){return nh(this,void 0,void 0,function(){var e,n;return rh(this,function(r){switch(r.label){case 0:null==t&&(t={}),e=0,n=this.callbacks,r.label=1;case 1:return e<n.length?[4,n[e].onTrainBegin(t)]:[3,4];case 2:r.sent(),r.label=3;case 3:return e++,[3,1];case 4:return[2]}})})},t.prototype.onTrainEnd=function(t){return nh(this,void 0,void 0,function(){var e,n;return rh(this,function(r){switch(r.label){case 0:null==t&&(t={}),e=0,n=this.callbacks,r.label=1;case 1:return e<n.length?[4,n[e].onTrainEnd(t)]:[3,4];case 2:r.sent(),r.label=3;case 3:return e++,[3,1];case 4:return[2]}})})},t}(),yd=function(t){function e(){return t.call(this)||this}return Qp(e,t),e.prototype.onEpochBegin=function(t){return nh(this,void 0,void 0,function(){return rh(this,function(t){return this.seen=0,this.totals={},[2]})})},e.prototype.onBatchEnd=function(t,e){return nh(this,void 0,void 0,function(){var t,n,r,i,a=this;return rh(this,function(o){for(i in null==e&&(e={}),t=null==e.size?0:e.size,this.seen+=t,n=function(n){var i=e[n];if("number"==typeof i)r.totals.hasOwnProperty(n)||(r.totals[n]=0),r.totals[n]=r.totals[n]+i*t;else{var o=void 0;n in r.totals?o=r.totals[n]:r.totals[n]=0;var s=_e(function(){return $s(a.totals[n],su(i,t))});r.totals[n]=s,null!=o&&o.dispose()}},r=this,e)n(i);return[2]})})},e.prototype.onEpochEnd=function(t,e){return nh(this,void 0,void 0,function(){var t,n,r,i,a,o=this;return rh(this,function(s){if(null!=e)for(t=function(t){if(null==n.totals[t])return"continue";"number"==typeof n.totals[t]?e[t]=n.totals[t]/n.seen:_e(function(){var n=su(Zs(1,o.seen),o.totals[t]);e[t]=n,o.totals[t].dispose(),ze(e[t])})},n=this,r=0,i=this.params.metrics;r<i.length;r++)a=i[r],t(a);return[2]})})},e}(gd),bd=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Qp(e,t),e.prototype.onTrainBegin=function(t){return nh(this,void 0,void 0,function(){return rh(this,function(t){return this.epoch=[],this.history={},[2]})})},e.prototype.onEpochEnd=function(t,e){return nh(this,void 0,void 0,function(){var n;return rh(this,function(r){for(n in null==e&&(e={}),this.epoch.push(t),e)null==this.history[n]&&(this.history[n]=[]),this.history[n].push(e[n]);return[2]})})},e.prototype.syncData=function(){return nh(this,void 0,void 0,function(){var t,e,n,r,i,a,o,s,u;return rh(this,function(l){switch(l.label){case 0:for(r in t=[],e=[],n=[],this.history)for(i=this.history[r],a=0;a<i.length;++a)"number"!=typeof i[a]&&(o=i[a],t.push(o.data()),e.push(r),n.push(a));return[4,Promise.all(t)];case 1:for(s=l.sent(),u=0;u<s.length;++u)this.history[e[u]][n[u]].dispose(),this.history[e[u]][n[u]]=s[u][0];return[2]}})})},e}(gd),xd=function(t){function e(e,n){var r=t.call(this)||this;if(r.currentEpoch=0,r.yieldEvery=n||"auto","auto"===r.yieldEvery&&(r.yieldEvery=md),"never"===r.yieldEvery&&null!=e.onYield)throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");return $.isNumber(r.yieldEvery)&&(r.maybeWait=function(t,e){var n,r=$.now();return function(){for(var i=[],a=0;a<arguments.length;a++)i[a]=arguments[a];var o=$.now();return o-r<e?n:(r=o,n=t.apply(void 0,i))}}(r.maybeWait.bind(r),r.yieldEvery)),r.trainBegin=e.onTrainBegin,r.trainEnd=e.onTrainEnd,r.epochBegin=e.onEpochBegin,r.epochEnd=e.onEpochEnd,r.batchBegin=e.onBatchBegin,r.batchEnd=e.onBatchEnd,r.yield=e.onYield,r}return Qp(e,t),e.prototype.maybeWait=function(t,e,n){return nh(this,void 0,void 0,function(){var r;return rh(this,function(i){switch(i.label){case 0:return r=[],null==this.yield?[3,2]:[4,fd(n)];case 1:i.sent(),r.push(this.yield(t,e,n)),i.label=2;case 2:return r.push(Jp()),[4,Promise.all(r)];case 3:return i.sent(),[2]}})})},e.prototype.onEpochBegin=function(t,e){return nh(this,void 0,void 0,function(){return rh(this,function(n){switch(n.label){case 0:return this.currentEpoch=t,null==this.epochBegin?[3,3]:[4,fd(e)];case 1:return n.sent(),[4,this.epochBegin(t,e)];case 2:n.sent(),n.label=3;case 3:return[2]}})})},e.prototype.onEpochEnd=function(t,e){return nh(this,void 0,void 0,function(){var n;return rh(this,function(r){switch(r.label){case 0:return n=[],null==this.epochEnd?[3,2]:[4,fd(e)];case 1:r.sent(),n.push(this.epochEnd(t,e)),r.label=2;case 2:return"epoch"===this.yieldEvery&&n.push(Jp()),[4,Promise.all(n)];case 3:return r.sent(),[2]}})})},e.prototype.onBatchBegin=function(t,e){return nh(this,void 0,void 0,function(){return rh(this,function(n){switch(n.label){case 0:return null==this.batchBegin?[3,3]:[4,fd(e)];case 1:return n.sent(),[4,this.batchBegin(t,e)];case 2:n.sent(),n.label=3;case 3:return[2]}})})},e.prototype.onBatchEnd=function(t,e){return nh(this,void 0,void 0,function(){var n;return rh(this,function(r){switch(r.label){case 0:return n=[],null==this.batchEnd?[3,2]:[4,fd(e)];case 1:r.sent(),n.push(this.batchEnd(t,e)),r.label=2;case 2:return"batch"===this.yieldEvery?n.push(Jp()):$.isNumber(this.yieldEvery)&&n.push(this.maybeWait(this.currentEpoch,t,e)),[4,Promise.all(n)];case 3:return r.sent(),[2]}})})},e.prototype.onTrainBegin=function(t){return nh(this,void 0,void 0,function(){return rh(this,function(e){switch(e.label){case 0:return null==this.trainBegin?[3,3]:[4,fd(t)];case 1:return e.sent(),[4,this.trainBegin(t)];case 2:e.sent(),e.label=3;case 3:return[2]}})})},e.prototype.onTrainEnd=function(t){return nh(this,void 0,void 0,function(){return rh(this,function(e){switch(e.label){case 0:return null==this.trainEnd?[3,3]:[4,fd(t)];case 1:return e.sent(),[4,this.trainEnd(t)];case 2:e.sent(),e.label=3;case 3:return[2]}})})},e}(gd);function wd(t,e){return null==t&&(t={}),t instanceof gd?[t]:Array.isArray(t)&&t[0]instanceof gd?t:dh(t).map(function(t){return new xd(t,e)})}var Cd=function(){function t(){}return t.registerCallbackConstructor=function(e,n){$.assert(e>=0&&Number.isInteger(e),function(){return"Verbosity level is expected to be an integer >= 0, but got "+e}),t.checkForDuplicate(n),null==t.constructors[e]&&(t.constructors[e]=[]),t.constructors[e].push(n)},t.checkForDuplicate=function(e){for(var n in t.constructors)t.constructors[+n].forEach(function(t){if(t===e)throw new sh("Duplicate callback constructor.")})},t.clear=function(){t.constructors={}},t.createCallbacks=function(e){var n=[];for(var r in t.constructors){var i=+r;e>=i&&n.push.apply(n,t.constructors[i])}return n.map(function(t){return new t})},t.constructors={},t}();function Nd(t,e,n,r,i,a,o,s,u){var l=new bd,c=[new yd].concat(Cd.createCallbacks(e));null!=t&&c.push.apply(c,t),c.push(l);var p=new vd(c);return p.setParams({epochs:n,initialEpoch:r,samples:i,steps:a,batchSize:o,verbose:e,doValidation:s,metrics:u}),{callbackList:p,history:l}}function Ed(t,e,n){return void 0===e&&(e={}),void 0===n&&(n=!1),bh(t,Op.SerializationMap.getMap().classNameMap,e,"layer",n)}function Sd(t,e){return _e(function(){"float32"!==t.dtype&&(t=t.asType("float32"));var n=Cl(vf(t),e,!0),r=dn(n.shape,ih()),i=Ns(eu(n,r));return Zs(t,i)})}function kd(t,e){return _e(function(){return bl(vf(fu(e,t)),-1)})}function Id(t,e){return _e(function(){return bl(Ko(fu(e,t)),-1)})}function Ad(t,e){return _e(function(){var n=fu(t,e),r=es(Ko(t),ih(),Number.MAX_VALUE),i=Ko(Zs(n,r));return su(100,bl(i,-1))})}function Rd(t,e,n){return void 0===n&&(n=!1),_e(function(){if(n)e=Rr(e);else{var r=Cl(e,e.shape.length-1,!0);e=Zs(e,r)}return e=es(e,ih(),1-ih()),ps(Cl(su(t.toFloat(),us(e)),e.shape.length-1))})}function Td(t,e){return _e(function(){var n=ss(function(t){var e=[tf(t.shape)];return t.reshape(e)}(t)).toInt(),r=(e=es(e,ih(),1-ih())).shape;return Rd(Kn(n,r[r.length-1]).reshape(r),e,!1)})}function Dd(t,e){return _e(function(){var n;return n=es(e,ih(),1-ih()),n=us(Zs(n,fu(1,n))),bl(function(t,e){if(!$.arraysEqual(t.shape,e.shape))throw new sh("logits and labels must have the same shape, but got shapes "+JSON.stringify(t.shape)+" and "+JSON.stringify(e.shape));return _e(function(){var n=e.relu(),r=e.abs().neg();return n.sub(e.mul(t)).add(r.exp().log1p())})}(t,n),-1)})}function Od(t,e){return _e(function(){var n=Sd(t,-1),r=Sd(e,-1),i=su(n,r);return ps(Cl(i,-1))})}var _d={meanSquaredError:kd,meanAbsoluteError:Id,meanAbsolutePercentageError:Ad,meanSquaredLogarithmicError:function(t,e){return _e(function(){var n=es(e,ih(),Number.MAX_VALUE),r=us($s(1,n)),i=es(t,ih(),Number.MAX_VALUE),a=us($s(1,i));return bl(vf(fu(r,a)),-1)})},squaredHinge:function(t,e){return _e(function(){var n=eu(0,fu(1,su(t,e)));return bl(vf(n),-1)})},hinge:function(t,e){return _e(function(){var n=eu(0,fu(1,su(t,e)));return bl(n,-1)})},categoricalHinge:function(t,e){return _e(function(){var n=Cl(su(t,e),-1),r=yl(su(fu(1,t),e),-1);return eu(0,$s(1,fu(r,n)))})},logcosh:function(t,e){return _e(function(){var n=Math.log(2),r=fu(e,t),i=fu($s(r,Cs(su(-2,r))),n);return bl(i,-1)})},categoricalCrossentropy:Rd,sparseCategoricalCrossentropy:Td,binaryCrossentropy:Dd,kullbackLeiblerDivergence:function(t,e){return _e(function(){var n=es(t,ih(),1),r=es(e,ih(),1);return Cl(su(t,us(Zs(n,r))),-1)})},poisson:function(t,e){return _e(function(){var n=us($s(ih(),e));return bl(fu(e,su(t,n)),-1)})},cosineProximity:Od};function Fd(t){if("string"==typeof t){if(t in _d)return _d[t];var e="Unknown loss "+t;throw t.toLowerCase().includes("softmaxcrossentropy")&&(e="Unknown loss "+t+'. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy'),new sh(e)}return t}function zd(t,e){return _e(function(){var n=su(.5,vn(e)),r=of(vu(e,n),t.dtype);return bl(mu(t,r),-1)})}function Md(t,e){return _e(function(){return of(mu(ml(t,-1),ml(e,-1)),"float32")})}function Ld(t,e){return _e(function(){return Us(t.equal(1),e.equal(1)).sum().cast("float32")})}function Pd(t,e){return _e(function(){var n=Ld(t,e),r=function(t,e){return _e(function(){return Us(t.equal(0),e.equal(1)).sum().cast("float32")})}(t,e),i=n.add(r);return Hs(vu(i,0),n.div(i),0).cast("float32")})}function Bd(t,e){return _e(function(){var n=Ld(t,e),r=function(t,e){return _e(function(){return Us(t.equal(1),e.equal(0)).sum().cast("float32")})}(t,e),i=n.add(r);return Hs(vu(i,0),n.div(i),0).cast("float32")})}function Wd(t,e){return Dd(t,e)}function Vd(t,e){return t.rank===e.rank&&(t=t.squeeze([t.rank-1])),(e=e.argMax(-1)).dtype!==t.dtype&&(e=e.asType(t.dtype)),mu(t,e).asType("float32")}var Ud=Rd,jd=Td,Gd={binaryAccuracy:zd,categoricalAccuracy:Md,precision:Pd,categoricalCrossentropy:Ud,sparseCategoricalCrossentropy:jd,mse:kd,MSE:kd,mae:Id,MAE:Id,mape:Ad,MAPE:Ad,cosine:Od};function qd(t){if(ph(null!==t,"Unknown LossOrMetricFn "+t),"string"==typeof t)return t;for(var e=void 0,n=0,r=Object.keys(_d);n<r.length;n++){var i=r[n];if(_d[i]===t){e=i;break}}if(void 0!==e)return e;for(var a=0,o=Object.keys(Gd);a<o.length;a++)if(i=o[a],Gd[i]===t){e=i;break}return void 0!==e?e:t.name}var Hd=1048576;function Kd(t,e,n){if(void 0===n&&(n=!1),null==t||"object"!=typeof t||Object.getPrototypeOf(t)!==Object.prototype||!function t(e){if(null===e)return!0;if("object"==typeof e){if(Object.getPrototypeOf(e)===Object.prototype){for(var n=0,r=Object.keys(e);n<r.length;n++){var i=r[n];if("string"!=typeof i)return!1;if(!t(e[i]))return!1}return!0}if(Array.isArray(e)){for(var a=0,o=e;a<o.length;a++)if(!t(o[a]))return!1;return!0}return!1}var s=typeof e;return"string"===s||"number"===s||"boolean"===s}(t))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(n){var r=JSON.stringify(t);r.length>Hd&&console.warn('User-defined metadata of model "'+e+'" is too large in size (length='+r.length+" when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= "+Hd+".")}}function $d(t,e,n,r){void 0===r&&(r=console.log);var i,a=function(t){var e=!0,n=[],r=[];for(var i in t.nodesByDepth)n.push(t.nodesByDepth[i]);for(var a=0,o=n;a<o.length;a++){var s=o[a];if(s.length>1||1===s.length&&s[0].inboundLayers.length>1){e=!1;break}r.push.apply(r,s)}if(e)for(var u=0,l=t.layers;u<l.length;u++){for(var c=!1,p=0,h=l[u].inboundNodes;p<h.length;p++){var f=h[p];if(-1!==r.indexOf(f)){if(c){e=!1;break}c=!0}}if(!e)break}return e}(t),o=["Layer (type)","Output shape","Param #"];if(a?(e=e||65,n=n||[.45,.85,1]):(e=e||98,n=n||[.33,.55,.67,1]),n[n.length-1]<=1&&(n=n.map(function(t){return Math.floor(e*t)})),!a)for(var s in o.push("Receives inputs"),i=[],t.nodesByDepth)i.push.apply(i,t.nodesByDepth[s]);r("_".repeat(e)),Xd(o,n,r),r("=".repeat(e));for(var u=t.layers,l=0;l<u.length;++l)a?Yd(u[l],n,r):Jd(u[l],n,i,r),r((l===u.length-1?"=":"_").repeat(e));t.checkTrainableWeightsConsistency();var c=function(t){return null!=t.collectedTrainableWeights?Qf(t.collectedTrainableWeights):Qf(t.trainableWeights)}(t),p=Qf(t.nonTrainableWeights);r("Total params: "+(c+p)),r("Trainable params: "+c),r("Non-trainable params: "+p),r("_".repeat(e))}function Xd(t,e,n){void 0===n&&(n=console.log);for(var r="",i=0;i<t.length;++i)i>0&&(r=r.slice(0,r.length-1)+" "),r=(r+=t[i]).slice(0,e[i]),r+=" ".repeat(e[i]-r.length);n(r)}function Yd(t,e,n){var r;try{r=JSON.stringify(t.outputShape)}catch(t){r="multiple"}Xd([t.name+" ("+t.getClassName()+")",r,t.countParams().toString()],e,n)}function Jd(t,e,n,r){var i;try{i=JSON.stringify(t.outputShape)}catch(t){i="multiple"}for(var a=[],o=0,s=t.inboundNodes;o<s.length;o++){var u=s[o];if(!(null!=n&&n.length>0&&-1===n.indexOf(u)))for(var l=0;l<u.inboundLayers.length;++l){var c=u.inboundLayers[l].name,p=u.nodeIndices[l],h=u.tensorIndices[l];a.push(c+"["+p+"]["+h+"]")}}var f=t.name,d=t.getClassName(),m=0===a.length?"":a[0];for(Xd([f+" ("+d+")",i,t.countParams().toString(),m],e,r),l=1;l<a.length;++l)Xd(["","","",a[l]],e,r)}function Zd(t,e,n){return("inboundNodes"===t||"outputLayers"===t||"inputLayers"===t)&&0===e&&"string"==typeof n}function Qd(t,e){if(null===t)return null;if("string"==typeof t)return gh(t);if("number"==typeof t||"boolean"==typeof t)return t;if(t instanceof Array){for(var n=[],r=t.length,i=0;i<r;++i){var a=t[i];Zd(e,i,a)?n.push(a):n.push(Qd(a,e))}return n}for(var o={},s=0,u=Object.keys(t);s<u.length;s++){var l=u[s],c=t[l];if("name"===l&&"string"==typeof c)o[l]=c;else{var p=gh(l);o[p]=Qd(c,p)}}return o}var tm=function(){function t(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof t)for(var n in e.id2Value)this.id2Value[n]=e.id2Value[n],n in e.id2Mask&&(this.id2Mask[n]=e.id2Mask[n]);else{if(null==e)return;for(var r=0,i=e;r<i.length;r++){var a=i[r];this.add(a.key,a.value)}}}return t.prototype.add=function(t,e,n){if(null!=this.id2Value[t.id])throw new sh("Duplicate key: name="+t.name+", id="+t.id);return this.id2Value[t.id]=function(t,e){if(null==t.dtype||t.dtype===e.dtype)return e;try{return Wn(e,t.dtype)}catch(n){throw new sh("The dtype of the feed ("+e.dtype+") can not be cast to the dtype of the key '"+t.name+"' ("+t.dtype+").")}}(t,e),this.name2Id[t.name]=t.id,null!=n&&(this.id2Mask[t.id]=n),this},t.prototype.addFeed=function(t){this.add(t.key,t.value)},t.prototype.hasKey=function(t){return null!=this.id2Value[t.id]},t.prototype.names=function(){return Object.keys(this.name2Id)},t.prototype.getValue=function(t){if(t instanceof ad){if(null==this.id2Value[t.id])throw new sh("Nonexistent key: "+t.name);return this.id2Value[t.id]}var e=this.name2Id[t];if(null==e)throw new sh("Feed dict has no SymbolicTensor name: "+t);return this.id2Value[e]},t.prototype.getMask=function(t){if(t instanceof ad){if(null==this.id2Value[t.id])throw new sh("Nonexistent key: "+t.name);return this.id2Mask[t.id]}var e=this.name2Id[t];if(null==e)throw new sh("Feed dict has no SymbolicTensor name: "+t);return this.id2Mask[e]},t.prototype.disposeMasks=function(){null!=this.id2Mask&&Fe(this.id2Mask)},t}(),em={},nm={};function rm(t,e,n,r){for(var i=null!=n&&n.training,a=Array.isArray(t),o=a?t:[t],s=o.map(function(t){return t.name}),u=[],l=e.names(),c=0,p=s;c<p.length;c++){var h=p[c];-1!==l.indexOf(h)?u.push(e.getValue(h)):u.push(null)}null!=r&&(r.maxNumTensors=-1/0,r.minNumTensors=1/0);var f,d,m=s.join(",")+"|"+e.names().join(",");if(null==em[m]){var g=function(t,e){$.assert(null!=t&&t.length>0,function(){return"Expected at least one fetch, got none"});var n=[],r={};if(1===t.length){var i=im(t[0],e);n=i.sorted,r=i.recipientMap}else for(var a=new Set,o=0,s=t;o<s.length;o++){for(var u=im(s[o],e),l=u.sorted,c=u.recipientMap,p=0,h=l;p<h.length;p++){var f=h[p];a.has(f.name)||(n.push(f),a.add(f.name))}var d=function(t){null==r[t]&&(r[t]=new Set),c[t].forEach(function(e){return r[t].add(e)})};for(var m in c)d(m)}return{sorted:n,recipientCounts:function(t){var e={};for(var n in t)e[n]=t[n].size;return e}(r)}}(o,e);f=g.sorted,d=g.recipientCounts,em[m]=f,nm[m]=d}f=em[m],d={},i||Object.assign(d,nm[m]);for(var v=new tm(e),y=0;y<f.length;++y){if(null!=r){var b=Oe().numTensors;b>r.maxNumTensors&&(r.maxNumTensors=b),b<r.minNumTensors&&(r.minNumTensors=b)}var x=f[y],w=x.sourceLayer;if(!(w instanceof pd)){for(var C=[],N=[],E=[],S=!1,k=0,I=x.inputs;k<I.length;k++){var A=I[k],R=v.getValue(A),T=v.getMask(A);C.push(R),N.push(T),null!=T&&(S=!0),i||(d[A.name]--,0!==d[A.name]||e.hasKey(A)||-1!==s.indexOf(A.name)||R.isDisposed||!0===A.sourceLayer.stateful||E.push(R))}S&&((n=n||{}).mask=N[0]);var D=dh(w.apply(C,n)),O=null;w.supportsMasking&&(O=w.computeMask(C,N));for(var _=am(x),F=Array.isArray(_)?_:[_],z=0;z<F.length;++z){v.hasKey(F[z])||v.add(F[z],D[z],Array.isArray(O)?O[0]:O);var M=s.indexOf(F[z].name);-1!==M&&(u[M]=D[z])}i||Fe(E)}}return v.disposeMasks(),a?u:u[0]}function im(t,e){for(var n=new Set,r=[],i={},a=0,o=e.names();a<o.length;a++){var s=o[a];n.add(s)}var u=[],l=[];for(u.push(t);u.length>0;){var c=u[u.length-1];if(n.has(c.name))u.pop();else{var p=l[l.length-1]===u.length-1;if(0===c.inputs.length||p)u.pop(),r.push(c),n.add(c.name),p&&l.pop();else{l.push(u.length-1);for(var h=0,f=c.inputs;h<f.length;h++){var d=f[h];null==i[d.name]&&(i[d.name]=new Set),i[d.name].add(c.name),n.has(d.name)||u.push(d)}}}}return{sorted:r,recipientMap:i}}function am(t){var e;if(1===t.sourceLayer.inboundNodes.length)e=t.sourceLayer.output;else{for(var n=null,r=0;r<t.sourceLayer.inboundNodes.length;++r)for(var i=0,a=t.sourceLayer.inboundNodes[r].outputTensors;i<a.length;i++)if(a[i].id===t.id){n=r;break}e=t.sourceLayer.getOutputAt(n)}return e}function om(t,e){return function(t,e,n){var r=e.length;if(null==t||Array.isArray(t)&&0===t.length)return e.map(function(t){return null});if(1===r)return Array.isArray(t)&&1===t.length?t:"object"==typeof t&&e[0]in t?[t[e[0]]]:[t];if(Array.isArray(t)){if(t.length!==r)throw new Error("Provided "+n+" is an array of "+t.length+" element(s), but the model has "+r+" outputs. Make sure a set of weights is provided for each model output.");return t}if("object"==typeof t&&Object.keys(t).length>0&&"object"==typeof t[Object.keys(t)[0]]){var i=[];return e.forEach(function(e){e in t?i.push(t[e]):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 "+e+" keys. Provided "+n+" not understood: "+JSON.stringify(t))}(t,e,"classWeight")}function sm(t,e,n,r){return nh(this,void 0,void 0,function(){var i,a,o,s,u;return rh(this,function(l){switch(l.label){case 0:if(null!=e||null!=r)throw new Error("Support sampleWeight is not implemented yet");return null==n?[3,2]:(i=_e(function(){if(1===t.shape.length)return t.clone();if(2===t.shape.length){if(t.shape[1]>1)return t.argMax(1);if(1===t.shape[1])return t.reshape([t.shape[0]]);throw new Error("Encountered unexpected last-dimension size ("+t.shape[1]+") during handling of class weights. The size is expected to be >= 1.")}throw new Error("Unexpected rank of target (y) tensor ("+t.rank+") during handling of class weights. The rank is expected to be 1 or 2.")}),s=(o=Array).from,[4,i.data()]);case 1:return a=s.apply(o,[l.sent()]),Fe(i),u=[],a.forEach(function(t){if(null==n[t])throw new Error("classWeight must contain all classes in the training data. The class "+t+" exists in the data but not in classWeight");u.push(n[t])}),[2,on(u,"float32")];case 2:return[2,null]}})})}function um(t,e){return su(t,e)}var lm=32;function cm(t,e){var n,r,i=e;n=i.xs,r=i.ys,$.assert(null!=n&&null!=r,function(){return"A Dataset iterator for fitDataset() is expected to generate objects of the form `{xs: xVal, ys: yVal}`, where the two values may be `tf.Tensor`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates "+e});var a=pm("input",t.inputNames,n),o=pm("output",t.outputNames,r),s=a[0].shape[0];$.assert(a.length===t.inputs.length,function(){return"LayersModel has "+t.inputs.length+" inputs, but the dataset provides "+a.length+" inputs. (Expected input keys: "+JSON.stringify(t.inputNames)+")"}),$.assert(o.length===t.outputs.length,function(){return"LayersModel has "+t.outputs.length+" outputs, but the dataset provides "+o.length+" outputs. (Expected output keys: "+JSON.stringify(t.outputNames)+")"});var u=function(e){$.assert(a[e].shape[0]===s,function(){return"Batch size mismatch: input "+t.inputNames[e]+" has "+a[e].shape[0]+"; expected "+s+" based on input "+t.inputNames[0]+"."})};for(var l in a)u(l);var c=function(e){$.assert(o[e].shape[0]===s,function(){return"Batch size mismatch: output "+t.outputNames[e]+" has "+o[e].shape[0]+"; expected "+s+" based on input "+t.inputNames[0]+"."})};for(var p in o)c(p);return{xs:a,ys:o}}function pm(t,e,n){if(n instanceof st)return[n];if(Array.isArray(n))return $.assert(n.length===e.length,function(){return"Received an array of "+n.length+" Tensors, but expected "+e.length+" to match the "+t+" keys "+e+"."}),n;for(var r=[],i=0,a=e;i<a.length;i++){var o=a[i];if(null==n[o])throw new sh("The feature data generated by the dataset lacks the required "+t+" key '"+o+"'.");r.push(n[o])}return r}function hm(t,e,n){return nh(this,void 0,void 0,function(){var r,i,a,o,s,u,l,c,p,h,f,d,m,g,v,y,b,x,w,C,N,E,S,k,I,A,R,T,D,O,_,F,z,M;return rh(this,function(L){switch(L.label){case 0:if(r=null!=n.batchesPerEpoch,$.assert(null!=t.optimizer,function(){return"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."}),$.assert(null!=n,function(){return"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."}),$.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}),$.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}),$.assert(null==n.validationSplit,function(){return"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."}),t.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");t.isTraining=!0,L.label=1;case 1:return L.trys.push([1,,26,27]),i=null!=n.validationData,a=void 0,o=void 0,i&&(fm(n.validationData)?$.assert(null==n.validationBatches||n.validationBatches>0&&Number.isInteger(n.validationBatches),function(){return"For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got "+n.validationBatches}):(s=function(t){if(3===t.length)throw new uh("Validation with sample weights is not implemented yet.");return{xs:t[0],ys:t[1]}}(n.validationData),a=s.xs,o=s.ys)),u=t.makeTrainFunction(),l=t.getDedupedMetricsNames(),c=void 0,c=i?l.slice().concat(l.map(function(t){return"val_"+t})):l.slice(),p=wd(n.callbacks,n.yieldEvery),h=null==n.verbose?1:n.verbose,f=Nd(p,h,n.epochs,null,null,function(t,e){var n=null;return null!=e.batchesPerEpoch?n=e.batchesPerEpoch:Number.isFinite(t.size)&&(n=t.size),n}(e,n),null,i,c),d=f.callbackList,m=f.history,d.setModel(t),t.history=m,[4,d.onTrainBegin()];case 2:return L.sent(),t.stopTraining_=!1,g=null==n.initialEpoch?0:n.initialEpoch,[4,e.iterator()];case 3:v=L.sent(),L.label=4;case 4:return g<n.epochs?(y={},[4,d.onEpochBegin(g)]):[3,23];case 5:return L.sent(),b=0,x=0,r?[3,7]:[4,e.iterator()];case 6:v=L.sent(),L.label=7;case 7:return!r||b<n.batchesPerEpoch?[4,v.next()]:[3,21];case 8:return w=L.sent(),r&&w.done?(console.warn("You provided `batchesPerEpoch` as "+n.batchesPerEpoch+", but your dataset iterator ran out of data after "+b+" batches; interrupting training. Make sure that your dataset can generate at least `batchesPerEpoch * epochs` batches (in this case, "+n.batchesPerEpoch*n.epochs+" batches). You may need to use the repeat() function when building your dataset."),[3,21]):null==w.value?[3,15]:(C=cm(t,w.value),N=C.xs,E=C.ys,(S={}).batch=x,S.size=N[0].shape[0],[4,d.onBatchBegin(x,S)]);case 9:if(L.sent(),k=[],null==n.classWeight)return[3,13];I=om(n.classWeight,t.outputNames),M=0,L.label=10;case 10:return M<I.length?(R=(A=k).push,[4,sm(E[M],null,I[M])]):[3,13];case 11:R.apply(A,[L.sent()]),L.label=12;case 12:return++M,[3,10];case 13:for(T=N.concat(E).concat(k),D=u(T),Fe(T),M=0;M<l.length;++M)O=l[M],_=D[M],S[O]=_,ze(_);return[4,d.onBatchEnd(x,S)];case 14:L.sent(),dd(S),x++,b++,L.label=15;case 15:return(r?b>=n.batchesPerEpoch:w.done)?i?(F=void 0,fm(n.validationData)?(z=dh,[4,t.evaluateDataset(n.validationData,{batches:n.validationBatches})]):[3,17]):[3,19]:[3,20];case 16:return F=z.apply(void 0,[L.sent()]),[3,18];case 17:F=dh(t.evaluate(a,o,{batchSize:null==n.validationBatchSize?lm:n.validationBatchSize,verbose:0})),L.label=18;case 18:for(M=0;M<t.metricsNames.length;++M)y["val_"+t.metricsNames[M]]=F[M];L.label=19;case 19:return[3,21];case 20:return t.stopTraining_?[3,21]:[3,7];case 21:return[4,d.onEpochEnd(g,y)];case 22:return L.sent(),g++,t.stopTraining_?[3,23]:[3,4];case 23:return[4,d.onTrainEnd()];case 24:return L.sent(),[4,t.history.syncData()];case 25:return L.sent(),[2,t.history];case 26:return t.isTraining=!1,[7];case 27:return[2]}})})}function fm(t){return"function"==typeof t.iterator}function dm(t){$.assert(t>0&&Number.isInteger(t),function(){return"batchSize is required to be a positive integer, but got "+t})}function mm(t,e,n){return null==t?[null]:Array.isArray(t)?t.map(function(t){return uf(t,e,n-e)}):uf(t,e,n-e)}function gm(t,e){return _e(function(){return null==t?null:Array.isArray(t)?t.map(function(t){return gm(t,e)}):gf(t,"int32"===e.dtype?e:e.toInt())})}function vm(t,e){for(var n=[],r=0,i=null;r<t;)(i=r+e)>=t&&(i=t),n.push([r,i]),r=i;return n}function ym(t,e,n,r){return void 0===r&&(r={}),nh(this,void 0,void 0,function(){var i,a,o,s,u,l,c,p,h,f,d,m,g,v,y,b,x,w,C,N,E,S;return rh(this,function(k){switch(k.label){case 0:if(t.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");t.isTraining=!0,k.label=1;case 1:return k.trys.push([1,,7,8]),dm(p=null==r.batchSize?32:r.batchSize),h=!1,[4,t.standardizeUserData(e,n,r.sampleWeight,r.classWeight,h,p)];case 2:if(f=k.sent(),i=f[0],a=f[1],c=f[2],d=!1,m=void 0,!(null!=r.validationData&&r.validationData.length>0))return[3,4];if(d=!0,2!==r.validationData.length)throw 3===r.validationData.length?new uh("validationData including sample weights is not supported yet."):new sh("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],g=!0,[4,t.standardizeUserData(o,s,null,null,g,p)];case 3:return v=k.sent(),u=v[0],l=v[1],m=u.concat(l),[3,5];case 4:null!=r.validationSplit&&r.validationSplit>0&&r.validationSplit<1?(d=!0,y=Math.floor(i[0].shape[0]*(1-r.validationSplit)),b=i[0].shape[0],u=mm(i,y,b),i=mm(i,0,y),l=mm(a,y,b),a=mm(a,0,y),m=u.concat(l)):null!=r.validationSteps&&(d=!0),k.label=5;case 5:return x=i.concat(a).concat(c),t.checkTrainableWeightsConsistency(),w=t.makeTrainFunction(),C=t.getDedupedMetricsNames(),N=void 0,E=void 0,d?(t.makeTestFunction(),N=t.testFunction,E=C.slice().concat(C.map(function(t){return"val_"+t}))):(N=null,m=[],E=C.slice()),S=wd(r.callbacks,r.yieldEvery),[4,function(t,e,n,r,i,a,o,s,u,l,c,p,h,f,d){return nh(this,void 0,void 0,function(){var m,g,v,y,b,x,w,C;return rh(this,function(N){switch(N.label){case 0:if(null==i&&(i=32),null==a&&(a=1),null==c&&(c=!0),null==h&&(h=0),m=!1,null!=u&&null!=l&&(m=!0),null!=d&&(m=!0,null==f))throw new sh("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");return null!=(g=t.checkNumSamples(n,i,f,"steps_per_epoch"))&&(v=af(0,g)),null==o&&(o=1),y=Nd(s,o,a,h,g,f,i,m,p),b=y.callbackList,x=y.history,b.setModel(t),t.history=x,[4,b.onTrainBegin()];case 1:N.sent(),t.stopTraining_=!1,w=function(a){var o,s,p,h,d;return rh(this,function(y){switch(y.label){case 0:return[4,b.onEpochBegin(a)];case 1:if(y.sent(),o={},null==f)return[3,2];throw new uh("stepsPerEpoch mode is not implemented yet.");case 2:if("batch"===c)throw new uh("batch shuffling is not implemneted yet");c&&$.shuffle(v),s=on(v),p=vm(g,i),h=function(a){var c;return rh(this,function(h){switch(h.label){case 0:return c={},[4,b.onBatchBegin(a,c)];case 1:return h.sent(),_e(function(){var h=p[a][0],f=p[a][1],d=uf(s,h,f-h);c.batch=a,c.size=f-h;for(var g=gm(n,d),v=e(g),y=0;y<r.length;++y){var b=r[y],x=v[y];c[b]=x,ze(x)}if(a===p.length-1&&m){var w=t.testLoop(u,l,i);for(y=0;y<r.length;++y)b=r[y],ze(x=w[y]),o["val_"+b]=x}}),[4,b.onBatchEnd(a,c)];case 2:return h.sent(),dd(c),t.stopTraining_?[2,"break"]:[2]}})},d=0,y.label=3;case 3:return d<p.length?[5,h(d)]:[3,6];case 4:if("break"===y.sent())return[3,6];y.label=5;case 5:return++d,[3,3];case 6:s.dispose(),y.label=7;case 7:return[4,b.onEpochEnd(a,o)];case 8:return y.sent(),t.stopTraining_?[2,"break"]:[2]}})},C=h,N.label=2;case 2:return C<a?[5,w(C)]:[3,5];case 3:if("break"===N.sent())return[3,5];N.label=4;case 4:return++C,[3,2];case 5:return[4,b.onTrainEnd()];case 6:return N.sent(),[4,t.history.syncData()];case 7:return N.sent(),[2,t.history]}})})}(t,w,x,C,p,r.epochs,r.verbose,S,N,m,r.shuffle,E,r.initialEpoch,null,null)];case 6:return[2,k.sent()];case 7:return t.isTraining=!1,xm(i,e),xm(a,n),xm(u,o),xm(l,s),null!=c&&Fe(c),[7];case 8:return[2]}})})}function bm(t){var e=[];t instanceof st&&(t=[t]);for(var n=0;n<t.length;++n){var r=t[n];if(1===r.rank)e.push(sf(r,1));else{if(0===r.rank)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");e.push(r)}}return e}function xm(t,e){if(null!=t){var n=[];if(e instanceof st)n.push(e.id);else if(Array.isArray(e))e.forEach(function(t){return n.push(t.id)});else if(null!=e)for(var r in e){var i=e[r];n.push(i.id)}var a=[];if(t instanceof st)-1===n.indexOf(t.id)&&a.push(t);else if(Array.isArray(t))t.forEach(function(t){-1===n.indexOf(t.id)&&a.push(t)});else if(null!=t)for(var o in t){var s=t[o];-1===n.indexOf(s.id)&&a.push(s)}a.forEach(function(t){t.isDisposed||t.dispose()})}}function wm(t){return Array.isArray(t)}function Cm(t){return!function(t){return t instanceof st}(t)&&!wm(t)}function Nm(t,e,n,r,i){if(void 0===r&&(r=!0),void 0===i&&(i=""),null==e||0===e.length){if(null!=t){var a=!1;if(wm(t)&&t.length>0)a=!0;else if(Cm(t)){for(var o in t)if(t.hasOwnProperty(o)){a=!0;break}}else a=!0;if(a)throw new sh("Error when checking model "+i+" expected no data, but got "+t)}return[]}if(null==t)return e.map(function(t){return null});var s;if(Cm(t)){t=t,s=[];for(var u=0,l=e;u<l.length;u++){var c=l[u];if(null==t[c])throw new sh('No data provided for "'+c+'". Need data for each key in: '+e);s.push(t[c])}}else if(wm(t)){if((t=t).length!==e.length)throw new sh("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 "+e.length+" Tensor(s), but instead got the following list of Tensor(s): "+t);s=t}else{if(t=t,e.length>1)throw new sh("The model "+i+" expects "+e.length+" Tensor(s), but only received one Tensor. Found: Tensor with shape "+t.shape);s=[t]}if(s=bm(s),null!=n)for(var p=0;p<e.length;++p)if(null!=n[p]){var h=s[p];if(h.shape.length!==n[p].length)throw new sh("Error when checking "+i+": expected "+e[p]+" to have "+n[p].length+" dimension(s). but got array with shape "+h.shape);for(var f=0;f<n[p].length;++f)if(0!==f||r){var d=h.shape[f],m=n[p][f];if(null!=m&&m>=0&&d!==m)throw new sh("Error when checking "+i+": expected "+e[p]+" to have shape ["+n[p]+"], but got array with shape ["+h.shape+"].")}}return s}function Em(t,e,n,r,i){var a;if(void 0===r&&(r=!0),void 0===i&&(i=""),Array.isArray(t)){if(t.length!==e.length)throw new sh("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 "+e.length+" Tensor(s), but instead got "+t.length+" Tensors(s).");a=t}else{if(e.length>1)throw new sh("The model expects "+e.length+" "+i+" Tensors, but only received one Tensor. Found: array with shape "+JSON.stringify(t.shape)+".");a=[t]}if(null!=n)for(var o=0;o<e.length;++o)if(null!=n[o]){var s=a[o];if(s.shape.length!==n[o].length)throw new sh("Error when checking "+i+": expected "+e[o]+" to have "+n[o].length+" dimension(s), but got array with shape "+JSON.stringify(s.shape));for(var u=0;u<n[o].length;++u)if(0!==u||r){var l=s.shape[u],c=n[o][u];if(null!=c&&c!==l)throw new sh("Error when checking "+i+": expected "+e[o]+" to have shape "+JSON.stringify(n[o])+" but got array with shape "+JSON.stringify(s.shape)+".")}}}var Sm=function(t){function e(e){var n=t.call(this,e)||this;return n.isTraining=!1,n}return Qp(e,t),e.prototype.summary=function(t,e,n){if(void 0===n&&(n=console.log),!this.built)throw new sh("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).");$d(this,t,e,n)},e.prototype.compile=function(t){var e=this;if(null==t.loss&&(t.loss=[]),this.loss=t.loss,"string"==typeof t.optimizer)this.optimizer_=function(t){var e={Adagrad:function(){return Xp.adagrad(.01)},Adadelta:function(){return Xp.adadelta(1,.95,ih())},Adam:function(){return Xp.adam(.001,.9,.999,ih())},Adamax:function(){return Xp.adamax(.002,.9,.999,ih(),0)},RMSProp:function(){return Xp.rmsprop(.001,.9,0,ih())},SGD:function(){return Xp.sgd(.01)}};if(e.adagrad=e.Adagrad,e.adadelta=e.Adadelta,e.adam=e.Adam,e.adamax=e.Adamax,e.rmsprop=e.RMSProp,e.sgd=e.SGD,t in e)return e[t]();throw new sh("Unknown Optimizer "+t)}(t.optimizer),this.isOptimizerOwned=!0;else{if(!(t.optimizer instanceof Wp))throw new sh("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=t.optimizer,this.isOptimizerOwned=!1}var n=[];if(Array.isArray(t.loss)||"string"==typeof t.loss||"function"==typeof t.loss)if(Array.isArray(t.loss)){if(t.loss.length!==this.outputs.length)throw new sh("When passing an Array as loss, it should have one entry per model output. The model has "+this.outputs.length+" output(s), but you passed loss="+t.loss+".");var r=t.loss;n=r.map(function(t){return Fd(t)})}else{var i=Fd(t.loss);this.outputs.forEach(function(t){n.push(i)})}else{for(var a in t.loss=t.loss,t.loss)if(-1===this.outputNames.indexOf(a))throw new sh('Unknown entry in loss dictionary: "'+a+'". Only expected the following keys: '+this.outputNames);for(var o=0,s=this.outputNames;o<s.length;o++){var u=s[o];null==t.loss[u]&&console.warn('Output "'+u+'" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to '+u+" during training"),n.push(Fd(t.loss[u]))}}this.lossFunctions=n,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(var l=0;l<this.outputs.length;++l){var c=this.internalOutputShapes[l],p=this.outputNames[l];this.feedOutputNames.push(p),this.feedOutputShapes.push(c),this.feedLossFns.push(this.lossFunctions[l])}var h=[];this.metrics=t.metrics,this.metricsNames=["loss"],this.metricsTensors=[],$h("loss",function(){for(var t=0;t<e.outputs.length;++t)if(-1===h.indexOf(t)){var n=e.lossFunctions[t];e.outputs.length>1&&(e.metricsTensors.push([n,t]),e.metricsNames.push(e.outputNames[t]+"_loss"))}});var f=function(t,e){if(null==t||Array.isArray(t)&&0===t.length)return e.map(function(t){return[]});var n;if("string"==typeof t||"function"==typeof t)n=[t];else{if(!Array.isArray(t)&&"object"!=typeof t)throw new TypeError("Type of metrics argument not understood. Expected an string,function, Array, or Object, found: "+t);n=t}if(Array.isArray(n))return e.map(function(t){return n});for(var r=[],i=0,a=e;i<a.length;i++){var o=a[i],s=n.hasOwnProperty(o)?n[o]:[];Array.isArray(s)||(s=[s]),r.push(s)}return r}(t.metrics,this.outputNames);$h("metric",function(){for(var t=function(t){if(-1!==h.indexOf(t))return"continue";!function(n){for(var r,i,a,o=function(n){if("string"==typeof n&&-1!==["accuracy","acc","crossentropy","ce"].indexOf(n)){var o=e.internalOutputShapes[t];1===o[o.length-1]||e.lossFunctions[t]===Dd?-1!==["accuracy","acc"].indexOf(n)?i=zd:-1!==["crossentropy","ce"].indexOf(n)&&(i=Wd):e.lossFunctions[t]===Td?-1!==["accuracy","acc"].indexOf(n)?i=Vd:-1!==["crossentropy","ce"].indexOf(n)&&(i=jd):-1!==["accuracy","acc"].indexOf(n)?i=Md:-1!==["crossentropy","ce"].indexOf(n)&&(i=Ud);var s=void 0;-1!==["accuracy","acc"].indexOf(n)?s="acc":-1!==["crossentropy","ce"].indexOf(n)&&(s="ce"),a=i,r=""+s}else{var u=function(t){if("string"==typeof t&&t in Gd)return Gd[t];if("string"!=typeof t&&null!=t)return t;throw new sh("Unknown metric "+t)}(n);a=u,r=""+qd(n)}var l;$h(r,function(){l=a}),function(t,n,r){e.outputNames.length>1&&(n=e.outputNames[t]+"_"+n),e.metricsNames.push(n),e.metricsTensors.push([r,t])}(t,r,l)},s=0,u=f[t];s<u.length;s++)o(u[s])}()},n=0;n<e.outputs.length;++n)t(n)}),this.collectedTrainableWeights=this.trainableWeights},e.prototype.checkTrainableWeightsConsistency=function(){null!=this.collectedTrainableWeights&&this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?")},e.prototype.evaluate=function(t,e,n){void 0===n&&(n={});var r=null==n.batchSize?32:n.batchSize;dm(r);var i=this.standardizeUserDataXY(t,e,!0,r);try{var a=i[0].concat(i[1]);this.makeTestFunction();var o=this.testFunction;return fh(this.testLoop(o,a,r,n.verbose,n.steps))}finally{xm(i[0],t),xm(i[1],e)}},e.prototype.evaluateDataset=function(t,e){return nh(this,void 0,void 0,function(){return rh(this,function(n){return this.makeTestFunction(),[2,function(t,e,n){return nh(this,void 0,void 0,function(){var r,i,a,o,s,u,l,c,p,h;return rh(this,function(f){switch(f.label){case 0:if(r=null!=(n=n||{}).batches,i=t.testFunction,a=[],n.verbose>0)throw new uh("Verbose mode is not implemented yet.");return $.assert(!r||n.batches>0&&Number.isInteger(n.batches),function(){return"Test loop expects `batches` to be a positive integer, but received "+JSON.stringify(n.batches)}),function(t){return"function"==typeof t.next}(e)?(s=e,[3,3]):[3,1];case 1:return[4,e.iterator()];case 2:s=f.sent(),f.label=3;case 3:o=s,u=0,l=0,c=function(){var e;return rh(this,function(s){switch(s.label){case 0:return[4,o.next()];case 1:return e=s.sent(),a=_e(function(){if(e.value){var n=cm(t,e.value),r=n.xs,o=n.ys,s=r.concat(o),c=_e(function(){return i(s)});if(Fe(s),0===l)for(var p=0;p<c.length;++p)a.push(an(0));var h=s[0].shape[0],f=function(t){var e=c[t],n=a[t];a[t]=_e(function(){return $s(a[t],su(h,e))}),l>0&&Fe(n)};for(p=0;p<c.length;++p)f(p);Fe(c),u+=h,++l}return a}),e.done?(r&&console.warn("Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least `batches` batches (in this case, "+n.batches+" batches). You may need to use the repeat() function when building your dataset."),[2,"break"]):[2]}})},f.label=4;case 4:return!r||l<n.batches?[5,c()]:[3,6];case 5:return"break"===f.sent()?[3,6]:[3,4];case 6:for(p=0;p<a.length;++p)h=a[p],a[p]=Zs(a[p],u),Fe(h);return[2,fh(a)]}})})}(this,t,e)]})})},e.prototype.checkNumSamples=function(t,e,n,r){var i;if(void 0===r&&(r="steps"),null!=n){if(i=null,null!=e)throw new sh("If "+r+" is set, batchSize must be null or undefined.Got batchSize = "+e)}else{if(null==t)throw new sh("Either the input data should have a defined shape, or "+r+" shoud be specified.");i=Array.isArray(t)?t[0].shape[0]:t.shape[0]}return i},e.prototype.execute=function(t,e){if(Array.isArray(e)&&0===e.length)throw new sh("`outputs` is an empty Array, which is not allowed.");var n=Array.isArray(e),r=n?e:[e],i=this.retrieveSymbolicTensors(r),a=new tm;if(t instanceof st&&(t=[t]),Array.isArray(t)){if(t.length!==this.inputs.length)throw new sh("The number of inputs provided ("+t.length+") does not match the number of inputs of this model ("+this.inputs.length+").");for(var o=0;o<this.inputs.length;++o)a.add(this.inputs[o],t[o])}else for(var s=0,u=this.inputs;s<u.length;s++){var l=u[s],c=t[l.name];if(null==c)throw new sh("No value is provided for the model's input "+l.name);a.add(l,c)}var p=rm(i,a);return n?p:p[0]},e.prototype.retrieveSymbolicTensors=function(t){for(var e=ch(null,t.length),n=t.length,r=0,i=this.layers;r<i.length;r++){for(var a=i[r],o=Array.isArray(a.output)?a.output:[a.output],s=o.map(function(t){return t.name}),u=0;u<t.length;++u){var l=s.indexOf(t[u]);if(-1!==l&&(e[u]=o[l],n--),0===n)break}if(0===n)break}if(n>0){var c=[];throw e.forEach(function(e,n){null==e&&c.push(t[n])}),new sh("Cannot find SymbolicTensors for output name(s): "+JSON.stringify(c))}return e},e.prototype.predictLoop=function(t,e,n){var r=this;return void 0===e&&(e=32),void 0===n&&(n=!1),_e(function(){var i=r.checkNumSamples(t);if(n)throw new uh("Verbose predictLoop() is not implemented yet.");for(var a=vm(i,e),o=r.outputs.map(function(t){return[]}),s=function(e){_e(function(){var n=a[e][0],i=a[e][1],o=mm(t,n,i),s=[];if(Array.isArray(o))for(var u=0;u<o.length;++u)s.push({key:r.inputs[u],value:o[u]});else s.push({key:r.inputs[0],value:o});var l=new tm(s);return rm(r.outputs,l)}).forEach(function(t,e){return o[e].push(t)})},u=0;u<a.length;++u)s(u);return fh(o.map(function(t){return bn(t,0)}))})},e.prototype.predict=function(t,e){void 0===e&&(e={});var n=bm(t);Em(n,this.inputNames,this.feedInputShapes,!1);try{var r=null==e.batchSize?32:e.batchSize;return dm(r),this.predictLoop(n,r)}finally{xm(n,t)}},e.prototype.predictOnBatch=function(t){Em(t,this.inputNames,this.feedInputShapes,!0);var e=(Array.isArray(t)?t[0]:t).shape[0];return this.predictLoop(t,e)},e.prototype.standardizeUserDataXY=function(t,e,n,r){if(void 0===n&&(n=!0),null==this.optimizer_)throw new oh("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");for(var i=[],a=0;a<this.feedOutputShapes.length;++a){var o=this.feedOutputShapes[a];this.feedLossFns[a]===Td?i.push(o.slice(0,o.length-1).concat([1])):i.push(o)}if(function(t,e,n){var r=wh(t.map(function(t){return t.shape[0]}));r.sort();var i=wh(e.map(function(t){return t.shape[0]}));if(i.sort(),r.length>1)throw new sh("All input Tensors (x) should have the same number of samples. Got array shapes: "+JSON.stringify(t.map(function(t){return t.shape})));if(i.length>1)throw new sh("All target Tensors (y) should have the same number of samples. Got array shapes: "+JSON.stringify(e.map(function(t){return t.shape})));if(r.length>0&&i.length>0&&!$.arraysEqual(r,i))throw new sh("Input Tensors should have the same number of samples as target Tensors. Found "+r[0]+" input sample(s) and "+i[0]+" target sample(s).")}(t=Nm(t,this.feedInputNames,this.feedInputShapes,!1,"input"),e=Nm(e,this.feedOutputNames,i,!1,"target")),function(t,e,n){for(var r=[kd,Dd,Rd],i=0;i<t.length;++i){var a=t[i],o=e[i],s=n[i];if(null!=o){if(o===Rd&&1===a.shape[a.shape.length-1])throw new sh("You are passing a target array of shape "+a.shape+" while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].");if(-1!==r.indexOf(o))for(var u=a.shape.slice(1),l=s.slice(1),c=0;c<u.length;++c){var p=u[c],h=l[c];if(null!=h&&p!==h)throw new sh("A target Tensor with shape "+a.shape+" was passed for an output of shape "+s+", while using a loss function that expects targets to have the same shape as the output.")}}}}(e,this.feedLossFns,this.feedOutputShapes),this.stateful&&null!=r&&r>0&&t[0].shape[0]%r!=0)throw new sh("In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size "+r+". Found: "+t[0].shape[0]+" sample(s).");return[t,e]},e.prototype.standardizeUserData=function(t,e,n,r,i,a){return void 0===i&&(i=!0),nh(this,void 0,void 0,function(){var o,s,u,l,c,p,h,f;return rh(this,function(d){switch(d.label){case 0:if(o=this.standardizeUserDataXY(t,e,i,a),s=o[0],u=o[1],null!=n)throw new Error("sample weight is not supported yet.");if(l=null,null==r)return[3,4];c=om(r,this.outputNames),l=[],p=0,d.label=1;case 1:return p<c.length?(f=(h=l).push,[4,sm(u[p],null,c[p])]):[3,4];case 2:f.apply(h,[d.sent()]),d.label=3;case 3:return++p,[3,1];case 4:return[2,[s,u,l]]}})})},e.prototype.testLoop=function(t,e,n,r,i){var a=this;return void 0===r&&(r=0),_e(function(){var o=a.checkNumSamples(e,n,i,"steps"),s=[];if(r>0)throw new uh("Verbose mode is not implemented yet.");if(null!=i)throw new uh("steps mode in testLoop() is not implemented yet");for(var u=vm(o,n),l=on(af(0,o)),c=0;c<u.length;++c){var p=u[c][0],h=u[c][1],f=uf(l,p,h-p),d=gm(e,f),m=t(d);if(0===c)for(var g=0;g<m.length;++g)s.push(an(0));for(g=0;g<m.length;++g){var v=m[g];s[g]=$s(s[g],su(h-p,v))}}for(g=0;g<s.length;++g)s[g]=Zs(s[g],o);return s})},e.prototype.getDedupedMetricsNames=function(){for(var t=this.metricsNames,e=[],n=0;n<t.length;++n){var r=t[n],i=r;hh(t,r)>1&&(i+="_"+hh(t.slice(0,n),r)),e.push(i)}return e},e.prototype.makeTrainFunction=function(){var t=this;return function(e){var n=[],r=e.slice(0,t.inputs.length),i=e.slice(t.inputs.length,t.inputs.length+t.outputs.length),a=e.slice(t.inputs.length+t.outputs.length,t.inputs.length+2*t.outputs.length),o=[],s=t.collectedTrainableWeights.map(function(t){return t.read()});return[t.optimizer_.minimize(function(){for(var e=[],s=0;s<t.inputs.length;++s)e.push({key:t.inputs[s],value:r[s]});var u,l=new tm(e),c=rm(t.outputs,l,{training:!0});for(s=0;s<t.lossFunctions.length;++s){var p=(0,t.lossFunctions[s])(i[s],c[s]);null!=a[s]&&(p=um(p,a[s]));var h=bl(p);n.push(h),u=0===s?p:$s(u,p)}for(s=0;s<t.metricsTensors.length;++s){var f=void 0;if(t.outputs.length>1&&s<t.outputs.length)f=n[s];else{var d=t.metricsTensors[s][0],m=t.metricsTensors[s][1];f=bl(d(i[m],c[m]))}ze(f),o.push(f)}return u=bl(u),t.calculateLosses().forEach(function(t){u=$s(u,t)}),u},!0,s)].concat(o)}},e.prototype.makeTestFunction=function(){var t=this;this.testFunction=function(e){return _e(function(){for(var n,r=[],i=e.slice(0,t.inputs.length),a=e.slice(t.inputs.length,t.inputs.length+t.outputs.length),o=[],s=0;s<t.inputs.length;++s)o.push({key:t.inputs[s],value:i[s]});var u=new tm(o),l=rm(t.outputs,u);for(s=0;s<t.lossFunctions.length;++s){var c=t.lossFunctions[s],p=bl(c(a[s],l[s]));n=0===s?p:$s(n,p),r.push(n)}for(s=0;s<t.metricsTensors.length;++s){var h=t.metricsTensors[s][0],f=t.metricsTensors[s][1],d=bl(h(a[f],l[f]));r.push(d)}return r})}},e.prototype.fit=function(t,e,n){return void 0===n&&(n={}),nh(this,void 0,void 0,function(){return rh(this,function(r){return[2,ym(this,t,e,n)]})})},e.prototype.fitDataset=function(t,e){return nh(this,void 0,void 0,function(){return rh(this,function(n){return[2,hm(this,t,e)]})})},e.prototype.trainOnBatch=function(t,e){return nh(this,void 0,void 0,function(){var n,r,i,a,o,s,u,l,c;return rh(this,function(p){switch(p.label){case 0:return[4,this.standardizeUserData(t,e)];case 1:n=p.sent(),r=n[0],i=n[1],a=this.makeTrainFunction(),o=a(r.concat(i)),s=[],u=0,l=o,p.label=2;case 2:return u<l.length?[4,l[u].data()]:[3,5];case 3:c=p.sent(),s.push(c[0]),p.label=4;case 4:return u++,[3,2];case 5:return Fe(o),[2,fh(s)]}})})},e.prototype.getNamedWeights=function(t){for(var e=[],n=null!=t&&t.trainableOnly,r=n?this.trainableWeights:this.weights,i=this.getWeights(n),a=0;a<r.length;++a)n&&!r[a].trainable||e.push({name:r[a].originalName,tensor:i[a]});return e},Object.defineProperty(e.prototype,"stopTraining",{get:function(){return this.stopTraining_},set:function(t){this.stopTraining_=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"optimizer",{get:function(){return this.optimizer_},set:function(t){this.optimizer_!==t&&(this.optimizer_=t,this.isOptimizerOwned=!1)},enumerable:!0,configurable:!0}),e.prototype.dispose=function(){var e=t.prototype.dispose.call(this);if(0===e.refCountAfterDispose&&null!=this.optimizer&&this.isOptimizerOwned){var n=Oe().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=n-Oe().numTensors}return e},e.prototype.getLossIdentifiers=function(){var t;if("string"==typeof this.loss)t=mh(this.loss);else if(Array.isArray(this.loss)){for(var e=0,n=this.loss;e<n.length;e++)if("string"!=typeof n[e])throw new Error("Serialization of non-string loss is not supported.");t=this.loss.map(function(t){return mh(t)})}else{var r=Object.keys(this.loss);t={};for(var i=this.loss,a=0,o=r;a<o.length;a++){var s=o[a];if("string"!=typeof i[s])throw new Error("Serialization of non-string loss is not supported.");t[s]=mh(i[s])}}return t},e.prototype.getMetricIdentifiers=function(){if("string"==typeof this.metrics||"function"==typeof this.metrics)return[mh(qd(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(function(t){return mh(qd(t))});var t={};for(var e in this.metrics)t[e]=mh(qd(this.metrics[e]));return t},e.prototype.getTrainingConfig=function(){return{loss:this.getLossIdentifiers(),metrics:this.getMetricIdentifiers(),optimizer_config:{class_name:this.optimizer.getClassName(),config:this.optimizer.getConfig()}}},e.prototype.loadTrainingConfig=function(t){if(null!=t.weighted_metrics)throw new Error("Loading weight_metrics is not supported yet.");if(null!=t.loss_weights)throw new Error("Loading loss_weights is not supported yet.");if(null!=t.sample_weight_mode)throw new Error("Loading sample_weight_mode is not supported yet.");var e,n,r=Ed(Qd(t.optimizer_config));if("string"==typeof t.loss)e=gh(t.loss);else if(Array.isArray(t.loss))e=t.loss.map(function(t){return gh(t)});else if(null!=t.loss)for(var i in e={},t.loss)e[i]=gh(t.loss[i]);if(Array.isArray(t.metrics))n=t.metrics.map(function(t){return gh(t)});else if(null!=t.metrics)for(var i in n={},t.metrics)n[i]=gh(t.metrics[i]);this.compile({loss:e,metrics:n,optimizer:r})},e.prototype.save=function(t,e){return nh(this,void 0,void 0,function(){var n,r,i,a,o,s,u,l,c,p,h,f,d,m;return rh(this,function(g){switch(g.label){case 0:if("string"==typeof t){if(0===(n=Ep.getSaveHandlers(t)).length)throw new sh("Cannot find any save handlers for URL '"+t+"'");if(n.length>1)throw new sh("Found more than one ("+n.length+") save handlers for URL '"+t+"'");t=n[0]}if(null==t.save)throw new sh("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return[4,Ep.encodeWeights(this.getNamedWeights(e))];case 1:return r=g.sent(),i=!1,a=null,o=this.toJSON(a,i),s={modelTopology:o,format:"layers-model",generatedBy:"TensorFlow.js tfjs-layers v1.2.11",convertedBy:null},null!=e&&e.includeOptimizer&&null!=this.optimizer?(s.trainingConfig=this.getTrainingConfig(),u="optimizer",f=(h=Ep).encodeWeights,[4,this.optimizer.getWeights()]):[3,4];case 2:return[4,f.apply(h,[g.sent(),u])];case 3:l=g.sent(),c=l.data,p=l.specs,(m=r.specs).push.apply(m,p),r.data=Ep.concatenateArrayBuffers([r.data,c]),g.label=4;case 4:return null!=this.userDefinedMetadata&&(d=!0,Kd(this.userDefinedMetadata,this.name,d),s.userDefinedMetadata=this.userDefinedMetadata),s.weightData=r.data,s.weightSpecs=r.specs,[2,t.save(s)]}})})},e.prototype.setUserDefinedMetadata=function(t){Kd(t,this.name),this.userDefinedMetadata=t},e.prototype.getUserDefinedMetadata=function(){return this.userDefinedMetadata},e.className="Model",e}(function(t){function e(n){var r=t.call(this,{})||this;if(r.containerNodes=new Set,r.name=n.name,null==r.name){var i=r.getClassName().toLowerCase();r.name=$f(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],wh(r.inputs).length!==r.inputs.length)throw new sh("The list of inputs passed to the model is redundant. All inputs should only appear once. Found: "+r.inputs.map(function(t){return t.name}));wh(r.outputs).length!==r.outputs.length&&console.warn("The list of outputs passed to the model is redundant. All outputs should only appear once. Found: "+r.outputs.map(function(t){return t.name})),r.inputLayers=[],r.inputLayersNodeIndices=[],r.inputLayersTensorIndices=[],r.outputLayers=[],r.outputLayersNodeIndices=[],r.outputLayersTensorIndices=[],r.layers=[],r.internalContainerRefs=[];for(var a=0,o=r.outputs;a<o.length;a++){var s=(k=o[a]).sourceLayer,u=k.nodeIndex,l=k.tensorIndex;r.outputLayers.push(s),r.outputLayersNodeIndices.push(u),r.outputLayersTensorIndices.push(l)}for(var c=0,p=r.inputs;c<p.length;c++)s=(k=p[c]).sourceLayer,u=k.nodeIndex,l=k.tensorIndex,ph(0===u,"input layer has >1 nodes"),ph(0===l,"input layer has >1 tensors"),r.inputLayers.push(s),r.inputLayersNodeIndices.push(u),r.inputLayersTensorIndices.push(l);r.inputNames=[],r.outputNames=[],r.feedInputShapes=[],r.feedInputNames=[],r.feedOutputNames=[];for(var h=0;h<r.inputLayers.length;h++){if(!((s=r.inputLayers[h])instanceof pd))throw new TypeError("Input layers to a LayersModel must be InputLayer objects. Received inputs: "+n.inputs+". Input "+h+" (0-based) originates from layer type "+s.getClassName()+".");r.inputNames.push(s.name),r.feedInputShapes.push(s.batchInputShape),r.feedInputNames.push(s.name)}for(var f=0,d=r.outputLayers;f<d.length;f++)s=d[f],r.outputNames.push(s.name);r.internalInputShapes=r.inputs.map(function(t){return t.shape}),r.internalOutputShapes=r.outputs.map(function(t){return t.shape});for(var m={},g={},v={},y={},b={},x=[],w=function(t,n,i,a,o,s){null!=a&&null!=o&&null!=s||(a=t.sourceLayer,o=t.nodeIndex,s=t.tensorIndex);var u=a.inboundNodes[o];if(-1!==i.indexOf(u))throw new oh("The tensor "+t.name+' at layer "'+a.name+'" is part of a cycle.');if(-1===n.indexOf(u)){r.containerNodes.add(e.nodeKey(a,o)),a.id in b||(b[a.id]=Object.keys(b).length),-1===i.indexOf(u)&&i.push(u);for(var l=u.inboundLayers.length,c=0;c<l;c++){var p=u.inputTensors[c],h=u.inboundLayers[c],f=u.nodeIndices[c],d=u.tensorIndices[c];w(p,n,i,h,f,d)}for(n.push(u);i.indexOf(u)>=0;)i.splice(i.indexOf(u),1);x.push(u)}},C=[],N=[],E=0,S=r.outputs;E<S.length;E++){var k=S[E];w(k,C,N)}for(var I=0,A=x.slice().reverse();I<A.length;I++){g[(Y=A[I]).id]=Y,Y.id in m||(m[Y.id]=0);var R=m[Y.id],T=null==v[Y.outboundLayer.id]?0:v[Y.outboundLayer.id];for(R=Math.max(R,T),v[Y.outboundLayer.id]=R,y[Y.outboundLayer.id]=Y.outboundLayer,m[Y.id]=R,h=0;h<Y.inboundLayers.length;h++){var D=Y.inboundLayers[h],O=(u=Y.nodeIndices[h],D.inboundNodes[u]),_=null==m[O.id]?0:m[O.id];m[O.id]=Math.max(R+1,_),g[O.id]=O}}var F={};for(var z in m)(R=m[z])in F||(F[R]=[]),F[R].push(g[z]);var M={};for(var L in v)(R=v[L])in M||(M[R]=[]),M[R].push(y[L]);var P=Object.keys(M).map(function(t){return parseInt(t,10)}).sort(xh);r.layers=[];for(var B=0,W=P;B<W.length;B++){var V=M[R=W[B]];V.sort(function(t,e){var n=b[t.id],r=b[e.id];return n<r?-1:n>r?1:0});for(var U=0,j=V;U<j.length;U++)(s=j[U])instanceof e&&r.internalContainerRefs.push(s),r.layers.push(s)}r.layersByDepth=M,P=Object.keys(F).map(function(t){return parseInt(t,10)}).sort(xh);for(var G=r.inputs.slice(),q=[],H=0,K=P;H<K.length;H++)for(var $=0,X=F[R=K[H]];$<X.length;$++){var Y;if(null!=(s=(Y=X[$]).outboundLayer)){for(var J=0,Z=Y.inputTensors;J<Z.length;J++)if(k=Z[J],-1===G.indexOf(k))throw new oh("Graph disconnected: cannot obtain value for tensor "+k+' at layer "'+s.name+'". The following previous layers were accessed without issue: '+q);for(var Q=0,tt=Y.outputTensors;Q<tt.length;Q++)k=tt[Q],G.push(k);q.push(s.name)}}r.nodesByDepth=F;for(var et=r.layers.map(function(t){return t.name}),nt=function(t){var e=et.filter(function(e){return e===t}).length;if(1!==e)throw new oh('The name "'+t+'" is used '+e+" times in the model. All layer names should be unique. Layer names: "+JSON.stringify(et))},rt=0,it=et;rt<it.length;rt++)nt(it[rt]);return r.outboundNodes=[],r.inboundNodes=[],new sd({outboundLayer:r,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:r.inputs,outputTensors:r.outputs,inputMasks:r.inputs.map(function(t){return null}),outputMasks:r.outputs.map(function(t){return null}),inputShapes:r.inputs.map(function(t){return t.shape}),outputShapes:r.outputs.map(function(t){return t.shape})}),r.built=!0,r._refCount=1,r}return Qp(e,t),e.prototype.assertNotDisposed=function(){if(0===this._refCount)throw new Error("Container '"+this.name+"' is already disposed.")},e.prototype.dispose=function(){this.assertNotDisposed();var t={refCountAfterDispose:null,numDisposedVariables:0};if(0==--this._refCount){for(var e=0,n=this.layers;e<n.length;e++){var r=n[e];t.numDisposedVariables+=r.dispose().numDisposedVariables}for(var i=0,a=this.internalContainerRefs;i<a.length;i++){var o=a[i];t.numDisposedVariables+=o.dispose().numDisposedVariables}}return t.refCountAfterDispose=this._refCount,t},Object.defineProperty(e.prototype,"trainable",{get:function(){return this.trainable_},set:function(t){this.layers.forEach(function(e){e._trainableWeights.forEach(function(e){return e.trainable=t})}),this.trainable_=t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"trainableWeights",{get:function(){if(this._trainableWeights.length>0)throw new sh("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];for(var t=[],e=0,n=this.layers;e<n.length;e++){var r=n[e];t=t.concat(r.trainableWeights)}return t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"nonTrainableWeights",{get:function(){for(var t=[],e=0,n=this.layers;e<n.length;e++){var r=n[e];t.push.apply(t,r.nonTrainableWeights)}if(!this.trainable){for(var i=[],a=0,o=this.layers;a<o.length;a++)r=o[a],i.push.apply(i,r.trainableWeights);return i.concat(t)}return t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"weights",{get:function(){return this.trainableWeights.concat(this.nonTrainableWeights)},enumerable:!0,configurable:!0}),e.prototype.loadWeights=function(t,e){void 0===e&&(e=!0);for(var n={},r=0,i=0,a=this.layers;i<a.length;i++)for(var o=0,s=a[i].weights;o<s.length;o++){var u=s[o];if(null!=n[u.originalName])throw new sh("Duplicate weight name: "+u.originalName);n[u.originalName]=u,r++}var l=[];for(var c in t){if(null!=n[c])l.push([n[c],t[c]]);else if(e)throw new sh("Provided weight data has no target variable: "+c);delete n[c]}if(e){var p=[];for(var h in n)p.push(h);if(p.length>0)throw new sh(p.length+" of "+r+" weights are not set: "+p)}rd(l)},e.prototype.updatedConfig=function(){var t=this.getConfig(),e={};return e.className=this.getClassName(),e.config=t,e.kerasVersion="tfjs-layers 1.2.11",e.backend="TensorFlow.js",e},e.prototype.toJSON=function(t,e){void 0===e&&(e=!0);var n=function t(e,n){if(null===e||void 0===e)return null;if("string"==typeof e)return mh(e);if("number"==typeof e||"boolean"==typeof e)return e;if(e instanceof Array){for(var r=[],i=e.length,a=0;a<i;++a){var o=e[a];Zd(n,a,o)?r.push(o):r.push(t(o,n))}return r}for(var s={},u=0,l=Object.keys(e);u<l.length;u++){var c=l[u],p=e[c];s[mh(c)]="name"!==c&&"className"!==c||"string"!=typeof p?t(p,c):p}return s}(this.updatedConfig());return e?JSON.stringify(n):n},e.prototype.call=function(t,e){var n=this;return _e(function(){t=dh(t);for(var r=new tm,i=0;i<n.inputs.length;++i)r.add(n.inputs[i],t[i]);return rm(n.outputs,r,e)})},e.prototype.computeMask=function(t,e){var n=this;return _e(function(){var r;return t=dh(t),r=null==e?ch(null,t.length):dh(e),n.runInternalGraph(t,r)[1]})},e.prototype.computeOutputShape=function(t){var e=Yf(t);if(e.length!==this.inputLayers.length)throw new sh("Invalid inputShape argument "+t+": model has "+this.inputLayers.length+" tensor inputs.");for(var n={},r=0;r<e.length;r++){var i=this.inputLayers[r],a=e[r];n[N=i.name+"_0_0"]=a}var o=Object.keys(this.nodesByDepth).map(function(t){return parseInt(t,10)}).sort(xh);if(o.length>1)for(var s=0,u=o;s<u.length;s++)for(var l=u[s],c=0,p=this.nodesByDepth[l];c<p.length;c++){var h=p[c];if(i=h.outboundLayer,-1===this.inputLayers.map(function(t){return t.id}).indexOf(i.id)){for(var f=[],d=0;d<h.inboundLayers.length;d++){var m=h.inboundLayers[d],g=h.nodeIndices[d],v=h.tensorIndices[d],y=n[N=m.name+"_"+g+"_"+v];f.push(y)}var b=Yf(i.computeOutputShape(fh(f))),x=i.inboundNodes.indexOf(h);for(d=0;d<b.length;d++)n[N=i.name+"_"+x+"_"+d]=b[d]}}var w=[],C=[];for(r=0;r<this.outputLayers.length;r++){i=this.outputLayers[r],x=this.outputLayersNodeIndices[r],v=this.outputLayersTensorIndices[r];var N=i.name+"_"+x+"_"+v;C.push(N)}for(r=0;r<C.length;r++){var E=C[r];ph(E in n),w.push(n[E])}return fh(w)},e.prototype.runInternalGraph=function(t,e){null==e&&(e=ch(null,t.length));for(var n={},r=0;r<this.inputs.length;++r){var i=this.inputs[r],a=t[r],o=e[r];n[i.id]=[a,o]}for(var s=0,u=Object.keys(this.nodesByDepth).map(function(t){return parseInt(t,10)}).sort(xh);s<u.length;s++)for(var l=u[s],c=0,p=this.nodesByDepth[l];c<p.length;c++){for(var h=p[c],f=h.outboundLayer,d=h.inputTensors,m=h.outputTensors,g=new Array,v=0,y=d;v<y.length;v++)(i=y[v]).id in n&&g.push(n[i.id]);if(g.length===d.length){var b={},x=void 0,w=void 0,C=void 0,N=void 0;if(null!=h.callArgs&&(b=h.callArgs),1===g.length){var E=g[0],S=E[0],k=E[1];null==b.mask&&(b.mask=k),C=dh(f.call(S,b)),N=dh(f.computeMask(S,k)),x=[S],w=[k]}else x=g.map(function(t){return t[0]}),w=g.map(function(t){return t[1]}),null==b.mask&&(b.mask=w),C=dh(f.call(x,b)),N=dh(f.computeMask(x,w));if(f.activityRegularizer)throw new uh("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(r=0;r<m.length;++r)i=m[r],a=C[r],o=N[r],n[i.id]=[a,o]}}for(var I=[],A=[],R=[],T=0,D=this.outputs;T<D.length;T++){ph((i=D[T]).id in n,"Could not compute output "+i.name+" : "+i.id);var O=n[i.id],_=O[0];o=O[1],R.push(_.shape),I.push(_),A.push(o)}return[I,A,R]},e.prototype.buildNodeConversionMap=function(t){for(var n,r={},i=0,a=this.layers;i<a.length;i++){var o=a[i];n=o instanceof e?1:0;for(var s=0;s<o.inboundNodes.length;s++){var u=e.nodeKey(o,s);this.containerNodes.has(u)&&(r[u]=n,n+=1)}}return r},e.prototype.getLayer=function(t,e){if(null!=e){if(this.layers.length<=e)throw new sh("Was asked to retrieve layer at index "+e+", but model only has "+this.layers.length+" layer(s).");return this.layers[e]}if(null==t)throw new sh("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===t)return i}throw new sh("No such layer: "+t)},e.prototype.calculateLosses=function(){var t=this;return _e(function(){for(var n=[],r=0,i=t.layers;r<i.length;r++)for(var a=i[r],o=0;o<a.inboundNodes.length;++o){var s=e.nodeKey(a,o);t.containerNodes.has(s)&&n.push.apply(n,a.calculateLosses())}return n})},e.prototype.getConfig=function(){for(var t={name:this.name},n=this.buildNodeConversionMap(this.layers),r=[],i=0,a=this.layers;i<a.length;i++){for(var o=(x=a[i]).getClassName(),s=x.getConfig(),u=[],l=0;l<x.inboundNodes.length;l++){var c=x.inboundNodes[l],p=e.nodeKey(x,l),h={};if(this.containerNodes.has(p)){if(c.callArgs)try{JSON.stringify(c.callArgs),h=c.callArgs}catch(t){console.warn("Layer "+x.name+" was passed non-serializable keyword arguments: "+c.callArgs+". They will not be included in the serialized model (and thus will be missing at deserialization time)."),h={}}if(c.inboundLayers.length>0){for(var f=[],d=0;d<c.inboundLayers.length;d++){var m=c.inboundLayers[d],g=c.nodeIndices[d],v=c.tensorIndices[d];null==(C=n[e.nodeKey(m,g)])&&(C=0),f.push([m.name,C,v,h])}u.push(f)}}}var y={};y.name=x.name,y.className=o,y.config=s,y.inboundNodes=u,r.push(y)}t.layers=r;var b=[];for(d=0;d<this.inputLayers.length;d++){var x=this.inputLayers[d];g=this.inputLayersNodeIndices[d],p=e.nodeKey(x,g),this.containerNodes.has(p)&&(null!==(C=n[p])&&void 0!==C||(C=0),v=this.inputLayersTensorIndices[d],b.push([x.name,C,v]))}t.inputLayers=b;var w=[];for(d=0;d<this.outputLayers.length;d++){var C;if(x=this.outputLayers[d],g=this.outputLayersNodeIndices[d],p=e.nodeKey(x,g),this.containerNodes.has(p))null!==(C=n[p])&&void 0!==C||(C=0),v=this.outputLayersTensorIndices[d],w.push([x.name,C,v])}return t.outputLayers=w,t},e.fromConfig=function(t,e,n,r){void 0===n&&(n={}),void 0===r&&(r=!1);var i={},a={};function o(t,e){t.name in a?a[t.name].push(e):a[t.name]=[e]}function s(t,e){for(var n,r=[],a=0,s=e;a<s.length;a++){var u=s[a],l=u[0],c=u[1],p=u[2];if(n=null==u[3]?{}:u[3],!(l in i))return void o(t,e);var h=i[l];if(h.inboundNodes.length<=c)return void o(t,e);var f=h.inboundNodes[c];r.push(f.outputTensors[p])}r.length>0&&t.apply(fh(r),n)}function u(t){var n=t.name,a=Ed(t,null!=e.customObjects?e.customObjects:{});a.setFastWeightInitDuringBuild(r),i[n]=a,t.inboundNodes.forEach(function(t){if(!(t instanceof Array))throw new sh("Corrupted configuration, expected array for nodeData: "+t);o(a,t)})}for(var l=e.name,c=e.layers,p=0,h=c;p<h.length;p++)u(m=h[p]);for(;!Ch(a);)for(var f=0,d=c;f<d.length;f++){var m=d[f];if((R=i[m.name]).name in a){var g=a[R.name];delete a[R.name];for(var v=0,y=g;v<y.length;v++)s(R,y[v])}}for(var b=[],x=[],w=0,C=e.inputLayers;w<C.length;w++){var N=(m=C[w])[0],E=m[1],S=m[2];ph(N in i);var k=(R=i[N]).inboundNodes[E].outputTensors;b.push(k[S])}for(var I=0,A=e.outputLayers;I<A.length;I++){var R;N=(m=A[I])[0],E=m[1],S=m[2],ph(N in i),k=(R=i[N]).inboundNodes[E].outputTensors,x.push(k[S])}return new t({inputs:b,outputs:x,name:l})},Object.defineProperty(e.prototype,"stateful",{get:function(){if(this._stateful)throw new sh("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(var t=0,e=this.layers;t<e.length;t++)if(e[t].stateful)return!0;return!1},enumerable:!0,configurable:!0}),e.prototype.resetStates=function(){var t=this;_e(function(){t.layers.forEach(function(t){t.stateful&&t.resetStates()})})},e}(ld));function km(t,e){return nh(this,void 0,void 0,function(){var n;return rh(this,function(r){if(null==e&&(e={}),"string"==typeof t){if(0===(n=Ep.getLoadHandlers(t,e.onProgress)).length)n.push(Ep.browserHTTPRequest(t,e));else if(n.length>1)throw new sh("Found more than one ("+n.length+") load handlers for URL '"+t+"'");t=n[0]}return[2,function(t,e,n){return nh(this,void 0,void 0,function(){var r,i,a,o,s,u,l,c,p;return rh(this,function(h){switch(h.label){case 0:if(null==n&&(n={}),null==t.load)throw new sh("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");return[4,t.load()];case 1:if(r=h.sent(),null!=(i=r.modelTopology).model_config&&(i=i.model_config),a=null==n.strict||n.strict,o=null!=r.weightData&&null!=r.weightSpecs&&a,s=Ed(Qd(i),e,o),null!=(u=r.trainingConfig)&&s.loadTrainingConfig(u),null!=r.userDefinedMetadata&&s.setUserDefinedMetadata(r.userDefinedMetadata),null==r.weightData)return[3,4];if(null==r.weightSpecs)throw new sh("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");return l=function(t,e){var n=Ep.decodeWeights(t,e),r={},i=[];return e.forEach(function(t){"optimizer"===t.group?i.push({name:t.name,tensor:n[t.name]}):r[t.name]=n[t.name]}),{modelWeights:r,optimizerWeights:i}}(r.weightData,r.weightSpecs),c=l.modelWeights,p=l.optimizerWeights,s.loadWeights(c,a),null!=s.optimizer&&p.length>0?[4,s.optimizer.setWeights(p)]:[3,3];case 2:h.sent(),h.label=3;case 3:Fe(c),Fe(p.map(function(t){return t.tensor})),h.label=4;case 4:return[2,s]}})})}(t,void 0,e)]})})}Op.registerClass(Sm);var Im=function(t){function e(e){var n=t.call(this,{inputs:[],outputs:[]})||this;if(e=e||{},n.trainable=!0,n.built=!1,n.name=null!=e.name?e.name:$f("sequential_"),null!=e.layers)for(var r=0,i=e.layers;r<i.length;r++){var a=i[r];n.add(a)}return n}return Qp(e,t),e.prototype.checkShape=function(t){if(t.inboundNodes[0].outputTensors[0].shape.some(function(t){return t<0}))throw new sh("Negative dimension size caused by adding layer "+t.name+" with input shape ["+t.inboundNodes[0].inputTensors[0].shape+"]")},e.prototype.add=function(t){var n,r=t instanceof e||t instanceof Sm;if(r){if(1!==(n=t).outputs.length)throw new sh("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 sh("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(0===this.outputs.length){if(0===t.inboundNodes.length){if(null==t.batchInputShape)throw new sh("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");var i=hd({batchShape:t.batchInputShape,dtype:t.dtype,name:t.name+"_input"});t.apply(i)}if(r)this.outputs=n.outputs,this.inputs=n.inputs;else{if(1!==t.inboundNodes.length)throw new sh("A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer "+t.name+" which has "+t.inboundNodes.length+" pre-existing inbound connections.");if(1!==t.inboundNodes[0].outputTensors.length)throw new sh("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(t),this.outputs=[t.inboundNodes[0].outputTensors[0]],this.inputs=function t(e,n,r){if((null==n||null!=r&&r>0)&&(n=e.sourceLayer,r=e.nodeIndex),0===n.inboundNodes.length)return[e];var i=n.inboundNodes[r];if(0===i.inboundLayers.length)return i.inputTensors;for(var a=[],o=0;o<i.inboundLayers.length;o++)for(var s=0,u=t(i.inputTensors[o],i.inboundLayers[o],i.nodeIndices[o]);s<u.length;s++){var l=u[s];-1===a.indexOf(l)&&a.push(l)}return a}(this.outputs[0])}this.inboundNodes=[],new sd({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:ch(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(function(t){return t.shape}),outputShapes:this.outputs[0].shape})}else{var a=t.apply(this.outputs[0]);if(Array.isArray(a))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(t),this.outputs=[a],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(t),this.built=!1},e.prototype.pop=function(){if(0===this.layers.length)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),0===this.layers.length)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{var t=this.layers.length-1;this.layers[t].outboundNodes=[],this.outputs=[this.layers[t].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}},e.prototype.call=function(t,e){return null==this.model&&this.build(),this.model.call(t,e)},e.prototype.build=function(t){if(Zf(t),0===this.inputs.length||0===this.outputs.length)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new Sm({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0},e.prototype.countParams=function(){return this.built||this.build(),t.prototype.countParams.call(this)},e.prototype.summary=function(e,n,r){void 0===r&&(r=console.log),this.built||this.build(),t.prototype.summary.call(this,e,n,r)},e.prototype.setWeights=function(t){null==this.model&&this.build(),this.model.setWeights(t)},e.prototype.evaluate=function(t,e,n){if(void 0===n&&(n={}),!this.built)throw new oh("The model needs to be compiled before being used.");return this.model.evaluate(t,e,n)},e.prototype.evaluateDataset=function(t,e){return nh(this,void 0,void 0,function(){return rh(this,function(n){if(!this.built)throw new oh("The model needs to be compiled before being used.");return[2,this.model.evaluateDataset(t,e)]})})},e.prototype.predict=function(t,e){return void 0===e&&(e={}),null==this.model&&this.build(),this.model.predict(t,e)},e.prototype.predictOnBatch=function(t){return null==this.model&&this.build(),this.model.predictOnBatch(t)},e.prototype.compile=function(t){this.build(),this.model.compile(t),this.optimizer_=this.model.optimizer,this.isOptimizerOwned=this.model.isOptimizerOwned,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames},Object.defineProperty(e.prototype,"optimizer",{get:function(){return null==this.model?void 0:this.model.optimizer},set:function(t){this.model.optimizer=t},enumerable:!0,configurable:!0}),e.prototype.fit=function(t,e,n){return void 0===n&&(n={}),nh(this,void 0,void 0,function(){return rh(this,function(r){if(!this.built)throw new oh("The model needs to be compiled before being used.");return[2,this.model.fit(t,e,n)]})})},e.prototype.fitDataset=function(t,e){return nh(this,void 0,void 0,function(){return rh(this,function(n){if(!this.built)throw new oh("The model needs to be compiled before being used.");return[2,this.model.fitDataset(t,e)]})})},e.prototype.trainOnBatch=function(t,e){return nh(this,void 0,void 0,function(){return rh(this,function(n){return[2,this.model.trainOnBatch(t,e)]})})},e.fromConfig=function(t,n,r,i){var a;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 sh("Legacy serialization format not supported yet.");a=n}else $.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=n.layers,delete n.layers,o=n;var s=new t(o);if(!(s instanceof e))throw new uh("Sequential.fromConfig called on non-Sequential input: "+s);for(var u=0,l=a;u<l.length;u++){var c=Ed(l[u],void 0,i);i&&c.setFastWeightInitDuringBuild(!0),s.add(c)}return s},Object.defineProperty(e.prototype,"stopTraining",{get:function(){if(null==this.model)throw new sh("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining},set:function(t){if(null==this.model)throw new sh("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=t},enumerable:!0,configurable:!0}),e.prototype.getConfig=function(){for(var t=[],e=0,n=this.layers;e<n.length;e++){var r=n[e],i={};i.className=r.getClassName(),i.config=r.getConfig(),t.push(i)}return t},e.className="Sequential",e}(Sm);function Am(t){return hd(t)}Op.registerClass(Im);var Rm=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Qp(e,t),e.prototype.getConfig=function(){return{}},e}(Op.Serializable),Tm=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Qp(e,t),e.prototype.apply=function(t,e){return void 0===e&&(e=1),function(t,e){if(void 0===e&&(e=1),1!==e)throw new uh("Support for alpha values other than 1 ("+e+") is not implemented yet.");return El(t)}(t,e)},e.className="elu",e}(Rm);Op.registerClass(Tm);var Dm=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Qp(e,t),e.prototype.apply=function(t){return Rl(t)},e.className="selu",e}(Rm);Op.registerClass(Dm);var Om=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Qp(e,t),e.prototype.apply=function(t){return Il(t)},e.className="relu",e}(Rm);Op.registerClass(Om);var _m=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Qp(e,t),e.prototype.apply=function(t){return _e(function(){return ru(6,Il(t))})},e.className="relu6",e}(Rm);Op.registerClass(_m);var Fm=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Qp(e,t),e.prototype.apply=function(t){return t},e.className="linear",e}(Rm);Op.registerClass(Fm);var zm=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Qp(e,t),e.prototype.apply=function(t){return ms(t)},e.className="sigmoid",e}(Rm);Op.registerClass(zm);var Mm=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Qp(e,t),e.prototype.apply=function(t){return function(t){return _e(function(){var e=$s(.5,su(.2,t));return es(e,0,1)})}(t)},e.className="hardSigmoid",e}(Rm);Op.registerClass(Mm);var Lm=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Qp(e,t),e.prototype.apply=function(t){return Cs(t)},e.className="softplus",e}(Rm);Op.registerClass(Lm);var Pm=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Qp(e,t),e.prototype.apply=function(t){return function(t){return _e(function(){return Zs(t,Ko(t).add(1))})}(t)},e.className="softsign",e}(Rm);Op.registerClass(Pm);var Bm=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Qp(e,t),e.prototype.apply=function(t){return Is(t)},e.className="tanh",e}(Rm);Op.registerClass(Bm);var Wm=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Qp(e,t),e.prototype.apply=function(t,e){return void 0===e&&(e=-1),Rr(t,e)},e.className="softmax",e}(Rm);Op.registerClass(Wm);var Vm=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Qp(e,t),e.prototype.apply=function(t,e){return void 0===e&&(e=-1),Tr(t,e)},e.className="logSoftmax",e}(Rm);function Um(t){return t.getClassName()}function jm(t,e){return void 0===e&&(e={}),bh(t,Op.SerializationMap.getMap().classNameMap,e,"activation")}function Gm(t){var e;return null==t?jm(e={className:"linear",config:{}}):"string"==typeof t?((e={}).className=t,e.config={},jm(e)):t instanceof Rm?t:jm(t)}function qm(t){if(null!=t&&"object"!=typeof t)throw new Error("Argument to L1L2 regularizer's constructor is expected to be an object, but received: "+t)}Op.registerClass(Vm);var Hm=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Qp(e,t),e}(Op.Serializable),Km=function(t){function e(e){var n=t.call(this)||this;return qm(e),n.l1=null==e||null==e.l1?.01:e.l1,n.l2=null==e||null==e.l2?.01:e.l2,n.hasL1=0!==n.l1,n.hasL2=0!==n.l2,n}return Qp(e,t),e.prototype.apply=function(t){var e=this;return _e(function(){var n=fn([1]);return e.hasL1&&(n=$s(n,Cl(su(e.l1,Ko(t))))),e.hasL2&&(n=$s(n,Cl(su(e.l2,vf(t))))),n.asScalar()})},e.prototype.getConfig=function(){return{l1:this.l1,l2:this.l2}},e.fromConfig=function(t,e){return new t({l1:e.l1,l2:e.l2})},e.className="L1L2",e}(Hm);Op.registerClass(Km);var $m={l1l2:"L1L2"};function Xm(t){return yh(t)}function Ym(t,e){return void 0===e&&(e={}),bh(t,Op.SerializationMap.getMap().classNameMap,e,"regularizer")}function Jm(t){return null==t?null:"string"==typeof t?Ym({className:t in $m?$m[t]:t,config:{}}):t instanceof Hm?t:Ym(t)}var Zm=function(t){function e(e){var n=t.call(this,null==e?{}:e)||this;return n.supportsMasking=!0,null!=e&&(n.maxValue=e.maxValue),n}return Qp(e,t),e.prototype.call=function(t,e){t=Jf(t);var n=Il(t);return null!=this.maxValue&&(n=es(n,0,this.maxValue)),n},e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e={maxValue:this.maxValue},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="ReLU",e}(ld);Op.registerClass(Zm);var Qm=function(t){function e(e){var n=t.call(this,null==e?{}:e)||this;return n.DEFAULT_ALPHA=.3,null==e&&(e={}),n.alpha=null==e.alpha?n.DEFAULT_ALPHA:e.alpha,n}return Qp(e,t),e.prototype.call=function(t,e){var n=Jf(t);return Sl(n,this.alpha)},e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e={alpha:this.alpha},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="LeakyReLU",e}(ld);Op.registerClass(Qm);var tg=function(t){function e(e){var n=t.call(this,null==e?{}:e)||this;if(n.DEFAULT_ALPHA_INITIALIZER="zeros",null==e&&(e={}),n.supportsMasking=!0,n.alphaInitializer=jf(e.alphaInitializer||n.DEFAULT_ALPHA_INITIALIZER),n.alphaRegularizer=Jm(e.alphaRegularizer),n.alphaConstraint=Mh(e.alphaConstraint),null==e.sharedAxes)n.sharedAxes=null;else if(Array.isArray(e.sharedAxes))n.sharedAxes=e.sharedAxes;else{if("number"!=typeof e.sharedAxes)throw new sh("Expected sharedAxes to be a number or an array of numbers, but got "+e.sharedAxes);n.sharedAxes=[e.sharedAxes]}return n}return Qp(e,t),e.prototype.build=function(t){var e=(t=Zf(t)).slice(1);if(null!=this.sharedAxes)for(var n=0,r=this.sharedAxes;n<r.length;n++)e[(a=r[n])-1]=1;this.alpha=this.addWeight("alpha",e,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);var i={};if(null!=this.sharedAxes)for(var a=1;a<t.length;++a)i[a]=t[a];this.inputSpec=[new id({ndim:t.length,axes:i})],this.built=!0},e.prototype.call=function(t,e){return t=Jf(t),kl(t,this.alpha.read())},e.prototype.getConfig=function(){var e={alphaInitializer:Uf(this.alphaInitializer),alphaRegularizer:Xm(this.alphaRegularizer),alphaConstraint:Fh(this.alphaConstraint),sharedAxes:this.sharedAxes},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="PReLU",e}(ld);Op.registerClass(tg);var eg=function(t){function e(e){var n=t.call(this,null==e?{}:e)||this;if(n.DEFAULT_ALPHA=1,null==e&&(e={}),null!=e.alpha&&e.alpha!==n.DEFAULT_ALPHA)throw new uh("Non-default alpha value ("+e.alpha+") is not supported by the ELU layer yet.");return n.alpha=null==e.alpha?n.DEFAULT_ALPHA:e.alpha,n}return Qp(e,t),e.prototype.call=function(t,e){var n=Jf(t);return El(n)},e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e={alpha:this.alpha},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="ELU",e}(ld);Op.registerClass(eg);var ng=function(t){function e(e){var n=t.call(this,null==e?{}:e)||this;return n.DEFAULT_THETA=1,null==e&&(e={}),n.theta=null==e.theta?n.DEFAULT_THETA:e.theta,n}return Qp(e,t),e.prototype.call=function(t,e){var n=Jf(t);return n.mul(of(n.greater(this.theta),"float32"))},e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e={theta:this.theta},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="ThresholdedReLU",e}(ld);Op.registerClass(ng);var rg=function(t){function e(e){var n=t.call(this,null==e?{}:e)||this;return n.DEFAULT_AXIS=1,null==e&&(e={}),n.softmax=(new Wm).apply,n.axis=null==e.axis?n.DEFAULT_AXIS:e.axis,n}return Qp(e,t),e.prototype.call=function(t,e){var n=Jf(t);return this.softmax(n,this.axis)},e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e={axis:this.axis},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="Softmax",e}(ld);function ig(t,e,n){if("number"==typeof t)return ch(t,e);if(t.length!==e)throw new sh("The "+n+" argument must be an integer or tuple of "+e+" integers. Received: "+t.length+" elements.");for(var r=0;r<e;++r){var i=t[r];if(!Qh(i))throw new sh("The "+n+" argument must be an integer or tuple of "+e+" integers. Received: "+JSON.stringify(t)+" including a non-integer number "+i)}return t}function ag(t,e,n,r,i){return void 0===i&&(i=1),null==t?t:(a="same"===n?t:t-(e+(e-1)*(i-1))+1,Math.floor((a+r-1)/r));var a}function og(t,e,n,r){if(null==t)return null;if("valid"===r)t=t*e+rf([n-e,0]);else{if("same"!==r)throw new sh("Unsupport padding mode: "+r+".");t*=e}return t}function sg(t,e){return _e(function(){return jh(e),"channelsFirst"===e?Tl(t,[0,2,3,1]):t})}function ug(t,e){return _e(function(){return jh(e),"channelsFirst"===e?Tl(t,[0,2,3,4,1]):t})}function lg(t,e,n,r,i,a,o,s){return void 0===r&&(r=[1,1]),void 0===i&&(i="valid"),void 0===s&&(s=null),_e(function(){if(null==a&&(a="channelsLast"),jh(a),3!==t.rank&&4!==t.rank)throw new sh("conv2dWithBiasActivation expects input to be of rank 3 or 4, but received "+t.rank+".");if(3!==e.rank&&4!==e.rank)throw new sh("conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received "+t.rank+".");var u=sg(t,a);if("causal"===i)throw new uh("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return u=Ec.conv2d({x:u,filter:e,strides:r,pad:"same"===i?"same":"valid",dilations:o,dataFormat:"NHWC",bias:n,activation:s}),"channelsFirst"===a&&(u=Tl(u,[0,3,1,2])),u})}Op.registerClass(rg);var cg=function(t){function e(n,r){var i=t.call(this,r)||this;if(i.bias=null,i.DEFAULT_KERNEL_INITIALIZER="glorotNormal",i.DEFAULT_BIAS_INITIALIZER="zeros",e.verifyArgs(r),i.rank=n,Sh(i.rank,"rank"),1!==i.rank&&2!==i.rank&&3!==i.rank)throw new uh("Convolution layer for rank other than 1, 2, or 3 ("+i.rank+") is not implemented yet.");if(i.kernelSize=ig(r.kernelSize,n,"kernelSize"),i.strides=ig(null==r.strides?1:r.strides,n,"strides"),i.padding=null==r.padding?"valid":r.padding,Gh(i.padding),i.dataFormat=null==r.dataFormat?"channelsLast":r.dataFormat,jh(i.dataFormat),i.activation=Gm(r.activation),i.useBias=null==r.useBias||r.useBias,i.biasInitializer=jf(r.biasInitializer||i.DEFAULT_BIAS_INITIALIZER),i.biasConstraint=Mh(r.biasConstraint),i.biasRegularizer=Jm(r.biasRegularizer),i.activityRegularizer=Jm(r.activityRegularizer),i.dilationRate=ig(null==r.dilationRate?1:r.dilationRate,n,"dilationRate"),1===i.rank&&Array.isArray(i.dilationRate)&&1!==i.dilationRate.length)throw new sh("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 sh("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 sh("dilationRate must be a number or array of three numbers for 3D convolution, but received "+JSON.stringify(i.dilationRate));return i}return Qp(e,t),e.verifyArgs=function(t){if(ph("kernelSize"in t,"required key 'kernelSize' not in config"),"number"!=typeof t.kernelSize&&!Eh(t.kernelSize,"number",1,3))throw new sh("BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received "+JSON.stringify(t.kernelSize)+".")},e.prototype.getConfig=function(){var e={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:Um(this.activation),useBias:this.useBias,biasInitializer:Uf(this.biasInitializer),biasRegularizer:Xm(this.biasRegularizer),activityRegularizer:Xm(this.activityRegularizer),biasConstraint:Fh(this.biasConstraint)},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e}(ld),pg=function(t){function e(n,r){var i=t.call(this,n,r)||this;return i.kernel=null,e.verifyArgs(r),i.filters=r.filters,Sh(i.filters,"filters"),i.kernelInitializer=jf(r.kernelInitializer||i.DEFAULT_KERNEL_INITIALIZER),i.kernelConstraint=Mh(r.kernelConstraint),i.kernelRegularizer=Jm(r.kernelRegularizer),i}return Qp(e,t),e.prototype.build=function(t){var e;t=Zf(t);var n="channelsFirst"===this.dataFormat?1:t.length-1;if(null==t[n])throw new sh("The channel dimension of the input should be defined. Found "+t[n]);var r=t[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:(e={},e[n]=r,e)}],this.built=!0},e.prototype.call=function(t,e){var n=this;return _e(function(){var e;t=Jf(t);var r=null==n.bias?null:n.bias.read(),i=kh(n.activation.getClassName());if(null!=i&&2===n.rank)e=lg(t,n.kernel.read(),r,n.strides,n.padding,n.dataFormat,n.dilationRate,i);else{if(1===n.rank)e=function(t,e,n,r,i,a,o){return void 0===r&&(r=1),void 0===i&&(i="valid"),void 0===o&&(o=1),_e(function(){if(null==a&&(a="channelsLast"),jh(a),3!==t.shape.length)throw new sh("The input of a conv1dWithBias operation should be 3, but is "+t.shape.length+" instead.");if(3!==e.shape.length)throw new sh("The kernel for a conv1dWithBias operation should be 3, but is "+e.shape.length+" instead");if(null!=n&&1!==n.shape.length)throw new sh("The bias for a conv1dWithBias operation should be 1, but is "+e.shape.length+" instead");if("channelsFirst"===a&&(t=Tl(t,[0,2,1])),"causal"===i)throw new uh("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");var s=zu(t,e,r,"same"===i?"same":"valid","NWC",o);return null!=n&&(s=bf(s,n)),s})}(t,n.kernel.read(),r,n.strides[0],n.padding,n.dataFormat,n.dilationRate[0]);else if(2===n.rank)e=lg(t,n.kernel.read(),r,n.strides,n.padding,n.dataFormat,n.dilationRate);else{if(3!==n.rank)throw new uh("convolutions greater than 3D are not implemented yet.");e=function(t,e,n,r,i,a,o){return void 0===r&&(r=[1,1,1]),void 0===i&&(i="valid"),_e(function(){if(null==a&&(a="channelsLast"),jh(a),4!==t.rank&&5!==t.rank)throw new sh("conv3dWithBias expects input to be of rank 4 or 5, but received "+t.rank+".");if(4!==e.rank&&5!==e.rank)throw new sh("conv3dWithBias expects kernel to be of rank 4 or 5, but received "+t.rank+".");var s=ug(t,a);if("causal"===i)throw new uh("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return s=Lu(s,e,r,"same"===i?"same":"valid","NDHWC",o),null!=n&&(s=bf(s,n)),"channelsFirst"===a&&(s=Tl(s,[0,4,1,2,3])),s})}(t,n.kernel.read(),r,n.strides,n.padding,n.dataFormat,n.dilationRate)}null!=n.activation&&(e=n.activation.apply(e))}return e})},e.prototype.computeOutputShape=function(t){t=Zf(t);for(var e=[],n="channelsLast"===this.dataFormat?t.slice(1,t.length-1):t.slice(2),r=0;r<n.length;++r){var i=ag(n[r],this.kernelSize[r],this.padding,this.strides[r],"number"==typeof this.dilationRate?this.dilationRate:this.dilationRate[r]);e.push(i)}var a=[t[0]];return"channelsLast"===this.dataFormat?(a=a.concat(e)).push(this.filters):(a.push(this.filters),a=a.concat(e)),a},e.prototype.getConfig=function(){var e={filters:this.filters,kernelInitializer:Uf(this.kernelInitializer),kernelRegularizer:Xm(this.kernelRegularizer),kernelConstraint:Fh(this.kernelConstraint)},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.verifyArgs=function(t){if(!("filters"in t)||"number"!=typeof t.filters||t.filters<1)throw new sh("Convolution layer expected config.filters to be a 'number' > 0 but got "+JSON.stringify(t.filters))},e}(cg),hg=function(t){function e(n){var r=t.call(this,2,n)||this;return e.verifyArgs(n),r}return Qp(e,t),e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this);return delete e.rank,e},e.verifyArgs=function(t){if("number"!=typeof t.kernelSize&&!Eh(t.kernelSize,"number",1,2))throw new sh("Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received "+JSON.stringify(t.kernelSize)+".")},e.className="Conv2D",e}(pg);Op.registerClass(hg);var fg=function(t){function e(n){var r=t.call(this,3,n)||this;return e.verifyArgs(n),r}return Qp(e,t),e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this);return delete e.rank,e},e.verifyArgs=function(t){if("number"!=typeof t.kernelSize&&(!Array.isArray(t.kernelSize)||1!==t.kernelSize.length&&3!==t.kernelSize.length))throw new sh("Conv3D expects config.kernelSize to be number or [number, number, number], but received "+JSON.stringify(t.kernelSize)+".")},e.className="Conv3D",e}(pg);Op.registerClass(fg);var dg=function(t){function e(e){var n=t.call(this,e)||this;if(n.inputSpec=[new id({ndim:4})],"same"!==n.padding&&"valid"!==n.padding)throw new sh("Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode "+n.padding);return n}return Qp(e,t),e.prototype.build=function(t){var e;if(4!==(t=Zf(t)).length)throw new sh("Input should have rank 4; Received input shape: "+JSON.stringify(t));var n="channelsFirst"===this.dataFormat?1:t.length-1;if(null==t[n])throw new sh("The channel dimension of the inputs should be defined. Found `None`.");var r=t[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 id({ndim:4,axes:(e={},e[n]=r,e)})],this.built=!0},e.prototype.call=function(t,e){var n=this;return _e(function(){var e=Jf(t);if(4!==e.shape.length)throw new sh("Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-"+e.shape.length);var r,i,a=e.shape,o=a[0];"channelsFirst"===n.dataFormat?(r=2,i=3):(r=1,i=2);var s=a[r],u=a[i],l=n.kernelSize[0],c=n.kernelSize[1],p=n.strides[0],h=n.strides[1],f=[o,og(s,p,l,n.padding),og(u,h,c,n.padding),n.filters];"channelsLast"!==n.dataFormat&&(e=Tl(e,[0,2,3,1]));var d=Gu(e,n.kernel.read(),f,n.strides,n.padding);return"channelsLast"!==n.dataFormat&&(d=Tl(d,[0,3,1,2])),null!=n.bias&&(d=bf(d,n.bias.read(),n.dataFormat)),null!=n.activation&&(d=n.activation.apply(d)),d})},e.prototype.computeOutputShape=function(t){var e,n,r,i=(t=Zf(t)).slice();"channelsFirst"===this.dataFormat?(e=1,n=2,r=3):(e=3,n=1,r=2);var a=this.kernelSize[0],o=this.kernelSize[1],s=this.strides[0],u=this.strides[1];return i[e]=this.filters,i[n]=og(i[n],s,a,this.padding),i[r]=og(i[r],u,o,this.padding),i},e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this);return delete e.dilationRate,e},e.className="Conv2DTranspose",e}(hg);Op.registerClass(dg);var mg=function(t){function e(e){return t.call(this,2,e)||this}return Qp(e,t),e.className="SeparableConv2D",e}(function(t){function e(e,n){var r=t.call(this,e,n)||this;if(r.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",r.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",r.depthwiseKernel=null,r.pointwiseKernel=null,null==n.filters)throw new sh("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=n.kernelInitializer||null!=n.kernelRegularizer||null!=n.kernelConstraint)throw new sh("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 sh("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=jf(n.depthwiseInitializer||r.DEFAULT_DEPTHWISE_INITIALIZER),r.depthwiseRegularizer=Jm(n.depthwiseRegularizer),r.depthwiseConstraint=Mh(n.depthwiseConstraint),r.pointwiseInitializer=jf(n.depthwiseInitializer||r.DEFAULT_POINTWISE_INITIALIZER),r.pointwiseRegularizer=Jm(n.pointwiseRegularizer),r.pointwiseConstraint=Mh(n.pointwiseConstraint),r}return Qp(e,t),e.prototype.build=function(t){var e;if((t=Zf(t)).length<this.rank+2)throw new sh("Inputs to SeparableConv"+this.rank+"D should have rank "+(this.rank+2)+", but received input shape: "+JSON.stringify(t));var n="channelsFirst"===this.dataFormat?1:t.length-1;if(null==t[n]||t[n]<0)throw new sh("The channel dimension of the inputs should be defined, but found "+JSON.stringify(t[n]));for(var r=t[n],i=this.kernelSize.concat([r,this.depthMultiplier]),a=[],o=0;o<this.rank;++o)a.push(1);a.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,"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 id({ndim:this.rank+2,axes:(e={},e[n]=r,e)})],this.built=!0},e.prototype.call=function(t,e){var n=this;return _e(function(){var e;if(t=Jf(t),1===n.rank)throw new uh("1D separable convolution is not implemented yet.");return 2===n.rank&&("channelsFirst"===n.dataFormat&&(t=Tl(t,[0,2,3,1])),e=ju(t,n.depthwiseKernel.read(),n.pointwiseKernel.read(),n.strides,n.padding,n.dilationRate,"NHWC")),n.useBias&&(e=bf(e,n.bias.read(),n.dataFormat)),null!=n.activation&&(e=n.activation.apply(e)),"channelsFirst"===n.dataFormat&&(e=Tl(e,[0,3,1,2])),e})},e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this);return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=Uf(this.depthwiseInitializer),e.pointwiseInitializer=Uf(this.pointwiseInitializer),e.depthwiseRegularizer=Xm(this.depthwiseRegularizer),e.pointwiseRegularizer=Xm(this.pointwiseRegularizer),e.depthwiseConstraint=Fh(this.depthwiseConstraint),e.pointwiseConstraint=Fh(this.pointwiseConstraint),e},e.className="SeparableConv",e}(pg));Op.registerClass(mg);var gg=function(t){function e(n){var r=t.call(this,1,n)||this;return e.verifyArgs(n),r.inputSpec=[{ndim:3}],r}return Qp(e,t),e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this);return delete e.rank,delete e.dataFormat,e},e.verifyArgs=function(t){if("number"!=typeof t.kernelSize&&!Eh(t.kernelSize,"number",1,1))throw new sh("Conv1D expects config.kernelSize to be number or number[] with length 1, but received "+JSON.stringify(t.kernelSize)+".")},e.className="Conv1D",e}(pg);Op.registerClass(gg);var vg=function(t){function e(e){var n=t.call(this,e)||this;return"number"==typeof e.cropping?n.cropping=[[e.cropping,e.cropping],[e.cropping,e.cropping]]:"number"==typeof e.cropping[0]?n.cropping=[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:n.cropping=e.cropping,n.dataFormat=void 0===e.dataFormat?"channelsLast":e.dataFormat,n.inputSpec=[{ndim:4}],n}return Qp(e,t),e.prototype.computeOutputShape=function(t){return"channelsFirst"===this.dataFormat?[t[0],t[1],t[2]-this.cropping[0][0]-this.cropping[0][1],t[3]-this.cropping[1][0]-this.cropping[1][1]]:[t[0],t[1]-this.cropping[0][0]-this.cropping[0][1],t[2]-this.cropping[1][0]-this.cropping[1][1],t[3]]},e.prototype.call=function(t,e){var n=this;return _e(function(){return t=Jf(t),"channelsLast"===n.dataFormat?cf(cf(t,n.cropping[0][0],t.shape[1]-n.cropping[0][0]-n.cropping[0][1],2),n.cropping[1][0],t.shape[2]-n.cropping[1][1]-n.cropping[1][0],3):cf(cf(t,n.cropping[0][0],t.shape[2]-n.cropping[0][0]-n.cropping[0][1],3),n.cropping[1][0],t.shape[3]-n.cropping[1][1]-n.cropping[1][0],4)})},e.prototype.getConfig=function(){var e={cropping:this.cropping,dataFormat:this.dataFormat},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="Cropping2D",e}(ld);Op.registerClass(vg);var yg=function(t){function e(e){var n=t.call(this,e)||this;return n.DEFAULT_SIZE=[2,2],n.inputSpec=[{ndim:4}],n.size=null==e.size?n.DEFAULT_SIZE:e.size,n.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,n}return Qp(e,t),e.prototype.computeOutputShape=function(t){if("channelsFirst"===this.dataFormat){var e=null==t[2]?null:this.size[0]*t[2],n=null==t[3]?null:this.size[1]*t[3];return[t[0],t[1],e,n]}return e=null==t[1]?null:this.size[0]*t[1],n=null==t[2]?null:this.size[1]*t[2],[t[0],e,n,t[3]]},e.prototype.call=function(t,e){var n=this;return _e(function(){var e=Jf(t),r=e.shape;if("channelsFirst"===n.dataFormat){e=Tl(e,[0,2,3,1]);var i=n.size[0]*r[2],a=n.size[1]*r[3],o=e.resizeNearestNeighbor([i,a]);return Tl(o,[0,3,1,2])}return i=n.size[0]*r[1],a=n.size[1]*r[2],e.resizeNearestNeighbor([i,a])})},e.prototype.getConfig=function(){var e={size:this.size,dataFormat:this.dataFormat},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="UpSampling2D",e}(ld);Op.registerClass(yg);var bg=function(t){function e(e){var n=t.call(this,2,e)||this;return n.depthwiseKernel=null,n.depthMultiplier=null==e.depthMultiplier?1:e.depthMultiplier,n.depthwiseInitializer=jf(e.depthwiseInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.depthwiseConstraint=Mh(e.depthwiseConstraint),n.depthwiseRegularizer=Jm(e.depthwiseRegularizer),n}return Qp(e,t),e.prototype.build=function(t){if((t=Zf(t)).length<4)throw new sh("Inputs to DepthwiseConv2D should have rank 4. Received input shape: "+JSON.stringify(t)+".");var e="channelsFirst"===this.dataFormat?1:3;if(null==t[e]||t[e]<0)throw new sh("The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not ("+t[e]+").");var n=t[e],r=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",r,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[n*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0},e.prototype.call=function(t,e){var n=this;return _e(function(){var e=function(t,e,n,r,i,a){return void 0===n&&(n=[1,1]),void 0===r&&(r="valid"),_e(function(){null==i&&(i="channelsLast"),jh(i);var o=sg(t,i);if(4!==t.rank)throw new sh("Input for depthwiseConv2d is required to be 4-D, but is instead "+t.rank+"-D");if(4!==e.rank)throw new sh("depthwiseKernel is required to be 4-D, but is instead "+e.rank+"-D");return o=Wu(o,e,n,"same"===r?"same":"valid","NHWC",a),"channelsFirst"===i&&(o=Tl(o,[0,3,1,2])),o})}(t=Jf(t),n.depthwiseKernel.read(),n.strides,n.padding,n.dataFormat,null);return n.useBias&&(e=bf(e,n.bias.read(),n.dataFormat)),null!=n.activation&&(e=n.activation.apply(e)),e})},e.prototype.computeOutputShape=function(t){t=Zf(t);var e="channelsFirst"===this.dataFormat?t[2]:t[1],n="channelsFirst"===this.dataFormat?t[3]:t[2],r="channelsFirst"===this.dataFormat?t[1]*this.depthMultiplier:t[3]*this.depthMultiplier,i=ag(e,this.kernelSize[0],this.padding,this.strides[0]),a=ag(n,this.kernelSize[1],this.padding,this.strides[1]);return"channelsFirst"===this.dataFormat?[t[0],r,i,a]:[t[0],i,a,r]},e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this);return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=Uf(this.depthwiseInitializer),e.depthwiseRegularizer=Xm(this.depthwiseRegularizer),e.depthwiseConstraint=Fh(this.depthwiseRegularizer),e},e.className="DepthwiseConv2D",e}(cg);Op.registerClass(bg);var xg=function(t){function e(e){var n=t.call(this,e)||this;return n.rate=Math.max(Math.min(e.rate,1),0),n.noiseShape=e.noiseShape,n.seed=e.seed,n.supportsMasking=!0,n}return Qp(e,t),e.prototype.getNoiseShape=function(t){if(null==this.noiseShape)return this.noiseShape;for(var e=t.shape,n=[],r=0;r<this.noiseShape.length;++r)n.push(null==this.noiseShape[r]?e[r]:this.noiseShape[r]);return n},e.prototype.call=function(t,e){var n=this;return _e(function(){n.invokeCallHook(t,e);var r=Jf(t);if(0<n.rate&&n.rate<1){var i=null!=e.training&&e.training,a=n.getNoiseShape(r);return wf(function(){return xf(r,n.rate,a,n.seed)},function(){return r},i)}return t})},e.prototype.getConfig=function(){var e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.prototype.dispose=function(){return t.prototype.dispose.call(this)},e.className="Dropout",e}(ld);Op.registerClass(xg);var wg=function(t){function e(e){var n=t.call(this,e)||this;if(n.activation=null,n.useBias=!0,n.kernel=null,n.bias=null,n.DEFAULT_KERNEL_INITIALIZER="glorotNormal",n.DEFAULT_BIAS_INITIALIZER="zeros",null==e.batchInputShape&&null==e.inputShape&&null!=e.inputDim){var r=null;null!=e.batchSize&&(r=e.batchSize),n.batchInputShape=[r,e.inputDim]}return n.units=e.units,Sh(n.units,"units"),n.activation=Gm(e.activation),null!=e.useBias&&(n.useBias=e.useBias),n.kernelInitializer=jf(e.kernelInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.biasInitializer=jf(e.biasInitializer||n.DEFAULT_BIAS_INITIALIZER),n.kernelConstraint=Mh(e.kernelConstraint),n.biasConstraint=Mh(e.biasConstraint),n.kernelRegularizer=Jm(e.kernelRegularizer),n.biasRegularizer=Jm(e.biasRegularizer),n.activityRegularizer=Jm(e.activityRegularizer),n.supportsMasking=!0,n.inputSpec=[{minNDim:2}],n}return Qp(e,t),e.prototype.build=function(t){var e,n=(t=Zf(t))[t.length-1];null==this.kernel&&(this.kernel=this.addWeight("kernel",[n,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:(e={},e[-1]=n,e)}],this.built=!0},e.prototype.computeOutputShape=function(t){var e=(t=Zf(t)).slice();return e[e.length-1]=this.units,e},e.prototype.call=function(t,e){var n=this;return _e(function(){n.invokeCallHook(t,e);var r,i=Jf(t),a=kh(n.activation.getClassName());return null!=a?r=mf(i,n.kernel.read(),a,n.bias?n.bias.read():null):(r=mf(i,n.kernel.read()),null!=n.bias&&(r=bf(r,n.bias.read())),null!=n.activation&&(r=n.activation.apply(r))),r})},e.prototype.getConfig=function(){var e={units:this.units,activation:Um(this.activation),useBias:this.useBias,kernelInitializer:Uf(this.kernelInitializer),biasInitializer:Uf(this.biasInitializer),kernelRegularizer:Xm(this.kernelRegularizer),biasRegularizer:Xm(this.biasRegularizer),activityRegularizer:Xm(this.activityRegularizer),kernelConstraint:Fh(this.kernelConstraint),biasConstraint:Fh(this.biasConstraint)},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="Dense",e}(ld);Op.registerClass(wg);var Cg=function(t){function e(e){var n=t.call(this,e||{})||this;return n.inputSpec=[{minNDim:3}],n}return Qp(e,t),e.prototype.computeOutputShape=function(t){for(var e=0,n=(t=Zf(t)).slice(1);e<n.length;e++)if(null==n[e])throw new sh('The shape of the input to "Flatten" is not fully defined (got '+t.slice(1)+'). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.');return[t[0],tf(t,1)]},e.prototype.call=function(t,e){var n=this;return _e(function(){return n.invokeCallHook(t,e),function(t){if(t.rank<=1)throw new sh("batchFlatten requires a minimum rank of 2. Got rank: "+t.rank+".");var e=[t.shape[0],tf(t.shape,1)];return t.reshape(e)}(Jf(t))})},e.className="Flatten",e}(ld);Op.registerClass(Cg);var Ng=function(t){function e(e){var n=t.call(this,e)||this;return n.supportsMasking=!0,n.activation=Gm(e.activation),n}return Qp(e,t),e.prototype.call=function(t,e){var n=this;return _e(function(){n.invokeCallHook(t,e);var r=Jf(t);return n.activation.apply(r)})},e.prototype.getConfig=function(){var e={activation:Um(this.activation)},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="Activation",e}(ld);Op.registerClass(Ng);var Eg=function(t){function e(e){var n=t.call(this,e)||this;return n.n=e.n,n.inputSpec=[{ndim:2}],n}return Qp(e,t),e.prototype.computeOutputShape=function(t){return[t[0],this.n,t[1]]},e.prototype.call=function(t,e){var n=this;return _e(function(){return function(t,e){return _e(function(){if(2!==t.shape.length)throw new sh("repeat() expects a rank-2 tensor, but received a rank-"+t.shape.length+" tensor.");return ff(sf(t,1),[1,e,1])})}(t=Jf(t),n.n)})},e.prototype.getConfig=function(){var e={n:this.n},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="RepeatVector",e}(ld);Op.registerClass(Eg);var Sg=function(t){function e(e){var n=t.call(this,e)||this;n.targetShape=e.targetShape;for(var r=0;r<n.targetShape.length;++r)n.isUnknown(n.targetShape[r])&&(n.targetShape[r]=null);return n}return Qp(e,t),e.prototype.isUnknown=function(t){return t<0||null==t},e.prototype.fixUnknownDimension=function(t,e){for(var n="Total size of new array must be unchanged.",r=e.slice(),i=1,a=null,o=0;o<r.length;++o){var s=r[o];if(this.isUnknown(s)){if(null!==a)throw new sh("Can only specifiy one unknown dimension.");a=o}else i*=s}var u=tf(t);if(null!==a){if(0===i||u%i!=0)throw new sh(n);r[a]=u/i}else if(u!==i)throw new sh(n);return r},e.prototype.computeOutputShape=function(t){for(var e=!1,n=0;n<t.length;++n)if(this.isUnknown(t[n])){e=!0;break}return e?t.slice(0,1).concat(this.targetShape):t.slice(0,1).concat(this.fixUnknownDimension(t.slice(1),this.targetShape))},e.prototype.call=function(t,e){var n=this;return _e(function(){n.invokeCallHook(t,e);var r=Jf(t),i=r.shape,a=i.slice(0,1).concat(n.fixUnknownDimension(i.slice(1),n.targetShape));return r.reshape(a)})},e.prototype.getConfig=function(){var e={targetShape:this.targetShape},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="Reshape",e}(ld);Op.registerClass(Sg);var kg=function(t){function e(e){var n=t.call(this,e)||this;if(null==e.dims)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(e.dims))throw new Error("Permute constructor requires `dims` to be an Array, but received "+e.dims+" instead.");var r=af(1,e.dims.length+1);if(!$.arraysEqual(e.dims.slice().sort(),r))throw new Error("Invalid permutation `dims`: "+JSON.stringify(e.dims)+" `dims` must contain consecutive integers starting from 1.");return n.dims=e.dims,n.dimsIncludingBatch=[0].concat(n.dims),n.inputSpec=[new id({ndim:n.dims.length+1})],n}return Qp(e,t),e.prototype.computeOutputShape=function(t){var e=(t=Zf(t)).slice();return this.dims.forEach(function(n,r){e[r+1]=t[n]}),e},e.prototype.call=function(t,e){return Tl(Jf(t),this.dimsIncludingBatch)},e.prototype.getConfig=function(){var e={dims:this.dims},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="Permute",e}(ld);Op.registerClass(kg);var Ig=function(t){function e(e){var n=t.call(this,null==e?{}:e)||this;return n.supportsMasking=!0,n.maskValue=null!=e?null==e.maskValue?0:e.maskValue:0,n}return Qp(e,t),e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this),n={maskValue:this.maskValue};return Object.assign(n,e),n},e.prototype.computeMask=function(t,e){var n=Jf(t);return dl(Su(n,this.maskValue),-1)},e.prototype.call=function(t,e){var n=this;return _e(function(){n.invokeCallHook(t,e);var r=Jf(t),i=dl(Su(r,n.maskValue),-1,!0);return r.mul(i.asType(r.dtype))})},e.className="Masking",e}(ld);Op.registerClass(Ig);var Ag=function(t){function e(e){var n=t.call(this,e)||this;if(n.embeddings=null,n.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",null==e.batchInputShape&&null==e.inputShape){var r=null;null!=e.batchSize&&(r=e.batchSize),null==e.inputLength?n.batchInputShape=[r,null]:n.batchInputShape=[r].concat(dh(e.inputLength))}return n.inputDim=e.inputDim,Sh(n.inputDim,"inputDim"),n.outputDim=e.outputDim,Sh(n.outputDim,"outputDim"),n.embeddingsInitializer=jf(e.embeddingsInitializer||n.DEFAULT_EMBEDDINGS_INITIALIZER),n.embeddingsRegularizer=Jm(e.embeddingsRegularizer),n.activityRegularizer=Jm(e.activityRegularizer),n.embeddingsConstraint=Mh(e.embeddingsConstraint),n.maskZero=e.maskZero,n.supportsMasking=e.maskZero,n.inputLength=e.inputLength,n}return Qp(e,t),e.prototype.build=function(t){this.embeddings=this.addWeight("embeddings",[this.inputDim,this.outputDim],this.dtype,this.embeddingsInitializer,this.embeddingsRegularizer,!0,this.embeddingsConstraint),this.built=!0},e.prototype.warnOnIncompatibleInputShape=function(t){},e.prototype.computeMask=function(t,e){var n=this;return _e(function(){return n.maskZero?(t=Jf(t),Su(t,yn(t))):null})},e.prototype.computeOutputShape=function(t){if(t=Zf(t),null==this.inputLength)return t.concat([this.outputDim]);var e=dh(this.inputLength);if(e.length!==t.length-1)throw new sh('"inputLength" is '+this.inputLength+", but received input shape has shape "+t);for(var n=0,r=0;r<e.length;++r){var i=e[r],a=t[r+1];if(null!=i&&null!=a&&i!==a)throw new sh('"inputLength" is '+this.inputLength+", but received input shape has shape "+t);null==i&&(e[n]=a),n++}return[t[0]].concat(e,[this.outputDim])},e.prototype.call=function(t,e){var n=this;return _e(function(){n.invokeCallHook(t,e);var r=Jf(t);return"int32"!==r.dtype&&(r=of(r,"int32")),gf(n.embeddings.read(),r.as1D()).reshape(Zf(n.computeOutputShape(r.shape)))})},e.prototype.getConfig=function(){var e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:Uf(this.embeddingsInitializer),embeddingsRegularizer:Xm(this.embeddingsRegularizer),activityRegularizer:Xm(this.activityRegularizer),embeddingsConstraint:Fh(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="Embedding",e}(ld);Op.registerClass(Ag);var Rg=function(t){function e(e){var n=t.call(this,e||{})||this;return n.supportsMasking=!0,n}return Qp(e,t),e.prototype.mergeFunction=function(t){throw new uh},e.prototype.computeElementwiseOpOutputShape=function(t,e){if(null==t||null==e)return null;if(t.length<e.length)return this.computeElementwiseOpOutputShape(e,t);if(0===e.length)return t;for(var n=t.slice(0,t.length-e.length),r=0;r<e.length;++r){var i=t[t.length-e.length+r],a=e[r];if(null==i||null==a||i<0||a<0)n.push(null);else if(1===i)n.push(a);else if(1===a)n.push(i);else{if(i!==a)throw new sh("Operands could not be broadcast together with shapes "+JSON.stringify(t)+" "+JSON.stringify(e));n.push(i)}}return n},e.prototype.build=function(t){if(Array.isArray(t)&&!Array.isArray(t[0])&&(t=[Zf(t)]),(t=t).length<2)throw new sh("A merge layer should be called on an Array of at least 2 inputs. Got "+t.length+" input(s).");for(var e=[],n=0,r=t;n<r.length;n++)null!=(o=r[n])&&null!==o[0]&&e.push(o[0]);if((e=wh(e)).length>1)throw new sh("Can not merge tensors with different batch sizes. Got tensors with shapes: "+JSON.stringify(t)+".");for(var i=null==t[0]?null:t[0].slice(1),a=1;a<t.length;++a){var o=null==t[a]?null:t[a].slice(1);i=this.computeElementwiseOpOutputShape(i,o)}var s=t.map(function(t){return t.length});-1===t.indexOf(null)&&1===wh(s).length?this.reshapeRequired=!1:this.reshapeRequired=!0},e.prototype.call=function(t,e){var n=this;return _e(function(){if(t=t,n.reshapeRequired){var e=[],r=t.map(function(t){return t.rank});if(-1===r.indexOf(null)){for(var i=rf(r),a=0,o=t;a<o.length;a++){for(var s=(h=o[a]).rank,u=0;u<i-s;++u)h=sf(h,1);e.push(h)}return n.mergeFunction(e)}for(var l=!1,c=0,p=t;c<p.length;c++){var h;if(null==(s=(h=p[c]).rank)){var f=h.shape,d=f[0],m=f.slice(1).concat([d]),g=h.reshape([d].concat(tf(f.slice(1))));g=(g=Tl(g,[1,0])).reshape(m),e.push(g),l=!0}else if(s>1){var v=af(1,s).concat([0]);e.push(Tl(h,v)),l=!0}else e.push(h)}var y=n.mergeFunction(e),b=y.rank;if(l)if(null==b){var x=y.shape;m=[d=x[x.length-1]].concat(x.slice(0,x.length-1)),y=Tl(y.reshape([-1,d]),[1,0]).reshape(m)}else b>1&&(v=[b-1].concat(af(0,b-1)),y=Tl(y,v));return y}return n.mergeFunction(t)})},e.prototype.computeOutputShape=function(t){var e;e=null==(t=t)[0]?null:t[0].slice(1);for(var n=1;n<t.length;++n){var r=null==t[n]?null:t[n].slice(1);e=this.computeElementwiseOpOutputShape(e,r)}for(var i=[],a=0,o=t;a<o.length;a++)null!=(r=o[a])&&null!==r[0]&&i.push(r[0]);return 1===(i=wh(i)).length?i.concat(e):[null].concat(e)},e.prototype.computeMask=function(t,e){return _e(function(){if(null==e)return null;if(!Array.isArray(e))throw new sh("`mask` should be an Array");if(!Array.isArray(t))throw new sh("`inputs` should be an Array");if(e.length!==t.length)throw new sh("The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths ("+t.length+" vs "+e.length+")");if(e.every(function(t){return null==t}))return null;for(var n=(e=e.map(function(t){return null==t?t:Gn(t,0)}))[0],r=1;r<e.length-1;++r)n=Us(n,e[r]);return n})},e}(ld),Tg=function(t){function e(e){return t.call(this,e)||this}return Qp(e,t),e.prototype.mergeFunction=function(t){return _e(function(){for(var e=t[0].clone(),n=1;n<t.length;++n)e=$s(e,t[n]);return e})},e.className="Add",e}(Rg);Op.registerClass(Tg);var Dg=function(t){function e(e){return t.call(this,e)||this}return Qp(e,t),e.prototype.mergeFunction=function(t){return _e(function(){for(var e=t[0].clone(),n=1;n<t.length;++n)e=su(e,t[n]);return e})},e.className="Multiply",e}(Rg);Op.registerClass(Dg);var Og=function(t){function e(e){return t.call(this,e)||this}return Qp(e,t),e.prototype.mergeFunction=function(t){return _e(function(){for(var e=t[0].clone(),n=1;n<t.length;++n)e=$s(e,t[n]);return su(1/t.length,e)})},e.className="Average",e}(Rg);Op.registerClass(Og);var _g=function(t){function e(e){return t.call(this,e)||this}return Qp(e,t),e.prototype.mergeFunction=function(t){return _e(function(){for(var e=t[0],n=1;n<t.length;++n)e=eu(e,t[n]);return e})},e.className="Maximum",e}(Rg);Op.registerClass(_g);var Fg=function(t){function e(e){return t.call(this,e)||this}return Qp(e,t),e.prototype.mergeFunction=function(t){return _e(function(){for(var e=t[0],n=1;n<t.length;++n)e=ru(e,t[n]);return e})},e.className="Minimum",e}(Rg);Op.registerClass(Fg);var zg=function(t){function e(e){var n=t.call(this,e)||this;return n.DEFAULT_AXIS=-1,null==e&&(e={}),n.axis=null==e.axis?n.DEFAULT_AXIS:e.axis,n.supportsMasking=!0,n.reshapeRequired=!1,n}return Qp(e,t),e.prototype.build=function(t){if(!Array.isArray(t)||!Array.isArray(t[0])||1===t.length)throw new sh("A `Concatenate` layer should be called on a list of at least 2 inputs");for(var e=!0,n=0,r=t=t;n<r.length;n++)if(null!=(c=r[n])){e=!1;break}if(!e){for(var i=[],a=0;a<t.length;++a){var o=t[a].slice();o.splice(this.axis,1);for(var s=!1,u=0,l=i;u<l.length;u++){var c=l[u];if($.arraysEqual(c,o)){s=!0;break}}s||i.push(o)}if(i.length>1)throw new sh("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(t))}},e.prototype.mergeFunction=function(t){var e=this;return _e(function(){return pf(t,e.axis)})},e.prototype.computeOutputShape=function(t){if(!Array.isArray(t)||!Array.isArray(t[0]))throw new sh("A `Concatenate` layer should be called on a list of inputs.");for(var e=t,n=e[0].slice(),r=this.axis<0?n.length+this.axis:this.axis,i=0,a=e.slice(1);i<a.length;i++){var o=a[i];if(null==n[r]||null==o[r]){n[r]=null;break}n[r]+=o[r]}return n},e.prototype.computeMask=function(t,e){var n=this;if(null==e)return null;if(!Array.isArray(e))throw new sh("`mask` should be an array for Concatenate");if(!Array.isArray(t))throw new sh("`inputs` should be an array for Concatenate");if(e.length!==t.length)throw new sh("Mismatch in the length of mask ("+e.length+") and the legnth of inputs ("+t.length+")");return _e(function(){var r=!0;if(e.forEach(function(t){null==t||(r=!1)}),r)return null;for(var i=[],a=0;a<t.length;++a)null==e[a]?i.push(vn(t[a]).asType("bool")):e[a].rank<t[a].rank?i.push(Gn(e[a],-1)):i.push(e[a]);var o=bn(i,n.axis);return fl(o,-1,!1)})},e.prototype.getConfig=function(){var e={axis:this.axis},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="Concatenate",e}(Rg);function Mg(t,e){for(;t<0;)t+=e;return t}Op.registerClass(zg);var Lg=function(t){function e(e){var n=t.call(this,e)||this;return n.axes=e.axes,n.normalize=null!=e.normalize&&e.normalize,n.supportsMasking=!0,n.reshapeRequired=!1,n}return Qp(e,t),e.prototype.build=function(t){$.assert(Array.isArray(t)&&2===t.length&&Array.isArray(t[0])&&Array.isArray(t[1]),function(){return"A `Dot` layer should be called on a list of exactly 2 inputs."});var e=t[0],n=t[1];if(e.length>3||n.length>3)throw new uh("Dot layer does not support tensors of 4D or higher rank yet.");var r=this.interpretAxes(e,n);if(e[r[0]]!==n[r[1]])throw new sh("Dimension incompatibility: "+e[r[0]]+" !== "+n[r[1]])},e.prototype.mergeFunction=function(t){if(2!==t.length)throw new sh("A `Dot` layer must be called on exactly 2 inputs, but received "+t.length+" input(s).");var e,n=t[0],r=t[1];return e=Array.isArray(this.axes)?this.axes.map(function(e,n){return Mg(e,t[n].shape.length)}):[Mg(this.axes,n.shape.length),Mg(this.axes,r.shape.length)],this.normalize&&(n=Sd(n,e[0]),r=Sd(r,e[1])),function(t,e,n){if(t.shape.length>3||e.shape.length>3)throw new uh("batchDot is not implemented for tensors of 4D or higher rank yet");if($.assert(t.shape.length>=2,function(){return"batchDot requires the rank of x to be >= 2, but got "+t.shape.length}),$.assert(t.shape.length>=2,function(){return"batchDot requires the rank of y to be >= 2, but got "+e.shape.length}),"number"==typeof n&&(n=[n,n]),"complex64"===t.dtype||"complex64"===e.dtype)throw new uh("batchDot is not implemented for complex64-type Tensors yet.");var r=t.shape.length,i=e.shape.length;null==n&&(n=[r-1,i-2]);var a=n;return _e(function(){var n,o;if(r>i){n=r-i;for(var s=[],u=0;u<n;++u)s.push(1);e=e.reshape(e.shape.concat(s))}else if(i>r){for(n=i-r,s=[],u=0;u<n;++u)s.push(1);t=t.reshape(t.shape.concat(s))}else n=0;if(2===t.shape.length&&2===e.shape.length)o=a[0]===a[1]?t.mulStrict(e).sum(a[0]):t.transpose([1,0]).mulStrict(e).sum(a[1]);else{var l=a[0]!==t.shape.length-1,c=a[1]===e.shape.length-1;o=t.matMul(e,l,c)}if(n>0){var p,h=[];for(u=p=r>i?r+i-3:r-1;u<p+n;++u)h.push(u);o=o.squeeze(h)}return 1===o.shape.length&&(o=o.expandDims(1)),o})}(n,r,e)},e.prototype.interpretAxes=function(t,e){return Array.isArray(this.axes)?this.axes:[Mg(this.axes,t.length),Mg(this.axes,e.length)]},e.prototype.computeOutputShape=function(t){$.assert(Array.isArray(t)&&2===t.length&&Array.isArray(t[0])&&Array.isArray(t[1]),function(){return"A `Dot` layer should be called on a list of exactly 2 inputs."});var e=t[0].slice(),n=t[1].slice();if(e.length>3||n.length>3)throw new uh("Dot layer does not support tensors of 4D or higher rank yet.");var r=this.interpretAxes(e,n);e.splice(r[0],1),n.splice(r[1],1),n.splice(0,1);var i=e.concat(n);return 1===i.length&&i.push(1),i},e.prototype.computeMask=function(t,e){return null},e.prototype.getConfig=function(){var e={axes:this.axes,normalize:this.normalize},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="Dot",e}(Rg);Op.registerClass(Lg);var Pg=function(t){function e(e){var n=t.call(this,e)||this;return n.supportsMasking=!0,n.stddev=e.stddev,n}return Qp(e,t),e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this),n={stddev:this.stddev};return Object.assign(n,e),n},e.prototype.call=function(t,e){var n=this;return _e(function(){n.invokeCallHook(t,e);var r=Jf(t);return wf(function(){return df(r.shape,0,n.stddev).add(r)},function(){return r},e.training||!1)})},e.className="GaussianNoise",e}(ld);Op.registerClass(Pg);var Bg=function(t){function e(e){var n=t.call(this,e)||this;return n.supportsMasking=!0,n.rate=e.rate,n}return Qp(e,t),e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this),n={rate:this.rate};return Object.assign(n,e),n},e.prototype.call=function(t,e){var n=this;return _e(function(){n.invokeCallHook(t,e);var r=Jf(t);return n.rate>0&&n.rate<1?wf(function(){var t=Math.sqrt(n.rate/(1-n.rate));return r.mul(df(r.shape,1,t))},function(){return r},e.training||!1):r})},e.className="GaussianDropout",e}(ld);Op.registerClass(Bg);var Wg=function(t){function e(e){var n=t.call(this,e)||this;return n.supportsMasking=!0,n.rate=e.rate,n.noiseShape=e.noiseShape,n}return Qp(e,t),e.prototype._getNoiseShape=function(t){return this.noiseShape||Jf(t).shape},e.prototype.computeOutputShape=function(t){return t},e.prototype.getConfig=function(){var e=t.prototype.getConfig.call(this),n={rate:this.rate};return Object.assign(n,e),n},e.prototype.call=function(t,e){var n=this;return _e(function(){if(n.rate<1&&n.rate>0){var r=n._getNoiseShape(t);return wf(function(){var e=Jf(t),i=-1.7580993408473766,a=yu(nr(r),n.rate);a=of(a,"float32");var o=Math.pow((1-n.rate)*(1+n.rate*Math.pow(i,2)),-.5),s=-o*i*n.rate;return e.mul(a).add(a.add(-1).mul(i)).mul(o).add(s)},function(){return Jf(t)},e.training||!1)}return t})},e.className="AlphaDropout",e}(ld);function Vg(t,e,n,r,i,a){var o;if(void 0===a&&(a=.001),2===t.rank)o=Bs(t,e,n,r,i,a);else if(3===t.rank)o=Ws(t,e,n,r,i,a);else{if(4!==t.rank)throw new uh("batchNormalization is not implemented for array of rank "+t.rank+" yet");o=Vs(t,e,n,r,i,a)}return o}function Ug(t,e,n,r,i){return void 0===i&&(i=.001),$.arraysEqual(r.slice().sort(),af(0,t.rank-1))?function(t,e,n,r,i){return void 0===i&&(i=.001),_e(function(){var a=wl(t,r),o=a.mean,s=a.variance;return[Vg(t,o,s,n,e,i),o,s]})}(t,e,n,r,i):function(t,e,n,r,i){return void 0===i&&(i=.001),_e(function(){for(var a=wl(t,r),o=a.mean,s=a.variance,u=[],l=0,c=af(0,t.rank);l<c.length;l++){var p=c[l];-1!==r.indexOf(p)?u.push(1):u.push(t.shape[p])}var h=o.reshape(u),f=s.reshape(u),d=null==e?null:e.reshape(u),m=null==n?null:n.reshape(u);return[Vg(t,h,f,m,d,i),o,s]})}(t,e,n,r,i)}Op.registerClass(Wg);var jg=function(t){function e(e){var n=this;return null==e&&(e={}),(n=t.call(this,e)||this).supportsMasking=!0,n.axis=null==e.axis?-1:e.axis,n.momentum=null==e.momentum?.99:e.momentum,n.epsilon=null==e.epsilon?.001:e.epsilon,n.center=null==e.center||e.center,n.scale=null==e.scale||e.scale,n.betaInitializer=jf(e.betaInitializer||"zeros"),n.gammaInitializer=jf(e.gammaInitializer||"ones"),n.movingMeanInitializer=jf(e.movingMeanInitializer||"zeros"),n.movingVarianceInitializer=jf(e.movingVarianceInitializer||"ones"),n.betaConstraint=Mh(e.betaConstraint),n.gammaConstraint=Mh(e.gammaConstraint),n.betaRegularizer=Jm(e.betaRegularizer),n.gammaRegularizer=Jm(e.gammaRegularizer),n}return Qp(e,t),e.prototype.build=function(t){var e;t=Zf(t);var n=this.axis>=0?this.axis:this.axis+t.length,r=t[n];if(null==r)throw new sh("Axis "+n+" of input tensor should have a defined dimension but the layer received an input with shape "+JSON.stringify(t)+".");this.inputSpec=[new id({ndim:t.length,axes:(e={},e[n]=r,e)})];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},e.prototype.call=function(t,e){var n=this;return _e(function(){var r=null!=e.training&&e.training,i=Jf(t),a=i.shape,o=a.length,s=af(0,o),u=n.axis>=0?n.axis:n.axis+o;s.splice(u,1);var l=ch(1,o);l[u]=a[u];var c=s.slice();c.sort();var p=!$.arraysEqual(c,af(0,o).slice(0,o-1));if(!r)return function(){if(p){var t=n.movingMean.read().reshape(l),e=n.movingVariance.read().reshape(l),r=n.center?n.beta.read().reshape(l):null,a=n.scale?n.gamma.read().reshape(l):null;return Vg(i,t,e,r,a,n.epsilon)}return Vg(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=Ug(i,n.gamma.read(),n.beta.read(),s,n.epsilon),f=h[0],d=h[1],m=h[2],g=function(t,e,n){_e(function(){var r=1-n,i=t.read(),a=i.sub(e).mul(r);t.write(i.sub(a))})};return g(n.movingMean,d,n.momentum),g(n.movingVariance,m,n.momentum),f})},e.prototype.getConfig=function(){var e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Uf(this.betaInitializer),gammaInitializer:Uf(this.gammaInitializer),movingMeanInitializer:Uf(this.movingMeanInitializer),movingVarianceInitializer:Uf(this.movingVarianceInitializer),betaRegularizer:Xm(this.betaRegularizer),gammaRegularizer:Xm(this.gammaRegularizer),betaConstraint:Fh(this.betaConstraint),gammaConstraint:Fh(this.gammaConstraint)},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="BatchNormalization",e}(ld);Op.registerClass(jg);var Gg=function(t){function e(e){var n=this;if(null==e&&(e={}),(n=t.call(this,e)||this).axis=null==e.axis?-1:e.axis,"number"==typeof n.axis){if(!Number.isInteger(n.axis))throw new Error("Expected axis to be an integer, but received "+n.axis)}else{if(!Array.isArray(n.axis))throw new Error("Expected axis to be an integer or an array of integers, but received "+JSON.stringify(n.axis));for(var r=0,i=n.axis;r<i.length;r++){var a=i[r];if(!Number.isInteger(a))throw new Error("Expected axis to be an array of integers, but received "+JSON.stringify(n.axis))}}return n.epsilon=null==e.epsilon?.001:e.epsilon,n.center=null==e.center||e.center,n.scale=null==e.scale||e.scale,n.betaInitializer=jf(e.betaInitializer||"zeros"),n.gammaInitializer=jf(e.gammaInitializer||"ones"),n.betaRegularizer=Jm(e.betaRegularizer),n.gammaRegularizer=Jm(e.gammaRegularizer),n.supportsMasking=!0,n}return Qp(e,t),e.prototype.build=function(t){var e=(t=Zf(t)).length;"number"==typeof this.axis&&(this.axis=[this.axis]);for(var n=0;n<this.axis.length;++n)this.axis[n]<0&&(this.axis[n]+=e);for(var r=0,i=this.axis;r<i.length;r++){var a=i[r];if(a<0||a>=e)throw new Error("Invalid axis: "+a)}if(this.axis.length!==wh(this.axis).length)throw new Error("Found duplicate axes in: "+this.axis);var o=this.axis.map(function(e){return t[e]});this.scale?this.gamma=this.addWeight("gamma",o,"float32",this.gammaInitializer,this.gammaRegularizer,!0):this.gamma=null,this.center?this.beta=this.addWeight("beta",o,"float32",this.betaInitializer,this.betaRegularizer,!0):this.beta=null,this.built=!0},e.prototype.call=function(t,e){var n=this,r=Jf(t),i=r.shape,a=i.length;return _e(function(){for(var t=wl(r,n.axis,!0),e=t.mean,o=t.variance,s=ch(1,a),u=0,l=n.axis;u<l.length;u++){var c=l[u];s[c]=i[c]}for(var p=function(t){return null!=t&&t.shape.length!==a&&n.axis!==[a-1]?t.reshape(s):t},h=p(n.gamma.read()),f=p(n.beta.read()),d=[],m=[],g=0;g<a;++g)-1!==n.axis.indexOf(g)?(d.push(i[g]),m.push(1)):(d.push(1),m.push(i[g]));return e=e.tile(d),o=o.tile(d),h=h.tile(m),f=f.tile(m),Vg(r,e,o,f,h,n.epsilon)})},e.prototype.getConfig=function(){var e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Uf(this.betaInitializer),gammaInitializer:Uf(this.gammaInitializer),betaRegularizer:Xm(this.betaRegularizer),gammaRegularizer:Xm(this.gammaRegularizer)},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="BatchNormalization",e}(ld);Op.registerClass(Gg);var qg=function(t){function e(e){var n=this;if(null==e&&(e={}),(n=t.call(this,e)||this).dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,null==e.padding)n.padding=[[1,1],[1,1]];else if("number"==typeof e.padding)n.padding=[[e.padding,e.padding],[e.padding,e.padding]];else{if(e.padding=e.padding,2!==e.padding.length)throw new sh("ZeroPadding2D expects padding to be a length-2 array, but received a length-"+e.padding.length+" array.");var r=void 0,i=void 0;if("number"==typeof e.padding[0])r=[e.padding[0],e.padding[0]],i=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,2!==e.padding[0].length)throw new sh("ZeroPadding2D expects height padding to be a length-2 array, but received a length-"+e.padding[0].length+" array.");if(r=e.padding[0],2!==e.padding[1].length)throw new sh("ZeroPadding2D expects width padding to be a length-2 array, but received a length-"+e.padding[1].length+" array.");i=e.padding[1]}n.padding=[r,i]}return n.inputSpec=[new id({ndim:4})],n}return Qp(e,t),e.prototype.computeOutputShape=function(t){var e,n;return t=Zf(t),"channelsFirst"===this.dataFormat?(e=null!=t[2]&&t[2]>=0?t[2]+this.padding[0][0]+this.padding[0][1]:null,n=null!=t[3]&&t[3]>=0?t[3]+this.padding[1][0]+this.padding[1][1]:null,[t[0],t[1],e,n]):(e=null!=t[1]&&t[1]>=0?t[1]+this.padding[0][0]+this.padding[0][1]:null,n=null!=t[2]&&t[2]>=0?t[2]+this.padding[1][0]+this.padding[1][1]:null,[t[0],e,n,t[3]])},e.prototype.call=function(t,e){var n=this;return _e(function(){return function(t,e,n){return _e(function(){if(4!==t.rank)throw new sh("temporalPadding expects input tensor to be 4-D, but received a "+t.rank+"-D tensor.");if(null==e&&(e=[[1,1],[1,1]]),2!==e.length||2!==e[0].length||2!==e[1].length)throw new sh("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(null==n&&(n="channelsLast"),"channelsLast"!==n&&"channelsFirst"!==n)throw new sh("Unknown data format: "+n+". Supported data formats are 'channelsLast' and 'channelsFirst.");var r;return r="channelsFirst"===n?[[0,0],[0,0],e[0],e[1]]:[[0,0],e[0],e[1],[0,0]],$n(t,r)})}(Jf(t),n.padding,n.dataFormat)})},e.prototype.getConfig=function(){var e={padding:this.padding,dataFormat:this.dataFormat},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="ZeroPadding2D",e}(ld);function Hg(t,e,n,r,i,a){return _e(function(){var o;jh(i),qh(a),Gh(r),null==n&&(n=[1,1]),null==r&&(r="valid"),null==i&&(i="channelsLast"),null==a&&(a="max"),t=sg(t,i);var s="same"===r?"same":"valid";return o="max"===a?nl(t,e,n,s):rl(t,e,n,s),"channelsFirst"===i&&(o=Tl(o,[0,3,1,2])),o})}function Kg(t,e,n,r,i,a){return _e(function(){var o;jh(i),qh(a),Gh(r),null==n&&(n=[1,1,1]),null==r&&(r="valid"),null==i&&(i="channelsLast"),null==a&&(a="max"),t=ug(t,i);var s="same"===r?"same":"valid";return o="max"===a?al(t,e,n,s):ol(t,e,n,s),"channelsFirst"===i&&(o=Tl(o,[0,4,1,2,3])),o})}Op.registerClass(qg);var $g=function(t){function e(e){var n=this;if(null==e.poolSize&&(e.poolSize=2),n=t.call(this,e)||this,"number"==typeof e.poolSize)n.poolSize=[e.poolSize];else{if(!Array.isArray(e.poolSize)||1!==e.poolSize.length||"number"!=typeof e.poolSize[0])throw new sh("poolSize for 1D convolutional layer must be a number or an Array of a single number, but received "+JSON.stringify(e.poolSize));n.poolSize=e.poolSize}if(Sh(n.poolSize,"poolSize"),null==e.strides)n.strides=n.poolSize;else if("number"==typeof e.strides)n.strides=[e.strides];else{if(!Array.isArray(e.strides)||1!==e.strides.length||"number"!=typeof e.strides[0])throw new sh("strides for 1D convolutional layer must be a number or an Array of a single number, but received "+JSON.stringify(e.strides));n.strides=e.strides}return Sh(n.strides,"strides"),n.padding=null==e.padding?"valid":e.padding,Gh(n.padding),n.inputSpec=[new id({ndim:3})],n}return Qp(e,t),e.prototype.computeOutputShape=function(t){var e=ag((t=Zf(t))[1],this.poolSize[0],this.padding,this.strides[0]);return[t[0],e,t[2]]},e.prototype.call=function(t,e){var n=this;return _e(function(){n.invokeCallHook(t,e),t=sf(Jf(t),2);var r=n.poolingFunction(Jf(t),[n.poolSize[0],1],[n.strides[0],1],n.padding,"channelsLast");return ar(r,[2])})},e.prototype.getConfig=function(){var e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e}(ld),Xg=function(t){function e(e){return t.call(this,e)||this}return Qp(e,t),e.prototype.poolingFunction=function(t,e,n,r,i){return jh(i),Gh(r),Hg(t,e,n,r,i,"max")},e.className="MaxPooling1D",e}($g);Op.registerClass(Xg);var Yg=function(t){function e(e){return t.call(this,e)||this}return Qp(e,t),e.prototype.poolingFunction=function(t,e,n,r,i){return jh(i),Gh(r),Hg(t,e,n,r,i,"avg")},e.className="AveragePooling1D",e}($g);Op.registerClass(Yg);var Jg=function(t){function e(e){var n=this;if(null==e.poolSize&&(e.poolSize=[2,2]),(n=t.call(this,e)||this).poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],null==e.strides)n.strides=n.poolSize;else if(Array.isArray(e.strides)){if(2!==e.strides.length)throw new sh("If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length "+e.strides.length+".");n.strides=e.strides}else n.strides=[e.strides,e.strides];return Sh(n.poolSize,"poolSize"),Sh(n.strides,"strides"),n.padding=null==e.padding?"valid":e.padding,n.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,jh(n.dataFormat),Gh(n.padding),n.inputSpec=[new id({ndim:4})],n}return Qp(e,t),e.prototype.computeOutputShape=function(t){t=Zf(t);var e="channelsFirst"===this.dataFormat?t[2]:t[1],n="channelsFirst"===this.dataFormat?t[3]:t[2];return e=ag(e,this.poolSize[0],this.padding,this.strides[0]),n=ag(n,this.poolSize[1],this.padding,this.strides[1]),"channelsFirst"===this.dataFormat?[t[0],t[1],e,n]:[t[0],e,n,t[3]]},e.prototype.call=function(t,e){var n=this;return _e(function(){return n.invokeCallHook(t,e),n.poolingFunction(Jf(t),n.poolSize,n.strides,n.padding,n.dataFormat)})},e.prototype.getConfig=function(){var e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e}(ld),Zg=function(t){function e(e){return t.call(this,e)||this}return Qp(e,t),e.prototype.poolingFunction=function(t,e,n,r,i){return jh(i),Gh(r),Hg(t,e,n,r,i,"max")},e.className="MaxPooling2D",e}(Jg);Op.registerClass(Zg);var Qg=function(t){function e(e){return t.call(this,e)||this}return Qp(e,t),e.prototype.poolingFunction=function(t,e,n,r,i){return jh(i),Gh(r),Hg(t,e,n,r,i,"avg")},e.className="AveragePooling2D",e}(Jg);Op.registerClass(Qg);var tv=function(t){function e(e){var n=this;if(null==e.poolSize&&(e.poolSize=[2,2,2]),(n=t.call(this,e)||this).poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],null==e.strides)n.strides=n.poolSize;else if(Array.isArray(e.strides)){if(3!==e.strides.length)throw new sh("If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length "+e.strides.length+".");n.strides=e.strides}else n.strides=[e.strides,e.strides,e.strides];return Sh(n.poolSize,"poolSize"),Sh(n.strides,"strides"),n.padding=null==e.padding?"valid":e.padding,n.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,jh(n.dataFormat),Gh(n.padding),n.inputSpec=[new id({ndim:5})],n}return Qp(e,t),e.prototype.computeOutputShape=function(t){t=Zf(t);var e="channelsFirst"===this.dataFormat?t[2]:t[1],n="channelsFirst"===this.dataFormat?t[3]:t[2],r="channelsFirst"===this.dataFormat?t[4]:t[3];return e=ag(e,this.poolSize[0],this.padding,this.strides[0]),n=ag(n,this.poolSize[1],this.padding,this.strides[1]),r=ag(r,this.poolSize[2],this.padding,this.strides[2]),"channelsFirst"===this.dataFormat?[t[0],t[1],e,n,r]:[t[0],e,n,r,t[4]]},e.prototype.call=function(t,e){var n=this;return _e(function(){return n.invokeCallHook(t,e),n.poolingFunction(Jf(t),n.poolSize,n.strides,n.padding,n.dataFormat)})},e.prototype.getConfig=function(){var e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e}(ld),ev=function(t){function e(e){return t.call(this,e)||this}return Qp(e,t),e.prototype.poolingFunction=function(t,e,n,r,i){return jh(i),Gh(r),Kg(t,e,n,r,i,"max")},e.className="MaxPooling3D",e}(tv);Op.registerClass(ev);var nv=function(t){function e(e){return t.call(this,e)||this}return Qp(e,t),e.prototype.poolingFunction=function(t,e,n,r,i){return jh(i),Gh(r),Kg(t,e,n,r,i,"avg")},e.className="AveragePooling3D",e}(tv);Op.registerClass(nv);var rv=function(t){function e(e){var n=t.call(this,e)||this;return n.inputSpec=[new id({ndim:3})],n}return Qp(e,t),e.prototype.computeOutputShape=function(t){return[t[0],t[2]]},e.prototype.call=function(t,e){throw new uh},e}(ld),iv=function(t){function e(e){return t.call(this,e||{})||this}return Qp(e,t),e.prototype.call=function(t,e){return _e(function(){var e=Jf(t);return bl(e,1)})},e.className="GlobalAveragePooling1D",e}(rv);Op.registerClass(iv);var av=function(t){function e(e){return t.call(this,e||{})||this}return Qp(e,t),e.prototype.call=function(t,e){return _e(function(){var e=Jf(t);return yl(e,1)})},e.className="GlobalMaxPooling1D",e}(rv);Op.registerClass(av);var ov=function(t){function e(e){var n=t.call(this,e)||this;return n.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,jh(n.dataFormat),n.inputSpec=[new id({ndim:4})],n}return Qp(e,t),e.prototype.computeOutputShape=function(t){return t=t,"channelsLast"===this.dataFormat?[t[0],t[3]]:[t[0],t[1]]},e.prototype.call=function(t,e){throw new uh},e.prototype.getConfig=function(){var e={dataFormat:this.dataFormat},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e}(ld),sv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Qp(e,t),e.prototype.call=function(t,e){var n=this;return _e(function(){var e=Jf(t);return"channelsLast"===n.dataFormat?bl(e,[1,2]):bl(e,[2,3])})},e.className="GlobalAveragePooling2D",e}(ov);Op.registerClass(sv);var uv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Qp(e,t),e.prototype.call=function(t,e){var n=this;return _e(function(){var e=Jf(t);return"channelsLast"===n.dataFormat?yl(e,[1,2]):yl(e,[2,3])})},e.className="GlobalMaxPooling2D",e}(ov);function lv(t,e,n,r){if(Array.isArray(t)){if(null!=e||null!=n)throw new sh("When inputs is an array, neither initialState or constants should be provided");null!=r&&(n=t.slice(t.length-r,t.length),t=t.slice(0,t.length-r)),t.length>1&&(e=t.slice(1,t.length)),t=t[0]}function i(t){return null==t||Array.isArray(t)?t:[t]}return{inputs:t,initialState:e=i(e),constants:n=i(n)}}function cv(t,e,n,r,i,a,o,s){return void 0===r&&(r=!1),void 0===o&&(o=!1),void 0===s&&(s=!1),_e(function(){var u=e.shape.length;if(u<3)throw new sh("Input should be at least 3D, but is "+u+"D.");var l=[1,0].concat(af(2,u));if(e=Tl(e,l),null!=a)throw new uh("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===u-1&&(i=Gn(i,-1)),i=Tl(i,l)),r&&(e=Xu(e,0),null!=i&&(i=Xu(i,0)));var c,p,h=[],f=n,d=e.shape[0],m=lr(e);null!=i&&(p=lr(i));for(var g,v=function(e){var n=m[e],r=_e(function(){return t(n,f)});if(null==i)c=r[0],f=r[1];else{var a=_e(function(){var t=p[e],n=vn(t).sub(t);return{output:r[0].mul(t).addStrict(f[0].mul(n)),newStates:f.map(function(e,i){return r[1][i].mul(t).addStrict(e.mul(n))})}});c=a.output,f=a.newStates}s&&h.push(c)},y=0;y<d;++y)v(y);return s&&(g=or(h,1)),[c,g,f]})}Op.registerClass(uv);var pv=function(t){function e(e){var n,r=t.call(this,e)||this;if(null==e.cell)throw new sh("cell property is missing for the constructor of RNN.");if(null==(n=Array.isArray(e.cell)?new bv({cells:e.cell}):e.cell).stateSize)throw new sh("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");return r.cell=n,r.returnSequences=null!=e.returnSequences&&e.returnSequences,r.returnState=null!=e.returnState&&e.returnState,r.goBackwards=null!=e.goBackwards&&e.goBackwards,r._stateful=null!=e.stateful&&e.stateful,r.unroll=null!=e.unroll&&e.unroll,r.supportsMasking=!0,r.inputSpec=[new id({ndim:3})],r.stateSpec=null,r.states_=null,r.numConstants=null,r.keptStates=[],r}return Qp(e,t),e.prototype.getStates=function(){return null==this.states_?af(0,Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1).map(function(t){return null}):this.states_},e.prototype.setStates=function(t){this.states_=t},e.prototype.computeOutputShape=function(t){Xf(t)&&(t=t[0]),t=t;var e=this.cell.stateSize;Array.isArray(e)||(e=[e]);var n,r=e[0];if(n=this.returnSequences?[t[0],t[1],r]:[t[0],r],this.returnState){for(var i=[],a=0,o=e;a<o.length;a++){var s=o[a];i.push([t[0],s])}return[n].concat(i)}return n},e.prototype.computeMask=function(t,e){var n=this;return _e(function(){Array.isArray(e)&&(e=e[0]);var t=n.returnSequences?e:null;if(n.returnState){var r=n.states.map(function(t){return null});return[t].concat(r)}return t})},Object.defineProperty(e.prototype,"states",{get:function(){if(null==this.states_){for(var t=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,e=[],n=0;n<t;++n)e.push(null);return e}return this.states_},set:function(t){this.states_=t},enumerable:!0,configurable:!0}),e.prototype.build=function(t){if(null!=this.numConstants)throw new uh("Constants support is not implemented in RNN yet.");Xf(t)&&(t=t[0]),t=t;var e=this.stateful?t[0]:null,n=t[t.length-1];this.inputSpec[0]=new id({shape:[e,null,n]});var r,i=[t[0]].concat(t.slice(2));if(this.cell.build(i),r=Array.isArray(this.cell.stateSize)?this.cell.stateSize:[this.cell.stateSize],null!=this.stateSpec){if(!$.arraysEqual(this.stateSpec.map(function(t){return t.shape[t.shape.length-1]}),r))throw new sh("An initialState was passed that is not compatible with cell.stateSize. Received stateSpec="+this.stateSpec+"; However cell.stateSize is "+this.cell.stateSize)}else this.stateSpec=r.map(function(t){return new id({shape:[null,t]})});this.stateful&&this.resetStates()},e.prototype.resetStates=function(t,e){var n=this;void 0===e&&(e=!1),_e(function(){if(!n.stateful)throw new ah("Cannot call resetStates() on an RNN Layer that is not stateful.");var r=n.inputSpec[0].shape[0];if(null==r)throw new sh("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(null==n.states_)Array.isArray(n.cell.stateSize)?n.states_=n.cell.stateSize.map(function(t){return fn([r,t])}):n.states_=[fn([r,n.cell.stateSize])];else if(null==t)Fe(n.states_),null!=n.keptStates&&(Fe(n.keptStates),n.keptStates=[]),Array.isArray(n.cell.stateSize)?n.states_=n.cell.stateSize.map(function(t){return fn([r,t])}):n.states_[0]=fn([r,n.cell.stateSize]);else{if(Array.isArray(t)||(t=[t]),t.length!==n.states_.length)throw new sh("Layer "+n.name+" expects "+n.states_.length+" state(s), but it received "+t.length+" state value(s). Input received: "+t);!0===e?n.keptStates.push(n.states_.slice()):Fe(n.states_);for(var i=0;i<n.states_.length;++i){var a=t[i],o=Array.isArray(n.cell.stateSize)?n.cell.stateSize[i]:n.cell.stateSize,s=[r,o];if(!$.arraysEqual(a.shape,s))throw new sh("State "+i+" is incompatible with layer "+n.name+": expected shape="+s+", received shape="+a.shape);n.states_[i]=a}}n.states_=n.states_.map(function(t){return ze(t.clone())})})},e.prototype.apply=function(e,n){var r=null==n?null:n.initialState,i=null==n?null:n.constants;null==n&&(n={});var a=lv(e,r,i,this.numConstants);e=a.inputs,r=a.initialState,i=a.constants;var o=[],s=[];if(null!=r){n.initialState=r,o=o.concat(r),this.stateSpec=[];for(var u=0,l=r;u<l.length;u++){var c=l[u];this.stateSpec.push(new id({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 ad){var p=[e].concat(o),h=this.inputSpec.concat(s),f=this.inputSpec;this.inputSpec=h;var d=t.prototype.apply.call(this,p,n);return this.inputSpec=f,d}return t.prototype.apply.call(this,e,n)},e.prototype.call=function(t,e){var n=this;return _e(function(){var r=null==e?null:e.mask,i=null==e?null:e.training,a=null==e?null:e.initialState;t=Jf(t),null==a&&(a=n.stateful?n.states_:n.getInitialState(t));var o=Array.isArray(n.cell.stateSize)?n.cell.stateSize.length:1;if(a.length!==o)throw new sh("RNN Layer has "+o+" state(s) but was passed "+a.length+" initial state(s).");n.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");var s={training:i},u=cv(function(t,e){var r=n.cell.call([t].concat(e),s);return[r[0],r.slice(1)]},t,a,n.goBackwards,r,null,n.unroll,n.returnSequences),l=u[0],c=u[1],p=u[2];n.stateful&&n.resetStates(p,i);var h=n.returnSequences?c:l;return n.returnState?[h].concat(p):h})},e.prototype.getInitialState=function(t){var e=this;return _e(function(){var n=fn(t.shape);return n=sf(n=Cl(n,[1,2])),Array.isArray(e.cell.stateSize)?e.cell.stateSize.map(function(t){return t>1?ff(n,[1,t]):n}):e.cell.stateSize>1?[ff(n,[1,e.cell.stateSize])]:[n]})},Object.defineProperty(e.prototype,"trainableWeights",{get:function(){return this.trainable?this.cell.trainableWeights:[]},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"nonTrainableWeights",{get:function(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights},enumerable:!0,configurable:!0}),e.prototype.setFastWeightInitDuringBuild=function(e){t.prototype.setFastWeightInitDuringBuild.call(this,e),null!=this.cell&&this.cell.setFastWeightInitDuringBuild(e)},e.prototype.getConfig=function(){var e={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};null!=this.numConstants&&(e.numConstants=this.numConstants);var n=this.cell.getConfig();e.cell={className:this.cell.getClassName(),config:n};var r=t.prototype.getConfig.call(this);return Object.assign(e,r),e},e.fromConfig=function(t,e,n){void 0===n&&(n={});var r=Ed(e.cell,n);return new t(Object.assign(e,{cell:r}))},e.className="RNN",e}(ld);Op.registerClass(pv);var hv=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Qp(e,t),e}(ld),fv=function(t){function e(e){var n=t.call(this,e)||this;return n.DEFAULT_ACTIVATION="tanh",n.DEFAULT_KERNEL_INITIALIZER="glorotNormal",n.DEFAULT_RECURRENT_INITIALIZER="orthogonal",n.DEFAULT_BIAS_INITIALIZER="zeros",n.units=e.units,Sh(n.units,"units"),n.activation=Gm(null==e.activation?n.DEFAULT_ACTIVATION:e.activation),n.useBias=null==e.useBias||e.useBias,n.kernelInitializer=jf(e.kernelInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.recurrentInitializer=jf(e.recurrentInitializer||n.DEFAULT_RECURRENT_INITIALIZER),n.biasInitializer=jf(e.biasInitializer||n.DEFAULT_BIAS_INITIALIZER),n.kernelRegularizer=Jm(e.kernelRegularizer),n.recurrentRegularizer=Jm(e.recurrentRegularizer),n.biasRegularizer=Jm(e.biasRegularizer),n.kernelConstraint=Mh(e.kernelConstraint),n.recurrentConstraint=Mh(e.recurrentConstraint),n.biasConstraint=Mh(e.biasConstraint),n.dropout=nf([1,rf([0,null==e.dropout?0:e.dropout])]),n.recurrentDropout=nf([1,rf([0,null==e.recurrentDropout?0:e.recurrentDropout])]),n.stateSize=n.units,n.dropoutMask=null,n.recurrentDropoutMask=null,n}return Qp(e,t),e.prototype.build=function(t){t=Zf(t),this.kernel=this.addWeight("kernel",[t[t.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0},e.prototype.call=function(t,e){var n=this;return _e(function(){if(2!==(t=t).length)throw new sh("SimpleRNNCell expects 2 input Tensors, got "+t.length+".");var r=t[1];t=t[0];var i,a=null!=e.training&&e.training;0<n.dropout&&n.dropout<1&&null==n.dropoutMask&&(n.dropoutMask=xv(function(){return vn(t)},n.dropout,a)),0<n.recurrentDropout&&n.recurrentDropout<1&&null==n.recurrentDropoutMask&&(n.recurrentDropoutMask=xv(function(){return vn(r)},n.recurrentDropout,a));var o=n.dropoutMask,s=n.recurrentDropoutMask;i=mf(null!=o?su(t,o):t,n.kernel.read()),null!=n.bias&&(i=bf(i,n.bias.read())),null!=s&&(r=su(r,s));var u=$s(i,mf(r,n.recurrentKernel.read()));return null!=n.activation&&(u=n.activation.apply(u)),[u,u]})},e.prototype.getConfig=function(){var e={units:this.units,activation:Um(this.activation),useBias:this.useBias,kernelInitializer:Uf(this.kernelInitializer),recurrentInitializer:Uf(this.recurrentInitializer),biasInitializer:Uf(this.biasInitializer),kernelRegularizer:Xm(this.kernelRegularizer),recurrentRegularizer:Xm(this.recurrentRegularizer),biasRegularizer:Xm(this.biasRegularizer),activityRegularizer:Xm(this.activityRegularizer),kernelConstraint:Fh(this.kernelConstraint),recurrentConstraint:Fh(this.recurrentConstraint),biasConstraint:Fh(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="SimpleRNNCell",e}(hv);Op.registerClass(fv);var dv=function(t){function e(e){return e.cell=new fv(e),t.call(this,e)||this}return Qp(e,t),e.prototype.call=function(e,n){var r=this;return _e(function(){null!=r.cell.dropoutMask&&(Fe(r.cell.dropoutMask),r.cell.dropoutMask=null),null!=r.cell.recurrentDropoutMask&&(Fe(r.cell.recurrentDropoutMask),r.cell.recurrentDropoutMask=null);var i=null==n?null:n.mask,a=null==n?null:n.training,o=null==n?null:n.initialState;return t.prototype.call.call(r,e,{mask:i,training:a,initialState:o})})},Object.defineProperty(e.prototype,"units",{get:function(){return this.cell.units},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"activation",{get:function(){return this.cell.activation},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"useBias",{get:function(){return this.cell.useBias},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelInitializer",{get:function(){return this.cell.kernelInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentInitializer",{get:function(){return this.cell.recurrentInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasInitializer",{get:function(){return this.cell.biasInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelRegularizer",{get:function(){return this.cell.kernelRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentRegularizer",{get:function(){return this.cell.recurrentRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasRegularizer",{get:function(){return this.cell.biasRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelConstraint",{get:function(){return this.cell.kernelConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentConstraint",{get:function(){return this.cell.recurrentConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasConstraint",{get:function(){return this.cell.biasConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"dropout",{get:function(){return this.cell.dropout},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentDropout",{get:function(){return this.cell.recurrentDropout},enumerable:!0,configurable:!0}),e.prototype.getConfig=function(){var e={units:this.units,activation:Um(this.activation),useBias:this.useBias,kernelInitializer:Uf(this.kernelInitializer),recurrentInitializer:Uf(this.recurrentInitializer),biasInitializer:Uf(this.biasInitializer),kernelRegularizer:Xm(this.kernelRegularizer),recurrentRegularizer:Xm(this.recurrentRegularizer),biasRegularizer:Xm(this.biasRegularizer),activityRegularizer:Xm(this.activityRegularizer),kernelConstraint:Fh(this.kernelConstraint),recurrentConstraint:Fh(this.recurrentConstraint),biasConstraint:Fh(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout},n=t.prototype.getConfig.call(this);return delete n.cell,Object.assign(e,n),e},e.fromConfig=function(t,e){return new t(e)},e.className="SimpleRNN",e}(pv);Op.registerClass(dv);var mv=function(t){function e(e){var n=t.call(this,e)||this;return n.DEFAULT_ACTIVATION="tanh",n.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",n.DEFAULT_KERNEL_INITIALIZER="glorotNormal",n.DEFAULT_RECURRENT_INITIALIZER="orthogonal",n.DEFAULT_BIAS_INITIALIZER="zeros",n.units=e.units,Sh(n.units,"units"),n.activation=Gm(void 0===e.activation?n.DEFAULT_ACTIVATION:e.activation),n.recurrentActivation=Gm(void 0===e.recurrentActivation?n.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),n.useBias=null==e.useBias||e.useBias,n.kernelInitializer=jf(e.kernelInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.recurrentInitializer=jf(e.recurrentInitializer||n.DEFAULT_RECURRENT_INITIALIZER),n.biasInitializer=jf(e.biasInitializer||n.DEFAULT_BIAS_INITIALIZER),n.kernelRegularizer=Jm(e.kernelRegularizer),n.recurrentRegularizer=Jm(e.recurrentRegularizer),n.biasRegularizer=Jm(e.biasRegularizer),n.kernelConstraint=Mh(e.kernelConstraint),n.recurrentConstraint=Mh(e.recurrentConstraint),n.biasConstraint=Mh(e.biasConstraint),n.dropout=nf([1,rf([0,null==e.dropout?0:e.dropout])]),n.recurrentDropout=nf([1,rf([0,null==e.recurrentDropout?0:e.recurrentDropout])]),n.implementation=e.implementation,n.stateSize=n.units,n.dropoutMask=null,n.recurrentDropoutMask=null,n}return Qp(e,t),e.prototype.build=function(t){var e=(t=Zf(t))[t.length-1];this.kernel=this.addWeight("kernel",[e,3*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,3*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[3*this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0},e.prototype.call=function(t,e){var n=this;return _e(function(){if(2!==(t=t).length)throw new sh("GRUCell expects 2 input Tensors (inputs, h, c), got "+t.length+".");var r=null!=e.training&&e.training,i=t[1];t=t[0],0<n.dropout&&n.dropout<1&&null==n.dropoutMask&&(n.dropoutMask=xv(function(){return vn(t)},n.dropout,r,3)),0<n.recurrentDropout&&n.recurrentDropout<1&&null==n.recurrentDropoutMask&&(n.recurrentDropoutMask=xv(function(){return vn(i)},n.recurrentDropout,r,3));var a,o,s,u=n.dropoutMask,l=n.recurrentDropoutMask;0<n.dropout&&n.dropout<1&&(t=su(t,u[0]));var c=mf(t,n.kernel.read());n.useBias&&(c=bf(c,n.bias.read())),0<n.recurrentDropout&&n.recurrentDropout<1&&(i=su(i,l[0]));var p=n.recurrentKernel.read(),h=En(p,[2*n.units,n.units],p.rank-1),f=h[0],d=h[1],m=mf(i,f),g=En(c,3,c.rank-1),v=g[0],y=g[1],b=g[2],x=En(m,2,m.rank-1),w=x[0],C=x[1];a=n.recurrentActivation.apply($s(v,w)),o=n.recurrentActivation.apply($s(y,C));var N=mf(su(o,i),d);s=n.activation.apply($s(b,N));var E=$s(su(a,i),su($s(1,ps(a)),s));return[E,E]})},e.prototype.getConfig=function(){var e={units:this.units,activation:Um(this.activation),recurrentActivation:Um(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Uf(this.kernelInitializer),recurrentInitializer:Uf(this.recurrentInitializer),biasInitializer:Uf(this.biasInitializer),kernelRegularizer:Xm(this.kernelRegularizer),recurrentRegularizer:Xm(this.recurrentRegularizer),biasRegularizer:Xm(this.biasRegularizer),activityRegularizer:Xm(this.activityRegularizer),kernelConstraint:Fh(this.kernelConstraint),recurrentConstraint:Fh(this.recurrentConstraint),biasConstraint:Fh(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="GRUCell",e}(hv);Op.registerClass(mv);var gv=function(t){function e(e){return 0===e.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new mv(e),t.call(this,e)||this}return Qp(e,t),e.prototype.call=function(e,n){var r=this;return _e(function(){null!=r.cell.dropoutMask&&(Fe(r.cell.dropoutMask),r.cell.dropoutMask=null),null!=r.cell.recurrentDropoutMask&&(Fe(r.cell.recurrentDropoutMask),r.cell.recurrentDropoutMask=null);var i=null==n?null:n.mask,a=null==n?null:n.training,o=null==n?null:n.initialState;return t.prototype.call.call(r,e,{mask:i,training:a,initialState:o})})},Object.defineProperty(e.prototype,"units",{get:function(){return this.cell.units},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"activation",{get:function(){return this.cell.activation},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentActivation",{get:function(){return this.cell.recurrentActivation},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"useBias",{get:function(){return this.cell.useBias},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelInitializer",{get:function(){return this.cell.kernelInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentInitializer",{get:function(){return this.cell.recurrentInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasInitializer",{get:function(){return this.cell.biasInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelRegularizer",{get:function(){return this.cell.kernelRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentRegularizer",{get:function(){return this.cell.recurrentRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasRegularizer",{get:function(){return this.cell.biasRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelConstraint",{get:function(){return this.cell.kernelConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentConstraint",{get:function(){return this.cell.recurrentConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasConstraint",{get:function(){return this.cell.biasConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"dropout",{get:function(){return this.cell.dropout},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentDropout",{get:function(){return this.cell.recurrentDropout},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"implementation",{get:function(){return this.cell.implementation},enumerable:!0,configurable:!0}),e.prototype.getConfig=function(){var e={units:this.units,activation:Um(this.activation),recurrentActivation:Um(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Uf(this.kernelInitializer),recurrentInitializer:Uf(this.recurrentInitializer),biasInitializer:Uf(this.biasInitializer),kernelRegularizer:Xm(this.kernelRegularizer),recurrentRegularizer:Xm(this.recurrentRegularizer),biasRegularizer:Xm(this.biasRegularizer),activityRegularizer:Xm(this.activityRegularizer),kernelConstraint:Fh(this.kernelConstraint),recurrentConstraint:Fh(this.recurrentConstraint),biasConstraint:Fh(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},n=t.prototype.getConfig.call(this);return delete n.cell,Object.assign(e,n),e},e.fromConfig=function(t,e){return 0===e.implmentation&&(e.implementation=1),new t(e)},e.className="GRU",e}(pv);Op.registerClass(gv);var vv=function(t){function e(e){var n=t.call(this,e)||this;return n.DEFAULT_ACTIVATION="tanh",n.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",n.DEFAULT_KERNEL_INITIALIZER="glorotNormal",n.DEFAULT_RECURRENT_INITIALIZER="orthogonal",n.DEFAULT_BIAS_INITIALIZER="zeros",n.units=e.units,Sh(n.units,"units"),n.activation=Gm(void 0===e.activation?n.DEFAULT_ACTIVATION:e.activation),n.recurrentActivation=Gm(void 0===e.recurrentActivation?n.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),n.useBias=null==e.useBias||e.useBias,n.kernelInitializer=jf(e.kernelInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.recurrentInitializer=jf(e.recurrentInitializer||n.DEFAULT_RECURRENT_INITIALIZER),n.biasInitializer=jf(e.biasInitializer||n.DEFAULT_BIAS_INITIALIZER),n.unitForgetBias=e.unitForgetBias,n.kernelRegularizer=Jm(e.kernelRegularizer),n.recurrentRegularizer=Jm(e.recurrentRegularizer),n.biasRegularizer=Jm(e.biasRegularizer),n.kernelConstraint=Mh(e.kernelConstraint),n.recurrentConstraint=Mh(e.recurrentConstraint),n.biasConstraint=Mh(e.biasConstraint),n.dropout=nf([1,rf([0,null==e.dropout?0:e.dropout])]),n.recurrentDropout=nf([1,rf([0,null==e.recurrentDropout?0:e.recurrentDropout])]),n.implementation=e.implementation,n.stateSize=[n.units,n.units],n.dropoutMask=null,n.recurrentDropoutMask=null,n}return Qp(e,t),e.prototype.build=function(t){var e,n,r=(t=Zf(t))[t.length-1];if(this.kernel=this.addWeight("kernel",[r,4*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,4*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){if(this.unitForgetBias){var i=this.biasInitializer,a=this.units;n=new((e=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return Qp(e,t),e.prototype.apply=function(t,e){var n=i.apply([a]),r=(new kf).apply([a]),o=i.apply([2*a]);return hf(hf(n,r),o)},e}(Ef)).className="CustomInit",e)}else n=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.units],null,n,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0},e.prototype.call=function(t,e){var n=this;return _e(function(){var r=null!=e.training&&e.training;if(3!==(t=t).length)throw new sh("LSTMCell expects 3 input Tensors (inputs, h, c), got "+t.length+".");var i=t[1],a=t[2];t=t[0],0<n.dropout&&n.dropout<1&&null==n.dropoutMask&&(n.dropoutMask=xv(function(){return vn(t)},n.dropout,r,4)),0<n.recurrentDropout&&n.recurrentDropout<1&&null==n.recurrentDropoutMask&&(n.recurrentDropoutMask=xv(function(){return vn(i)},n.recurrentDropout,r,4));var o,s,u,l,c=n.dropoutMask,p=n.recurrentDropoutMask;0<n.dropout&&n.dropout<1&&(t=su(t,c[0]));var h=mf(t,n.kernel.read());0<n.recurrentDropout&&n.recurrentDropout<1&&(i=su(i,p[0])),h=$s(h,mf(i,n.recurrentKernel.read())),n.useBias&&(h=bf(h,n.bias.read()));var f=En(h,4,h.rank-1),d=f[0],m=f[1],g=f[2],v=f[3];o=n.recurrentActivation.apply(d),s=n.recurrentActivation.apply(m),u=$s(su(s,a),su(o,n.activation.apply(g))),l=n.recurrentActivation.apply(v);var y=su(l,n.activation.apply(u));return[y,y,u]})},e.prototype.getConfig=function(){var e={units:this.units,activation:Um(this.activation),recurrentActivation:Um(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Uf(this.kernelInitializer),recurrentInitializer:Uf(this.recurrentInitializer),biasInitializer:Uf(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:Xm(this.kernelRegularizer),recurrentRegularizer:Xm(this.recurrentRegularizer),biasRegularizer:Xm(this.biasRegularizer),activityRegularizer:Xm(this.activityRegularizer),kernelConstraint:Fh(this.kernelConstraint),recurrentConstraint:Fh(this.recurrentConstraint),biasConstraint:Fh(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.className="LSTMCell",e}(hv);Op.registerClass(vv);var yv=function(t){function e(e){return 0===e.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new vv(e),t.call(this,e)||this}return Qp(e,t),e.prototype.call=function(e,n){var r=this;return _e(function(){null!=r.cell.dropoutMask&&(Fe(r.cell.dropoutMask),r.cell.dropoutMask=null),null!=r.cell.recurrentDropoutMask&&(Fe(r.cell.recurrentDropoutMask),r.cell.recurrentDropoutMask=null);var i=null==n?null:n.mask,a=null==n?null:n.training,o=null==n?null:n.initialState;return t.prototype.call.call(r,e,{mask:i,training:a,initialState:o})})},Object.defineProperty(e.prototype,"units",{get:function(){return this.cell.units},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"activation",{get:function(){return this.cell.activation},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentActivation",{get:function(){return this.cell.recurrentActivation},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"useBias",{get:function(){return this.cell.useBias},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelInitializer",{get:function(){return this.cell.kernelInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentInitializer",{get:function(){return this.cell.recurrentInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasInitializer",{get:function(){return this.cell.biasInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"unitForgetBias",{get:function(){return this.cell.unitForgetBias},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelRegularizer",{get:function(){return this.cell.kernelRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentRegularizer",{get:function(){return this.cell.recurrentRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasRegularizer",{get:function(){return this.cell.biasRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"kernelConstraint",{get:function(){return this.cell.kernelConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentConstraint",{get:function(){return this.cell.recurrentConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"biasConstraint",{get:function(){return this.cell.biasConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"dropout",{get:function(){return this.cell.dropout},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"recurrentDropout",{get:function(){return this.cell.recurrentDropout},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"implementation",{get:function(){return this.cell.implementation},enumerable:!0,configurable:!0}),e.prototype.getConfig=function(){var e={units:this.units,activation:Um(this.activation),recurrentActivation:Um(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Uf(this.kernelInitializer),recurrentInitializer:Uf(this.recurrentInitializer),biasInitializer:Uf(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:Xm(this.kernelRegularizer),recurrentRegularizer:Xm(this.recurrentRegularizer),biasRegularizer:Xm(this.biasRegularizer),activityRegularizer:Xm(this.activityRegularizer),kernelConstraint:Fh(this.kernelConstraint),recurrentConstraint:Fh(this.recurrentConstraint),biasConstraint:Fh(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},n=t.prototype.getConfig.call(this);return delete n.cell,Object.assign(e,n),e},e.fromConfig=function(t,e){return 0===e.implmentation&&(e.implementation=1),new t(e)},e.className="LSTM",e}(pv);Op.registerClass(yv);var bv=function(t){function e(e){var n=t.call(this,e)||this;return n.cells=e.cells,n}return Qp(e,t),Object.defineProperty(e.prototype,"stateSize",{get:function(){for(var t=[],e=0,n=this.cells.slice().reverse();e<n.length;e++){var r=n[e];Array.isArray(r.stateSize)?t.push.apply(t,r.stateSize):t.push(r.stateSize)}return t},enumerable:!0,configurable:!0}),e.prototype.call=function(t,e){var n=this;return _e(function(){for(var r=(t=t).slice(1),i=[],a=0,o=n.cells.slice().reverse();a<o.length;a++){var s=o[a];Array.isArray(s.stateSize)?i.push(r.splice(0,s.stateSize.length)):i.push(r.splice(0,1))}i.reverse();for(var u,l=[],c=0;c<n.cells.length;++c)s=n.cells[c],r=i[c],u=0===c?[t[0]].concat(r):[u[0]].concat(r),u=s.call(u,e),l.push(u.slice(1));r=[];for(var p=0,h=l.slice().reverse();p<h.length;p++){var f=h[p];r.push.apply(r,f)}return[u[0]].concat(r)})},e.prototype.build=function(t){var e;Xf(t)&&(t=t[0]),t=t,this.cells.forEach(function(n,r){$h("RNNCell_"+r,function(){n.build(t),e=Array.isArray(n.stateSize)?n.stateSize[0]:n.stateSize,t=[t[0],e]})}),this.built=!0},e.prototype.getConfig=function(){for(var e=[],n=0,r=this.cells;n<r.length;n++){var i=r[n];e.push({className:i.getClassName(),config:i.getConfig()})}var a={cells:e},o=t.prototype.getConfig.call(this);return Object.assign(a,o),a},e.fromConfig=function(t,e,n){void 0===n&&(n={});for(var r=[],i=0,a=e.cells;i<a.length;i++){var o=a[i];r.push(Ed(o,n))}return new t({cells:r})},Object.defineProperty(e.prototype,"trainableWeights",{get:function(){if(!this.trainable)return[];for(var t=[],e=0,n=this.cells;e<n.length;e++){var r=n[e];t.push.apply(t,r.trainableWeights)}return t},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"nonTrainableWeights",{get:function(){for(var t=[],e=0,n=this.cells;e<n.length;e++){var r=n[e];t.push.apply(t,r.nonTrainableWeights)}if(!this.trainable){for(var i=[],a=0,o=this.cells;a<o.length;a++)r=o[a],i.push.apply(i,r.trainableWeights);return i.concat(t)}return t},enumerable:!0,configurable:!0}),e.prototype.getWeights=function(){for(var t=[],e=0,n=this.cells;e<n.length;e++){var r=n[e];t.push.apply(t,r.weights)}return nd(t)},e.prototype.setWeights=function(t){for(var e=[],n=0,r=this.cells;n<r.length;n++)for(var i=r[n],a=i.weights.length,o=t.splice(a),s=0;s<i.weights.length;++s)e.push([i.weights[s],o[s]]);rd(e)},e.className="StackedRNNCells",e}(hv);function xv(t,e,n,r){function i(){return xf(t(),e)}if(void 0===n&&(n=null),void 0===r&&(r=1),r>1){for(var a=[],o=0;o<r;o++)a.push(wf(i,t,n));return a.map(function(t){return ze(t.clone())})}return ze(wf(i,t,n).clone())}Op.registerClass(bv);var wv=function(t){function e(e){var n=t.call(this,e)||this;return n.layer=e.layer,n}return Qp(e,t),e.prototype.build=function(t){this.built=!0},Object.defineProperty(e.prototype,"trainable",{get:function(){return null!=this.layer&&this.layer.trainable},set:function(t){null!=this.layer&&(this.layer.trainable=t)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"trainableWeights",{get:function(){return this.layer.trainableWeights},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"nonTrainableWeights",{get:function(){return this.layer.nonTrainableWeights},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"updates",{get:function(){return this.layer._updates},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"losses",{get:function(){return this.layer.losses},enumerable:!0,configurable:!0}),e.prototype.getWeights=function(){return this.layer.getWeights()},e.prototype.setWeights=function(t){this.layer.setWeights(t)},e.prototype.getConfig=function(){var e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.prototype.setFastWeightInitDuringBuild=function(e){t.prototype.setFastWeightInitDuringBuild.call(this,e),null!=this.layer&&this.layer.setFastWeightInitDuringBuild(e)},e.fromConfig=function(t,e,n){void 0===n&&(n={});var r=Ed(e.layer,n);delete e.layer;var i={layer:r};return Object.assign(i,e),new t(i)},e}(ld),Cv=function(t){function e(e){var n=t.call(this,e)||this;return n.supportsMasking=!0,n}return Qp(e,t),e.prototype.build=function(e){if((e=Zf(e)).length<3)throw new sh("TimeDistributed layer expects an input shape >= 3D, but received input shape "+JSON.stringify(e));this.inputSpec=[{shape:e}];var n=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(n),this.layer.built=!0),t.prototype.build.call(this,e)},e.prototype.computeOutputShape=function(t){var e=[(t=Zf(t))[0]].concat(t.slice(2)),n=this.layer.computeOutputShape(e),r=t[1];return[n[0],r].concat(n.slice(1))},e.prototype.call=function(t,e){var n=this;return _e(function(){return cv(function(t,r){return[Jf(n.layer.call(t,e)),[]]},t=Jf(t),[],!1,null,null,!1,!0)[1]})},e.className="TimeDistributed",e}(wv);Op.registerClass(Cv);var Nv="concat",Ev=function(t){function e(e){var n=t.call(this,e)||this,r=e.layer.getConfig(),i={};i.className=e.layer.getClassName(),i.config=r,n.forwardLayer=Ed(i),r.goBackwards=!0!==r.goBackwards;var a={};if(a.className=e.layer.getClassName(),a.config=r,n.backwardLayer=Ed(a),n.forwardLayer.name="forward_"+n.forwardLayer.name,n.backwardLayer.name="backward_"+n.backwardLayer.name,n.mergeMode=void 0===e.mergeMode?Nv:e.mergeMode,function(t){Nh(Vh,"BidirectionalMergeMode",t)}(n.mergeMode),e.weights)throw new uh("weights support is not implemented for Bidirectional layer yet.");return n._stateful=e.layer.stateful,n.returnSequences=e.layer.returnSequences,n.returnState=e.layer.returnState,n.supportsMasking=!0,n._trainable=!0,n.inputSpec=e.layer.inputSpec,n.numConstants=null,n}return Qp(e,t),Object.defineProperty(e.prototype,"trainable",{get:function(){return this._trainable},set:function(t){this._trainable=t,null!=this.forwardLayer&&(this.forwardLayer.trainable=t),null!=this.backwardLayer&&(this.backwardLayer.trainable=t)},enumerable:!0,configurable:!0}),e.prototype.getWeights=function(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())},e.prototype.setWeights=function(t){var e=t.length,n=Math.floor(e/2);this.forwardLayer.setWeights(t.slice(0,n)),this.backwardLayer.setWeights(t.slice(n))},e.prototype.computeOutputShape=function(t){var e,n,r,i=this.forwardLayer.computeOutputShape(t);return Array.isArray(i)&&Array.isArray(i[0])||(i=[i]),i=i,this.returnState?(r=i.slice(1),e=i[0]):e=i[0],e=e,"concat"===this.mergeMode?(e[e.length-1]*=2,n=[e]):n=null==this.mergeMode?[e,e.slice()]:[e],this.returnState?null==this.mergeMode?n.concat(r).concat(r.slice()):[e].concat(r).concat(r.slice()):fh(n)},e.prototype.apply=function(e,n){var r=null==n?null:n.initialState,i=null==n?null:n.constants;null==n&&(n={});var a=lv(e,r,i,this.numConstants);if(e=a.inputs,r=a.initialState,i=a.constants,Array.isArray(e)&&(r=e.slice(1),e=e[0]),(null==r||0===r.length)&&null==i)return t.prototype.apply.call(this,e,n);var o=[],s=[];if(null!=r){var u=r.length;if(u%2>0)throw new sh("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");n.initialState=r,o.push.apply(o,r);var l=r.map(function(t){return new id({shape:t.shape})});this.forwardLayer.stateSpec=l.slice(0,u/2),this.backwardLayer.stateSpec=l.slice(u/2),s.push.apply(s,l)}if(null!=i)throw new uh("Support for constants in Bidirectional layers is not implemented yet.");for(var c=o[0]instanceof ad,p=0,h=o;p<h.length;p++)if(h[p]instanceof ad!==c)throw new sh("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(c){var f=[e].concat(o),d=this.inputSpec.concat(s),m=this.inputSpec;this.inputSpec=d;var g=t.prototype.apply.call(this,f,n);return this.inputSpec=m,g}return t.prototype.apply.call(this,e,n)},e.prototype.call=function(t,e){var n=this;return _e(function(){if(null!=e.mask)throw new uh("The support for masking is not implemented for Bidirectional layers yet.");var r,i,a,o,s=e.initialState;if(null==s)r=n.forwardLayer.call(t,e),i=n.backwardLayer.call(t,e);else{var u=s.slice(0,s.length/2),l=s.slice(s.length/2);r=n.forwardLayer.call(t,Object.assign(e,{initialState:u})),i=n.backwardLayer.call(t,Object.assign(e,{initialState:l}))}return n.returnState&&(Array.isArray(r)&&(a=r.slice(1).concat(i.slice(1))),r=r[0],i=i[0]),n.returnSequences&&(i=Xu(i,1)),"concat"===n.mergeMode?o=pf([r,i]):"sum"===n.mergeMode?o=$s(r,i):"ave"===n.mergeMode?o=su(.5,$s(r,i)):"mul"===n.mergeMode?o=su(r,i):null==n.mergeMode&&(o=[r,i]),n.returnState?null==n.mergeMode?o.concat(a):[o].concat(a):o})},e.prototype.resetStates=function(t){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()},e.prototype.build=function(t){var e=this;$h(this.forwardLayer.name,function(){e.forwardLayer.build(t)}),$h(this.backwardLayer.name,function(){e.backwardLayer.build(t)}),this.built=!0},Object.defineProperty(e.prototype,"trainableWeights",{get:function(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"nonTrainableWeights",{get:function(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)},enumerable:!0,configurable:!0}),e.prototype.setFastWeightInitDuringBuild=function(e){t.prototype.setFastWeightInitDuringBuild.call(this,e),null!=this.forwardLayer&&this.forwardLayer.setFastWeightInitDuringBuild(e),null!=this.backwardLayer&&this.backwardLayer.setFastWeightInitDuringBuild(e)},e.prototype.getConfig=function(){var e={mergeMode:this.mergeMode},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e.fromConfig=function(t,e){var n=Ed(e.layer);if(delete e.layer,null!=e.numConstants)throw new uh("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");var r=e;return r.layer=n,new t(r)},e.className="Bidirectional",e}(wv);function Sv(t){return new Yg(t)}function kv(t){return new Qg(t)}function Iv(t){return new nv(t)}function Av(t){return new av(t)}function Rv(t){return new uv(t)}function Tv(t){return new Xg(t)}function Dv(t){return new Zg(t)}Op.registerClass(Ev);var Ov=Av,_v=Rv,Fv=Tv,zv=Dv;var Mv=Object.freeze({inputLayer:function(t){return new pd(t)},elu:function(t){return new eg(t)},reLU:function(t){return new Zm(t)},leakyReLU:function(t){return new Qm(t)},prelu:function(t){return new tg(t)},softmax:function(t){return new rg(t)},thresholdedReLU:function(t){return new ng(t)},conv1d:function(t){return new gg(t)},conv2d:function(t){return new hg(t)},conv2dTranspose:function(t){return new dg(t)},conv3d:function(t){return new fg(t)},separableConv2d:function(t){return new mg(t)},cropping2D:function(t){return new vg(t)},upSampling2d:function(t){return new yg(t)},depthwiseConv2d:function(t){return new bg(t)},activation:function(t){return new Ng(t)},dense:function(t){return new wg(t)},dropout:function(t){return new xg(t)},flatten:function(t){return new Cg(t)},repeatVector:function(t){return new Eg(t)},reshape:function(t){return new Sg(t)},permute:function(t){return new kg(t)},embedding:function(t){return new Ag(t)},add:function(t){return new Tg(t)},average:function(t){return new Og(t)},concatenate:function(t){return new zg(t)},maximum:function(t){return new _g(t)},minimum:function(t){return new Fg(t)},multiply:function(t){return new Dg(t)},dot:function(t){return new Lg(t)},batchNormalization:function(t){return new jg(t)},layerNormalization:function(t){return new Gg(t)},zeroPadding2d:function(t){return new qg(t)},averagePooling1d:Sv,avgPool1d:function(t){return Sv(t)},avgPooling1d:function(t){return Sv(t)},averagePooling2d:kv,avgPool2d:function(t){return kv(t)},avgPooling2d:function(t){return kv(t)},averagePooling3d:Iv,avgPool3d:function(t){return Iv(t)},avgPooling3d:function(t){return Iv(t)},globalAveragePooling1d:function(t){return new iv(t)},globalAveragePooling2d:function(t){return new sv(t)},globalMaxPooling1d:Av,globalMaxPooling2d:Rv,maxPooling1d:Tv,maxPooling2d:Dv,maxPooling3d:function(t){return new ev(t)},gru:function(t){return new gv(t)},gruCell:function(t){return new mv(t)},lstm:function(t){return new yv(t)},lstmCell:function(t){return new vv(t)},simpleRNN:function(t){return new dv(t)},simpleRNNCell:function(t){return new fv(t)},rnn:function(t){return new pv(t)},stackedRNNCells:function(t){return new bv(t)},bidirectional:function(t){return new Ev(t)},timeDistributed:function(t){return new Cv(t)},globalMaxPool1d:Ov,globalMaxPool2d:_v,maxPool1d:Fv,maxPool2d:zv,Layer:ld,RNN:pv,RNNCell:hv,input:Am,gaussianNoise:function(t){return new Pg(t)},gaussianDropout:function(t){return new Bg(t)},alphaDropout:function(t){return new Wg(t)},masking:function(t){return new Ig(t)}});var Lv=Object.freeze({binaryAccuracy:function(t,e){return zd(t,e)},binaryCrossentropy:function(t,e){return Wd(t,e)},sparseCategoricalAccuracy:function(t,e){return Vd(t,e)},categoricalAccuracy:function(t,e){return Md(t,e)},categoricalCrossentropy:function(t,e){return Ud(t,e)},precision:function(t,e){return Pd(t,e)},recall:function(t,e){return Bd(t,e)},cosineProximity:function(t,e){return Od(t,e)},meanAbsoluteError:function(t,e){return Id(t,e)},meanAbsolutePercentageError:function(t,e){return Ad(t,e)},MAPE:function(t,e){return Ad(t,e)},mape:function(t,e){return Ad(t,e)},meanSquaredError:function(t,e){return kd(t,e)},MSE:function(t,e){return kd(t,e)},mse:function(t,e){return kd(t,e)}}),Pv=Object.freeze({modelFromJSON:function(t,e){return nh(this,void 0,void 0,function(){var n,r,i,a,o,s,u,l;return rh(this,function(c){switch(c.label){case 0:return"modelTopology"in t||(t={modelTopology:t}),null!=(n=(t=t).modelTopology).model_config&&(n=n.model_config),r=Qd(n),i=Ed(r,e),null==t.weightsManifest?[3,2]:[4,Ep.loadWeights(t.weightsManifest,t.pathPrefix,i.weights.map(function(t){return t.originalName}))];case 1:for(a=c.sent(),o={},s=0,u=i.weights;s<u.length;s++)l=u[s],o[l.originalName]=a[l.originalName];i.loadWeights(o),Fe(a),c.label=2;case 2:return[2,i]}})})}});var Bv=Object.freeze({l1l2:function(t){return new Km(t)},l1:function(t){return function(t){return qm(t),new Km({l1:null!=t?t.l1:null,l2:0})}(t)},l2:function(t){return function(t){return qm(t),new Km({l2:null!=t?t.l2:null,l1:0})}(t)}}),Wv=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.model=null,e}return Qp(e,t),e.prototype.setModel=function(t){if(!(t instanceof Sm))throw new Error("model must be a LayersModel, not some other Container");this.model=t},e}(gd);function Vv(t,e){return t<e}function Uv(t,e){return t>e}var jv=function(t){function e(e){var n=t.call(this)||this;if(null==e&&(e={}),e.restoreBestWeights)throw new uh("restoreBestWeights = True is not implemented in EarlyStopping yet.");return n.monitor=e.monitor||"val_loss",n.minDelta=Math.abs(e.minDelta||0),n.patience=e.patience||0,n.verbose=e.verbose||0,n.mode=e.mode||"auto",n.baseline=e.baseline,-1===["auto","min","max"].indexOf(n.mode)&&(console.warn("EarlyStopping mode '"+n.mode+"' is invalid. Falling back to mode 'auto'."),n.mode="auto"),"min"===n.mode?n.monitorFunc=Vv:"max"===n.mode?n.monitorFunc=Uv:-1!==n.monitor.indexOf("acc")?n.monitorFunc=Uv:n.monitorFunc=Vv,n.monitorFunc===Vv&&(n.minDelta*=-1),n}return Qp(e,t),e.prototype.onTrainBegin=function(t){return nh(this,void 0,void 0,function(){return rh(this,function(t){return this.wait=0,this.stoppedEpoch=0,null!=this.baseline?this.best=this.baseline:this.best=this.monitorFunc===Vv?1/0:-1/0,[2]})})},e.prototype.onEpochEnd=function(t,e){return nh(this,void 0,void 0,function(){var n;return rh(this,function(r){switch(r.label){case 0:return[4,fd(e)];case 1:return r.sent(),null==(n=this.getMonitorValue(e))?[2]:(this.monitorFunc(n-this.minDelta,this.best)?(this.best=n,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=t,this.model.stopTraining=!0)),[2])}})})},e.prototype.onTrainEnd=function(t){return nh(this,void 0,void 0,function(){return rh(this,function(t){return this.stoppedEpoch>0&&this.verbose&&console.log("Epoch "+this.stoppedEpoch+": early stopping."),[2]})})},e.prototype.getMonitorValue=function(t){null==t&&(t={});var e=t[this.monitor];return null==e&&console.warn("Metric for EarlyStopping "+this.monitor+" is not available. Available metrics are: "+Object.keys(t)),e},e}(Wv);var Gv,qv,Hv={earlyStopping:function(t){return new jv(t)}},Kv=function(){return(Kv=Object.assign||function(t){for(var e,n=1,r=arguments.length;n<r;n++)for(var i in e=arguments[n])Object.prototype.hasOwnProperty.call(e,i)&&(t[i]=e[i]);return t}).apply(this,arguments)};function $v(t,e,n,r){return new(n||(n=Promise))(function(i,a){function o(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?i(t.value):new n(function(e){e(t.value)}).then(o,s)}u((r=r.apply(t,e||[])).next())})}function Xv(t,e){var n,r,i,a,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[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(;o;)try{if(n=1,r&&(i=2&a[0]?r.return:a[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,a[1])).done)return i;switch(r=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,r=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!(i=(i=o.trys).length>0&&i[i.length-1])&&(6===a[0]||2===a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){o.label=a[1];break}if(6===a[0]&&o.label<i[1]){o.label=i[1],i=a;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(a);break}i[2]&&o.ops.pop(),o.trys.pop();continue}a=e.call(t,o)}catch(t){a=[6,t],r=0}finally{n=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,s])}}}!function(t){t[t.DT_INVALID=0]="DT_INVALID",t[t.DT_FLOAT=1]="DT_FLOAT",t[t.DT_DOUBLE=2]="DT_DOUBLE",t[t.DT_INT32=3]="DT_INT32",t[t.DT_UINT8=4]="DT_UINT8",t[t.DT_INT16=5]="DT_INT16",t[t.DT_INT8=6]="DT_INT8",t[t.DT_STRING=7]="DT_STRING",t[t.DT_COMPLEX64=8]="DT_COMPLEX64",t[t.DT_INT64=9]="DT_INT64",t[t.DT_BOOL=10]="DT_BOOL",t[t.DT_QINT8=11]="DT_QINT8",t[t.DT_QUINT8=12]="DT_QUINT8",t[t.DT_QINT32=13]="DT_QINT32",t[t.DT_BFLOAT16=14]="DT_BFLOAT16",t[t.DT_FLOAT_REF=101]="DT_FLOAT_REF",t[t.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",t[t.DT_INT32_REF=103]="DT_INT32_REF",t[t.DT_UINT8_REF=104]="DT_UINT8_REF",t[t.DT_INT16_REF=105]="DT_INT16_REF",t[t.DT_INT8_REF=106]="DT_INT8_REF",t[t.DT_STRING_REF=107]="DT_STRING_REF",t[t.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",t[t.DT_INT64_REF=109]="DT_INT64_REF",t[t.DT_BOOL_REF=110]="DT_BOOL_REF",t[t.DT_QINT8_REF=111]="DT_QINT8_REF",t[t.DT_QUINT8_REF=112]="DT_QUINT8_REF",t[t.DT_QINT32_REF=113]="DT_QINT32_REF",t[t.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF"}(Gv||(Gv={})),function(t){!function(t){t[t.LEGACY=0]="LEGACY",t[t.V1=1]="V1",t[t.V2=2]="V2"}(t.CheckpointFormatVersion||(t.CheckpointFormatVersion={}))}(qv||(qv={}));var Yv={};function Jv(t){return Yv[t]}function Zv(t,e,n,r){var i=e.inputParams[t];if(i&&void 0!==i.inputIndexStart){var a=i.inputIndexStart,o=0===i.inputIndexEnd?void 0:void 0===i.inputIndexEnd?a+1:i.inputIndexEnd;if("tensor"===i.type)return Qv(e.inputNames[i.inputIndexStart],n,r);if("tensors"===i.type)return e.inputNames.slice(a,o).map(function(t){return Qv(t,n,r)});var s=Array.prototype.slice.call(Qv(e.inputNames.slice(a)[0],n,r).dataSync());return"number"===i.type?s[0]:s}var u=e.attrParams[t];return u&&u.value}function Qv(t,e,n){var r=ny(t),i=r[0],a=r[1],o=n.currentContextIds.find(function(t){return!!e[ey(i,t)]});return void 0!==o?e[ey(i,o)][a]:void 0}function ty(t,e){var n=ny(t),r=n[0],i=n[1];return[ey(r,e&&e.currentContextId),i]}function ey(t,e){return e?t+"-"+e:t}function ny(t){var e=t.lastIndexOf(":");return-1===e?[t,0]:[t.substring(0,e),Number(t.substring(e+1))]}function ry(t,e){for(var n=[],r=0;r<t.length;r+=e)n.push(t.slice(r,r+e));return n}var iy=Object.freeze({json:[{tfOpName:"Add",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddV2",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddN",category:"arithmetic",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"BiasAdd",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sub",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"RealDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Div",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mul",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Maximum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}]},{tfOpName:"Minimum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}]},{tfOpName:"Pow",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorMod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]}),ay=Object.freeze({json:[{tfOpName:"Abs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan2",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ceil",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ClipByValue",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"clip_value_min",name:"clipValueMin",type:"number"},{tfName:"clip_value_max",name:"clipValueMax",type:"number"}]},{tfOpName:"Complex",category:"basic_math",inputs:[{start:0,name:"real",type:"tensor"},{start:1,name:"imag",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ComplexAbs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Elu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Exp",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Floor",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Imag",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Neg",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Real",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Prelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"alpha",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu6",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"clipValueMin",name:"clipValueMin",type:"number",defaultValue:0},{tfName:"clipValueMax",name:"clipValueMax",type:"number",defaultValue:6}]},{tfOpName:"Selu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sigmoid",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Rsqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Square",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sign",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Round",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Expm1",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log1p",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Softplus",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Erf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Prod",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axes",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LeakyRelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"alpha",name:"alpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]}),oy=Object.freeze({json:[{tfOpName:"LoopCond",category:"control",inputs:[{start:0,name:"pred",type:"tensor"}]},{tfOpName:"Switch",category:"control",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"pred",type:"tensor"}]},{tfOpName:"Merge",category:"control",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"Enter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"frame_name",name:"frameName",type:"string"},{tfName:"is_constant",name:"isConstant",type:"bool"}]},{tfOpName:"Exit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NextIteration",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayV3",category:"control",inputs:[{start:0,name:"size",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"dynamic_size",name:"dynamicSize",type:"bool"},{tfName:"clear_after_read",name:"clearAfterRead",type:"bool"},{tfName:"identical_element_shapes",name:"identicalElementShapes",type:"bool"},{tfName:"tensor_array_name",name:"name",type:"string"}]},{tfOpName:"TensorArrayWriteV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayReadV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"index",type:"number"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayGatherV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"indices",type:"number[]"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"}]},{tfOpName:"TensorArrayScatterV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"indices",type:"number[]"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArrayConcatV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape_except0",name:"elementShapeExcept0",type:"shape",notSupported:!0}]},{tfOpName:"TensorArraySplitV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"tensor",type:"tensor"},{start:2,name:"lengths",type:"number[]"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArraySizeV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"},{start:1,name:"flowIn",type:"number"}]},{tfOpName:"TensorArrayCloseV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"number"}]}]}),sy=Object.freeze({json:[{tfOpName:"AvgPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AvgPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Conv1D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"stride",name:"stride",type:"number"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NWC"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"dilation",name:"dilation",type:"number",defaultValue:1}]},{tfOpName:"Conv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"useCudnnOnGpu",name:"useCudnnOnGpu",type:"bool"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"_FusedConv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"use_cudnn_on_gpu",name:"useCudnnOnGpu",type:"bool",defaultValue:!0},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4}]},{tfOpName:"Conv2DBackpropInput",category:"convolution",inputs:[{start:2,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:0,name:"outputShape",type:"number[]"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"DepthwiseConv2d",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"DepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"Conv3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]}]}),uy=Object.freeze({json:[{tfOpName:"Fill",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"},{start:1,name:"value",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"LinSpace",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"num",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"OneHot",category:"creation",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"depth",type:"number"},{start:2,name:"onValue",type:"number",defaultValue:1},{start:3,name:"offValue",type:"number",defaultValue:0}],attrs:[{tfName:"axis",name:"axis",type:"number",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ones",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"OnesLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"RandomUniform",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number",defaultValue:0},{tfName:"maxval",name:"maxval",type:"number",defaultValue:1},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Range",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"step",type:"number",defaultValue:0}],attrs:[{tfName:"Tidx",name:"dtype",type:"dtype"}]},{tfOpName:"TruncatedNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"means",name:"mean",type:"number",defaultValue:0},{tfName:"stddev",name:"stdDev",type:"number",defaultValue:1},{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Zeros",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"ZerosLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Multinomial",category:"creation",inputs:[{start:0,name:"logits",type:"tensor"},{start:1,name:"numSamples",type:"number"}],attrs:[{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number"},{tfName:"T",name:"dtype",type:"dtype"},{tfName:"output_dtype",name:"output_dtype",type:"dtype"}]}]}),ly=Object.freeze({json:[{tfOpName:"NonMaxSuppressionV2",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV3",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}]},{tfOpName:"Where",category:"dynamic",inputs:[{start:0,name:"condition",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ListDiff",category:"dynamic",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]}),cy=Object.freeze({json:[{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]}]}),py=Object.freeze({json:[{tfOpName:"PlaceholderWithDefault",category:"graph",inputs:[{start:0,name:"default",type:"tensor"}],attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Placeholder",category:"graph",attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Const",category:"graph"},{tfOpName:"Identity",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IdentityN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Snapshot",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Rank",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Size",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Shape",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"ShapeN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Print",category:"graph",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"data",type:"tensors"}],attrs:[{tfName:"message",name:"message",type:"string"},{tfName:"first_n",name:"firstN",type:"number",notSupported:!0},{tfName:"summarize",name:"summarize",type:"number",defaultValue:3}]},{tfOpName:"NoOp",category:"graph",inputs:[]},{tfOpName:"StopGradient",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"FakeQuantWithMinMaxVars",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"min",name:"min",type:"number"},{tfName:"max",name:"max",type:"number"}]}]}),hy=Object.freeze({json:[{tfOpName:"ResizeBilinear",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ResizeNearestNeighbor",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"CropAndResize",category:"image",inputs:[{start:0,name:"image",type:"tensor"},{start:1,name:"boxes",type:"tensor"},{start:2,name:"boxInd",type:"tensor"},{start:3,name:"cropSize",type:"number[]"}],attrs:[{tfName:"method",name:"method",type:"string"},{tfName:"extrapolation_value",name:"extrapolationValue",type:"number"}]}]}),fy=Object.freeze({json:[{tfOpName:"Equal",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NotEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Greater",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"GreaterEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Less",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LessEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalAnd",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalNot",category:"logical",inputs:[{start:0,name:"a",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalOr",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Select",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]}),dy=Object.freeze({json:[{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMulV2",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]}),my=Object.freeze({json:[{tfOpName:"FusedBatchNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV2",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV3",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"LRN",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"depth_radius",name:"radius",type:"number",defaultValue:5},{tfName:"bias",name:"bias",type:"number",defaultValue:1},{tfName:"alpha",name:"alpha",type:"number",defaultValue:1},{tfName:"beta",name:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"LogSoftmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"SparseToDense",category:"normalization",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!0,notSupported:!0}]}]}),gy=Object.freeze({json:[{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]}]}),vy=Object.freeze({json:[{tfOpName:"ConcatV2",category:"slice_join",inputs:[{start:0,end:-1,name:"tensors",type:"tensors"},{start:-1,name:"axis",type:"number"}]},{tfOpName:"Concat",category:"slice_join",inputs:[{start:1,end:0,name:"tensors",type:"tensors"},{start:0,name:"axis",type:"number"}]},{tfOpName:"GatherV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Gather",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"validate_indices",name:"validateIndices",type:"bool",notSupported:!0}]},{tfOpName:"Reverse",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"dims",type:"bool",notSupported:!0}]},{tfOpName:"ReverseV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}]},{tfOpName:"Slice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"size",type:"number[]"}]},{tfOpName:"StridedSlice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"end",type:"number[]"},{start:3,name:"strides",type:"number[]"}],attrs:[{tfName:"begin_mask",name:"beginMask",type:"number",defaultValue:0},{tfName:"end_mask",name:"endMask",type:"number",defaultValue:0},{tfName:"new_axis_mask",name:"newAxisMask",type:"number",defaultValue:0},{tfName:"ellipsis_mask",name:"ellipsisMask",type:"number",defaultValue:0},{tfName:"shrink_axis_mask",name:"shrinkAxisMask",type:"number",defaultValue:0}]},{tfOpName:"Pack",category:"slice_join",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Unpack",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"num",name:"num",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Tile",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"reps",type:"number[]"}]},{tfOpName:"Split",category:"slice_join",inputs:[{start:0,name:"axis",type:"number",defaultValue:0},{start:1,name:"x",type:"tensor"}],attrs:[{tfName:"num_split",name:"numOrSizeSplits",type:"number",defaultValue:1}]},{tfOpName:"SplitV",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"numOrSizeSplits",type:"number[]"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"ScatterNd",category:"slice_join",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"shape",type:"number[]"}]},{tfOpName:"GatherNd",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}]},{tfOpName:"SparseToDense",category:"slice_join",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!1,notSupported:!0}]}]}),yy=Object.freeze({json:[{tfOpName:"FFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"RFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]},{tfOpName:"IRFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]}]}),by=Object.freeze({json:[{tfOpName:"Cast",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"SrcT",name:"sdtype",type:"dtype",notSupported:!0},{tfName:"DstT",name:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Pad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"constant_value",name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"},{start:2,name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"Squeeze",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"axis",tfDeprecatedName:"squeeze_dims",name:"axis",type:"number[]"}]},{tfOpName:"SpaceToBatchND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"paddings",type:"number[]"}]},{tfOpName:"BatchToSpaceND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"crops",type:"number[]"}]},{tfOpName:"DepthToSpace",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"block_size",name:"blockSize",type:"number"},{tfName:"data_format",name:"dataFormat",type:"string"}]}]}),xy=function(){function t(){var t=[iy,ay,oy,sy,uy,ly,cy,fy,hy,py,dy,my,gy,vy,yy,by],e=[].concat.apply([],t.map(function(t){return t.json}));this.opMappers=e.reduce(function(t,e){return t[e.tfOpName]=e,t},{})}return Object.defineProperty(t,"Instance",{get:function(){return this._instance||(this._instance=new this)},enumerable:!0,configurable:!0}),t.prototype.transformGraph=function(t){var e=this,n=[],r=[],i=t.node.reduce(function(t,i){return t[i.name]=e.mapNode(i),"Placeholder"===i.op&&n.push(t[i.name]),"Const"===i.op&&r.push(t[i.name]),t},{}),a=[],o=[],s=Object.keys(i);return s.forEach(function(t){var e=i[t];e.inputNames.forEach(function(t){var n=ty(t)[0];e.inputs.push(i[n]),i[n].children.push(e)}),0===e.inputs.length&&a.push(e)}),s.forEach(function(t){var e=i[t];0===e.children.length&&o.push(e)}),{nodes:i,inputs:a,outputs:o,weights:r,placeholders:n}},t.prototype.mapNode=function(t){var e=Jv(t.op)||this.opMappers[t.op]||{};null==t.attr&&(t.attr={});var n={name:t.name,op:t.op,category:e.category,inputNames:(t.input||[]).map(function(t){return t.startsWith("^")?t.substr(1):t}),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:t.attr};return null!=e.inputs&&(n.inputParams=e.inputs.reduce(function(t,e){return t[e.name]={type:e.type,inputIndexStart:e.start,inputIndexEnd:e.end},t},{})),null!=e.attrs&&(n.attrParams=e.attrs.reduce(function(e,n){var r=n.type,i=void 0;switch(n.type){case"string":void 0===(i=Cy(t.attr,n.tfName,n.defaultValue))&&n.tfDeprecatedName&&(i=Cy(t.attr,n.tfDeprecatedName,n.defaultValue));break;case"string[]":void 0===(i=Dy(t.attr,n.tfName,n.defaultValue))&&n.tfDeprecatedName&&(i=Dy(t.attr,n.tfDeprecatedName,n.defaultValue));break;case"number":void 0===(i=Ey(t.attr,n.tfName,n.defaultValue||0))&&n.tfDeprecatedName&&(i=Ey(t.attr,n.tfDeprecatedName,n.defaultValue));break;case"number[]":void 0===(i=Ty(t.attr,n.tfName,n.defaultValue))&&n.tfDeprecatedName&&(i=Ty(t.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool":void 0===(i=Ny(t.attr,n.tfName,n.defaultValue))&&n.tfDeprecatedName&&(i=Ny(t.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool[]":void 0===(i=_y(t.attr,n.tfName,n.defaultValue))&&n.tfDeprecatedName&&(i=_y(t.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape":void 0===(i=Ry(t.attr,n.tfName,n.defaultValue))&&n.tfDeprecatedName&&(i=Ry(t.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape[]":void 0===(i=Oy(t.attr,n.tfName,n.defaultValue))&&n.tfDeprecatedName&&(i=Oy(t.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype":void 0===(i=ky(t.attr,n.tfName,n.defaultValue))&&n.tfDeprecatedName&&(i=ky(t.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype[]":void 0===(i=Iy(t.attr,n.tfName,n.defaultValue))&&n.tfDeprecatedName&&(i=Iy(t.attr,n.tfDeprecatedName,n.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error("Unsupported param type: "+n.type+" for op: "+t.op)}return e[n.name]={value:i,type:r},e},{})),n},t}();function wy(e,n){var r=Array.isArray(e)?String.fromCharCode.apply(null,e):function(e){var n=t.ENV.global;if(void 0!==n.atob)return n.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()")}(e);return n?r:r.toLowerCase()}function Cy(t,e,n,r){void 0===r&&(r=!1);var i=t[e];return null!=i?wy(i.s,r):n}function Ny(t,e,n){var r=t[e];return r?r.b:n}function Ey(t,e,n){var r=t[e]||{},i=null!=r.i?r.i:null!=r.f?r.f:n;return"number"==typeof i?i:parseInt(i,10)}function Sy(t){switch("string"==typeof t&&(t=Gv[t]),t){case Gv.DT_FLOAT:return"float32";case Gv.DT_INT32:return"int32";case Gv.DT_BOOL:return"bool";case Gv.DT_DOUBLE:return"float32";case Gv.DT_STRING:return"string";default:return null}}function ky(t,e,n){var r=t[e];return r&&r.type?Sy(r.type):n}function Iy(t,e,n){var r=t[e];return r&&r.list&&r.list.type?r.list.type.map(function(t){return Sy(t)}):n}function Ay(t){if(!t.unknownRank)return null!=t.dim?t.dim.map(function(t){return"number"==typeof t.size?t.size:parseInt(t.size,10)}):[]}function Ry(t,e,n){var r=t[e];return r&&r.shape?Ay(r.shape):n}function Ty(t,e,n){var r=t[e];return r?((r.list.f&&r.list.f.length?r.list.f:r.list.i)||[]).map(function(t){return"number"==typeof t?t:parseInt(t,10)}):n}function Dy(t,e,n,r){void 0===r&&(r=!1);var i=t[e];return i&&i.list&&i.list.s?i.list.s.map(function(t){return wy(t,r)}):n}function Oy(t,e,n){var r=t[e];return r&&r.list&&r.list.shape?r.list.shape.map(function(t){return Ay(t)}):n}function _y(t,e,n){var r=t[e];return r&&r.list&&r.list.b?r.list.b:n}var Fy=function(){function t(t,e,n){var r=this;this.node=t,this.tensorMap=e,this.context=n,this.inputs=[],this.attrs={},this.inputs=t.inputNames.map(function(t){return r.getInput(t)}),null!=t.rawAttrs&&(this.attrs=Object.keys(t.rawAttrs).reduce(function(t,e){return t[e]=r.getAttr(e),t},{}))}return t.prototype.getInput=function(t){return Qv(t,this.tensorMap,this.context)},t.prototype.getAttr=function(t,e){var n=this.node.rawAttrs[t];if(null!=n.tensor)return Qv(t,this.tensorMap,this.context);if(null!=n.i||null!=n.f)return Ey(this.node.rawAttrs,t,e);if(null!=n.s)return Cy(this.node.rawAttrs,t,e);if(null!=n.b)return Ny(this.node.rawAttrs,t,e);if(null!=n.shape)return Ry(this.node.rawAttrs,t,e);if(null!=n.type)return ky(this.node.rawAttrs,t,e);if(null!=n.list){if(null!=n.list.i||null!=n.list.f)return Ty(this.node.rawAttrs,t,e);if(null!=n.list.s)return Dy(this.node.rawAttrs,t,e);if(null!=n.list.shape)return Oy(this.node.rawAttrs,t,e);if(null!=n.list.b)return _y(this.node.rawAttrs,t,e);if(null!=n.list.type)return Iy(this.node.rawAttrs,t,e)}return e},t}(),zy=function(t,e,n){switch(t.op){case"BiasAdd":case"AddV2":case"Add":return[$s(Zv("a",t,e,n),Zv("b",t,e,n))];case"AddN":return[Xs(Zv("tensors",t,e,n))];case"FloorMod":case"Mod":return[au(Zv("a",t,e,n),Zv("b",t,e,n))];case"Mul":return[su(Zv("a",t,e,n),Zv("b",t,e,n))];case"RealDiv":case"Div":return[Zs(Zv("a",t,e,n),Zv("b",t,e,n))];case"FloorDiv":return[tu(Zv("a",t,e,n),Zv("b",t,e,n))];case"Sub":return[fu(Zv("a",t,e,n),Zv("b",t,e,n))];case"Minimum":return[ru(Zv("a",t,e,n),Zv("b",t,e,n))];case"Maximum":return[eu(Zv("a",t,e,n),Zv("b",t,e,n))];case"Pow":return[lu(Zv("a",t,e,n),Zv("b",t,e,n))];case"SquaredDifference":return[pu(Zv("a",t,e,n),Zv("b",t,e,n))];default:throw TypeError("Node type "+t.op+" is not implemented")}},My=function(t,e,n){switch(t.op){case"Abs":case"ComplexAbs":return[Ko(Zv("x",t,e,n))];case"Acos":return[$o(Zv("x",t,e,n))];case"Acosh":return[Xo(Zv("x",t,e,n))];case"Asin":return[Yo(Zv("x",t,e,n))];case"Asinh":return[Jo(Zv("x",t,e,n))];case"Atan":return[Zo(Zv("x",t,e,n))];case"Atan2":return[Js(Zv("x",t,e,n),Zv("y",t,e,n))];case"Atanh":return[Qo(Zv("x",t,e,n))];case"Ceil":return[ts(Zv("x",t,e,n))];case"Complex":return[Qe(Zv("real",t,e,n),Zv("imag",t,e,n))];case"Cos":return[ns(Zv("x",t,e,n))];case"Cosh":return[rs(Zv("x",t,e,n))];case"Elu":return[El(Zv("x",t,e,n))];case"Erf":return[is(Zv("x",t,e,n))];case"Exp":return[as(Zv("x",t,e,n))];case"Expm1":return[os(Zv("x",t,e,n))];case"Floor":return[ss(Zv("x",t,e,n))];case"Log":return[us(Zv("x",t,e,n))];case"Log1p":return[ls(Zv("x",t,e,n))];case"Imag":return[en(Zv("x",t,e,n))];case"Neg":return[ps(Zv("x",t,e,n))];case"Reciprocal":return[hs(Zv("x",t,e,n))];case"Real":return[tn(Zv("x",t,e,n))];case"Relu":return[Il(Zv("x",t,e,n))];case"Round":return[fs(Zv("x",t,e,n))];case"Selu":return[Rl(Zv("x",t,e,n))];case"Sigmoid":return[ms(Zv("x",t,e,n))];case"Sin":return[xs(Zv("x",t,e,n))];case"Sign":return[gs(Zv("x",t,e,n))];case"Sinh":return[ws(Zv("x",t,e,n))];case"Softplus":return[Cs(Zv("x",t,e,n))];case"Sqrt":return[Ns(Zv("x",t,e,n))];case"Square":return[Es(Zv("x",t,e,n))];case"Tanh":return[Is(Zv("x",t,e,n))];case"Tan":return[ks(Zv("x",t,e,n))];case"Relu6":case"ClipByValue":return[es(Zv("x",t,e,n),Zv("clipValueMin",t,e,n),Zv("clipValueMax",t,e,n))];case"Rsqrt":return[ds(Qv(t.inputNames[0],e,n))];case"Prod":return[Nl(Zv("x",t,e,n),Zv("axes",t,e,n))];case"LeakyRelu":return[Sl(Zv("x",t,e,n),Zv("alpha",t,e,n))];default:throw TypeError("Node type "+t.op+" is not implemented")}},Ly=function(){function t(e,n,r,i,a,o,s){this.name=e,this.dtype=n,this.maxSize=r,this.elementShape=i,this.identicalElementShapes=a,this.dynamicSize=o,this.clearAfterRead=s,this.tensors=[],this.closed_=!1,this.id=t.nextId++}return Object.defineProperty(t.prototype,"closed",{get:function(){return this.closed_},enumerable:!0,configurable:!0}),t.prototype.clearAndClose=function(){this.tensors.forEach(function(t){return t.tensor.dispose()}),this.tensors=[],this.closed_=!0},t.prototype.size=function(){return this.tensors.length},t.prototype.read=function(t){if(this.closed_)throw new Error("TensorArray "+this.name+" has already been closed.");if(t<0||t>=this.tensors.length)throw new Error("Tried to read from index "+t+", but array size is: "+this.tensors.length);var e=this.tensors[t];if(e.cleared)throw new Error("TensorArray "+this.name+": Could not read index "+t+" twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).");return this.clearAfterRead&&(e.cleared=!0),e.read=!0,e.tensor},t.prototype.readMany=function(t){var e=this;return t.map(function(t){return e.read(t)})},t.prototype.write=function(t,e){if(this.closed_)throw new Error("TensorArray "+this.name+" has already been closed.");if(t<0||!this.dynamicSize&&t>=this.maxSize)throw new Error("Tried to write to index "+t+", but array is not resizeable and size is: "+this.maxSize);var n=this.tensors[t]||{};if(e.dtype!==this.dtype)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+t+",\n because the value dtype is "+e.dtype+", but TensorArray dtype is "+this.dtype+".");if(0!==this.size()||null!=this.elementShape&&0!==this.elementShape.length||(this.elementShape=e.shape),this.assertShapesMatchAllowUndefinedSize(this.elementShape,e.shape,"TensorArray "+this.name+": Could not write to TensorArray index "+t+"."),n&&n.read)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+t+", because it has already been read.");if(n&&n.written)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+t+", because it has already been written.");n.tensor=e,n.written=!0,this.tensors[t]=n},t.prototype.writeMany=function(t,e){var n=this;if(t.length!==e.length)throw new Error("TensorArray "+this.name+": could not write multiple tensors,because the index size: "+t.length+" is not the same as tensors size: "+e.length+".");t.forEach(function(t,r){return n.write(t,e[r])})},t.prototype.gather=function(t,e){if(e&&e!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but gather requested dtype "+e);if(!t){t=[];for(var n=0;n<this.size();n++)t.push(n)}if(0===t.length)return nn([],[0].concat(this.elementShape));var r=this.readMany(t);return this.assertShapesMatchAllowUndefinedSize(this.elementShape,r[0].shape,"TensorArray shape mismatch: "),or(r,0)},t.prototype.concat=function(t){if(t&&t!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but concat requested dtype "+t);if(0===this.size())return nn([],[0].concat(this.elementShape));for(var e=[],n=0;n<this.size();n++)e.push(n);var r=this.readMany(e);return this.assertShapesMatchAllowUndefinedSize(this.elementShape,r[0].shape,"TensorArray shape mismatch: tensor array shape ("+this.elementShape+") vs first tensor shape ("+r[0].shape+")"),bn(r,0)},t.prototype.scatter=function(t,e){if(e.dtype!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but tensor has dtype "+e.dtype);if(t.length!==e.shape[0])throw new Error("Expected len(indices) == tensor.shape[0], but saw: "+t.length+" vs. "+e.shape[0]);var n=Math.max.apply(Math,t);if(!this.dynamicSize&&n>=this.maxSize)throw new Error("Max index must be < array size ("+n+" vs. "+this.maxSize+")");this.writeMany(t,lr(e,0))},t.prototype.split=function(t,e){var n=this;if(e.dtype!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but tensor has dtype "+e.dtype);var r=0,i=t.map(function(t){return r+=t});if(r!==e.shape[0])throw new Error("Expected sum of lengths to be equal to\n tensor.shape[0], but sum of lengths is\n "+r+", and tensor's shape is: "+e.shape);if(!this.dynamicSize&&t.length!==this.maxSize)throw new Error("TensorArray's size is not equal to the size of lengths ("+this.maxSize+" vs. "+t.length+"), and the TensorArray is not marked as dynamically resizeable");var a=0===r?0:e.size/r,o=[];_e(function(){e=e.reshape([1,r,a]);for(var s=0;s<t.length;++s){var u=[0,0===s?0:i[s-1],0],l=[1,t[s],a];o[s]=sl(e,u,l).reshape(n.elementShape)}return o});for(var s=[],u=0;u<t.length;u++)s[u]=u;this.writeMany(s,o)},t.prototype.assertShapesMatchAllowUndefinedSize=function(t,e,n){void 0===n&&(n=""),$.assert(this.shapesEqualAllowUndefinedSize(t,e),function(){return n+" Shapes "+t+" and "+e+" must match"})},t.prototype.shapesEqualAllowUndefinedSize=function(t,e){if(t.length!==e.length)return!1;for(var n=0;n<t.length;n++)if(-1!==t[n]&&-1!==e[n]&&t[n]!==e[n])return!1;return!0},t.nextId=0,t}();var Py=function(t,e,n){var r,i;switch(t.op){case"Conv1D":var a=Zv("stride",t,e,n),o=Zv("pad",t,e,n),s=Zv("dataFormat",t,e,n).toUpperCase(),u=Zv("dilation",t,e,n);return[zu(Zv("x",t,e,n),Zv("filter",t,e,n),a,o,s,u)];case"Conv2D":a=Zv("strides",t,e,n),o=Zv("pad",t,e,n),s=Zv("dataFormat",t,e,n).toUpperCase();var l=Zv("dilations",t,e,n);return[Mu(Zv("x",t,e,n),Zv("filter",t,e,n),[a[1],a[2]],o,s,[l[1],l[2]])];case"_FusedConv2D":var c=(r=Zv("fusedOps",t,e,n))[0],p=r[1],h="biasadd"===c,f="prelu"===p,d="fusedbatchnorm"===c,m=Zv("numArgs",t,e,n);if(h){if(f&&2!==m)throw new Error("Fused Conv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!f&&1!==m)throw new Error("Fused Conv2d with BiasAdd must have one extra argument: bias.")}if(d)throw new Error("Fused Conv2d with FusedBatchNorm is not supported.");a=Zv("strides",t,e,n),o=Zv("pad",t,e,n),s=Zv("dataFormat",t,e,n).toUpperCase(),l=Zv("dilations",t,e,n);var g=(i=Zv("args",t,e,n))[0],v=i[1];return[Ec.conv2d({x:Zv("x",t,e,n),filter:Zv("filter",t,e,n),strides:[a[1],a[2]],pad:o,dataFormat:s,dilations:[l[1],l[2]],bias:g,activation:p,preluActivationWeights:v})];case"Conv2DBackpropInput":case"Conv2dTranspose":var y=Zv("outputShape",t,e,n);return a=Zv("strides",t,e,n),o=Zv("pad",t,e,n),[Gu(Zv("x",t,e,n),Zv("filter",t,e,n),y,[a[1],a[2]],o)];case"DepthwiseConv2dNative":case"DepthwiseConv2d":return a=Zv("strides",t,e,n),o=Zv("pad",t,e,n),l=Zv("dilations",t,e,n),s=Zv("dataFormat",t,e,n).toUpperCase(),[Wu(Zv("input",t,e,n),Zv("filter",t,e,n),[a[1],a[2]],o,s,[l[1],l[2]])];case"Conv3D":return a=Zv("strides",t,e,n),o=Zv("pad",t,e,n),s=Zv("dataFormat",t,e,n).toUpperCase(),l=Zv("dilations",t,e,n),[Lu(Zv("x",t,e,n),Zv("filter",t,e,n),[a[1],a[2],a[3]],o,s,[l[1],l[2],l[3]])];case"AvgPool":a=Zv("strides",t,e,n),o=Zv("pad",t,e,n);var b=Zv("kernelSize",t,e,n);return[rl(Zv("x",t,e,n),[b[1],b[2]],[a[1],a[2]],o)];case"MaxPool":return a=Zv("strides",t,e,n),o=Zv("pad",t,e,n),b=Zv("kernelSize",t,e,n),[nl(Zv("x",t,e,n),[b[1],b[2]],[a[1],a[2]],o)];case"AvgPool3D":return a=Zv("strides",t,e,n),o=Zv("pad",t,e,n),b=Zv("kernelSize",t,e,n),[ol(Zv("x",t,e,n),[b[1],b[2],b[3]],[a[1],a[2],a[3]],o)];case"MaxPool3D":return a=Zv("strides",t,e,n),o=Zv("pad",t,e,n),b=Zv("kernelSize",t,e,n),[al(Zv("x",t,e,n),[b[1],b[2],b[3]],[a[1],a[2],a[3]],o)];default:throw TypeError("Node type "+t.op+" is not implemented")}},By=function(t,e,n){switch(t.op){case"Fill":var r=Zv("shape",t,e,n),i=Zv("dtype",t,e,n);return[dn(r,Zv("value",t,e,n),i)];case"LinSpace":var a=Zv("start",t,e,n);return[mn(a,Zv("stop",t,e,n),Zv("num",t,e,n))];case"Multinomial":var o=Zv("logits",t,e,n),s=Zv("numSamples",t,e,n),u=Zv("seed",t,e,n);return[Hn(o,s,u)];case"OneHot":var l=Zv("indices",t,e,n),c=Zv("depth",t,e,n),p=Zv("onValue",t,e,n),h=Zv("offValue",t,e,n);return[Kn(l,c,p,h)];case"Ones":return[hn(Zv("shape",t,e,n),Zv("dtype",t,e,n))];case"OnesLike":return[vn(Zv("x",t,e,n))];case"RandomUniform":return[nr(Zv("shape",t,e,n),Zv("minval",t,e,n),Zv("maxval",t,e,n),Zv("dtype",t,e,n))];case"Range":return[gn(a=Zv("start",t,e,n),Zv("stop",t,e,n),Zv("step",t,e,n),Zv("dtype",t,e,n))];case"TruncatedNormal":r=Zv("shape",t,e,n);var f=Zv("mean",t,e,n),d=Zv("stdDev",t,e,n);return u=Zv("seed",t,e,n),[ur(r,f,d,Zv("dtype",t,e,n),u)];case"Zeros":return[fn(Zv("shape",t,e,n),Zv("dtype",t,e,n))];case"ZerosLike":return[yn(Zv("x",t,e,n))];default:throw TypeError("Node type "+t.op+" is not implemented")}};var Wy=function(t,e,n){switch(t.op){case"TopKV2":var r=Zv("x",t,e,n),i=Zv("k",t,e,n),a=Zv("sorted",t,e,n),o=Ll(r,i,a);return[o.values,o.indices];default:throw TypeError("Node type "+t.op+" is not implemented")}},Vy=function(t,e,n){switch(t.op){case"Const":return e[t.name];case"PlaceholderWithDefault":var r=Zv("default",t,e,n);return[Qv(t.name,e,n)||r];case"Placeholder":return[Qv(t.name,e,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":return[Zv("x",t,e,n).clone()];case"IdentityN":return Zv("x",t,e,n).map(function(t){return t.clone()});case"Snapshot":return[Zv("x",t,e,n).clone()];case"Shape":return[on(Zv("x",t,e,n).shape,"int32")];case"ShapeN":return Zv("x",t,e,n).map(function(t){return on(t.shape)});case"Size":return[an(Zv("x",t,e,n).size,"int32")];case"Rank":return[an(Zv("x",t,e,n).rank,"int32")];case"NoOp":return[];case"Print":var i=Zv("x",t,e,n),a=Zv("data",t,e,n),o=Zv("message",t,e,n),s=Zv("summarize",t,e,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(o);for(var u=0;u<a.length;u++)console.log(Array.prototype.slice.call(a[u].dataSync()).slice(0,s));return[i];default:throw TypeError("Node type "+t.op+" is not implemented")}},Uy=function(t,e,n){switch(t.op){case"ResizeBilinear":var r=Zv("images",t,e,n),i=Zv("size",t,e,n),a=Zv("alignCorners",t,e,n);return[xc.resizeBilinear(r,[i[0],i[1]],a)];case"ResizeNearestNeighbor":return r=Zv("images",t,e,n),i=Zv("size",t,e,n),a=Zv("alignCorners",t,e,n),[xc.resizeNearestNeighbor(r,[i[0],i[1]],a)];case"CropAndResize":var o=Zv("image",t,e,n),s=Zv("boxes",t,e,n),u=Zv("boxInd",t,e,n),l=Zv("cropSize",t,e,n),c=Zv("method",t,e,n),p=Zv("extrapolationValue",t,e,n);return[xc.cropAndResize(o,s,u,l,c,p)];default:throw TypeError("Node type "+t.op+" is not implemented")}},jy=function(t,e,n){switch(t.op){case"Equal":return[mu(Zv("a",t,e,n),Zv("b",t,e,n))];case"NotEqual":return[Su(Zv("a",t,e,n),Zv("b",t,e,n))];case"Greater":return[vu(Zv("a",t,e,n),Zv("b",t,e,n))];case"GreaterEqual":return[yu(Zv("a",t,e,n),Zv("b",t,e,n))];case"Less":return[wu(Zv("a",t,e,n),Zv("b",t,e,n))];case"LessEqual":return[Cu(Zv("a",t,e,n),Zv("b",t,e,n))];case"LogicalAnd":return[Us(Zv("a",t,e,n),Zv("b",t,e,n))];case"LogicalNot":return[js(Zv("a",t,e,n))];case"LogicalOr":return[Gs(Zv("a",t,e,n),Zv("b",t,e,n))];case"Select":return[Hs(Zv("condition",t,e,n),Zv("a",t,e,n),Zv("b",t,e,n))];default:throw TypeError("Node type "+t.op+" is not implemented")}},Gy=function(t,e,n){switch(t.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[Hu(Zv("a",t,e,n),Zv("b",t,e,n),Zv("transposeA",t,e,n),Zv("transposeB",t,e,n))];case"Transpose":return[Tl(Zv("x",t,e,n),Zv("perm",t,e,n))];default:throw TypeError("Node type "+t.op+" is not implemented")}},qy=function(t,e,n){switch(t.op){case"FusedBatchNorm":case"FusedBatchNormV2":case"FusedBatchNormV3":return[Ps(Zv("x",t,e,n),Zv("mean",t,e,n),Zv("variance",t,e,n),Zv("offset",t,e,n),Zv("scale",t,e,n),Zv("epsilon",t,e,n))];case"LRN":return[Dl(Zv("x",t,e,n),Zv("radius",t,e,n),Zv("bias",t,e,n),Zv("alpha",t,e,n),Zv("beta",t,e,n))];case"Softmax":return[Rr(Zv("x",t,e,n))];case"LogSoftmax":return[Tr(Zv("x",t,e,n))];case"SparseToDense":return[Gl(Zv("sparseIndices",t,e,n),Zv("outputShape",t,e,n),Zv("sparseValues",t,e,n),Zv("defaultValue",t,e,n))];default:throw TypeError("Node type "+t.op+" is not implemented")}},Hy=function(t,e,n){switch(t.op){case"Max":var r=Zv("axis",t,e,n),i=Zv("keepDims",t,e,n);return[yl(Zv("x",t,e,n),r,i)];case"Mean":return r=Zv("axis",t,e,n),i=Zv("keepDims",t,e,n),[bl(Zv("x",t,e,n),r,i)];case"Min":return r=Zv("axis",t,e,n),i=Zv("keepDims",t,e,n),[xl(Zv("x",t,e,n),r,i)];case"Sum":return r=Zv("axis",t,e,n),i=Zv("keepDims",t,e,n),[Cl(Zv("x",t,e,n),r,i)];case"All":return r=Zv("axis",t,e,n),i=Zv("keepDims",t,e,n),[fl(Zv("x",t,e,n),r,i)];case"Any":return r=Zv("axis",t,e,n),i=Zv("keepDims",t,e,n),[dl(Zv("x",t,e,n),r,i)];case"ArgMax":return r=Zv("axis",t,e,n),[ml(Zv("x",t,e,n),r)];case"ArgMin":return r=Zv("axis",t,e,n),[gl(Zv("x",t,e,n),r)];case"Prod":return r=Zv("axis",t,e,n),i=Zv("keepDims",t,e,n),[Nl(Zv("x",t,e,n),r,i)];default:throw TypeError("Node type "+t.op+" is not implemented")}},Ky=function(t,e,n){switch(t.op){case"ConcatV2":case"Concat":var r=Zv("axis",t,e,n),i=Zv("tensors",t,e,n);return[bn(i,r)];case"GatherV2":case"Gather":r=Zv("axis",t,e,n);var a=Zv("x",t,e,n),o=Zv("indices",t,e,n);return[Ru(a,o.asType("int32"),r)];case"ReverseV2":case"Reverse":return r=Zv("axis",t,e,n),a=Zv("x",t,e,n),[Xu(a,r)];case"Slice":var s=Zv("begin",t,e,n),u=Zv("size",t,e,n);return[sl(Zv("x",t,e,n),s,u)];case"StridedSlice":s=Zv("begin",t,e,n);var l=Zv("end",t,e,n),c=Zv("strides",t,e,n),p=Zv("beginMask",t,e,n),h=Zv("endMask",t,e,n),f=Zv("ellipsisMask",t,e,n),d=Zv("newAxisMask",t,e,n),m=Zv("shrinkAxisMask",t,e,n),g=Zv("x",t,e,n);if(1===s.length&&g.shape.length>1)for(var v=1;v<g.shape.length;v++)s.push(0),l.push(g.shape[v]),c.push(c[0]);return[Ml(g,s,l,c,p,h,f,d,m)];case"Pack":return _e(function(){var r=Zv("axis",t,e,n),i=Zv("tensors",t,e,n),a=i[0].shape,o=i[0].squeeze().shape,s=i.map(function(t){var e=$.arraysEqual(t.shape,a);if(!e&&!$.arraysEqual(t.squeeze().shape,o))throw new Error("the input tensors shape does not match");return e?t:t.reshape(a)});return[or(s,r)]});case"Unpack":return _e(function(){var r=Zv("axis",t,e,n),i=Zv("tensor",t,e,n);return lr(i,r)});case"Tile":var y=Zv("reps",t,e,n);return[sr(Zv("x",t,e,n),y)];case"Split":case"SplitV":r=Zv("axis",t,e,n);var b=Zv("numOrSizeSplits",t,e,n);return En(Zv("x",t,e,n),b,r);case"ScatterNd":o=Zv("indices",t,e,n);var x=Zv("values",t,e,n),w=Zv("shape",t,e,n);return[Pl(o,x,w)];case"GatherNd":var C=Zv("x",t,e,n);return o=Zv("indices",t,e,n),[ql(C,o)];case"SparseToDense":o=Zv("sparseIndices",t,e,n),w=Zv("outputShape",t,e,n);var N=Zv("sparseValues",t,e,n),E=Zv("defaultValue",t,e,n);return[Gl(o,N,w,N.dtype===E.dtype?E:E.asType(N.dtype))];default:throw TypeError("Node type "+t.op+" is not implemented")}},$y=function(t,e,n){switch(t.op){case"FFT":return[Bl(Zv("x",t,e,n))];case"IFFT":return[Wl(Zv("x",t,e,n))];case"RFFT":return[Vl(Zv("x",t,e,n))];case"IRFFT":return[Ul(Zv("x",t,e,n))];default:throw TypeError("Node type "+t.op+" is not implemented")}},Xy=function(t,e,n){switch(t.op){case"Cast":return[Wn(Zv("x",t,e,n),Zv("dtype",t,e,n))];case"ExpandDims":var r=Zv("axis",t,e,n);return[Gn(Zv("x",t,e,n),r)];case"Squeeze":return r=Zv("axis",t,e,n),[ar(Zv("x",t,e,n),r)];case"Reshape":return[rr(Zv("x",t,e,n),Zv("shape",t,e,n))];case"PadV2":case"Pad":return[$n(Zv("x",t,e,n),ry(Zv("padding",t,e,n),2),Zv("constantValue",t,e,n))];case"SpaceToBatchND":var i=Zv("blockShape",t,e,n),a=ry(Zv("paddings",t,e,n),2);return[ir(Zv("x",t,e,n),i,a)];case"BatchToSpaceND":i=Zv("blockShape",t,e,n);var o=ry(Zv("crops",t,e,n),2);return[Bn(Zv("x",t,e,n),i,o)];case"DepthToSpace":var s=Zv("blockSize",t,e,n),u=Zv("dataFormat",t,e,n).toUpperCase();return[jn(Zv("x",t,e,n),s,u)];default:throw TypeError("Node type "+t.op+" is not implemented")}};function Yy(t,e,n){var r=function(t,e,n){switch(t.category){case"arithmetic":return zy(t,e,n);case"basic_math":return My(t,e,n);case"control":return function(t,e,n){return $v(this,void 0,void 0,function(){var r,i,a,o,s,u,l,c,p,h,f,d,m,g,v,y,b,x,w,C,N,E,S,k,I,A,R,T,D,O,_,F,z,M;return Xv(this,function(L){switch(L.label){case 0:switch(t.op){case"LoopCond":return[3,1];case"Switch":return[3,2];case"Merge":return[3,4];case"Enter":return[3,5];case"Exit":return[3,6];case"NextIteration":return[3,7];case"TensorArrayV3":return[3,8];case"TensorArrayWriteV3":return[3,9];case"TensorArrayReadV3":return[3,10];case"TensorArrayGatherV3":return[3,11];case"TensorArrayScatterV3":return[3,12];case"TensorArrayConcatV3":return[3,13];case"TensorArraySplitV3":return[3,14];case"TensorArraySizeV3":return[3,15];case"TensorArrayCloseV3":return[3,16]}return[3,17];case 1:return[2,[Zv("pred",t,e,n).clone()]];case 2:return r=Zv("pred",t,e,n),i=Zv("data",t,e,n),[4,r.data()];case 3:return[2,L.sent()[0]?[void 0,i.clone()]:[i.clone(),void 0]];case 4:return[2,(a=t.inputNames.find(function(t){return void 0!==Qv(t,e,n)}))?[Qv(a,e,n).clone()]:void 0];case 5:return o=Zv("frameName",t,e,n),s=Zv("tensor",t,e,n),n.enterFrame(o),[2,[s.clone()]];case 6:return u=Zv("tensor",t,e,n),n.exitFrame(),[2,[u.clone()]];case 7:return l=Zv("tensor",t,e,n),n.nextIteration(),[2,[l.clone()]];case 8:return c=Zv("size",t,e,n),p=Zv("dtype",t,e,n),h=Zv("elementShape",t,e,n),f=Zv("dynamicSize",t,e,n),d=Zv("clearAfterRead",t,e,n),m=Zv("identicalElementShapes",t,e,n),g=Zv("name",t,e,n),v=new Ly(g,p,c,h,m,f,d),n.addTensorArray(v),[2,[an(v.id),an(1)]];case 9:return y=Zv("tensorArrayId",t,e,n),b=Zv("index",t,e,n),x=Zv("tensor",t,e,n),n.getTensorArray(y).write(b,x),[2,[an(1)]];case 10:return w=Zv("tensorArrayId",t,e,n),C=Zv("index",t,e,n),[2,[n.getTensorArray(w).read(C)]];case 11:return N=Zv("tensorArrayId",t,e,n),E=Zv("indices",t,e,n),S=Zv("dtype",t,e,n),[2,[n.getTensorArray(N).gather(E,S)]];case 12:return k=Zv("tensorArrayId",t,e,n),I=Zv("indices",t,e,n),A=Zv("tensor",t,e,n),n.getTensorArray(k).scatter(I,A),[2,[an(1)]];case 13:return R=Zv("tensorArrayId",t,e,n),T=n.getTensorArray(R),D=Zv("dtype",t,e,n),[2,[T.concat(D)]];case 14:return O=Zv("tensorArrayId",t,e,n),_=Zv("tensor",t,e,n),F=Zv("lengths",t,e,n),n.getTensorArray(O).split(F,_),[2,[an(1)]];case 15:return z=Zv("tensorArrayId",t,e,n),[2,[an(n.getTensorArray(z).size(),"int32")]];case 16:return M=Zv("tensorArrayId",t,e,n),n.getTensorArray(M).clearAndClose(),[2,[]];case 17:throw TypeError("Node type "+t.op+" is not implemented")}})})}(t,e,n);case"convolution":return Py(t,e,n);case"creation":return By(t,e,n);case"dynamic":return function(t,e,n){return $v(this,void 0,void 0,function(){var r,i,a,o,s;return Xv(this,function(u){switch(u.label){case 0:switch(t.op){case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":return[3,1];case"Where":return[3,3];case"ListDiff":return[3,5]}return[3,6];case 1:return r=Zv("boxes",t,e,n),i=Zv("scores",t,e,n),a=Zv("maxOutputSize",t,e,n),o=Zv("iouThreshold",t,e,n),s=Zv("scoreThreshold",t,e,n),[4,xc.nonMaxSuppressionAsync(r,i,a,o,s)];case 2:return[2,[u.sent()]];case 3:return[4,Ks(Zv("condition",t,e,n))];case 4:return[2,[u.sent()]];case 5:return[2,cr(Zv("x",t,e,n),Zv("y",t,e,n))];case 6:throw TypeError("Node type "+t.op+" is not implemented")}})})}(t,e,n);case"evaluation":return Wy(t,e,n);case"image":return Uy(t,e,n);case"graph":return Vy(t,e,n);case"logical":return jy(t,e,n);case"matrices":return Gy(t,e,n);case"normalization":return qy(t,e,n);case"reduction":return Hy(t,e,n);case"slice_join":return Ky(t,e,n);case"spectral":return $y(t,e,n);case"transformation":return Xy(t,e,n);case"custom":var r=Jv(t.op);if(r&&r.customExecutor)return r.customExecutor(new Fy(t,e,n));throw TypeError("Custom op "+t.op+" is not registered.");default:throw TypeError("Unknown op '"+t.op+"'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()")}}(t,e,n);return r instanceof Promise?r.then(function(t){return[].concat(t)}):[].concat(r)}var Jy=function(){function t(t,e){this.weightMap=t,this.tensorArrayMap=e,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}return t.prototype.newFrame=function(t,e){return{id:t,frameName:e,iterationId:0}},Object.defineProperty(t.prototype,"currentContext",{get:function(){return this.contexts},set:function(t){this.contexts!==t&&(this.contexts=t,this.generateCurrentContextIds())},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"currentContextId",{get:function(){return this._currentContextIds[0]},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"currentContextIds",{get:function(){return this._currentContextIds},enumerable:!0,configurable:!0}),t.prototype.generateCurrentContextIds=function(){for(var t=[],e=0;e<this.contexts.length-1;e++){var n=this.contexts.slice(0,this.contexts.length-e);t.push(this.contextIdforContexts(n))}t.push(""),this._currentContextIds=t},t.prototype.contextIdforContexts=function(t){return t?t.map(function(t){return 0===t.id&&0===t.iterationId?"":t.frameName+"-"+t.iterationId}).join("/"):""},t.prototype.enterFrame=function(t){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,t)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))},t.prototype.exitFrame=function(){if(!(this.contexts&&this.contexts.length>1))throw new Error("Cannot exit frame, the context is empty");this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift()},t.prototype.nextIteration=function(){if(!(this.contexts&&this.contexts.length>0))throw new Error("Cannot increase frame iteration, the context is empty");this.contexts=this.contexts.slice(),this.lastId++;var t=Object.assign({},this.contexts[this.contexts.length-1]);t.iterationId+=1,t.id=this.lastId,this.contexts.splice(-1,1,t),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))},t.prototype.getWeight=function(t){return this.weightMap[t]},t.prototype.addTensorArray=function(t){this.tensorArrayMap[t.id]=t},t.prototype.getTensorArray=function(t){return this.tensorArrayMap[t]},t}();function Zy(t,e,n){for(var r=new Set,i=[],a=null,o=null,s=new Set,u=e.slice();u.length>0;){var l=u.pop();(eb(l)||nb(l))&&null==a&&(o=(a=l).children.map(function(t){return t.name}).filter(function(t){return r.has(t)})),r.add(l.name),null==n[l.name]&&null==t[l.name]&&(0!==l.inputs.length?l.inputs.forEach(function(t){s.has(t.name)||(s.add(t.name),u.push(t))}):i.push(l.name))}return{inputs:t,outputs:e,usedNodes:r,missingInputs:i,dynamicNode:a,syncInputs:o}}var Qy=["Switch","Merge","Enter","Exit","NextIteration"],tb=["NonMaxSuppressionV2","NonMaxSuppressionV3","Where"];function eb(t){return Qy.indexOf(t.op)>=0}function nb(t){return tb.indexOf(t.op)>=0}var rb=function(){function t(t){this.graph=t,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this.placeholders=t.placeholders,this._outputs=t.outputs}return Object.defineProperty(t.prototype,"weightMap",{get:function(){return this._weightMap},set:function(t){var e=Object.keys(t).map(function(e){return t[e].map(function(t){return t.id})});this.weightIds=[].concat.apply([],e),this._weightMap=t},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputs",{get:function(){return this.placeholders.map(function(t){return{name:t.name,shape:t.attrParams.shape?t.attrParams.shape.value:void 0,dtype:t.attrParams.dtype?t.attrParams.dtype.value:void 0}})},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"outputs",{get:function(){return this._outputs.map(function(t){return{name:t.name,shape:t.attrParams.shape?t.attrParams.shape.value:void 0,dtype:t.attrParams.dtype?t.attrParams.dtype.value:void 0}})},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputNodes",{get:function(){return this.placeholders.map(function(t){return t.name})},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"outputNodes",{get:function(){return this.outputs.map(function(t){return t.name})},enumerable:!0,configurable:!0}),t.prototype.getCompilationKey=function(t,e){var n=t.map(function(t){return t.name}).sort(),r=e.map(function(t){return t.name}).sort();return n.join(this.SEPERATOR)+"--"+r.join(this.SEPERATOR)},t.prototype.compile=function(t,e){var n=Zy(t,e,this.weightMap),r=n.missingInputs,i=n.dynamicNode,a=n.syncInputs;if(null!=i)throw new Error("This execution contains the node '"+i.name+"', which has the dynamic op '"+i.op+"'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs ["+a+"]");if(r.length>0){var o=e.map(function(t){return t.name}),s=Object.keys(t);throw new Error("Cannot compute the outputs ["+o+"] from the provided inputs ["+s+"]. Missing the following inputs: ["+r+"]")}return function(t,e,n){var r=n.usedNodes,i=n.inputs,a=[];Object.keys(i).map(function(e){return t.nodes[e]}).forEach(function(t){r.has(t.name)&&a.push(t)}),t.weights.forEach(function(t){r.has(t.name)&&a.push(t)});for(var o=new Set,s=[];a.length>0;){var u=a.pop();o.add(u.name),e[u.name]||s.push(u),u.children.forEach(function(t){!o.has(t.name)&&r.has(t.name)&&t.inputs.every(function(t){return o.has(t.name)})&&a.push(t)})}return s}(this.graph,this.weightMap,n)},t.prototype.execute=function(t,e){var n=this,r=Object.keys(t).sort();this.checkInputs(t),this.checkInputShapeAndType(t),this.checkOutputs(e);var i=r.map(function(t){return n.graph.nodes[t]}),a=e.map(function(t){return n.graph.nodes[ny(t)[0]]}),o=this.getCompilationKey(i,a),s=this.compiledMap.get(o);null==s&&(s=this.compile(t,a),this.compiledMap.set(o,s));var u={};return _e(function(){var r=new Jy(n._weightMap,u),i=Kv({},n.weightMap);Object.keys(t).forEach(function(e){i[e]=[t[e]]});for(var a=n.getFrozenTensorIds(i),o={},l=0;l<s.length;l++){var c=s[l];if(!i[c.name]){var p=Yy(c,i,r);if(p instanceof Promise)throw new Error("The execution of the op '"+c.op+"' returned a promise. Please use model.executeAsync() instead.");i[c.name]=p,n.checkTensorForDisposal(c.name,c,i,r,a,e,o)}}return e.map(function(t){return Qv(t,i,r)})})},t.prototype.getFrozenTensorIds=function(t){var e=[].concat.apply([],Object.keys(t).map(function(e){return t[e]}).map(function(t){return t.map(function(t){return t.id})}));return new Set(e)},t.prototype.checkTensorForDisposal=function(t,e,n,r,i,a,o){"control"!==e.category&&-1===a.indexOf(t)&&(n[t].forEach(function(t){null!=t&&(o[t.id]=(o[t.id]||0)+e.children.length)}),e.inputs.forEach(function(t){if("control"!==t.category){var e=function(t,e,n){return e[ey(t,n.currentContextId)]}(t.name,n,r);null!=e&&e.forEach(function(t){if(t&&!i.has(t.id)){var e=o[t.id];1===e?(t.dispose(),delete o[t.id]):null!=e&&o[t.id]--}})}}))},t.prototype.executeAsync=function(t,e){return $v(this,void 0,void 0,function(){var n,r,i,a,o,s,u=this;return Xv(this,function(l){switch(l.label){case 0:return this.checkInputs(t),this.checkInputShapeAndType(t),this.checkOutputs(e),n={},r=new Jy(this._weightMap,n),[4,this.executeWithControlFlow(t,r,e)];case 1:return i=l.sent(),a=e.map(function(t){return Qv(t,i,r)}),o=new Set(a.map(function(t){return t.id})),s=new Set(Object.keys(t).map(function(e){return t[e].id})),Object.keys(i).forEach(function(t){i[t].forEach(function(t){!t||t.isDisposed||o.has(t.id)||s.has(t.id)||-1!==u.weightIds.indexOf(t.id)||t.dispose()})}),[2,a]}})})},t.prototype.executeWithControlFlow=function(t,e,n){return $v(this,void 0,void 0,function(){var r,i,a,o,s,u,l,c,p,h,f,d,m,g,v,y,b=this;return Xv(this,function(x){switch(x.label){case 0:r=Object.keys(t),i=r.map(function(t){return b.graph.nodes[t]}),a=n.map(function(t){return b.graph.nodes[ny(t)[0]]}),o=Zy(t,a,this.weightMap),s=o.usedNodes,u=o.missingInputs,l=o.dynamicNode,c=o.syncInputs,p=i.concat(this.graph.weights).map(function(t){return{node:t,contexts:e.currentContext}}),h=Kv({},this.weightMap),Object.keys(t).forEach(function(e){h[e]=[t[e]]}),f={},d=this.getFrozenTensorIds(h),m={},x.label=1;case 1:return p.length>0?(g=this.processStack(i,p,e,h,m,d,n,f,s),[4,Promise.all(g)]):[3,3];case 2:return x.sent(),[3,1];case 3:if(null==l&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead."),(v=a.filter(function(t){return!eb(t)&&!Qv(t.name,h,e)}).map(function(t){return t.name})).length>0)throw y="",null!=l&&(y="Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs ["+c+"]"),new Error("Cannot compute the outputs ["+v+"] from the provided inputs ["+r+"]. Consider providing the following inputs: ["+u+"]. "+y);return[2,h]}})})},t.prototype.processStack=function(t,e,n,r,i,a,o,s,u){for(var l=this,c=[],p=function(){var p=e.pop();n.currentContext=p.contexts;var f="";if("Enter"===p.node.op&&Zv("isConstant",p.node,r,n)&&(f=ty(p.node.name,n)[0]),-1===t.indexOf(p.node)){var d=Yy(p.node,r,n);f||(f=ty(p.node.name,n)[0]);var m=n.currentContext;d instanceof Promise?c.push(d.then(function(t){return r[f]=t,n.currentContext=m,l.checkTensorForDisposal(f,p.node,r,n,a,o,s),l.processChildNodes(p.node,e,n,r,i,u),t})):(r[f]=d,h.checkTensorForDisposal(f,p.node,r,n,a,o,s),h.processChildNodes(p.node,e,n,r,i,u))}else h.processChildNodes(p.node,e,n,r,i,u)},h=this;e.length>0;)p();return c},t.prototype.processChildNodes=function(t,e,n,r,i,a){t.children.forEach(function(t){var o=ty(t.name,n)[0];!i[o]&&a.has(t.name)&&("Merge"===t.op?t.inputNames.some(function(t){return!!Qv(t,r,n)})&&(i[o]=!0,e.push({contexts:n.currentContext,node:t})):t.inputNames.every(function(t){return!!Qv(t,r,n)})&&(i[o]=!0,e.push({contexts:n.currentContext,node:t})))})},t.prototype.dispose=function(){var t=this;Object.keys(this.weightMap).forEach(function(e){return t.weightMap[e].forEach(function(t){return t.dispose()})})},t.prototype.checkInputShapeAndType=function(t){var e=this;Object.keys(t).forEach(function(n){var r=t[n],i=e.graph.nodes[n];if(i.attrParams.shape&&i.attrParams.shape.value){var a=i.attrParams.shape.value,o=a.length===r.shape.length&&r.shape.every(function(t,e){return-1===a[e]||a[e]===t});$.assert(o,function(){return"The shape of dict['"+i.name+"'] provided in model.execute(dict) must be ["+a+"], but was ["+r.shape+"]"})}i.attrParams.dtype&&i.attrParams.dtype.value&&$.assert(r.dtype===i.attrParams.dtype.value,function(){return"The dtype of dict['"+i.name+"'] provided in model.execute(dict) must be "+i.attrParams.dtype.value+", but was "+r.dtype})})},t.prototype.checkInputs=function(t){var e=this,n=Object.keys(t).filter(function(t){return!e.graph.nodes[t]});if(n.length>0)throw new Error("The dict provided in model.execute(dict) has keys: ["+n+"] that are not part of graph")},t.prototype.checkOutputs=function(t){var e=this;t.forEach(function(t){var n=ny(t)[0];if(!e.graph.nodes[n])throw new Error("The output '"+t+"' is not found in the graph")})},t}(),ib="?tfjs-format=file",ab="model.json",ob=function(){function t(t,e){void 0===e&&(e={}),this.modelUrl=t,this.loadOptions=e,this.version="n/a",null==e&&(this.loadOptions={})}return Object.defineProperty(t.prototype,"modelVersion",{get:function(){return this.version},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputNodes",{get:function(){return this.executor.inputNodes},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"outputNodes",{get:function(){return this.executor.outputNodes},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"inputs",{get:function(){return this.executor.inputs},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"outputs",{get:function(){return this.executor.outputs},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"weights",{get:function(){return this.executor.weightMap},enumerable:!0,configurable:!0}),t.prototype.findIOHandler=function(){var t=this.modelUrl;if(null!=t.load)this.handler=t;else if(null!=this.loadOptions.requestInit)this.handler=Ep.browserHTTPRequest(t,this.loadOptions);else{var e=Ep.getLoadHandlers(t,this.loadOptions.onProgress);if(0===e.length)e.push(Ep.browserHTTPRequest(t,this.loadOptions));else if(e.length>1)throw new Error("Found more than one ("+e.length+") load handlers for URL '"+[t]+"'");this.handler=e[0]}},t.prototype.load=function(){return $v(this,void 0,void 0,function(){var t,e,n;return Xv(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 t=r.sent(),e=t.modelTopology,this.version=e.versions.producer+"."+e.versions.minConsumer,n=Ep.decodeWeights(t.weightData,t.weightSpecs),this.executor=new rb(xy.Instance.transformGraph(e)),this.executor.weightMap=this.convertTensorMapToTensorsMap(n),[2,!0]}})})},t.prototype.predict=function(t,e){return this.execute(t,this.outputNodes)},t.prototype.normalizeInputs=function(t){if(!(t instanceof st||Array.isArray(t)))return t;if((t=Array.isArray(t)?t:[t]).length!==this.inputNodes.length)throw new Error("Input tensor count mismatch,the graph model has "+this.inputNodes.length+" placeholders, while there are "+t.length+" input tensors.");return this.inputNodes.reduce(function(e,n,r){return e[n]=t[r],e},{})},t.prototype.normalizeOutputs=function(t){return t=t||this.outputNodes,Array.isArray(t)?t:[t]},t.prototype.execute=function(t,e){t=this.normalizeInputs(t),e=this.normalizeOutputs(e);var n=this.executor.execute(t,e);return n.length>1?n:n[0]},t.prototype.executeAsync=function(t,e){return $v(this,void 0,void 0,function(){var n;return Xv(this,function(r){switch(r.label){case 0:return t=this.normalizeInputs(t),e=this.normalizeOutputs(e),[4,this.executor.executeAsync(t,e)];case 1:return[2,(n=r.sent()).length>1?n:n[0]]}})})},t.prototype.convertTensorMapToTensorsMap=function(t){return Object.keys(t).reduce(function(e,n){return e[n]=[t[n]],e},{})},t.prototype.dispose=function(){this.executor.dispose()},t}();var sb=function(t,e){return(sb=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,e)};function ub(t,e){function n(){this.constructor=t}sb(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}function lb(t,e,n,r){return new(n||(n=Promise))(function(i,a){function o(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?i(t.value):new n(function(e){e(t.value)}).then(o,s)}u((r=r.apply(t,e||[])).next())})}function cb(t,e){var n,r,i,a,o={label:0,sent:function(){if(1&i[0])throw i[1];return i[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(;o;)try{if(n=1,r&&(i=2&a[0]?r.return:a[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,a[1])).done)return i;switch(r=0,i&&(a=[2&a[0],i.value]),a[0]){case 0:case 1:i=a;break;case 4:return o.label++,{value:a[1],done:!1};case 5:o.label++,r=a[1],a=[0];continue;case 7:a=o.ops.pop(),o.trys.pop();continue;default:if(!(i=(i=o.trys).length>0&&i[i.length-1])&&(6===a[0]||2===a[0])){o=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){o.label=a[1];break}if(6===a[0]&&o.label<i[1]){o.label=i[1],i=a;break}if(i&&o.label<i[2]){o.label=i[2],o.ops.push(a);break}i[2]&&o.ops.pop(),o.trys.pop();continue}a=e.call(t,o)}catch(t){a=[6,t],r=0}finally{n=i=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,s])}}}function pb(t,e){return t(e={exports:{}},e.exports),e.exports}var hb=pb(function(t){!function(t,e,n){function r(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}function i(t,e){var n=new function(t){var e,n=this,r=(e=4022871197,function(t){t=t.toString();for(var n=0;n<t.length;n++){var r=.02519603282416938*(e+=t.charCodeAt(n));r-=e=r>>>0,e=(r*=e)>>>0,e+=4294967296*(r-=e)}return 2.3283064365386963e-10*(e>>>0)});n.next=function(){var t=2091639*n.s0+2.3283064365386963e-10*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=t-(n.c=0|t)},n.c=1,n.s0=r(" "),n.s1=r(" "),n.s2=r(" "),n.s0-=r(t),n.s0<0&&(n.s0+=1),n.s1-=r(t),n.s1<0&&(n.s1+=1),n.s2-=r(t),n.s2<0&&(n.s2+=1),r=null}(t),i=e&&e.state,a=n.next;return a.int32=function(){return 4294967296*n.next()|0},a.double=function(){return a()+1.1102230246251565e-16*(2097152*a()|0)},a.quick=a,i&&("object"==typeof i&&r(i,n),a.state=function(){return r(n,{})}),a}e&&e.exports?e.exports=i:this.alea=i}(0,t)}),fb=pb(function(t){!function(t,e,n){function r(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e}function i(t,e){var n=new function(t){var e=this,n="";e.x=0,e.y=0,e.z=0,e.w=0,e.next=function(){var t=e.x^e.x<<11;return e.x=e.y,e.y=e.z,e.z=e.w,e.w^=e.w>>>19^t^t>>>8},t===(0|t)?e.x=t:n+=t;for(var r=0;r<n.length+64;r++)e.x^=0|n.charCodeAt(r),e.next()}(t),i=e&&e.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},a.int32=n.next,a.quick=a,i&&("object"==typeof i&&r(i,n),a.state=function(){return r(n,{})}),a}e&&e.exports?e.exports=i:this.xor128=i}(0,t)}),db=pb(function(t){!function(t,e,n){function r(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e.v=t.v,e.d=t.d,e}function i(t,e){var n=new function(t){var e=this,n="";e.next=function(){var t=e.x^e.x>>>2;return e.x=e.y,e.y=e.z,e.z=e.w,e.w=e.v,(e.d=e.d+362437|0)+(e.v=e.v^e.v<<4^t^t<<1)|0},e.x=0,e.y=0,e.z=0,e.w=0,e.v=0,t===(0|t)?e.x=t:n+=t;for(var r=0;r<n.length+64;r++)e.x^=0|n.charCodeAt(r),r==n.length&&(e.d=e.x<<10^e.x>>>4),e.next()}(t),i=e&&e.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},a.int32=n.next,a.quick=a,i&&("object"==typeof i&&r(i,n),a.state=function(){return r(n,{})}),a}e&&e.exports?e.exports=i:this.xorwow=i}(0,t)}),mb=pb(function(t){!function(t,e,n){function r(t,e){return e.x=t.x.slice(),e.i=t.i,e}function i(t,e){null==t&&(t=+new Date);var n=new function(t){var e=this;e.next=function(){var t,n,r=e.x,i=e.i;return t=r[i],n=(t^=t>>>7)^t<<24,n^=(t=r[i+1&7])^t>>>10,n^=(t=r[i+3&7])^t>>>3,n^=(t=r[i+4&7])^t<<7,t=r[i+7&7],n^=(t^=t<<13)^t<<9,r[i]=n,e.i=i+1&7,n},function(t,e){var n,r=[];if(e===(0|e))r[0]=e;else for(e=""+e,n=0;n<e.length;++n)r[7&n]=r[7&n]<<15^e.charCodeAt(n)+r[n+1&7]<<13;for(;r.length<8;)r.push(0);for(n=0;n<8&&0===r[n];++n);for(8==n?r[7]=-1:r[n],t.x=r,t.i=0,n=256;n>0;--n)t.next()}(e,t)}(t),i=e&&e.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},a.int32=n.next,a.quick=a,i&&(i.x&&r(i,n),a.state=function(){return r(n,{})}),a}e&&e.exports?e.exports=i:this.xorshift7=i}(0,t)}),gb=pb(function(t){!function(t,e,n){function r(t,e){return e.i=t.i,e.w=t.w,e.X=t.X.slice(),e}function i(t,e){null==t&&(t=+new Date);var n=new function(t){var e=this;e.next=function(){var t,n,r=e.w,i=e.X,a=e.i;return e.w=r=r+1640531527|0,n=i[a+34&127],t=i[a=a+1&127],n^=n<<13,t^=t<<17,n^=n>>>15,t^=t>>>12,n=i[a]=n^t,e.i=a,n+(r^r>>>16)|0},function(t,e){var n,r,i,a,o,s=[],u=128;for(e===(0|e)?(r=e,e=null):(e+="\0",r=0,u=Math.max(u,e.length)),i=0,a=-32;a<u;++a)e&&(r^=e.charCodeAt((a+32)%e.length)),0===a&&(o=r),r^=r<<10,r^=r>>>15,r^=r<<4,r^=r>>>13,a>=0&&(o=o+1640531527|0,i=0==(n=s[127&a]^=r+o)?i+1:0);for(i>=128&&(s[127&(e&&e.length||0)]=-1),i=127,a=512;a>0;--a)r=s[i+34&127],n=s[i=i+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[i]=r^n;t.w=o,t.X=s,t.i=i}(e,t)}(t),i=e&&e.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},a.int32=n.next,a.quick=a,i&&(i.X&&r(i,n),a.state=function(){return r(n,{})}),a}e&&e.exports?e.exports=i:this.xor4096=i}(0,t)}),vb=pb(function(t){!function(t,e,n){function r(t,e){return e.a=t.a,e.b=t.b,e.c=t.c,e.d=t.d,e}function i(t,e){var n=new function(t){var e=this,n="";e.next=function(){var t=e.b,n=e.c,r=e.d,i=e.a;return t=t<<25^t>>>7^n,n=n-r|0,r=r<<24^r>>>8^i,i=i-t|0,e.b=t=t<<20^t>>>12^n,e.c=n=n-r|0,e.d=r<<16^n>>>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):n+=t;for(var r=0;r<n.length+20;r++)e.b^=0|n.charCodeAt(r),e.next()}(t),i=e&&e.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},a.int32=n.next,a.quick=a,i&&("object"==typeof i&&r(i,n),a.state=function(){return r(n,{})}),a}e&&e.exports?e.exports=i:this.tychei=i}(0,t)}),yb=pb(function(t){!function(e,n){var r,i=this,a=256,o=6,s="random",u=n.pow(a,o),l=n.pow(2,52),c=2*l,p=a-1;function h(t,h,g){var v=[],y=d(function t(e,n){var r,i=[],a=typeof e;if(n&&"object"==a)for(r in e)try{i.push(t(e[r],n-1))}catch(t){}return i.length?i:"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),(i.crypto||i.msCrypto).getRandomValues(t)),m(t)}catch(t){var n=i.navigator,o=n&&n.plugins;return[+new Date,i,o,i.screen,m(e)]}}():t,3),v),b=new function(t){var e,n=t.length,r=this,i=0,o=r.i=r.j=0,s=r.S=[];for(n||(t=[n++]);i<a;)s[i]=i++;for(i=0;i<a;i++)s[i]=s[o=p&o+t[i%n]+(e=s[i])],s[o]=e;(r.g=function(t){for(var e,n=0,i=r.i,o=r.j,s=r.S;t--;)e=s[i=p&i+1],n=n*a+s[p&(s[i]=s[o=p&o+e])+(s[o]=e)];return r.i=i,r.j=o,n})(a)}(v),x=function(){for(var t=b.g(o),e=u,n=0;t<l;)t=(t+n)*a,e*=a,n=b.g(1);for(;t>=c;)t/=2,e/=2,n>>>=1;return(t+n)/e};return x.int32=function(){return 0|b.g(4)},x.quick=function(){return b.g(4)/4294967296},x.double=x,d(m(b.S),e),(h.pass||g||function(t,e,r,i){return i&&(i.S&&f(i,b),t.state=function(){return f(b,{})}),r?(n[s]=t,e):t})(x,y,"global"in h?h.global:this==n,h.state)}function f(t,e){return e.i=t.i,e.j=t.j,e.S=t.S.slice(),e}function d(t,e){for(var n,r=t+"",i=0;i<r.length;)e[p&i]=p&(n^=19*e[p&i])+r.charCodeAt(i++);return m(e)}function m(t){return String.fromCharCode.apply(0,t)}if(n["seed"+s]=h,d(n.random(),e),t.exports){t.exports=h;try{r=require("crypto")}catch(t){}}}([],Math)});yb.alea=hb,yb.xor128=fb,yb.xorwow=db,yb.xorshift7=mb,yb.xor4096=gb,yb.tychei=vb;var bb=yb.alea;function xb(t,e,n,r){if(void 0===n&&(n=new Map),void 0===r&&(r=new Set),null==t)return null;if(r.has(t))throw new Error("Circular references are not supported.");if(n.has(t))return n.get(t);var 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(Eb(t)){var a=Array.isArray(t)?[]:{};for(var o in r.add(t),t){var s=xb(t[o],e,n,r);a[o]=s}return r.delete(t),a}throw new Error("Can't recurse into non-iterable type: "+t)}return n.set(t,i.value),i.value}function wb(t,e){return void 0===e&&(e=Cb),function t(e,n,r){void 0===r&&(r=new Set);var i=e[0];if(r.has(i))throw new Error("Circular references are not supported.");var a=n(e);if(a.recurse&&null!==a.value)throw new Error("A deep zip function may not return both a value and recurse=true.");if(a.recurse){if(Eb(i)){var o=Array.isArray(i)?[]:{};r.add(i);var s=function(i){var a=t(e.map(function(t){return t[i]}),n,r);o[i]=a};for(var u in i)s(u);return r.delete(i),o}throw new Error("Can't recurse into non-iterable type: "+i)}return a.value}(t,e)}function Cb(t){return null===t?null:Eb(t[0])?{value:null,recurse:!0}:{value:t,recurse:!1}}function Nb(t,e){return lb(this,void 0,void 0,function(){var n,r,i,a,o,s;return cb(this,function(u){switch(u.label){case 0:n=new Map,xb(t,e,n),r=0,i=Array.from(n.keys()),u.label=1;case 1:return r<i.length?(a=i[r],(o=n.get(a))instanceof Promise?[4,o]:[3,3]):[3,4];case 2:s=u.sent(),n.set(a,s),u.label=3;case 3:return r++,[3,1];case 4:return[2,xb(t,e,n)]}})})}function Eb(t){return null!=t&&!ArrayBuffer.isView(t)&&(Array.isArray(t)||"object"==typeof t&&!(t instanceof st))}function Sb(t){return function(t,e){return xb(t,e)}(t,kb)}function kb(t){return t instanceof st?{value:t.clone(),recurse:!1}:Eb(t)?{value:null,recurse:!0}:{value:t,recurse:!1}}var Ib=function(){function t(t){if(this.capacity=t,this.begin=0,this.end=0,null==t)throw new RangeError("Can't create a ring buffer of unknown capacity.");if(t<1)throw new RangeError("Can't create ring buffer of capacity < 1.");this.data=new Array(t),this.doubledCapacity=2*t}return t.prototype.wrap=function(t){for(;t<0;)t+=this.doubledCapacity;return t%this.doubledCapacity},t.prototype.get=function(t){if(t<0)throw new RangeError("Can't get item at a negative index.");return this.data[t%this.capacity]},t.prototype.set=function(t,e){if(t<0)throw new RangeError("Can't set item at a negative index.");this.data[t%this.capacity]=e},t.prototype.length=function(){var t=this.end-this.begin;return t<0&&(t=this.doubledCapacity+t),t},t.prototype.isFull=function(){return this.length()===this.capacity},t.prototype.isEmpty=function(){return 0===this.length()},t.prototype.push=function(t){if(this.isFull())throw new RangeError("Ring buffer is full.");this.set(this.end,t),this.end=this.wrap(this.end+1)},t.prototype.pushAll=function(t){for(var e=0,n=t;e<n.length;e++){var r=n[e];this.push(r)}},t.prototype.pop=function(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");this.end=this.wrap(this.end-1);var t=this.get(this.end);return this.set(this.end,void 0),t},t.prototype.unshift=function(t){if(this.isFull())throw new RangeError("Ring buffer is full.");this.begin=this.wrap(this.begin-1),this.set(this.begin,t)},t.prototype.shift=function(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");var t=this.get(this.begin);return this.set(this.begin,void 0),this.begin=this.wrap(this.begin+1),t},t.prototype.shuffleExcise=function(t){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");var e=this.wrap(this.begin+t),n=this.get(e);return this.set(e,this.pop()),n},t}(),Ab=function(t){function e(){return t.call(this,e.INITIAL_CAPACITY)||this}return ub(e,t),e.prototype.isFull=function(){return!1},e.prototype.push=function(e){t.prototype.isFull.call(this)&&this.expand(),t.prototype.push.call(this,e)},e.prototype.unshift=function(e){t.prototype.isFull.call(this)&&this.expand(),t.prototype.unshift.call(this,e)},e.prototype.expand=function(){for(var t=2*this.capacity,e=new Array(t),n=this.length(),r=0;r<n;r++)e[r]=this.get(this.wrap(this.begin+r));this.data=e,this.capacity=t,this.doubledCapacity=2*this.capacity,this.begin=0,this.end=n},e.INITIAL_CAPACITY=32,e}(Ib);function Rb(t){return new _b(t)}function Tb(t){return new Fb(t)}var Db,Ob=function(){function t(){}return t.prototype.toArray=function(){return lb(this,void 0,void 0,function(){var t,e;return cb(this,function(n){switch(n.label){case 0:return t=[],[4,this.next()];case 1:e=n.sent(),n.label=2;case 2:return e.done?[3,4]:(t.push(e.value),[4,this.next()]);case 3:return e=n.sent(),[3,2];case 4:return[2,t]}})})},t.prototype.toArrayForTest=function(){return lb(this,void 0,void 0,function(){var t,e,n;return cb(this,function(r){switch(r.label){case 0:return t=this.prefetch(100),e=[],[4,t.next()];case 1:n=r.sent(),r.label=2;case 2:return n.done?[3,4]:(e.push(n.value),[4,t.next()]);case 3:return n=r.sent(),[3,2];case 4:return[2,e]}})})},t.prototype.resolveFully=function(){return lb(this,void 0,void 0,function(){var t;return cb(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 lb(this,void 0,void 0,function(){var e,n;return cb(this,function(r){switch(r.label){case 0:return[4,this.next()];case 1:e=r.sent(),n=t(e.value),r.label=2;case 2:return e.done||!n?[3,4]:[4,this.next()];case 3:return e=r.sent(),n=t(e.value),[3,2];case 4:return[2]}})})},t.prototype.handleErrors=function(t){return new Vb(this,t)},t.prototype.filter=function(t){return new Bb(this,t)},t.prototype.map=function(t){return new Wb(this,t)},t.prototype.mapAsync=function(t){return new Ub(this,t)},t.prototype.serialMapAsync=function(t){return new Ub(this,t).serial()},t.prototype.flatmap=function(t){return new Gb(this,t)},t.prototype.forEachAsync=function(t){return lb(this,void 0,void 0,function(){return cb(this,function(e){return[2,this.map(t).resolveFully()]})})},t.prototype.serialForEach=function(t){return lb(this,void 0,void 0,function(){return cb(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 Pb(this,t,e)},t.prototype.columnMajorBatch=function(t,e,n){return void 0===e&&(e=!0),void 0===n&&(n=Cb),this.rowMajorBatch(t,e).map(function(t){return wb(t,n)})},t.prototype.concatenate=function(t,e){return new qb(Rb([this,t]),e)},t.prototype.take=function(t){return t<0||null==t?this:new Lb(this,t)},t.prototype.skip=function(t){return t<0||null==t?this:new Mb(this,t)},t.prototype.prefetch=function(t){return new Kb(this,t)},t.prototype.shuffle=function(t,e){return new $b(this,t,e)},t.prototype.serial=function(){return new zb(this)},t}(),_b=function(t){function e(e){var n=t.call(this)||this;return n.items=e,n.trav=0,n}return ub(e,t),e.prototype.summary=function(){return"Array of "+this.items.length+" items"},e.prototype.next=function(){return lb(this,void 0,void 0,function(){var t;return cb(this,function(e){return this.trav>=this.items.length?[2,{value:null,done:!0}]:(t=this.items[this.trav],this.trav++,[2,{value:Sb(t),done:!1}])})})},e}(Ob),Fb=function(t){function e(e){var n=t.call(this)||this;return n.nextFn=e,n}return ub(e,t),e.prototype.summary=function(){return"Function call"},e.prototype.next=function(){return lb(this,void 0,void 0,function(){return cb(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}(Ob),zb=function(t){function e(e){var n=t.call(this)||this;return n.upstream=e,n.lastRead=Promise.resolve({value:null,done:!1}),n}return ub(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Serial"},e.prototype.next=function(){return lb(this,void 0,void 0,function(){var t=this;return cb(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return lb(this,void 0,void 0,function(){return cb(this,function(t){return[2,this.upstream.next()]})})},e}(Ob),Mb=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.maxCount=n,r.count=0,r.lastRead=Promise.resolve({value:null,done:!1}),r}return ub(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Skip"},e.prototype.next=function(){return lb(this,void 0,void 0,function(){var t=this;return cb(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return lb(this,void 0,void 0,function(){var t;return cb(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]:(Fe(t.value),[3,0]);case 2:return[2,this.upstream.next()]}})})},e}(Ob),Lb=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.maxCount=n,r.count=0,r}return ub(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Take"},e.prototype.next=function(){return lb(this,void 0,void 0,function(){return cb(this,function(t){return this.count++>=this.maxCount?[2,{value:null,done:!0}]:[2,this.upstream.next()]})})},e}(Ob),Pb=function(t){function e(e,n,r){void 0===r&&(r=!0);var i=t.call(this)||this;return i.upstream=e,i.batchSize=n,i.enableSmallLastBatch=r,i.lastRead=Promise.resolve({value:null,done:!1}),i}return ub(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> RowMajorBatch"},e.prototype.next=function(){return lb(this,void 0,void 0,function(){var t=this;return cb(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return lb(this,void 0,void 0,function(){var t,e;return cb(this,function(n){switch(n.label){case 0:t=[],n.label=1;case 1:return t.length<this.batchSize?[4,this.upstream.next()]:[3,3];case 2:return(e=n.sent()).done?this.enableSmallLastBatch&&t.length>0?[2,{value:t,done:!1}]:[2,{value:null,done:!0}]:(t.push(e.value),[3,1]);case 3:return[2,{value:t,done:!1}]}})})},e}(Ob),Bb=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.predicate=n,r.lastRead=Promise.resolve({value:null,done:!1}),r}return ub(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Filter"},e.prototype.next=function(){return lb(this,void 0,void 0,function(){var t=this;return cb(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return lb(this,void 0,void 0,function(){var t;return cb(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]:(Fe(t.value),[3,0]);case 2:return[2]}})})},e}(Ob),Wb=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.transform=n,r}return ub(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Map"},e.prototype.next=function(){return lb(this,void 0,void 0,function(){var t,e,n,r,i,a,o;return cb(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=wt.getTensorsInContainer(t.value),n=this.transform(t.value),r=wt.getTensorsInContainer(n),i=0,a=e;i<a.length;i++)o=a[i],wt.isTensorInList(o,r)||o.dispose();return[2,{value:n,done:!1}]}})})},e}(Ob),Vb=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.handler=n,r.count=0,r.lastRead=Promise.resolve({value:null,done:!1}),r}return ub(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> handleErrors"},e.prototype.next=function(){return lb(this,void 0,void 0,function(){var t=this;return cb(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return lb(this,void 0,void 0,function(){var t;return cb(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}(Ob),Ub=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.transform=n,r}return ub(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> AsyncMap"},e.prototype.next=function(){return lb(this,void 0,void 0,function(){var t,e,n,r,i,a,o;return cb(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=wt.getTensorsInContainer(t.value),[4,this.transform(t.value)]);case 2:for(n=s.sent(),r=wt.getTensorsInContainer(n),i=0,a=e;i<a.length;i++)o=a[i],wt.isTensorInList(o,r)||o.dispose();return[2,{value:n,done:!1}]}})})},e}(Ob),jb=function(t){function e(){var e=t.call(this)||this;return e.outputQueue=new Ab,e.lastRead=Promise.resolve({value:null,done:!1}),e}return ub(e,t),e.prototype.next=function(){return lb(this,void 0,void 0,function(){var t=this;return cb(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return lb(this,void 0,void 0,function(){return cb(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}(Ob),Gb=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.transform=n,r}return ub(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Flatmap"},e.prototype.pump=function(){return lb(this,void 0,void 0,function(){var t,e,n,r,i,a,o;return cb(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=wt.getTensorsInContainer(t.value),n=this.transform(t.value),r=wt.getTensorsInContainer(n),this.outputQueue.pushAll(n),i=0,a=e;i<a.length;i++)o=a[i],wt.isTensorInList(o,r)||o.dispose();return[2,!0]}})})},e}(jb),qb=function(t){function e(e,n){var r=t.call(this)||this;return r.baseErrorHandler=n,r.lastRead=null,r.iterator=null,r.moreIterators=e,r}return ub(e,t),e.prototype.summary=function(){return"TODO: fill in upstream of chained summaries -> Chained"},e.prototype.next=function(){return lb(this,void 0,void 0,function(){return cb(this,function(t){return this.lastRead=this.readFromChain(this.lastRead),[2,this.lastRead]})})},e.prototype.readFromChain=function(t){return lb(this,void 0,void 0,function(){var e,n;return cb(this,function(r){switch(r.label){case 0:return[4,t];case 1:return r.sent(),null!=this.iterator?[3,3]:[4,this.moreIterators.next()];case 2:if((e=r.sent()).done)return[2,{value:null,done:!0}];this.iterator=e.value,null!=this.baseErrorHandler&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler)),r.label=3;case 3:return[4,this.iterator.next()];case 4:return(n=r.sent()).done?(this.iterator=null,[2,this.readFromChain(t)]):[2,n]}})})},e}(Ob);!function(t){t[t.FAIL=0]="FAIL",t[t.SHORTEST=1]="SHORTEST",t[t.LONGEST=2]="LONGEST"}(Db||(Db={}));var Hb=function(t){function e(e,n){void 0===n&&(n=Db.FAIL);var r=t.call(this)||this;return r.iterators=e,r.mismatchMode=n,r.count=0,r.currentPromise=null,r}return ub(e,t),e.prototype.summary=function(){return"{TODO: fill in upstream of zip summaries} -> Zip"},e.prototype.nextState=function(t){return lb(this,void 0,void 0,function(){function e(t){return t instanceof Ob?{value:t.next().then(function(t){return n++,t.done&&r++,t.value}),recurse:!1}:{value:null,recurse:!0}}var n,r,i;return cb(this,function(a){switch(a.label){case 0:return[4,t];case 1:return a.sent(),n=0,r=0,[4,Nb(this.iterators,e)];case 2:if(i=a.sent(),n===r)return[2,{value:null,done:!0}];if(r>0)switch(this.mismatchMode){case Db.FAIL:throw new Error("Zipped streams should have the same length. Mismatched at element "+this.count+".");case Db.SHORTEST:return[2,{value:null,done:!0}];case Db.LONGEST:}return this.count++,[2,{value:i,done:!1}]}})})},e.prototype.next=function(){return lb(this,void 0,void 0,function(){return cb(this,function(t){return this.currentPromise=this.nextState(this.currentPromise),[2,this.currentPromise]})})},e}(Ob),Kb=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.bufferSize=n,r.buffer=new Ib(n),r}return ub(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}(Ob),$b=function(t){function e(e,n,r){var i=t.call(this,e,n)||this;return i.upstream=e,i.windowSize=n,i.upstreamExhausted=!1,i.random=bb(r||$.now().toString()),i.lastRead=Promise.resolve({value:null,done:!1}),i}return ub(e,t),e.prototype.next=function(){return lb(this,void 0,void 0,function(){var t=this;return cb(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 lb(this,void 0,void 0,function(){var t,e;return cb(this,function(n){switch(n.label){case 0:this.upstreamExhausted||this.refill(),n.label=1;case 1:return this.buffer.isEmpty()?[3,3]:(t=this.chooseIndex(),[4,this.buffer.shuffleExcise(t)]);case 2:return(e=n.sent()).done?(this.upstreamExhausted=!0,[3,1]):(this.refill(),[2,e]);case 3:return[2,{value:null,done:!0}]}})})},e}(Kb),Xb=function(){function t(){this.size=null}return t.prototype.batch=function(t,e){var n=this;void 0===e&&(e=!0);var r=this;return $.assert(t>0,function(){return"batchSize needs to be positive, but it is\n "+t}),Yb(function(){return lb(n,void 0,void 0,function(){return cb(this,function(n){switch(n.label){case 0:return[4,r.iterator()];case 1:return[2,n.sent().columnMajorBatch(t,e,Jb)]}})})},this.size===1/0||null==this.size?this.size:e?Math.ceil(this.size/t):Math.floor(this.size/t))},t.prototype.concatenate=function(t){var e=this,n=this;return Yb(function(){return lb(e,void 0,void 0,function(){var e,r;return cb(this,function(i){switch(i.label){case 0:return[4,n.iterator()];case 1:return r=(e=i.sent()).concatenate,[4,t.iterator()];case 2:return[2,r.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,n=this;return Yb(function(){return lb(e,void 0,void 0,function(){return cb(this,function(e){switch(e.label){case 0:return[4,n.iterator()];case 1:return[2,e.sent().filter(function(e){return _e(function(){return t(e)})})]}})})},this.size===1/0?1/0:null)},t.prototype.forEachAsync=function(t){return lb(this,void 0,void 0,function(){return cb(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 lb(this,void 0,void 0,function(){return cb(this,function(e){return De("dataset.forEach() is deprecated and will be removed. Please use dataset.forEachAsync() instead"),[2,this.forEachAsync(t)]})})},t.prototype.map=function(t){var e=this,n=this;return Yb(function(){return lb(e,void 0,void 0,function(){return cb(this,function(e){switch(e.label){case 0:return[4,n.iterator()];case 1:return[2,e.sent().map(function(e){return _e(function(){return t(e)})})]}})})},this.size)},t.prototype.mapAsync=function(t){var e=this,n=this;return Yb(function(){return lb(e,void 0,void 0,function(){return cb(this,function(e){switch(e.label){case 0:return[4,n.iterator()];case 1:return[2,e.sent().mapAsync(t)]}})})},this.size)},t.prototype.prefetch=function(t){var e=this;if(null==t)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");var n=this;return Yb(function(){return lb(e,void 0,void 0,function(){return cb(this,function(e){switch(e.label){case 0:return[4,n.iterator()];case 1:return[2,e.sent().prefetch(t)]}})})},this.size)},t.prototype.repeat=function(t){var e=this,n=this;return Yb(function(){return lb(e,void 0,void 0,function(){var e=this;return cb(this,function(r){return[2,function(t,e){return new qb(t,e)}(Tb(function(){return lb(e,void 0,void 0,function(){var t;return cb(this,function(e){switch(e.label){case 0:return t={},[4,n.iterator()];case 1:return[2,(t.value=e.sent(),t.done=!1,t)]}})})}).take(t))]})})},null!=this.size&&t>0?this.size*t:0===t?0:null!=this.size&&(void 0===t||t<0)?1/0:null)},t.prototype.skip=function(t){var e=this,n=this;return Yb(function(){return lb(e,void 0,void 0,function(){return cb(this,function(e){switch(e.label){case 0:return[4,n.iterator()];case 1:return[2,e.sent().skip(t)]}})})},null!=this.size&&t>=0&&this.size>=t?this.size-t:null!=this.size&&(this.size<t||void 0===t||t<0)?0:null)},t.prototype.shuffle=function(t,e,n){var r=this;if(void 0===n&&(n=!0),null==t||t<0)throw null==this.size?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError("`Dataset.shuffle()` requires bufferSize to be specified. If your data fits in main memory (for regular JS objects), and/or GPU memory (for `tf.Tensor`s), consider setting bufferSize to the dataset size ("+this.size+" elements)");var i=this,a=bb(e||$.now().toString());return Yb(function(){return lb(r,void 0,void 0,function(){var e;return cb(this,function(r){switch(r.label){case 0:return e=a.int32(),n&&(e+=a.int32()),[4,i.iterator()];case 1:return[2,r.sent().shuffle(t,e.toString())]}})})},this.size)},t.prototype.take=function(t){var e=this,n=this;return Yb(function(){return lb(e,void 0,void 0,function(){return cb(this,function(e){switch(e.label){case 0:return[4,n.iterator()];case 1:return[2,e.sent().take(t)]}})})},null!=this.size&&this.size>t?t:null!=this.size&&this.size<=t?this.size:null)},t.prototype.toArray=function(){return lb(this,void 0,void 0,function(){return cb(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 lb(this,void 0,void 0,function(){return cb(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 Yb(t,e){return void 0===e&&(e=null),new(function(n){function r(){var t=null!==n&&n.apply(this,arguments)||this;return t.size=e,t}return ub(r,n),r.prototype.iterator=function(){return lb(this,void 0,void 0,function(){return cb(this,function(e){return[2,t()]})})},r}(Xb))}function Jb(t){return null===t?null:function(t){return null==t||function(t){return null===t||"object"!=typeof t&&"function"!=typeof t}(t)||Array.isArray(t)||"object"==typeof t&&t instanceof st||$.isTypedArray(t)}(t[0])?{value:function(t){if(0===t.length)throw new Error("Can't make a batch of zero elements.");return t[0]instanceof st?or(t):nn(t)}(t),recurse:!1}:{value:null,recurse:!0}}var Zb=function(t){function e(e){var n=t.call(this)||this;return n.input=e,n}return ub(e,t),e.prototype.iterator=function(){return lb(this,void 0,void 0,function(){var t;return cb(this,function(e){switch(e.label){case 0:return[4,this.input.iterator()];case 1:return t=e.sent(),[2,t.decodeUTF8().split("\n").map(function(t){return t.endsWith("\r")&&(t=t.slice(0,-1)),t})]}})})},e}(Xb),Qb=Symbol("out"),tx=Symbol("field"),ex=Symbol("quote"),nx=Symbol("quoteafterquote"),rx=Symbol("quoteinquote"),ix=function(t){function e(e,n){var r=t.call(this)||this;return r.input=e,r.hasHeader=!0,r.fullColumnNames=null,r.columnNamesValidated=!1,r.columnConfigs=null,r.configuredColumnsOnly=!1,r.delimiter=",",r.delimWhitespace=!1,r.base=new Zb(e),n||(n={}),r.hasHeader=!1!==n.hasHeader,r.fullColumnNames=n.columnNames,r.columnConfigs=n.columnConfigs,r.configuredColumnsOnly=n.configuredColumnsOnly,n.delimWhitespace?($.assert(null==n.delimiter,function(){return"Delimiter should not be provided when delimWhitespace is true."}),r.delimWhitespace=!0,r.delimiter=" "):r.delimiter=n.delimiter?n.delimiter:",",r}return ub(e,t),e.prototype.columnNames=function(){return lb(this,void 0,void 0,function(){return cb(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 lb(this,void 0,void 0,function(){var t,e,n,r,i,a,o=this;return cb(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&&$.assert(t.length===this.fullColumnNames.length,function(){return"The length of provided columnNames ("+o.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+t.length.toString()+")."}),this.fullColumnNames||(this.fullColumnNames=t),e=this.fullColumnNames.reduce(function(t,e){return t[e]=t[e]+1||1,t},{}),n=Object.keys(e).filter(function(t){return e[t]>1}),$.assert(0===n.length,function(){return"Duplicate column names found: "+n.toString()}),this.columnConfigs)for(r=0,i=Object.keys(this.columnConfigs);r<i.length;r++)if(a=i[r],-1===this.fullColumnNames.indexOf(a))throw new Error('The key "'+a+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").");return this.columnNamesValidated=!0,[2]}})})},e.prototype.maybeReadHeaderLine=function(){return lb(this,void 0,void 0,function(){var t,e;return cb(this,function(n){switch(n.label){case 0:return this.hasHeader?[4,this.base.iterator()]:[3,3];case 1:return[4,n.sent().next()];case 2:if((t=n.sent()).done)throw new Error("No data was found for CSV parsing.");return e=t.value,[2,this.parseRow(e,!1)];case 3:return[2,null]}})})},e.prototype.iterator=function(){return lb(this,void 0,void 0,function(){var t,e=this;return cb(this,function(n){switch(n.label){case 0:return this.columnNamesValidated?[3,2]:[4,this.setColumnNames()];case 1:n.sent(),n.label=2;case 2:return[4,this.base.iterator()];case 3:return t=n.sent(),this.hasHeader&&(t=t.skip(1)),[2,t.map(function(t){return e.makeDataElement(t)})]}})})},e.prototype.makeDataElement=function(t){for(var e=this.parseRow(t),n={},r={},i=0;i<this.fullColumnNames.length;i++){var a=this.fullColumnNames[i],o=this.columnConfigs?this.columnConfigs[a]:null;if(!this.configuredColumnsOnly||o){var s=e[i],u=null;if(""===s)if(o&&void 0!==o.default)u=o.default;else{if(o&&(o.required||o.isLabel))throw new Error("Required column "+a+" is empty in this line: "+t);u=void 0}else{var l=Number(s);if(isNaN(l))u=o&&"bool"===o.dtype?this.getBoolean(s):s;else if(o&&o.dtype)switch(o.dtype){case"float32":u=l;break;case"int32":u=Math.floor(l);break;case"bool":u=this.getBoolean(s);break;default:u=l}else u=l}o&&o.isLabel?r[a]=u:n[a]=u}}return 0===Object.keys(r).length?n:{xs:n,ys:r}},e.prototype.getBoolean=function(t){return"1"===t||"true"===t.toLowerCase()?1:0},e.prototype.parseRow=function(t,e){void 0===e&&(e=!0);for(var n=[],r=0,i=t.length,a=Qb,o=0;o<i;o++)switch(a){case Qb:switch(t.charAt(o)){case'"':r=o+1,a=ex;break;case this.delimiter:if(r=o+1," "===this.delimiter&&this.delimWhitespace)break;n.push(""),a=Qb;break;default:a=tx,r=o}break;case tx:switch(t.charAt(o)){case this.delimiter:n.push(t.substring(r,o)),a=Qb,r=o+1}break;case ex:switch(t.charAt(o)){case'"':a=nx}break;case nx:switch(t.charAt(o)){case this.delimiter:n.push(t.substring(r,o-1)),a=Qb,r=o+1;break;case'"':a=ex;break;default:a=rx}break;case rx:switch(t.charAt(o)){case'"':a=ex}}if(a===nx?n.push(t.substring(r,i-1)):n.push(t.substring(r)),e&&n.length!==this.fullColumnNames.length)throw new Error("Invalid row in csv file. Should have "+this.fullColumnNames.length+" elements in a row, but got "+n);return n},e}(Xb),ax=function(e){function n(t){var n=e.call(this)||this;n.microphoneConfig=t,n.isClosed=!1,n.fftSize=t.fftSize||1024;var r=Math.log2(n.fftSize);if(n.fftSize<0||r<4||r>14||!Number.isInteger(r))throw new Error("Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got "+n.fftSize);if(n.numFrames=t.numFramesPerSpectrogram||43,n.sampleRateHz=t.sampleRateHz,n.columnTruncateLength=t.columnTruncateLength||n.fftSize,n.audioTrackConstraints=t.audioTrackConstraints,n.smoothingTimeConstant=t.smoothingTimeConstant||0,n.includeSpectrogram=!1!==t.includeSpectrogram,n.includeWaveform=!0===t.includeWaveform,!n.includeSpectrogram&&!n.includeWaveform)throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.");return n}return ub(n,e),n.prototype.summary=function(){return"microphone"},n.create=function(e){return void 0===e&&(e={}),lb(this,void 0,void 0,function(){var r;return cb(this,function(i){switch(i.label){case 0:if(t.ENV.get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");return[4,(r=new n(e)).start()];case 1:return i.sent(),[2,r]}})})},n.prototype.start=function(){return lb(this,void 0,void 0,function(){var t,e,n,r;return cb(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(n=window.AudioContext||window.webkitAudioContext,this.audioContext=new n,this.sampleRateHz){if(this.audioContext.sampleRate!==this.sampleRateHz)throw new Error("Mismatch in sampling rate: Expected: "+this.sampleRateHz+"; Actual: "+this.audioContext.sampleRate)}else this.sampleRateHz=this.audioContext.sampleRate;return r=this.audioContext.createMediaStreamSource(this.stream),this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2*this.fftSize,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,r.connect(this.analyser),this.freqData=new Float32Array(this.fftSize),this.timeData=new Float32Array(this.fftSize),[2]}})})},n.prototype.next=function(){return lb(this,void 0,void 0,function(){var t,e,n,r,i;return cb(this,function(a){switch(a.label){case 0:return this.isClosed?[2,{value:null,done:!0}]:[4,this.getAudioData()];case 1:return n=a.sent(),this.includeSpectrogram&&(r=this.flattenQueue(n.freqDataQueue),t=this.getTensorFromAudioDataArray(r,[this.numFrames,this.columnTruncateLength,1])),this.includeWaveform&&(i=this.flattenQueue(n.timeDataQueue),e=this.getTensorFromAudioDataArray(i,[this.numFrames*this.fftSize,1])),[2,{value:{spectrogram:t,waveform:e},done:!1}]}})})},n.prototype.capture=function(){return lb(this,void 0,void 0,function(){return cb(this,function(t){switch(t.label){case 0:return[4,this.next()];case 1:return[2,t.sent().value]}})})},n.prototype.getAudioData=function(){return lb(this,void 0,void 0,function(){var t,e,n,r=this;return cb(this,function(i){return t=[],e=[],n=0,[2,new Promise(function(i){var a=setInterval(function(){r.includeSpectrogram&&(r.analyser.getFloatFrequencyData(r.freqData),r.freqData[0]===-1/0&&i({freqDataQueue:t,timeDataQueue:e}),t.push(r.freqData.slice(0,r.columnTruncateLength))),r.includeWaveform&&(r.analyser.getFloatTimeDomainData(r.timeData),e.push(r.timeData.slice())),++n===r.numFrames&&(clearInterval(a),i({freqDataQueue:t,timeDataQueue:e}))},r.fftSize/r.sampleRateHz*1e3)})]})})},n.prototype.stop=function(){this.isClosed||(this.isClosed=!0,this.analyser.disconnect(),this.audioContext.close(),null!=this.stream&&this.stream.getTracks().length>0&&this.stream.getTracks()[0].stop())},n.prototype.toArray=function(){throw new Error("Can not convert infinite audio stream to array.")},n.prototype.getSampleRate=function(){return this.sampleRateHz},n.prototype.flattenQueue=function(t){var e=t[0].length,n=new Float32Array(t.length*e);return t.forEach(function(t,r){return n.set(t,r*e)}),n},n.prototype.getTensorFromAudioDataArray=function(t,e){var n=new Float32Array($.sizeFromShape(e));return n.set(t,n.length-t.length),nn(n,e)},n}(Ob),ox=function(e){function n(t,n){var r=e.call(this)||this;if(r.webcamVideoElement=t,r.webcamConfig=n,r.isClosed=!0,r.resize=!1,r.needToResize())if(r.resize=!0,r.cropSize=[r.webcamConfig.resizeHeight,r.webcamConfig.resizeWidth],r.cropBoxInd=on([0],"int32"),r.webcamConfig.centerCrop){var i=1*r.webcamConfig.resizeWidth/r.webcamVideoElement.width,a=1*r.webcamConfig.resizeHeight/r.webcamVideoElement.height,o=(1-i)/2,s=(1-a)/2,u=o+i,l=a+s;r.cropBox=sn([s,o,l,u],[1,4])}else r.cropBox=sn([0,0,1,1],[1,4]);return r}return ub(n,e),n.prototype.summary=function(){return"webcam"},n.create=function(e,r){return void 0===r&&(r={}),lb(this,void 0,void 0,function(){var i;return cb(this,function(a){switch(a.label){case 0:if(t.ENV.get("IS_NODE"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!e){if(e=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.");e.width=r.resizeWidth,e.height=r.resizeHeight}return[4,(i=new n(e,r)).start()];case 1:return a.sent(),[2,i]}})})},n.prototype.start=function(){return lb(this,void 0,void 0,function(){var t,e,n=this;return cb(this,function(r){switch(r.label){case 0:this.webcamConfig.facingMode&&$.assert("user"===this.webcamConfig.facingMode||"environment"===this.webcamConfig.facingMode,function(){return"Invalid webcam facing mode: "+n.webcamConfig.facingMode+". Please provide 'user' or 'environment'"}),r.label=1;case 1:return r.trys.push([1,3,,4]),t=this,[4,navigator.mediaDevices.getUserMedia({video:{deviceId:this.webcamConfig.deviceId,facingMode:this.webcamConfig.facingMode?this.webcamConfig.facingMode:"user",width:this.webcamVideoElement.width,height:this.webcamVideoElement.height}})];case 2:return t.stream=r.sent(),[3,4];case 3:throw(e=r.sent()).message="Error thrown while initializing video stream: "+e.message,e;case 4:if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream}catch(t){console.log(t),this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}return this.webcamVideoElement.play(),this.isClosed=!1,[2,new Promise(function(t){n.webcamVideoElement.onloadedmetadata=function(){t()}})]}})})},n.prototype.next=function(){return lb(this,void 0,void 0,function(){var t;return cb(this,function(e){if(this.isClosed)return[2,{value:null,done:!0}];try{t=Ap.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]})})},n.prototype.needToResize=function(){return!(!this.webcamConfig.resizeWidth||!this.webcamConfig.resizeHeight||this.webcamVideoElement.width===this.webcamConfig.resizeWidth&&this.webcamVideoElement.height===this.webcamConfig.resizeHeight)},n.prototype.cropAndResizeFrame=function(t){var e=this;return _e(function(){var n,r=t.toFloat().expandDims(0),i=(n=xc.cropAndResize(r,e.cropBox,e.cropBoxInd,e.cropSize,"bilinear")).shape;return n.reshape(i.slice(1))})},n.prototype.capture=function(){return lb(this,void 0,void 0,function(){return cb(this,function(t){switch(t.label){case 0:return[4,this.next()];case 1:return[2,t.sent().value]}})})},n.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},n.prototype.toArray=function(){throw new Error("Can not convert infinite video stream to array.")},n}(Ob),sx=function(){},ux=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ub(e,t),e.prototype.split=function(t){return new lx(this,t)},e}(Ob),lx=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.impl=new cx(e,n),r}return ub(e,t),e.prototype.summary=function(){return this.impl.summary()},e.prototype.next=function(){return lb(this,void 0,void 0,function(){return cb(this,function(t){return[2,this.impl.next()]})})},e}(ux),cx=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.separator=n,r.carryover="",r}return ub(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Split('"+this.separator+"')"},e.prototype.pump=function(){return lb(this,void 0,void 0,function(){var t,e,n,r,i;return cb(this,function(a){switch(a.label){case 0:return[4,this.upstream.next()];case 1:if((t=a.sent()).done)return""===this.carryover?[2,!1]:(this.outputQueue.push(this.carryover),this.carryover="",[2,!0]);for((e=t.value.split(this.separator))[0]=this.carryover+e[0],n=0,r=e.slice(0,-1);n<r.length;n++)i=r[n],this.outputQueue.push(i);return this.carryover=e[e.length-1],[2,!0]}})})},e}(jb),px=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return ub(e,t),e.prototype.decodeUTF8=function(){return new hx(this)},e}(Ob),hx=function(t){function e(e){var n=t.call(this)||this;return n.upstream=e,n.impl=new fx(e),n}return ub(e,t),e.prototype.summary=function(){return this.impl.summary()},e.prototype.next=function(){return lb(this,void 0,void 0,function(){return cb(this,function(t){return[2,this.impl.next()]})})},e}(ux),fx=function(e){function n(n){var r=e.call(this)||this;if(r.upstream=n,t.ENV.get("IS_BROWSER"))r.decoder=new TextDecoder("utf-8");else{var i=require("string_decoder").StringDecoder;r.decoder=new i("utf8")}return r}return ub(n,e),n.prototype.summary=function(){return this.upstream.summary()+" -> Utf8"},n.prototype.pump=function(){return lb(this,void 0,void 0,function(){var e,n,r;return cb(this,function(i){switch(i.label){case 0:return[4,this.upstream.next()];case 1:return(e=i.sent()).done?[2,!1]:(n=e.value,r=t.ENV.get("IS_BROWSER")?this.decoder.decode(n,{stream:!0}):this.decoder.write(Buffer.from(n.buffer)),this.outputQueue.push(r),[2,!0])}})})},n}(jb),dx=function(e){function n(n,r){void 0===r&&(r={});var i=e.call(this)||this;return i.file=n,i.options=r,$.assert(n instanceof Uint8Array||!!t.ENV.get("IS_BROWSER")&&(n instanceof File||n instanceof Blob),function(){return"FileChunkIterator only supports File, Blob and Uint8Array right now."}),i.offset=r.offset||0,i.chunkSize=r.chunkSize||1048576,i}return ub(n,e),n.prototype.summary=function(){return"FileChunks "+this.file},n.prototype.next=function(){return lb(this,void 0,void 0,function(){var t,e,n=this;return cb(this,function(r){switch(r.label){case 0:return this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size)?[2,{value:null,done:!0}]:(t=new Promise(function(t,e){var r=n.offset+n.chunkSize;if(n.file instanceof Uint8Array)t(new Uint8Array(n.file.slice(n.offset,r)));else{var i=new FileReader;i.onload=function(n){var r=i.result;if(r instanceof ArrayBuffer&&(r=new Uint8Array(r)),!(r instanceof Uint8Array))return e(new TypeError("FileReader returned unknown type."));t(r)},i.onabort=function(t){return e(new Error("Aborted"))},i.onerror=function(t){return e(new Error(t.type))};var a=n.file.slice(n.offset,r);i.readAsArrayBuffer(a)}n.offset=r}),e={},[4,t]);case 1:return[2,(e.value=r.sent(),e.done=!1,e)]}})})},n}(px);var mx=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 gx(t){return"string"==typeof t&&"file://"===t.substr(0,7)}var vx=function(e){function n(t,n){void 0===n&&(n={});var r=e.call(this)||this;return r.input=t,r.options=n,r}return ub(n,e),n.prototype.iterator=function(){return lb(this,void 0,void 0,function(){var e;return cb(this,function(n){return gx(this.input)&&t.ENV.get("IS_NODE")&&(e=require("fs"),this.input=e.readFileSync(this.input.substr(7))),[2,new dx(this.input,this.options)]})})},n}(sx),yx=function(t){function e(e,n){void 0===n&&(n={});var r=t.call(this)||this;return r.url=e,r.fileOptions=n,r}return ub(e,t),e.prototype.iterator=function(){return lb(this,void 0,void 0,function(){return cb(this,function(t){return gx(this.url)?[2,new vx(this.url,this.fileOptions).iterator()]:[2,function(t,e){return void 0===e&&(e={}),lb(this,void 0,void 0,function(){var n,r,i,a,o;return cb(this,function(s){switch(s.label){case 0:return"string"==typeof t?n=t:(n=t.url,r=mx(t)),[4,$.fetch(n,r)];case 1:return(i=s.sent()).ok?(o=Uint8Array.bind,[4,i.arrayBuffer()]):[3,3];case 2:return a=new(o.apply(Uint8Array,[void 0,s.sent()])),[2,new dx(a,e)];case 3:throw new Error(i.statusText)}})})}(this.url,this.fileOptions)]})})},e}(sx);var bx=Object.freeze({array:function(t){var e=this;return Yb(function(){return lb(e,void 0,void 0,function(){return cb(this,function(e){return[2,Rb(t)]})})},t.length)},Dataset:Xb,zip:function(t){var e,n=this;if(!Eb(t))throw new Error("The argument to zip() must be an object or array.");if(Array.isArray(t))for(var r=0;r<t.length;r++)e=null==e?t[r].size:Math.min(e,t[r].size);else if(t instanceof Object)for(var i in t)e=null==e?t[i].size:Math.min(e,t[i].size);return Yb(function(){return lb(n,void 0,void 0,function(){return cb(this,function(e){switch(e.label){case 0:return[4,Nb(t,function(t){if(t instanceof Xb)return{value:t.iterator(),recurse:!1};if(Eb(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,function(t,e){return void 0===e&&(e=Db.FAIL),new Hb(t,e)}(e.sent(),Db.SHORTEST)]}})})},e)},CSVDataset:ix,TextLineDataset:Zb,csv:function(t,e){return void 0===e&&(e={}),new ix(new yx(t),e)},func:function(t){var e=this,n=Tb(t);return Yb(function(){return lb(e,void 0,void 0,function(){return cb(this,function(t){return[2,n]})})})},generator:function(t){var e=this;return Yb(function(){return lb(e,void 0,void 0,function(){var e;return cb(this,function(n){switch(n.label){case 0:return[4,t()];case 1:return e=n.sent(),[2,Tb(function(){return e.next()})]}})})})},microphone:function(t){return lb(this,void 0,void 0,function(){return cb(this,function(e){return[2,ax.create(t)]})})},webcam:function(t,e){return lb(this,void 0,void 0,function(){return cb(this,function(n){return[2,ox.create(t,e)]})})},FileDataSource:vx,URLDataSource:yx,version_data:"1.2.11"}),xx={"tfjs-core":"1.2.11","tfjs-data":"1.2.11","tfjs-layers":"1.2.11","tfjs-converter":"1.2.11",tfjs:"1.2.11"};t.data=bx,t.version=xx,t.AdadeltaOptimizer=Vp,t.AdagradOptimizer=Up,t.AdamOptimizer=jp,t.AdamaxOptimizer=Gp,t.DataStorage=Dr,t.Environment=a,t.KernelBackend=Or,t.MomentumOptimizer=Hp,t.Optimizer=Wp,t.RMSPropOptimizer=Kp,t.SGDOptimizer=qp,t.Tensor=st,t.TensorBuffer=rt,t.Variable=ut,t.abs=Ko,t.acos=$o,t.acosh=Xo,t.add=$s,t.addN=Xs,t.addStrict=Ys,t.all=fl,t.any=dl,t.argMax=ml,t.argMin=gl,t.asin=Yo,t.asinh=Jo,t.atan=Zo,t.atan2=Js,t.atanh=Qo,t.avgPool=rl,t.avgPool3d=ol,t.backend=Me,t.backend_util=Jr,t.basicLSTMCell=_l,t.batchNorm=Ps,t.batchNorm2d=Bs,t.batchNorm3d=Ws,t.batchNorm4d=Vs,t.batchNormalization=Ls,t.batchNormalization2d=Fs,t.batchNormalization3d=zs,t.batchNormalization4d=Ms,t.batchToSpaceND=Bn,t.booleanMaskAsync=Du,t.browser=Ap,t.buffer=Ln,t.cast=Wn,t.ceil=ts,t.clipByValue=es,t.clone=Vn,t.complex=Qe,t.concat=bn,t.concat1d=xn,t.concat2d=wn,t.concat3d=Cn,t.concat4d=Nn,t.conv1d=zu,t.conv2d=Mu,t.conv2dTranspose=Gu,t.conv3d=Lu,t.conv3dTranspose=qu,t.cos=ns,t.cosh=rs,t.cumsum=Un,t.customGrad=Ir,t.deprecationWarn=De,t.depthToSpace=jn,t.depthwiseConv2d=Wu,t.diag=Hl,t.disableDeprecationWarnings=function(){o().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")},t.dispose=Fe,t.disposeVariables=function(){Et.disposeVariables()},t.div=Zs,t.divStrict=Qs,t.dot=Ku,t.dropout=Kl,t.elu=El,t.enableDebugMode=function(){o().set("DEBUG",!0)},t.enableProdMode=function(){o().set("PROD",!0)},t.engine=function(){return Et},t.env=o,t.equal=mu,t.equalStrict=gu,t.erf=is,t.exp=as,t.expandDims=Gn,t.expm1=os,t.eye=qn,t.fft=Bl,t.fill=dn,t.findBackend=function(t){return Et.findBackend(t)},t.findBackendFactory=function(t){return Et.findBackendFactory(t)},t.floor=ss,t.floorDiv=tu,t.frame=Jl,t.fused=Ec,t.gather=Ru,t.gatherND=ql,t.getBackend=function(){return Et.backendName},t.grad=function(t){return p(L(t),function(){return"The f passed in grad(f) must be a function"}),function(e,n){var r=We(e,"x","tf.grad",null),i=null!=n?We(n,"dy","tf.grad"):null;return Et.tidy(function(){var e=Et.gradients(function(){return t(r)},[r],i),n=e.value,a=e.grads;return null!=i&&h(n.shape,i.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Ar(a),a[0]})}},t.grads=function(t){return p(L(t),function(){return"The f passed in grads(f) must be a function"}),function(e,n){p(Array.isArray(e),function(){return"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s"});var r=Ve(e,"args","tf.grads",null),i=null!=n?We(n,"dy","tf.grads"):null;return Et.tidy(function(){var e=Et.gradients(function(){return t.apply(void 0,r)},r,i),n=e.value,a=e.grads;return null!=i&&h(n.shape,i.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Ar(a),a})}},t.greater=vu,t.greaterEqual=yu,t.greaterEqualStrict=bu,t.greaterStrict=xu,t.hammingWindow=Yl,t.hannWindow=Xl,t.ifft=Wl,t.imag=en,t.image=xc,t.inTopKAsync=tc,t.io=Ep,t.irfft=Ul,t.isFinite=bs,t.isInf=ys,t.isNaN=vs,t.keep=ze,t.leakyRelu=Sl,t.less=wu,t.lessEqual=Cu,t.lessEqualStrict=Nu,t.lessStrict=Eu,t.linalg=dc,t.linspace=mn,t.localResponseNormalization=Dl,t.log=us,t.log1p=ls,t.logSigmoid=cs,t.logSoftmax=Tr,t.logSumExp=vl,t.logicalAnd=Us,t.logicalNot=js,t.logicalOr=Gs,t.logicalXor=qs,t.losses=cc,t.matMul=Hu,t.math=kp,t.max=yl,t.maxPool=nl,t.maxPool3d=al,t.maximum=eu,t.maximumStrict=nu,t.mean=bl,t.memory=Oe,t.min=xl,t.minimum=ru,t.minimumStrict=iu,t.mod=au,t.modStrict=ou,t.moments=wl,t.movingAverage=zl,t.mul=su,t.mulStrict=uu,t.multiRNNCell=Fl,t.multinomial=Hn,t.neg=ps,t.nextFrame=Jp,t.norm=Ol,t.notEqual=Su,t.notEqualStrict=ku,t.oneHot=Kn,t.ones=hn,t.onesLike=vn,t.op=Ze,t.outerProduct=$u,t.pad=$n,t.pad1d=Xn,t.pad2d=Yn,t.pad3d=Jn,t.pad4d=Zn,t.pool=il,t.pow=lu,t.powStrict=cu,t.prelu=kl,t.print=Pn,t.prod=Nl,t.profile=function(t){return Et.profile(t)},t.rand=Qn,t.randomGamma=er,t.randomNormal=tr,t.randomUniform=nr,t.range=gn,t.ready=function(){return Et.ready()},t.real=tn,t.reciprocal=hs,t.registerBackend=function(t,e,n){return void 0===n&&(n=1),Et.registerBackend(t,e,n)},t.relu=Il,t.relu6=Al,t.removeBackend=function(t){Et.removeBackend(t)},t.reshape=rr,t.reverse=Xu,t.reverse1d=Yu,t.reverse2d=Ju,t.reverse3d=Zu,t.reverse4d=Qu,t.rfft=Vl,t.round=fs,t.rsqrt=ds,t.scalar=an,t.scatterND=Pl,t.selu=Rl,t.separableConv2d=ju,t.serialization=Op,t.setBackend=function(t){return Et.setBackend(t)},t.setPlatform=function(t,e){o().setPlatform(t,e)},t.setdiff1dAsync=cr,t.sigmoid=ms,t.sign=gs,t.signal=Ql,t.sin=xs,t.sinh=ws,t.slice=sl,t.slice1d=ul,t.slice2d=ll,t.slice3d=cl,t.slice4d=pl,t.softmax=Rr,t.softplus=Cs,t.spaceToBatchND=ir,t.sparseToDense=Gl,t.spectral=jl,t.split=En,t.sqrt=Ns,t.square=Es,t.squaredDifference=pu,t.squaredDifferenceStrict=hu,t.squeeze=ar,t.stack=or,t.step=Ss,t.stft=Zl,t.stridedSlice=Ml,t.sub=fu,t.subStrict=du,t.sum=Cl,t.tan=ks,t.tanh=Is,t.tensor=nn,t.tensor1d=on,t.tensor2d=sn,t.tensor3d=un,t.tensor4d=ln,t.tensor5d=cn,t.tensor6d=pn,t.tensor_util=wt,t.test_util=Pp,t.tidy=_e,t.tile=sr,t.time=function(t){return Et.time(t)},t.topk=Ll,t.train=Xp,t.transpose=Tl,t.truncatedNormal=ur,t.unsortedSegmentSum=Tu,t.unstack=lr,t.util=$,t.valueAndGrad=function(t){return p(L(t),function(){return"The f passed in valueAndGrad(f) must be a function"}),function(e,n){p(e instanceof st,function(){return"The x passed in valueAndGrad(f)(x) must be a tensor"}),p(null==n||n instanceof st,function(){return"The dy passed in valueAndGrad(f)(x, dy) must be a tensor"});var r=Et.gradients(function(){return t(e)},[e],n),i=r.grads,a=r.value;return Ar(i),{grad:i[0],value:a}}},t.valueAndGrads=function(t){return p(L(t),function(){return"The f passed in valueAndGrads(f) must be a function"}),function(e,n){p(Array.isArray(e)&&e.every(function(t){return t instanceof st}),function(){return"The args passed in valueAndGrads(f)(args) must be array of tensors"}),p(null==n||n instanceof st,function(){return"The dy passed in valueAndGrads(f)(args, dy) must be a tensor"});var r=Et.gradients(function(){return t.apply(void 0,e)},e,n);return null!=n&&h(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Ar(r.grads),r}},t.variable=ft,t.variableGrads=kr,t.version_core="1.2.11",t.webgl=Bp,t.where=Hs,t.whereAsync=Ks,t.zeros=fn,t.zerosLike=yn,t.constraints=Lh,t.initializers=Gf,t.layers=Mv,t.metrics=Lv,t.models=Pv,t.regularizers=Bv,t.CallbackList=vd,t.CustomCallback=xd,t.History=bd,t.Callback=Wv,t.callbacks=Hv,t.EarlyStopping=jv,t.InputSpec=id,t.SymbolicTensor=ad,t.LayersModel=Sm,t.input=Am,t.loadLayersModel=function(t,e){return null==e&&(e={}),km(t,e)},t.model=function(t){return new Sm(t)},t.registerCallbackConstructor=function(t,e){Cd.registerCallbackConstructor(t,e)},t.sequential=function(t){return new Im(t)},t.RNN=pv,t.Sequential=Im,t.LayerVariable=ed,t.version_layers="1.2.11",t.GraphModel=ob,t.loadGraphModel=function(t,e){return void 0===e&&(e={}),$v(this,void 0,void 0,function(){var n;return Xv(this,function(r){switch(r.label){case 0:if(null==t)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");return null==e&&(e={}),e.fromTFHub&&null==t.load&&(t.endsWith("/")||(t+="/"),t=""+t+ab+ib),[4,(n=new ob(t,e)).load()];case 1:return r.sent(),[2,n]}})})},t.deregisterOp=function(t){delete Yv[t]},t.registerOp=function(t,e){var n={tfOpName:t,category:"custom",inputs:[],attrs:[],customExecutor:e};Yv[t]=n},t.version_converter="1.2.11",Object.defineProperty(t,"__esModule",{value:!0})});
|
|
//# sourceMappingURL=tf.min.js.map
|