text: parcelRequire=function(e,r,t,n){var i,o="function"==typeof parcelRequire&&parcelRequire,u="function"==typeof require&&require;function f(t,n){if(!r[t]){if(!e[t]){var i="function"==typeof parcelRequire&&parcelRequire;if(!n&&i)return i(t,!0);if(o)return o(t,!0);if(u&&"string"==typeof t)return u(t);var c=new Error("Cannot find module '"+t+"'");throw c.code="MODULE_NOT_FOUND",c}p.resolve=function(r){return e[t][1][r]||r},p.cache={};var l=r[t]=new f.Module(t);e[t][0].call(l.exports,p,l,l.exports,this)}return r[t].exports;function p(e){return f(p.resolve(e))}}f.isParcelRequire=!0,f.Module=function(e){this.id=e,this.bundle=f,this.exports={}},f.modules=e,f.cache=r,f.parent=o,f.register=function(r,t){e[r]=[function(e,r){r.exports=t},{}]};for(var c=0;c<t.length;c++)try{f(t[c])}catch(e){i||(i=e)}if(t.length){var l=f(t[t.length-1]);"object"==typeof exports&&"undefined"!=typeof module?module.exports=l:"function"==typeof define&&define.amd?define(function(){return l}):n&&(this[n]=l)}if(parcelRequire=f,i)throw i;return f}({"sC8V":[function(require,module,exports) {
  
  },{}],"g5IB":[function(require,module,exports) {
  
  var t,e,n=module.exports={};function r(){throw new Error("setTimeout has not been defined")}function o(){throw new Error("clearTimeout has not been defined")}function i(e){if(t===setTimeout)return setTimeout(e,0);if((t===r||!t)&&setTimeout)return t=setTimeout,setTimeout(e,0);try{return t(e,0)}catch(n){try{return t.call(null,e,0)}catch(n){return t.call(this,e,0)}}}function u(t){if(e===clearTimeout)return clearTimeout(t);if((e===o||!e)&&clearTimeout)return e=clearTimeout,clearTimeout(t);try{return e(t)}catch(n){try{return e.call(null,t)}catch(n){return e.call(this,t)}}}!function(){try{t="function"==typeof setTimeout?setTimeout:r}catch(n){t=r}try{e="function"==typeof clearTimeout?clearTimeout:o}catch(n){e=o}}();var c,s=[],l=!1,a=-1;function f(){l&&c&&(l=!1,c.length?s=c.concat(s):a=-1,s.length&&h())}function h(){if(!l){var t=i(f);l=!0;for(var e=s.length;e;){for(c=s,s=[];++a<e;)c&&c[a].run();a=-1,e=s.length}c=null,l=!1,u(t)}}function m(t,e){this.fun=t,this.array=e}function p(){}n.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];s.push(new m(t,e)),1!==s.length||l||i(h)},m.prototype.run=function(){this.fun.apply(null,this.array)},n.title="browser",n.env={},n.argv=[],n.version="",n.versions={},n.on=p,n.addListener=p,n.once=p,n.off=p,n.removeListener=p,n.removeAllListeners=p,n.emit=p,n.prependListener=p,n.prependOnceListener=p,n.listeners=function(t){return[]},n.binding=function(t){throw new Error("process.binding is not supported")},n.cwd=function(){return"/"},n.chdir=function(t){throw new Error("process.chdir is not supported")},n.umask=function(){return 0};
  },{}],"FRly":[function(require,module,exports) {
  "use strict";exports.byteLength=u,exports.toByteArray=i,exports.fromByteArray=d;for(var r=[],t=[],e="undefined"!=typeof Uint8Array?Uint8Array:Array,n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0,a=n.length;o<a;++o)r[o]=n[o],t[n.charCodeAt(o)]=o;function h(r){var t=r.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var e=r.indexOf("=");return-1===e&&(e=t),[e,e===t?0:4-e%4]}function u(r){var t=h(r),e=t[0],n=t[1];return 3*(e+n)/4-n}function c(r,t,e){return 3*(t+e)/4-e}function i(r){var n,o,a=h(r),u=a[0],i=a[1],f=new e(c(r,u,i)),A=0,d=i>0?u-4:u;for(o=0;o<d;o+=4)n=t[r.charCodeAt(o)]<<18|t[r.charCodeAt(o+1)]<<12|t[r.charCodeAt(o+2)]<<6|t[r.charCodeAt(o+3)],f[A++]=n>>16&255,f[A++]=n>>8&255,f[A++]=255&n;return 2===i&&(n=t[r.charCodeAt(o)]<<2|t[r.charCodeAt(o+1)]>>4,f[A++]=255&n),1===i&&(n=t[r.charCodeAt(o)]<<10|t[r.charCodeAt(o+1)]<<4|t[r.charCodeAt(o+2)]>>2,f[A++]=n>>8&255,f[A++]=255&n),f}function f(t){return r[t>>18&63]+r[t>>12&63]+r[t>>6&63]+r[63&t]}function A(r,t,e){for(var n,o=[],a=t;a<e;a+=3)n=(r[a]<<16&16711680)+(r[a+1]<<8&65280)+(255&r[a+2]),o.push(f(n));return o.join("")}function d(t){for(var e,n=t.length,o=n%3,a=[],h=0,u=n-o;h<u;h+=16383)a.push(A(t,h,h+16383>u?u:h+16383));return 1===o?(e=t[n-1],a.push(r[e>>2]+r[e<<4&63]+"==")):2===o&&(e=(t[n-2]<<8)+t[n-1],a.push(r[e>>10]+r[e>>4&63]+r[e<<2&63]+"=")),a.join("")}t["-".charCodeAt(0)]=62,t["_".charCodeAt(0)]=63;
  },{}],"Quj6":[function(require,module,exports) {
  exports.read=function(a,o,t,r,h){var M,p,w=8*h-r-1,f=(1<<w)-1,e=f>>1,i=-7,N=t?h-1:0,n=t?-1:1,s=a[o+N];for(N+=n,M=s&(1<<-i)-1,s>>=-i,i+=w;i>0;M=256*M+a[o+N],N+=n,i-=8);for(p=M&(1<<-i)-1,M>>=-i,i+=r;i>0;p=256*p+a[o+N],N+=n,i-=8);if(0===M)M=1-e;else{if(M===f)return p?NaN:1/0*(s?-1:1);p+=Math.pow(2,r),M-=e}return(s?-1:1)*p*Math.pow(2,M-r)},exports.write=function(a,o,t,r,h,M){var p,w,f,e=8*M-h-1,i=(1<<e)-1,N=i>>1,n=23===h?Math.pow(2,-24)-Math.pow(2,-77):0,s=r?0:M-1,u=r?1:-1,l=o<0||0===o&&1/o<0?1:0;for(o=Math.abs(o),isNaN(o)||o===1/0?(w=isNaN(o)?1:0,p=i):(p=Math.floor(Math.log(o)/Math.LN2),o*(f=Math.pow(2,-p))<1&&(p--,f*=2),(o+=p+N>=1?n/f:n*Math.pow(2,1-N))*f>=2&&(p++,f/=2),p+N>=i?(w=0,p=i):p+N>=1?(w=(o*f-1)*Math.pow(2,h),p+=N):(w=o*Math.pow(2,N-1)*Math.pow(2,h),p=0));h>=8;a[t+s]=255&w,s+=u,w/=256,h-=8);for(p=p<<h|w,e+=h;e>0;a[t+s]=255&p,s+=u,p/=256,e-=8);a[t+s-u]|=128*l};
  },{}],"aqZJ":[function(require,module,exports) {
  var r={}.toString;module.exports=Array.isArray||function(t){return"[object Array]"==r.call(t)};
  },{}],"aMB2":[function(require,module,exports) {
  
  var global = arguments[3];
  var t=arguments[3],r=require("base64-js"),e=require("ieee754"),n=require("isarray");function i(){try{var t=new Uint8Array(1);return t.__proto__={__proto__:Uint8Array.prototype,foo:function(){return 42}},42===t.foo()&&"function"==typeof t.subarray&&0===t.subarray(1,1).byteLength}catch(r){return!1}}function o(){return f.TYPED_ARRAY_SUPPORT?2147483647:1073741823}function u(t,r){if(o()<r)throw new RangeError("Invalid typed array length");return f.TYPED_ARRAY_SUPPORT?(t=new Uint8Array(r)).__proto__=f.prototype:(null===t&&(t=new f(r)),t.length=r),t}function f(t,r,e){if(!(f.TYPED_ARRAY_SUPPORT||this instanceof f))return new f(t,r,e);if("number"==typeof t){if("string"==typeof r)throw new Error("If encoding is specified then the first argument must be a string");return c(this,t)}return s(this,t,r,e)}function s(t,r,e,n){if("number"==typeof r)throw new TypeError('"value" argument must not be a number');return"undefined"!=typeof ArrayBuffer&&r instanceof ArrayBuffer?g(t,r,e,n):"string"==typeof r?l(t,r,e):y(t,r)}function h(t){if("number"!=typeof t)throw new TypeError('"size" argument must be a number');if(t<0)throw new RangeError('"size" argument must not be negative')}function a(t,r,e,n){return h(r),r<=0?u(t,r):void 0!==e?"string"==typeof n?u(t,r).fill(e,n):u(t,r).fill(e):u(t,r)}function c(t,r){if(h(r),t=u(t,r<0?0:0|w(r)),!f.TYPED_ARRAY_SUPPORT)for(var e=0;e<r;++e)t[e]=0;return t}function l(t,r,e){if("string"==typeof e&&""!==e||(e="utf8"),!f.isEncoding(e))throw new TypeError('"encoding" must be a valid string encoding');var n=0|v(r,e),i=(t=u(t,n)).write(r,e);return i!==n&&(t=t.slice(0,i)),t}function p(t,r){var e=r.length<0?0:0|w(r.length);t=u(t,e);for(var n=0;n<e;n+=1)t[n]=255&r[n];return t}function g(t,r,e,n){if(r.byteLength,e<0||r.byteLength<e)throw new RangeError("'offset' is out of bounds");if(r.byteLength<e+(n||0))throw new RangeError("'length' is out of bounds");return r=void 0===e&&void 0===n?new Uint8Array(r):void 0===n?new Uint8Array(r,e):new Uint8Array(r,e,n),f.TYPED_ARRAY_SUPPORT?(t=r).__proto__=f.prototype:t=p(t,r),t}function y(t,r){if(f.isBuffer(r)){var e=0|w(r.length);return 0===(t=u(t,e)).length?t:(r.copy(t,0,0,e),t)}if(r){if("undefined"!=typeof ArrayBuffer&&r.buffer instanceof ArrayBuffer||"length"in r)return"number"!=typeof r.length||W(r.length)?u(t,0):p(t,r);if("Buffer"===r.type&&n(r.data))return p(t,r.data)}throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.")}function w(t){if(t>=o())throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o().toString(16)+" bytes");return 0|t}function d(t){return+t!=t&&(t=0),f.alloc(+t)}function v(t,r){if(f.isBuffer(t))return t.length;if("undefined"!=typeof ArrayBuffer&&"function"==typeof ArrayBuffer.isView&&(ArrayBuffer.isView(t)||t instanceof ArrayBuffer))return t.byteLength;"string"!=typeof t&&(t=""+t);var e=t.length;if(0===e)return 0;for(var n=!1;;)switch(r){case"ascii":case"latin1":case"binary":return e;case"utf8":case"utf-8":case void 0:return $(t).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*e;case"hex":return e>>>1;case"base64":return K(t).length;default:if(n)return $(t).length;r=(""+r).toLowerCase(),n=!0}}function E(t,r,e){var n=!1;if((void 0===r||r<0)&&(r=0),r>this.length)return"";if((void 0===e||e>this.length)&&(e=this.length),e<=0)return"";if((e>>>=0)<=(r>>>=0))return"";for(t||(t="utf8");;)switch(t){case"hex":return x(this,r,e);case"utf8":case"utf-8":return Y(this,r,e);case"ascii":return L(this,r,e);case"latin1":case"binary":return D(this,r,e);case"base64":return S(this,r,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,r,e);default:if(n)throw new TypeError("Unknown encoding: "+t);t=(t+"").toLowerCase(),n=!0}}function b(t,r,e){var n=t[r];t[r]=t[e],t[e]=n}function R(t,r,e,n,i){if(0===t.length)return-1;if("string"==typeof e?(n=e,e=0):e>2147483647?e=2147483647:e<-2147483648&&(e=-2147483648),e=+e,isNaN(e)&&(e=i?0:t.length-1),e<0&&(e=t.length+e),e>=t.length){if(i)return-1;e=t.length-1}else if(e<0){if(!i)return-1;e=0}if("string"==typeof r&&(r=f.from(r,n)),f.isBuffer(r))return 0===r.length?-1:_(t,r,e,n,i);if("number"==typeof r)return r&=255,f.TYPED_ARRAY_SUPPORT&&"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(t,r,e):Uint8Array.prototype.lastIndexOf.call(t,r,e):_(t,[r],e,n,i);throw new TypeError("val must be string, number or Buffer")}function _(t,r,e,n,i){var o,u=1,f=t.length,s=r.length;if(void 0!==n&&("ucs2"===(n=String(n).toLowerCase())||"ucs-2"===n||"utf16le"===n||"utf-16le"===n)){if(t.length<2||r.length<2)return-1;u=2,f/=2,s/=2,e/=2}function h(t,r){return 1===u?t[r]:t.readUInt16BE(r*u)}if(i){var a=-1;for(o=e;o<f;o++)if(h(t,o)===h(r,-1===a?0:o-a)){if(-1===a&&(a=o),o-a+1===s)return a*u}else-1!==a&&(o-=o-a),a=-1}else for(e+s>f&&(e=f-s),o=e;o>=0;o--){for(var c=!0,l=0;l<s;l++)if(h(t,o+l)!==h(r,l)){c=!1;break}if(c)return o}return-1}function A(t,r,e,n){e=Number(e)||0;var i=t.length-e;n?(n=Number(n))>i&&(n=i):n=i;var o=r.length;if(o%2!=0)throw new TypeError("Invalid hex string");n>o/2&&(n=o/2);for(var u=0;u<n;++u){var f=parseInt(r.substr(2*u,2),16);if(isNaN(f))return u;t[e+u]=f}return u}function m(t,r,e,n){return Q($(r,t.length-e),t,e,n)}function P(t,r,e,n){return Q(G(r),t,e,n)}function T(t,r,e,n){return P(t,r,e,n)}function B(t,r,e,n){return Q(K(r),t,e,n)}function U(t,r,e,n){return Q(H(r,t.length-e),t,e,n)}function S(t,e,n){return 0===e&&n===t.length?r.fromByteArray(t):r.fromByteArray(t.slice(e,n))}function Y(t,r,e){e=Math.min(t.length,e);for(var n=[],i=r;i<e;){var o,u,f,s,h=t[i],a=null,c=h>239?4:h>223?3:h>191?2:1;if(i+c<=e)switch(c){case 1:h<128&&(a=h);break;case 2:128==(192&(o=t[i+1]))&&(s=(31&h)<<6|63&o)>127&&(a=s);break;case 3:o=t[i+1],u=t[i+2],128==(192&o)&&128==(192&u)&&(s=(15&h)<<12|(63&o)<<6|63&u)>2047&&(s<55296||s>57343)&&(a=s);break;case 4:o=t[i+1],u=t[i+2],f=t[i+3],128==(192&o)&&128==(192&u)&&128==(192&f)&&(s=(15&h)<<18|(63&o)<<12|(63&u)<<6|63&f)>65535&&s<1114112&&(a=s)}null===a?(a=65533,c=1):a>65535&&(a-=65536,n.push(a>>>10&1023|55296),a=56320|1023&a),n.push(a),i+=c}return O(n)}exports.Buffer=f,exports.SlowBuffer=d,exports.INSPECT_MAX_BYTES=50,f.TYPED_ARRAY_SUPPORT=void 0!==t.TYPED_ARRAY_SUPPORT?t.TYPED_ARRAY_SUPPORT:i(),exports.kMaxLength=o(),f.poolSize=8192,f._augment=function(t){return t.__proto__=f.prototype,t},f.from=function(t,r,e){return s(null,t,r,e)},f.TYPED_ARRAY_SUPPORT&&(f.prototype.__proto__=Uint8Array.prototype,f.__proto__=Uint8Array,"undefined"!=typeof Symbol&&Symbol.species&&f[Symbol.species]===f&&Object.defineProperty(f,Symbol.species,{value:null,configurable:!0})),f.alloc=function(t,r,e){return a(null,t,r,e)},f.allocUnsafe=function(t){return c(null,t)},f.allocUnsafeSlow=function(t){return c(null,t)},f.isBuffer=function(t){return!(null==t||!t._isBuffer)},f.compare=function(t,r){if(!f.isBuffer(t)||!f.isBuffer(r))throw new TypeError("Arguments must be Buffers");if(t===r)return 0;for(var e=t.length,n=r.length,i=0,o=Math.min(e,n);i<o;++i)if(t[i]!==r[i]){e=t[i],n=r[i];break}return e<n?-1:n<e?1:0},f.isEncoding=function(t){switch(String(t).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},f.concat=function(t,r){if(!n(t))throw new TypeError('"list" argument must be an Array of Buffers');if(0===t.length)return f.alloc(0);var e;if(void 0===r)for(r=0,e=0;e<t.length;++e)r+=t[e].length;var i=f.allocUnsafe(r),o=0;for(e=0;e<t.length;++e){var u=t[e];if(!f.isBuffer(u))throw new TypeError('"list" argument must be an Array of Buffers');u.copy(i,o),o+=u.length}return i},f.byteLength=v,f.prototype._isBuffer=!0,f.prototype.swap16=function(){var t=this.length;if(t%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(var r=0;r<t;r+=2)b(this,r,r+1);return this},f.prototype.swap32=function(){var t=this.length;if(t%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(var r=0;r<t;r+=4)b(this,r,r+3),b(this,r+1,r+2);return this},f.prototype.swap64=function(){var t=this.length;if(t%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(var r=0;r<t;r+=8)b(this,r,r+7),b(this,r+1,r+6),b(this,r+2,r+5),b(this,r+3,r+4);return this},f.prototype.toString=function(){var t=0|this.length;return 0===t?"":0===arguments.length?Y(this,0,t):E.apply(this,arguments)},f.prototype.equals=function(t){if(!f.isBuffer(t))throw new TypeError("Argument must be a Buffer");return this===t||0===f.compare(this,t)},f.prototype.inspect=function(){var t="",r=exports.INSPECT_MAX_BYTES;return this.length>0&&(t=this.toString("hex",0,r).match(/.{2}/g).join(" "),this.length>r&&(t+=" ... ")),"<Buffer "+t+">"},f.prototype.compare=function(t,r,e,n,i){if(!f.isBuffer(t))throw new TypeError("Argument must be a Buffer");if(void 0===r&&(r=0),void 0===e&&(e=t?t.length:0),void 0===n&&(n=0),void 0===i&&(i=this.length),r<0||e>t.length||n<0||i>this.length)throw new RangeError("out of range index");if(n>=i&&r>=e)return 0;if(n>=i)return-1;if(r>=e)return 1;if(this===t)return 0;for(var o=(i>>>=0)-(n>>>=0),u=(e>>>=0)-(r>>>=0),s=Math.min(o,u),h=this.slice(n,i),a=t.slice(r,e),c=0;c<s;++c)if(h[c]!==a[c]){o=h[c],u=a[c];break}return o<u?-1:u<o?1:0},f.prototype.includes=function(t,r,e){return-1!==this.indexOf(t,r,e)},f.prototype.indexOf=function(t,r,e){return R(this,t,r,e,!0)},f.prototype.lastIndexOf=function(t,r,e){return R(this,t,r,e,!1)},f.prototype.write=function(t,r,e,n){if(void 0===r)n="utf8",e=this.length,r=0;else if(void 0===e&&"string"==typeof r)n=r,e=this.length,r=0;else{if(!isFinite(r))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");r|=0,isFinite(e)?(e|=0,void 0===n&&(n="utf8")):(n=e,e=void 0)}var i=this.length-r;if((void 0===e||e>i)&&(e=i),t.length>0&&(e<0||r<0)||r>this.length)throw new RangeError("Attempt to write outside buffer bounds");n||(n="utf8");for(var o=!1;;)switch(n){case"hex":return A(this,t,r,e);case"utf8":case"utf-8":return m(this,t,r,e);case"ascii":return P(this,t,r,e);case"latin1":case"binary":return T(this,t,r,e);case"base64":return B(this,t,r,e);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return U(this,t,r,e);default:if(o)throw new TypeError("Unknown encoding: "+n);n=(""+n).toLowerCase(),o=!0}},f.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};var I=4096;function O(t){var r=t.length;if(r<=I)return String.fromCharCode.apply(String,t);for(var e="",n=0;n<r;)e+=String.fromCharCode.apply(String,t.slice(n,n+=I));return e}function L(t,r,e){var n="";e=Math.min(t.length,e);for(var i=r;i<e;++i)n+=String.fromCharCode(127&t[i]);return n}function D(t,r,e){var n="";e=Math.min(t.length,e);for(var i=r;i<e;++i)n+=String.fromCharCode(t[i]);return n}function x(t,r,e){var n=t.length;(!r||r<0)&&(r=0),(!e||e<0||e>n)&&(e=n);for(var i="",o=r;o<e;++o)i+=Z(t[o]);return i}function C(t,r,e){for(var n=t.slice(r,e),i="",o=0;o<n.length;o+=2)i+=String.fromCharCode(n[o]+256*n[o+1]);return i}function M(t,r,e){if(t%1!=0||t<0)throw new RangeError("offset is not uint");if(t+r>e)throw new RangeError("Trying to access beyond buffer length")}function k(t,r,e,n,i,o){if(!f.isBuffer(t))throw new TypeError('"buffer" argument must be a Buffer instance');if(r>i||r<o)throw new RangeError('"value" argument is out of bounds');if(e+n>t.length)throw new RangeError("Index out of range")}function N(t,r,e,n){r<0&&(r=65535+r+1);for(var i=0,o=Math.min(t.length-e,2);i<o;++i)t[e+i]=(r&255<<8*(n?i:1-i))>>>8*(n?i:1-i)}function z(t,r,e,n){r<0&&(r=4294967295+r+1);for(var i=0,o=Math.min(t.length-e,4);i<o;++i)t[e+i]=r>>>8*(n?i:3-i)&255}function F(t,r,e,n,i,o){if(e+n>t.length)throw new RangeError("Index out of range");if(e<0)throw new RangeError("Index out of range")}function j(t,r,n,i,o){return o||F(t,r,n,4,3.4028234663852886e38,-3.4028234663852886e38),e.write(t,r,n,i,23,4),n+4}function q(t,r,n,i,o){return o||F(t,r,n,8,1.7976931348623157e308,-1.7976931348623157e308),e.write(t,r,n,i,52,8),n+8}f.prototype.slice=function(t,r){var e,n=this.length;if((t=~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),(r=void 0===r?n:~~r)<0?(r+=n)<0&&(r=0):r>n&&(r=n),r<t&&(r=t),f.TYPED_ARRAY_SUPPORT)(e=this.subarray(t,r)).__proto__=f.prototype;else{var i=r-t;e=new f(i,void 0);for(var o=0;o<i;++o)e[o]=this[o+t]}return e},f.prototype.readUIntLE=function(t,r,e){t|=0,r|=0,e||M(t,r,this.length);for(var n=this[t],i=1,o=0;++o<r&&(i*=256);)n+=this[t+o]*i;return n},f.prototype.readUIntBE=function(t,r,e){t|=0,r|=0,e||M(t,r,this.length);for(var n=this[t+--r],i=1;r>0&&(i*=256);)n+=this[t+--r]*i;return n},f.prototype.readUInt8=function(t,r){return r||M(t,1,this.length),this[t]},f.prototype.readUInt16LE=function(t,r){return r||M(t,2,this.length),this[t]|this[t+1]<<8},f.prototype.readUInt16BE=function(t,r){return r||M(t,2,this.length),this[t]<<8|this[t+1]},f.prototype.readUInt32LE=function(t,r){return r||M(t,4,this.length),(this[t]|this[t+1]<<8|this[t+2]<<16)+16777216*this[t+3]},f.prototype.readUInt32BE=function(t,r){return r||M(t,4,this.length),16777216*this[t]+(this[t+1]<<16|this[t+2]<<8|this[t+3])},f.prototype.readIntLE=function(t,r,e){t|=0,r|=0,e||M(t,r,this.length);for(var n=this[t],i=1,o=0;++o<r&&(i*=256);)n+=this[t+o]*i;return n>=(i*=128)&&(n-=Math.pow(2,8*r)),n},f.prototype.readIntBE=function(t,r,e){t|=0,r|=0,e||M(t,r,this.length);for(var n=r,i=1,o=this[t+--n];n>0&&(i*=256);)o+=this[t+--n]*i;return o>=(i*=128)&&(o-=Math.pow(2,8*r)),o},f.prototype.readInt8=function(t,r){return r||M(t,1,this.length),128&this[t]?-1*(255-this[t]+1):this[t]},f.prototype.readInt16LE=function(t,r){r||M(t,2,this.length);var e=this[t]|this[t+1]<<8;return 32768&e?4294901760|e:e},f.prototype.readInt16BE=function(t,r){r||M(t,2,this.length);var e=this[t+1]|this[t]<<8;return 32768&e?4294901760|e:e},f.prototype.readInt32LE=function(t,r){return r||M(t,4,this.length),this[t]|this[t+1]<<8|this[t+2]<<16|this[t+3]<<24},f.prototype.readInt32BE=function(t,r){return r||M(t,4,this.length),this[t]<<24|this[t+1]<<16|this[t+2]<<8|this[t+3]},f.prototype.readFloatLE=function(t,r){return r||M(t,4,this.length),e.read(this,t,!0,23,4)},f.prototype.readFloatBE=function(t,r){return r||M(t,4,this.length),e.read(this,t,!1,23,4)},f.prototype.readDoubleLE=function(t,r){return r||M(t,8,this.length),e.read(this,t,!0,52,8)},f.prototype.readDoubleBE=function(t,r){return r||M(t,8,this.length),e.read(this,t,!1,52,8)},f.prototype.writeUIntLE=function(t,r,e,n){(t=+t,r|=0,e|=0,n)||k(this,t,r,e,Math.pow(2,8*e)-1,0);var i=1,o=0;for(this[r]=255&t;++o<e&&(i*=256);)this[r+o]=t/i&255;return r+e},f.prototype.writeUIntBE=function(t,r,e,n){(t=+t,r|=0,e|=0,n)||k(this,t,r,e,Math.pow(2,8*e)-1,0);var i=e-1,o=1;for(this[r+i]=255&t;--i>=0&&(o*=256);)this[r+i]=t/o&255;return r+e},f.prototype.writeUInt8=function(t,r,e){return t=+t,r|=0,e||k(this,t,r,1,255,0),f.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),this[r]=255&t,r+1},f.prototype.writeUInt16LE=function(t,r,e){return t=+t,r|=0,e||k(this,t,r,2,65535,0),f.TYPED_ARRAY_SUPPORT?(this[r]=255&t,this[r+1]=t>>>8):N(this,t,r,!0),r+2},f.prototype.writeUInt16BE=function(t,r,e){return t=+t,r|=0,e||k(this,t,r,2,65535,0),f.TYPED_ARRAY_SUPPORT?(this[r]=t>>>8,this[r+1]=255&t):N(this,t,r,!1),r+2},f.prototype.writeUInt32LE=function(t,r,e){return t=+t,r|=0,e||k(this,t,r,4,4294967295,0),f.TYPED_ARRAY_SUPPORT?(this[r+3]=t>>>24,this[r+2]=t>>>16,this[r+1]=t>>>8,this[r]=255&t):z(this,t,r,!0),r+4},f.prototype.writeUInt32BE=function(t,r,e){return t=+t,r|=0,e||k(this,t,r,4,4294967295,0),f.TYPED_ARRAY_SUPPORT?(this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t):z(this,t,r,!1),r+4},f.prototype.writeIntLE=function(t,r,e,n){if(t=+t,r|=0,!n){var i=Math.pow(2,8*e-1);k(this,t,r,e,i-1,-i)}var o=0,u=1,f=0;for(this[r]=255&t;++o<e&&(u*=256);)t<0&&0===f&&0!==this[r+o-1]&&(f=1),this[r+o]=(t/u>>0)-f&255;return r+e},f.prototype.writeIntBE=function(t,r,e,n){if(t=+t,r|=0,!n){var i=Math.pow(2,8*e-1);k(this,t,r,e,i-1,-i)}var o=e-1,u=1,f=0;for(this[r+o]=255&t;--o>=0&&(u*=256);)t<0&&0===f&&0!==this[r+o+1]&&(f=1),this[r+o]=(t/u>>0)-f&255;return r+e},f.prototype.writeInt8=function(t,r,e){return t=+t,r|=0,e||k(this,t,r,1,127,-128),f.TYPED_ARRAY_SUPPORT||(t=Math.floor(t)),t<0&&(t=255+t+1),this[r]=255&t,r+1},f.prototype.writeInt16LE=function(t,r,e){return t=+t,r|=0,e||k(this,t,r,2,32767,-32768),f.TYPED_ARRAY_SUPPORT?(this[r]=255&t,this[r+1]=t>>>8):N(this,t,r,!0),r+2},f.prototype.writeInt16BE=function(t,r,e){return t=+t,r|=0,e||k(this,t,r,2,32767,-32768),f.TYPED_ARRAY_SUPPORT?(this[r]=t>>>8,this[r+1]=255&t):N(this,t,r,!1),r+2},f.prototype.writeInt32LE=function(t,r,e){return t=+t,r|=0,e||k(this,t,r,4,2147483647,-2147483648),f.TYPED_ARRAY_SUPPORT?(this[r]=255&t,this[r+1]=t>>>8,this[r+2]=t>>>16,this[r+3]=t>>>24):z(this,t,r,!0),r+4},f.prototype.writeInt32BE=function(t,r,e){return t=+t,r|=0,e||k(this,t,r,4,2147483647,-2147483648),t<0&&(t=4294967295+t+1),f.TYPED_ARRAY_SUPPORT?(this[r]=t>>>24,this[r+1]=t>>>16,this[r+2]=t>>>8,this[r+3]=255&t):z(this,t,r,!1),r+4},f.prototype.writeFloatLE=function(t,r,e){return j(this,t,r,!0,e)},f.prototype.writeFloatBE=function(t,r,e){return j(this,t,r,!1,e)},f.prototype.writeDoubleLE=function(t,r,e){return q(this,t,r,!0,e)},f.prototype.writeDoubleBE=function(t,r,e){return q(this,t,r,!1,e)},f.prototype.copy=function(t,r,e,n){if(e||(e=0),n||0===n||(n=this.length),r>=t.length&&(r=t.length),r||(r=0),n>0&&n<e&&(n=e),n===e)return 0;if(0===t.length||0===this.length)return 0;if(r<0)throw new RangeError("targetStart out of bounds");if(e<0||e>=this.length)throw new RangeError("sourceStart out of bounds");if(n<0)throw new RangeError("sourceEnd out of bounds");n>this.length&&(n=this.length),t.length-r<n-e&&(n=t.length-r+e);var i,o=n-e;if(this===t&&e<r&&r<n)for(i=o-1;i>=0;--i)t[i+r]=this[i+e];else if(o<1e3||!f.TYPED_ARRAY_SUPPORT)for(i=0;i<o;++i)t[i+r]=this[i+e];else Uint8Array.prototype.set.call(t,this.subarray(e,e+o),r);return o},f.prototype.fill=function(t,r,e,n){if("string"==typeof t){if("string"==typeof r?(n=r,r=0,e=this.length):"string"==typeof e&&(n=e,e=this.length),1===t.length){var i=t.charCodeAt(0);i<256&&(t=i)}if(void 0!==n&&"string"!=typeof n)throw new TypeError("encoding must be a string");if("string"==typeof n&&!f.isEncoding(n))throw new TypeError("Unknown encoding: "+n)}else"number"==typeof t&&(t&=255);if(r<0||this.length<r||this.length<e)throw new RangeError("Out of range index");if(e<=r)return this;var o;if(r>>>=0,e=void 0===e?this.length:e>>>0,t||(t=0),"number"==typeof t)for(o=r;o<e;++o)this[o]=t;else{var u=f.isBuffer(t)?t:$(new f(t,n).toString()),s=u.length;for(o=0;o<e-r;++o)this[o+r]=u[o%s]}return this};var V=/[^+\/0-9A-Za-z-_]/g;function X(t){if((t=J(t).replace(V,"")).length<2)return"";for(;t.length%4!=0;)t+="=";return t}function J(t){return t.trim?t.trim():t.replace(/^\s+|\s+$/g,"")}function Z(t){return t<16?"0"+t.toString(16):t.toString(16)}function $(t,r){var e;r=r||1/0;for(var n=t.length,i=null,o=[],u=0;u<n;++u){if((e=t.charCodeAt(u))>55295&&e<57344){if(!i){if(e>56319){(r-=3)>-1&&o.push(239,191,189);continue}if(u+1===n){(r-=3)>-1&&o.push(239,191,189);continue}i=e;continue}if(e<56320){(r-=3)>-1&&o.push(239,191,189),i=e;continue}e=65536+(i-55296<<10|e-56320)}else i&&(r-=3)>-1&&o.push(239,191,189);if(i=null,e<128){if((r-=1)<0)break;o.push(e)}else if(e<2048){if((r-=2)<0)break;o.push(e>>6|192,63&e|128)}else if(e<65536){if((r-=3)<0)break;o.push(e>>12|224,e>>6&63|128,63&e|128)}else{if(!(e<1114112))throw new Error("Invalid code point");if((r-=4)<0)break;o.push(e>>18|240,e>>12&63|128,e>>6&63|128,63&e|128)}}return o}function G(t){for(var r=[],e=0;e<t.length;++e)r.push(255&t.charCodeAt(e));return r}function H(t,r){for(var e,n,i,o=[],u=0;u<t.length&&!((r-=2)<0);++u)n=(e=t.charCodeAt(u))>>8,i=e%256,o.push(i),o.push(n);return o}function K(t){return r.toByteArray(X(t))}function Q(t,r,e,n){for(var i=0;i<n&&!(i+e>=r.length||i>=t.length);++i)r[i+e]=t[i];return i}function W(t){return t!=t}
  },{"base64-js":"FRly","ieee754":"Quj6","isarray":"aqZJ","buffer":"aMB2"}],"PqBP":[function(require,module,exports) {
  var global = arguments[3];
  var process = require("process");
  var Buffer = require("buffer").Buffer;
  var t=arguments[3],e=require("process"),n=require("buffer").Buffer;Object.defineProperty(exports,"__esModule",{value:!0}),exports.backend=un,exports.buffer=lr,exports.customGrad=so,exports.deprecationWarn=qe,exports.disableDeprecationWarnings=He,exports.dispose=Qe,exports.disposeVariables=Ke,exports.enableDebugMode=Ge,exports.enableProdMode=Ve,exports.engine=je,exports.env=u,exports.fill=Un,exports.findBackend=on,exports.findBackendFactory=an,exports.getBackend=nn,exports.getKernel=p,exports.getKernelsForBackend=h,exports.grad=no,exports.grads=ro,exports.keep=Je,exports.linspace=Vn,exports.memory=Xe,exports.nextFrame=od,exports.ones=Wn,exports.op=In,exports.print=pr,exports.profile=$e,exports.range=Gn,exports.ready=en,exports.registerBackend=sn,exports.registerKernel=d,exports.removeBackend=rn,exports.scalar=Tn,exports.setBackend=tn,exports.setPlatform=cn,exports.tensor=Dn,exports.tensor1d=Fn,exports.tensor2d=On,exports.tensor3d=_n,exports.tensor4d=Mn,exports.tensor5d=Bn,exports.tensor6d=Pn,exports.tidy=Ye,exports.time=Ze,exports.unregisterKernel=f,exports.valueAndGrad=oo,exports.valueAndGrads=ao,exports.variable=Ln,exports.variableGrads=io,exports.zeros=zn,exports.irfft=exports.io=exports.inTopKAsync=exports.image=exports.imag=exports.ifft=exports.hannWindow=exports.hammingWindow=exports.greaterStrict=exports.greaterEqualStrict=exports.greaterEqual=exports.greater=exports.gatherND=exports.gather=exports.fused=exports.frame=exports.floorDiv=exports.floor=exports.fft=exports.eye=exports.expm1=exports.expandDims=exports.exp=exports.erf=exports.equalStrict=exports.equal=exports.elu=exports.dropout=exports.dot=exports.divStrict=exports.divNoNan=exports.div=exports.diag=exports.depthwiseConv2d=exports.depthToSpace=exports.cumsum=exports.cosh=exports.cos=exports.conv3dTranspose=exports.conv3d=exports.conv2dTranspose=exports.conv2d=exports.conv1d=exports.concat4d=exports.concat3d=exports.concat2d=exports.concat1d=exports.concat=exports.complex=exports.clone=exports.clipByValue=exports.ceil=exports.cast=exports.browser=exports.booleanMaskAsync=exports.batchToSpaceND=exports.batchNormalization4d=exports.batchNormalization3d=exports.batchNormalization2d=exports.batchNormalization=exports.batchNorm4d=exports.batchNorm3d=exports.batchNorm2d=exports.batchNorm=exports.basicLSTMCell=exports.backend_util=exports.avgPool3d=exports.avgPool=exports.atanh=exports.atan2=exports.atan=exports.asinh=exports.asin=exports.argMin=exports.argMax=exports.any=exports.all=exports.addStrict=exports.addN=exports.add=exports.acosh=exports.acos=exports.abs=exports.Variable=exports.TensorBuffer=exports.Tensor=exports.SGDOptimizer=exports.Reduction=exports.Rank=exports.RMSPropOptimizer=exports.Optimizer=exports.MomentumOptimizer=exports.KernelBackend=exports.Environment=exports.ENV=exports.DataStorage=exports.AdamaxOptimizer=exports.AdamOptimizer=exports.AdagradOptimizer=exports.AdadeltaOptimizer=void 0,exports.squeeze=exports.squaredDifferenceStrict=exports.squaredDifference=exports.square=exports.sqrt=exports.split=exports.spectral=exports.sparseToDense=exports.spaceToBatchND=exports.softplus=exports.softmax=exports.slice_util=exports.slice4d=exports.slice3d=exports.slice2d=exports.slice1d=exports.slice=exports.sinh=exports.sin=exports.signal=exports.sign=exports.sigmoid=exports.setdiff1dAsync=exports.serialization=exports.separableConv2d=exports.selu=exports.scatterND=exports.rsqrt=exports.round=exports.rfft=exports.reverse4d=exports.reverse3d=exports.reverse2d=exports.reverse1d=exports.reverse=exports.reshape=exports.relu6=exports.relu=exports.reciprocal=exports.real=exports.randomUniform=exports.randomNormal=exports.randomGamma=exports.rand=exports.prod=exports.prelu=exports.powStrict=exports.pow=exports.pool=exports.pad4d=exports.pad3d=exports.pad2d=exports.pad1d=exports.pad=exports.outerProduct=exports.onesLike=exports.oneHot=exports.notEqualStrict=exports.notEqual=exports.norm=exports.neg=exports.multinomial=exports.multiRNNCell=exports.mulStrict=exports.mul=exports.movingAverage=exports.moments=exports.modStrict=exports.mod=exports.minimumStrict=exports.minimum=exports.min=exports.mean=exports.maximumStrict=exports.maximum=exports.maxPool3d=exports.maxPool=exports.max=exports.math=exports.matMul=exports.losses=exports.logicalXor=exports.logicalOr=exports.logicalNot=exports.logicalAnd=exports.logSumExp=exports.logSoftmax=exports.logSigmoid=exports.log1p=exports.log=exports.localResponseNormalization=exports.linalg=exports.lessStrict=exports.lessEqualStrict=exports.lessEqual=exports.less=exports.leakyRelu=exports.isNaN=exports.isInf=exports.isFinite=void 0,exports.zerosLike=exports.whereAsync=exports.where=exports.webgl=exports.version_core=exports.util=exports.unstack=exports.unsortedSegmentSum=exports.truncatedNormal=exports.transpose=exports.train=exports.topk=exports.tile=exports.test_util=exports.tensor_util=exports.tanh=exports.tan=exports.sum=exports.subStrict=exports.sub=exports.stridedSlice=exports.stft=exports.step=exports.stack=void 0;var r=function(t,e){return(r=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 o(t,e){function n(){this.constructor=t}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}function a(t,e,n,r){return new(n||(n=Promise))(function(o,a){function i(t){try{u(r.next(t))}catch(t){a(t)}}function s(t){try{u(r.throw(t))}catch(t){a(t)}}function u(t){t.done?o(t.value):new n(function(e){e(t.value)}).then(i,s)}u((r=r.apply(t,e||[])).next())})}function i(t,e){var n,r,o,a,i={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return a={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(a){return function(s){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;i;)try{if(n=1,r&&(o=2&a[0]?r.return:a[0]?r.throw||((o=r.return)&&o.call(r),0):r.next)&&!(o=o.call(r,a[1])).done)return o;switch(r=0,o&&(a=[2&a[0],o.value]),a[0]){case 0:case 1:o=a;break;case 4:return i.label++,{value:a[1],done:!1};case 5:i.label++,r=a[1],a=[0];continue;case 7:a=i.ops.pop(),i.trys.pop();continue;default:if(!(o=(o=i.trys).length>0&&o[o.length-1])&&(6===a[0]||2===a[0])){i=0;continue}if(3===a[0]&&(!o||a[1]>o[0]&&a[1]<o[3])){i.label=a[1];break}if(6===a[0]&&i.label<o[1]){i.label=o[1],o=a;break}if(o&&i.label<o[2]){i.label=o[2],i.ops.push(a);break}o[2]&&i.ops.pop(),i.trys.pop();continue}a=e.call(t,i)}catch(t){a=[6,t],r=0}finally{n=o=0}if(5&a[0])throw a[1];return{value:a[0]?a[1]:void 0,done:!0}}([a,s])}}}var s=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],o=n[1];t.urlFlags[r]=function(t,e){if("true"===(e=e.toLowerCase())||"false"===e)return"true"===e;if(""+ +e===e)return+e;throw new Error("Could not parse value flag value "+e+" for flag "+t+".")}(r,o)})}},t}();function u(){return c}exports.Environment=s;var c=null;exports.ENV=c;var l=new Map;function p(t,e){var n=v(t,e);return l.get(n)}function h(t){for(var e=l.entries(),n=[];;){var r=e.next(),o=r.done,a=r.value;if(o)break;var i=a[0],s=a[1];i.split("_")[0]===t&&n.push(s)}return n}function d(t){var e=t.kernelName,n=t.backendName,r=v(e,n);if(l.has(r))throw new Error("The kernel '"+e+"' for backend '"+n+"' is already registered");l.set(r,t)}function f(t,e){var n=v(t,e);if(!l.has(n))throw new Error("The kernel '"+t+"' for backend '"+e+"' is not registered");l.delete(n)}function v(t,e){return e+"_"+t}function m(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 g(t,e,n){return Math.max(t,Math.min(e,n))}function x(t){return t%2==0?t:t+1}function y(t){for(var e=0,n=0;n<t.length;n++)e+=t[n];return e}function b(t,e){if(!t)throw new Error("string"==typeof e?e:e())}function w(t,e,n){void 0===n&&(n=""),b(I(t,e),function(){return n+" Shapes "+t+" and "+e+" must match"})}function C(t){b(null!=t,function(){return"The input to the tensor constructor must be a non-null value."})}function E(t,e,n){if(void 0===e&&(e=[]),void 0===n&&(n=!1),null==e&&(e=[]),Array.isArray(t)||W(t)&&!n)for(var r=0;r<t.length;++r)E(t[r],e,n);else e.push(t);return e}function R(t){if(0===t.length)return 1;for(var e=t[0],n=1;n<t.length;n++)e*=t[n];return e}function I(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 k(t){return t%1==0}function S(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 A(t){var e=Math.ceil(Math.sqrt(t));return[e,Math.ceil(t/e)]}function D(t,e){return e<=t.length?t:t+" ".repeat(e-t.length)}function N(t,e,n){return void 0===e&&(e=function(t){return 0}),new Promise(function(r,o){var a=0,i=function(){if(t())r();else{var s=e(++a);null!=n&&a>=n?o():setTimeout(i,s)}};i()})}function T(t,e){for(var n=1,r=-1,o=0;o<t.length;++o)if(t[o]>=0)n*=t[o];else if(-1===t[o]){if(-1!==r)throw Error("Shapes can only have 1 implicit size. Found -1 at dim "+r+" and dim "+o);r=o}else if(t[o]<0)throw Error("Shapes can not be < 0. Found "+t[o]+" at dim "+o);if(-1===r){if(e>0&&e!==n)throw Error("Size("+e+") must match the product of shape "+t);return t}if(0===n)throw Error("Cannot infer the missing size in ["+t+"] when there are 0 elements");if(e%n!=0)throw Error("The implicit shape can't be a fractional number. Got "+e+" / "+n);var a=t.slice();return a[r]=e/n,a}function F(t,e){var n=e.length;return b((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}),b(t.every(function(t){return k(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 O(t,e){for(var n=[],r=[],o=null!=e&&Array.isArray(e)&&0===e.length,a=null==e||o?null:F(e,t).sort(),i=0,s=0;s<t.length;++s){if(null!=a){if(a[i]===s&&1!==t[s])throw new Error("Can't squeeze axis "+s+" since its dim '"+t[s]+"' is not 1");(null==a[i]||a[i]>s)&&1===t[s]&&(n.push(t[s]),r.push(s)),a[i]<=s&&i++}1!==t[s]&&(n.push(t[s]),r.push(s))}return{newShape:n,keptDims:r}}function _(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 M(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 B(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 P(t){return"bool"===t||"complex64"===t||"float32"===t||"int32"===t||"string"===t}function L(t,e){return!("complex64"===e||"float32"===e&&"complex64"!==t||"int32"===e&&"float32"!==t&&"complex64"!==t||"bool"===e&&"bool"===t)}function W(t){return t instanceof Float32Array||t instanceof Int32Array||t instanceof Uint8Array}function z(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 U(t){if(null==t)return 0;var e=0;return t.forEach(function(t){return e+=t.length}),e}function V(t){return"string"==typeof t||t instanceof String}function G(t){return"boolean"==typeof t}function H(t){return"number"==typeof t}function q(t){return Array.isArray(t)?q(t[0]):t instanceof Float32Array?"float32":t instanceof Int32Array||t instanceof Uint8Array?"int32":H(t)?"float32":V(t)?"string":G(t)?"bool":"float32"}function K(t){return!!(t&&t.constructor&&t.call&&t.apply)}function j(t,e){for(var n=e;n<t;++n)if(t%n==0)return n;return t}function X(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 $(t,e,n){if("string"===e)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(t)&&(t=E(t)),n&&B(t,e),function(t,e){return t instanceof Float32Array&&"float32"===e||t instanceof Int32Array&&"int32"===e||t instanceof Uint8Array&&"bool"===e}(t,e))return t;if(null==e||"float32"===e||"complex64"===e)return new Float32Array(t);if("int32"===e)return new Int32Array(t);if("bool"===e){for(var r=new Uint8Array(t.length),o=0;o<r.length;++o)0!==Math.round(t[o])&&(r[o]=1);return r}throw new Error("Unknown data type "+e)}function Y(t,e){if(0===t.length)return e[0];var n=t.reduce(function(t,e){return t*e});if(0===n)return[];if(n!==e.length)throw new Error("["+t+"] does not match the input size.");return function t(e,n,r){var o=new Array;if(1===n.length)for(var a=n[0],i=0;i<a;i++)o[i]=r[e+i];else{a=n[0];var s=n.slice(1),u=s.reduce(function(t,e){return t*e});for(i=0;i<a;i++)o[i]=t(e+i*u,s,r)}return o}(0,t,e)}function Q(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 Z(){return u().platform.now()}function tt(t){t.forEach(function(e){b(Number.isInteger(e)&&e>=0,function(){return"Tensor must have a shape comprised of positive integers but got shape ["+t+"]."})})}function et(t,e){return void 0===e&&(e="utf-8"),e=e||"utf-8",u().platform.encode(t,e)}function nt(t,e){return void 0===e&&(e="utf-8"),e=e||"utf-8",u().platform.decode(t,e)}var rt=Object.freeze({shuffle:m,clamp:g,nearestLargerEven:x,sum:y,randUniform:function(t,e){var n=Math.random();return e*n+(1-n)*t},distSquared:function(t,e){for(var n=0,r=0;r<t.length;r++){var o=Number(t[r])-Number(e[r]);n+=o*o}return n},assert:b,assertShapesMatch:w,assertNonNull:C,flatten:E,sizeFromShape:R,isScalarShape:function(t){return 0===t.length},arraysEqual:I,isInt:k,tanh:S,sizeToSquarishShape:A,createShuffledIndices:function(t){for(var e=new Uint32Array(t),n=0;n<t;++n)e[n]=n;return m(e),e},rightPad:D,repeatedTry:N,inferFromImplicitShape:T,parseAxisParam:F,squeezeShape:O,getTypedArrayFromDType:_,getArrayFromDType:M,checkConversionForErrors:B,isValidDtype:P,hasEncodingLoss:L,isTypedArray:W,bytesPerElement:z,bytesFromStringArray:U,isString:V,isBoolean:G,isNumber:H,inferDtype:q,isFunction:K,nearestDivisor:j,computeStrides:X,toTypedArray:$,toNestedArray:Y,makeOnesTypedArray:Q,makeZerosTypedArray:J,now:Z,assertNonNegativeIntegerDimensions:tt,fetch:function(t,e){return u().platform.fetch(t,e)},encodeString:et,decodeString:nt}),ot=function(){function t(t,e){this.backendTimer=t,this.logger=e,null==e&&(this.logger=new at)}return t.prototype.profileKernel=function(t,e,n){var r,o=this,a=this.backendTimer.time(function(){r=n()});return r.forEach(function(n){n.data().then(function(r){!function(t,e,n){if("float32"!==e)return!1;for(var r=0;r<t.length;r++){var o=t[r];if(isNaN(o)||!isFinite(o))return console.warn("Found "+o+" in the result of '"+n+"'"),!0}}(r,n.dtype,t),a.then(function(a){var i="";null!=a.getExtraProfileInfo&&(i=a.getExtraProfileInfo()),o.logger.logKernelProfile(t,n,r,a.kernelMs,e,i)})})}),r},t}();exports.util=rt;var at=function(){function t(){}return t.prototype.logKernelProfile=function(t,e,n,r,o,a){var i=D(r+"ms",9),s=D(t,25),u=e.rank,c=e.size,l=D(e.shape.toString(),14),p="";for(var h in o){var d=o[h].shape,f=d.length;p+=h+": "+f+"D "+(f>0?d:"")+" "}console.log("%c"+s+"\t%c"+i+"\t%c"+u+"D "+l+"\t%c"+c+"\t%c"+p+"\t%c"+a,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")},t}(),it=20,st=3,ut=7;function ct(t,e,n,r){var o=X(e),a=function(t,e,n,r){var o=R(e),a=r[r.length-1],i=new Array(a).fill(0),s=e.length,u="complex64"===n?ht(t):t;if(s>1)for(var c=0;c<o/a;c++)for(var l=c*a,p=0;p<a;p++)i[p]=Math.max(i[p],lt(u[l+p],0,n).length);return i}(t,e,n,o),i=e.length,s=function t(e,n,r,o,a,i){void 0===i&&(i=!0);var s="complex64"===r?2:1,u=n[0],c=n.length;if(0===c)return"complex64"===r?[lt(ht(e)[0],0,r)]:"bool"===r?[pt(e[0])]:[e[0].toString()];if(1===c){if(u>it){var l=st*s,p=Array.from(e.slice(0,l)),h=Array.from(e.slice((u-st)*s,u*s));return"complex64"===r&&(p=ht(p),h=ht(h)),["["+p.map(function(t,e){return lt(t,a[e],r)}).join(", ")+", ..., "+h.map(function(t,e){return lt(t,a[u-st+e],r)}).join(", ")+"]"]}return["["+("complex64"===r?ht(e):Array.from(e)).map(function(t,e){return lt(t,a[e],r)}).join(", ")+"]"]}var d=n.slice(1),f=o.slice(1),v=o[0]*s,m=[];if(u>it){for(var g=0;g<st;g++){var x=(y=g*v)+v;m.push.apply(m,t(e.slice(y,x),d,r,f,a,!1))}m.push("...");for(g=u-st;g<u;g++){x=(y=g*v)+v;m.push.apply(m,t(e.slice(y,x),d,r,f,a,g===u-1))}}else for(g=0;g<u;g++){var y;x=(y=g*v)+v;m.push.apply(m,t(e.slice(y,x),d,r,f,a,g===u-1))}var b=2===c?",":"";m[0]="["+m[0]+b;for(g=1;g<m.length-1;g++)m[g]=" "+m[g]+b;var w=",\n";for(g=2;g<c;g++)w+="\n";return m[m.length-1]=" "+m[m.length-1]+"]"+(i?"":w),m}(t,e,n,o,a),u=["Tensor"];return r&&(u.push("  dtype: "+n),u.push("  rank: "+i),u.push("  shape: ["+e+"]"),u.push("  values:")),u.push(s.map(function(t){return"    "+t}).join("\n")),u.join("\n")}function lt(t,e,n){return D(Array.isArray(t)?parseFloat(t[0].toFixed(ut))+" + "+parseFloat(t[1].toFixed(ut))+"j":V(t)?"'"+t+"'":"bool"===n?pt(t):parseFloat(t.toFixed(ut)).toString(),e)}function pt(t){return 0===t?"false":"true"}function ht(t){for(var e=[],n=0;n<t.length;n+=2)e.push([t[n],t[n+1]]);return e}var dt=function(){function t(t,e,n){var r=this;if(this.dtype=e,this.shape=t.slice(),this.size=R(t),null!=n){var o=n.length;b(o===this.size,function(){return"Length of values '"+o+"' does not match the size inferred by the shape '"+r.size+"'."})}if("complex64"===e)throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||M(e,this.size),this.strides=X(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]),b(n.length===this.rank,function(){return"The number of provided coordinates ("+n.length+") must match the rank ("+e.rank+")"});var o=this.locToIndex(n);this.values[o]=t},t.prototype.get=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];0===t.length&&(t=[0]);for(var n=0,r=0,o=t;r<o.length;r++){var a=o[r];if(a<0||a>=this.shape[n]){var i="Requested out of range element at "+t+".   Buffer shape="+this.shape;throw new Error(i)}n++}for(var s=t[t.length-1],u=0;u<t.length-1;++u)s+=this.strides[u]*t[u];return this.values[s]},t.prototype.locToIndex=function(t){if(0===this.rank)return 0;if(1===this.rank)return t[0];for(var e=t[t.length-1],n=0;n<t.length-1;++n)e+=this.strides[n]*t[n];return e},t.prototype.indexToLoc=function(t){if(0===this.rank)return[];if(1===this.rank)return[t];for(var e=new Array(this.shape.length),n=0;n<e.length-1;++n)e[n]=Math.floor(t/this.strides[n]),t-=e[n]*this.strides[n];return e[e.length-1]=t,e},Object.defineProperty(t.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),t.prototype.toTensor=function(){return ft().makeTensor(this.values,this.shape,this.dtype)},t}(),ft=null,vt=null,mt=null;exports.TensorBuffer=dt;var gt=function(){function t(t,e,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=t.slice(),this.dtype=e||"float32",this.size=R(t),this.strides=X(t),this.dataId=n,this.id=r,this.rankType=this.rank<5?this.rank.toString():"higher"}return t.prototype.flatten=function(){return this.throwIfDisposed(),this.as1D()},t.prototype.asScalar=function(){return this.throwIfDisposed(),b(1===this.size,function(){return"The array must have only 1 element."}),this.reshape([])},t.prototype.as1D=function(){return this.throwIfDisposed(),this.reshape([this.size])},t.prototype.as2D=function(t,e){return this.throwIfDisposed(),this.reshape([t,e])},t.prototype.as3D=function(t,e,n){return this.throwIfDisposed(),this.reshape([t,e,n])},t.prototype.as4D=function(t,e,n,r){return this.throwIfDisposed(),this.reshape([t,e,n,r])},t.prototype.as5D=function(t,e,n,r,o){return this.throwIfDisposed(),this.reshape([t,e,n,r,o])},t.prototype.asType=function(t){return this.throwIfDisposed(),vt.cast(this,t)},Object.defineProperty(t.prototype,"rank",{get:function(){return this.shape.length},enumerable:!0,configurable:!0}),t.prototype.buffer=function(){return a(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,vt.buffer(this.shape,this.dtype,t)]}})})},t.prototype.bufferSync=function(){return vt.buffer(this.shape,this.dtype,this.dataSync())},t.prototype.array=function(){return a(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,Y(this.shape,t)]}})})},t.prototype.arraySync=function(){return Y(this.shape,this.dataSync())},t.prototype.data=function(){return a(this,void 0,void 0,function(){var t,e;return i(this,function(n){switch(n.label){case 0:return this.throwIfDisposed(),t=ft().read(this.dataId),"string"!==this.dtype?[3,2]:[4,t];case 1:e=n.sent();try{return[2,e.map(function(t){return nt(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=ft().readSync(this.dataId);if("string"===this.dtype)try{return t.map(function(t){return nt(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 a(this,void 0,void 0,function(){var t;return i(this,function(e){switch(e.label){case 0:return this.throwIfDisposed(),[4,ft().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||(ft().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),vt.print(this,t)},t.prototype.reshape=function(t){return this.throwIfDisposed(),vt.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),vt.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),vt.cumsum(this,t,e,n)},t.prototype.squeeze=function(t){return this.throwIfDisposed(),vt.squeeze(this,t)},t.prototype.clone=function(){return this.throwIfDisposed(),vt.clone(this)},t.prototype.oneHot=function(t,e,n){return this.throwIfDisposed(),vt.oneHot(this,t,e,n)},t.prototype.toString=function(t){return void 0===t&&(t=!1),ct(this.dataSync(),this.shape,this.dtype,t)},t.prototype.tile=function(t){return this.throwIfDisposed(),vt.tile(this,t)},t.prototype.gather=function(t,e){return void 0===e&&(e=0),this.throwIfDisposed(),vt.gather(this,t,e)},t.prototype.matMul=function(t,e,n){return void 0===e&&(e=!1),void 0===n&&(n=!1),this.throwIfDisposed(),vt.matMul(this,t,e,n)},t.prototype.dot=function(t){return this.throwIfDisposed(),vt.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(),vt.norm(this,t,e,n)},t.prototype.slice=function(t,e){return this.throwIfDisposed(),vt.slice(this,t,e)},t.prototype.reverse=function(t){return this.throwIfDisposed(),vt.reverse(this,t)},t.prototype.concat=function(e,n){return void 0===n&&(n=0),this.throwIfDisposed(),e instanceof t&&(e=[e]),vt.concat([this].concat(e),n)},t.prototype.split=function(t,e){return void 0===e&&(e=0),this.throwIfDisposed(),vt.split(this,t,e)},t.prototype.stack=function(t,e){return void 0===e&&(e=0),vt.stack([this,t],e)},t.prototype.unstack=function(t){return void 0===t&&(t=0),vt.unstack(this,t)},t.prototype.pad=function(t,e){return void 0===e&&(e=0),vt.pad(this,t,e)},t.prototype.batchNormalization=function(t,e,n,r,o){return void 0===n&&(n=.001),mt("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon"),this.batchNorm(t,e,o,r,n)},t.prototype.batchNorm=function(t,e,n,r,o){return void 0===o&&(o=.001),this.throwIfDisposed(),vt.batchNorm(this,t,e,n,r,o)},t.prototype.all=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),vt.all(this,t,e)},t.prototype.any=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),vt.any(this,t,e)},t.prototype.logSumExp=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),vt.logSumExp(this,t,e)},t.prototype.sum=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),vt.sum(this,t,e)},t.prototype.prod=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),vt.prod(this,t,e)},t.prototype.mean=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),vt.mean(this,t,e)},t.prototype.min=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),vt.min(this,t,e)},t.prototype.max=function(t,e){return void 0===t&&(t=null),void 0===e&&(e=!1),this.throwIfDisposed(),vt.max(this,t,e)},t.prototype.argMin=function(t){return void 0===t&&(t=null),this.throwIfDisposed(),vt.argMin(this,t)},t.prototype.argMax=function(t){return void 0===t&&(t=null),this.throwIfDisposed(),vt.argMax(this,t)},t.prototype.cast=function(t){return this.throwIfDisposed(),vt.cast(this,t)},t.prototype.add=function(t){return this.throwIfDisposed(),vt.add(this,t)},t.prototype.addStrict=function(t){return this.throwIfDisposed(),vt.addStrict(this,t)},t.prototype.atan2=function(t){return this.throwIfDisposed(),vt.atan2(this,t)},t.prototype.sub=function(t){return this.throwIfDisposed(),vt.sub(this,t)},t.prototype.subStrict=function(t){return this.throwIfDisposed(),vt.subStrict(this,t)},t.prototype.pow=function(t){return this.throwIfDisposed(),vt.pow(this,t)},t.prototype.powStrict=function(t){return this.throwIfDisposed(),vt.powStrict(this,t)},t.prototype.mul=function(t){return this.throwIfDisposed(),vt.mul(this,t)},t.prototype.mulStrict=function(t){return this.throwIfDisposed(),vt.mulStrict(this,t)},t.prototype.div=function(t){return this.throwIfDisposed(),vt.div(this,t)},t.prototype.divNoNan=function(t){return this.throwIfDisposed(),vt.divNoNan(this,t)},t.prototype.floorDiv=function(t){return this.throwIfDisposed(),vt.floorDiv(this,t)},t.prototype.divStrict=function(t){return this.throwIfDisposed(),vt.divStrict(this,t)},t.prototype.minimum=function(t){return this.throwIfDisposed(),vt.minimum(this,t)},t.prototype.minimumStrict=function(t){return this.throwIfDisposed(),vt.minimumStrict(this,t)},t.prototype.maximum=function(t){return this.throwIfDisposed(),vt.maximum(this,t)},t.prototype.maximumStrict=function(t){return this.throwIfDisposed(),vt.maximumStrict(this,t)},t.prototype.mod=function(t){return this.throwIfDisposed(),vt.mod(this,t)},t.prototype.modStrict=function(t){return this.throwIfDisposed(),vt.modStrict(this,t)},t.prototype.squaredDifference=function(t){return this.throwIfDisposed(),vt.squaredDifference(this,t)},t.prototype.squaredDifferenceStrict=function(t){return this.throwIfDisposed(),vt.squaredDifferenceStrict(this,t)},t.prototype.transpose=function(t){return this.throwIfDisposed(),vt.transpose(this,t)},t.prototype.notEqual=function(t){return this.throwIfDisposed(),vt.notEqual(this,t)},t.prototype.notEqualStrict=function(t){return this.throwIfDisposed(),vt.notEqualStrict(this,t)},t.prototype.less=function(t){return this.throwIfDisposed(),vt.less(this,t)},t.prototype.lessStrict=function(t){return this.throwIfDisposed(),vt.lessStrict(this,t)},t.prototype.equal=function(t){return this.throwIfDisposed(),vt.equal(this,t)},t.prototype.equalStrict=function(t){return this.throwIfDisposed(),vt.equalStrict(this,t)},t.prototype.lessEqual=function(t){return this.throwIfDisposed(),vt.lessEqual(this,t)},t.prototype.lessEqualStrict=function(t){return this.throwIfDisposed(),vt.lessEqualStrict(this,t)},t.prototype.greater=function(t){return this.throwIfDisposed(),vt.greater(this,t)},t.prototype.greaterStrict=function(t){return this.throwIfDisposed(),vt.greaterStrict(this,t)},t.prototype.greaterEqual=function(t){return this.throwIfDisposed(),vt.greaterEqual(this,t)},t.prototype.greaterEqualStrict=function(t){return this.throwIfDisposed(),vt.greaterEqualStrict(this,t)},t.prototype.logicalAnd=function(t){return this.throwIfDisposed(),vt.logicalAnd(this,t)},t.prototype.logicalOr=function(t){return this.throwIfDisposed(),vt.logicalOr(this,t)},t.prototype.logicalNot=function(){return this.throwIfDisposed(),vt.logicalNot(this)},t.prototype.logicalXor=function(t){return this.throwIfDisposed(),vt.logicalXor(this,t)},t.prototype.where=function(t,e){return this.throwIfDisposed(),vt.where(t,this,e)},t.prototype.neg=function(){return this.throwIfDisposed(),vt.neg(this)},t.prototype.ceil=function(){return this.throwIfDisposed(),vt.ceil(this)},t.prototype.floor=function(){return this.throwIfDisposed(),vt.floor(this)},t.prototype.sign=function(){return this.throwIfDisposed(),vt.sign(this)},t.prototype.isNaN=function(){return this.throwIfDisposed(),vt.isNaN(this)},t.prototype.isInf=function(){return this.throwIfDisposed(),vt.isInf(this)},t.prototype.isFinite=function(){return this.throwIfDisposed(),vt.isFinite(this)},t.prototype.exp=function(){return this.throwIfDisposed(),vt.exp(this)},t.prototype.expm1=function(){return this.throwIfDisposed(),vt.expm1(this)},t.prototype.log=function(){return this.throwIfDisposed(),vt.log(this)},t.prototype.log1p=function(){return this.throwIfDisposed(),vt.log1p(this)},t.prototype.sqrt=function(){return this.throwIfDisposed(),vt.sqrt(this)},t.prototype.rsqrt=function(){return this.throwIfDisposed(),vt.rsqrt(this)},t.prototype.square=function(){return this.throwIfDisposed(),vt.square(this)},t.prototype.reciprocal=function(){return this.throwIfDisposed(),vt.reciprocal(this)},t.prototype.abs=function(){return this.throwIfDisposed(),vt.abs(this)},t.prototype.clipByValue=function(t,e){return this.throwIfDisposed(),vt.clipByValue(this,t,e)},t.prototype.relu=function(){return this.throwIfDisposed(),vt.relu(this)},t.prototype.relu6=function(){return this.throwIfDisposed(),vt.relu6(this)},t.prototype.elu=function(){return this.throwIfDisposed(),vt.elu(this)},t.prototype.selu=function(){return this.throwIfDisposed(),vt.selu(this)},t.prototype.leakyRelu=function(t){return void 0===t&&(t=.2),this.throwIfDisposed(),vt.leakyRelu(this,t)},t.prototype.prelu=function(t){return this.throwIfDisposed(),vt.prelu(this,t)},t.prototype.sigmoid=function(){return this.throwIfDisposed(),vt.sigmoid(this)},t.prototype.logSigmoid=function(){return this.throwIfDisposed(),vt.logSigmoid(this)},t.prototype.softplus=function(){return this.throwIfDisposed(),vt.softplus(this)},t.prototype.zerosLike=function(){return this.throwIfDisposed(),vt.zerosLike(this)},t.prototype.onesLike=function(){return this.throwIfDisposed(),vt.onesLike(this)},t.prototype.sin=function(){return this.throwIfDisposed(),vt.sin(this)},t.prototype.cos=function(){return this.throwIfDisposed(),vt.cos(this)},t.prototype.tan=function(){return this.throwIfDisposed(),vt.tan(this)},t.prototype.asin=function(){return this.throwIfDisposed(),vt.asin(this)},t.prototype.acos=function(){return this.throwIfDisposed(),vt.acos(this)},t.prototype.atan=function(){return this.throwIfDisposed(),vt.atan(this)},t.prototype.sinh=function(){return this.throwIfDisposed(),vt.sinh(this)},t.prototype.cosh=function(){return this.throwIfDisposed(),vt.cosh(this)},t.prototype.tanh=function(){return this.throwIfDisposed(),vt.tanh(this)},t.prototype.asinh=function(){return this.throwIfDisposed(),vt.asinh(this)},t.prototype.acosh=function(){return this.throwIfDisposed(),vt.acosh(this)},t.prototype.atanh=function(){return this.throwIfDisposed(),vt.atanh(this)},t.prototype.erf=function(){return this.throwIfDisposed(),vt.erf(this)},t.prototype.round=function(){return this.throwIfDisposed(),vt.round(this)},t.prototype.step=function(t){return void 0===t&&(t=0),this.throwIfDisposed(),vt.step(this,t)},t.prototype.softmax=function(t){return void 0===t&&(t=-1),this.throwIfDisposed(),vt.softmax(this,t)},t.prototype.logSoftmax=function(t){return void 0===t&&(t=-1),this.throwIfDisposed(),vt.logSoftmax(this,t)},t.prototype.resizeBilinear=function(t,e){return void 0===e&&(e=!1),this.throwIfDisposed(),vt.image.resizeBilinear(this,t,e)},t.prototype.resizeNearestNeighbor=function(t,e){return void 0===e&&(e=!1),this.throwIfDisposed(),vt.image.resizeNearestNeighbor(this,t,e)},t.prototype.conv1d=function(t,e,n,r,o,a){return void 0===r&&(r="NWC"),void 0===o&&(o=1),this.throwIfDisposed(),vt.conv1d(this,t,e,n,r,o,a)},t.prototype.conv2d=function(t,e,n,r,o,a){return void 0===r&&(r="NHWC"),void 0===o&&(o=[1,1]),this.throwIfDisposed(),vt.conv2d(this,t,e,n,r,o,a)},t.prototype.conv2dTranspose=function(t,e,n,r,o){return this.throwIfDisposed(),vt.conv2dTranspose(this,t,e,n,r,o)},t.prototype.depthwiseConv2D=function(t,e,n,r,o,a){return void 0===r&&(r="NHWC"),void 0===o&&(o=[1,1]),this.throwIfDisposed(),vt.depthwiseConv2d(this,t,e,n,r,o,a)},t.prototype.separableConv2d=function(t,e,n,r,o,a){return void 0===o&&(o=[1,1]),void 0===a&&(a="NHWC"),this.throwIfDisposed(),vt.separableConv2d(this,t,e,n,r,o,a)},t.prototype.avgPool=function(t,e,n,r){return this.throwIfDisposed(),vt.avgPool(this,t,e,n,r)},t.prototype.maxPool=function(t,e,n,r){return this.throwIfDisposed(),vt.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),vt.localResponseNormalization(this,t,e,n,r)},t.prototype.pool=function(t,e,n,r,o){return this.throwIfDisposed(),vt.pool(this,t,e,n,r,o)},t.prototype.variable=function(t,e,n){return void 0===t&&(t=!0),this.throwIfDisposed(),ft().makeVariable(this,t,e,n)},t.prototype.unsortedSegmentSum=function(t,e){return this.throwIfDisposed(),vt.unsortedSegmentSum(this,t,e)},t.prototype.batchToSpaceND=function(t,e){return this.throwIfDisposed(),vt.batchToSpaceND(this,t,e)},t.prototype.spaceToBatchND=function(t,e){return this.throwIfDisposed(),vt.spaceToBatchND(this,t,e)},t.prototype.topk=function(t,e){return void 0===t&&(t=1),void 0===e&&(e=!0),this.throwIfDisposed(),vt.topk(this,t,e)},t.prototype.stridedSlice=function(t,e,n,r,o,a,i,s){return void 0===r&&(r=0),void 0===o&&(o=0),void 0===a&&(a=0),void 0===i&&(i=0),void 0===s&&(s=0),this.throwIfDisposed(),vt.stridedSlice(this,t,e,n,r,o,a,i,s)},t.prototype.depthToSpace=function(t,e){return this.throwIfDisposed(),vt.depthToSpace(this,t,e)},t.prototype.fft=function(){return this.throwIfDisposed(),vt.spectral.fft(this)},t.prototype.ifft=function(){return this.throwIfDisposed(),vt.spectral.ifft(this)},t.prototype.rfft=function(){return this.throwIfDisposed(),vt.spectral.rfft(this)},t.prototype.irfft=function(){return this.throwIfDisposed(),vt.spectral.irfft(this)},t}();exports.Tensor=gt,Object.defineProperty(gt,Symbol.hasInstance,{value:function(t){return!!t&&null!=t.dataId&&null!=t.shape&&null!=t.dtype}});var xt,yt,bt,wt,Ct,Et=function(t){function e(e,n,r,o){var a=t.call(this,e.shape,e.dtype,e.dataId,o)||this;return a.trainable=n,a.name=r,a}return o(e,t),e.prototype.assign=function(t){if(t.dtype!==this.dtype)throw new Error("dtype of the new value ("+t.dtype+") and previous value ("+this.dtype+") must match");if(!I(t.shape,this.shape))throw new Error("shape of the new value ("+t.shape+") and previous value ("+this.shape+") must match");ft().disposeTensor(this),this.dataId=t.dataId,ft().incRef(this,null)},e.prototype.dispose=function(){ft().disposeVariable(this),this.isDisposedInternal=!0},e}(gt);exports.Variable=Et,exports.Rank=xt,Object.defineProperty(Et,Symbol.hasInstance,{value:function(t){return t instanceof gt&&null!=t.assign&&t.assign instanceof Function}}),function(t){t.R0="R0",t.R1="R1",t.R2="R2",t.R3="R3",t.R4="R4",t.R5="R5",t.R6="R6"}(xt||(exports.Rank=xt={})),function(t){t.float32="float32",t.int32="int32",t.bool="int32",t.complex64="complex64"}(yt||(yt={})),function(t){t.float32="float32",t.int32="int32",t.bool="bool",t.complex64="complex64"}(bt||(bt={})),function(t){t.float32="float32",t.int32="float32",t.bool="float32",t.complex64="complex64"}(wt||(wt={})),function(t){t.float32="complex64",t.int32="complex64",t.bool="complex64",t.complex64="complex64"}(Ct||(Ct={}));var Rt={float32:wt,int32:yt,bool:bt,complex64:Ct};function It(t,e){if("string"===t||"string"===e){if("string"===t&&"string"===e)return"string";throw new Error("Can not upcast "+t+" with "+e)}return Rt[t][e]}function kt(t){return It(t,"int32")}function St(t,e){if(t.dtype===e.dtype)return[t,e];var n=It(t.dtype,e.dtype);return[t.cast(n),e.cast(n)]}function At(t,e){b(t.dtype===e.dtype,function(){return"The dtypes of the first("+t.dtype+") and second("+e.dtype+") input must match"})}function Dt(t){var e=[];return function t(e,n,r){if(null!=e)if(e instanceof gt)n.push(e);else if(o=e,Array.isArray(o)||"object"==typeof o){var o,a=e;for(var i in a){var s=a[i];r.has(s)||(r.add(s),t(s,n,r))}}}(t,e,new Set),e}var Nt,Tt=Object.freeze({makeTypesMatch:St,assertTypesMatch:At,isTensorInList:function(t,e){for(var n=0;n<e.length;n++)if(e[n].id===t.id)return!0;return!1},getTensorsInContainer:Dt}),Ft=function(){function t(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null}}return t.prototype.dispose=function(){for(var t in this.registeredVariables)this.registeredVariables[t].dispose()},t}(),Ot=function(){function t(t){this.ENV=t,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Ft}return t.prototype.ready=function(){return a(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 a(this,void 0,void 0,function(){var e,n,r;return i(this,function(o){switch(o.label){case 0:if(null==this.registryFactory[t])throw new Error("Backend name '"+t+"' not found in registry");return this.backendName=t,null!=this.registry[t]?[3,4]:(this.backendInstance=null,e=this.initializeBackend(t),n=e.success,e.asyncInit?[4,n]:[3,2]);case 1:return r=o.sent(),[3,3];case 2:r=n,o.label=3;case 3:if(!r)return[2,!1];o.label=4;case 4:return this.backendInstance=this.registry[t],this.setupRegisteredKernels(),this.profiler=new ot(this.backendInstance),[2,!0]}})})},t.prototype.setupRegisteredKernels=function(){var t=this;h(this.backendName).forEach(function(e){null!=e.setupFunc&&e.setupFunc(t.backendInstance)})},t.prototype.disposeRegisteredKernels=function(t){var e=this;h(t).forEach(function(n){null!=n.disposeFunc&&n.disposeFunc(e.registry[t])})},t.prototype.initializeBackend=function(t){var e=this,n=this.registryFactory[t];if(null==n)throw new Error("Cannot initialize backend "+t+", no registration found.");try{var r=n.factory();if(Promise.resolve(r)===r){var o=++this.pendingBackendInitId,a=r.then(function(n){return!(o<e.pendingBackendInitId||(e.registry[t]=n,e.pendingBackendInit=null,0))}).catch(function(n){return!(o<e.pendingBackendInitId||(e.pendingBackendInit=null,console.warn("Initialization of backend "+t+" failed"),console.warn(n.stack||n.message),1))});return this.pendingBackendInit=a,{success:a,asyncInit:!0}}return this.registry[t]=r,{success:!0,asyncInit:!1}}catch(e){return console.warn("Initialization of backend "+t+" failed"),console.warn(e.stack||e.message),{success:!1,asyncInit:!1}}},t.prototype.removeBackend=function(t){if(!(t in this.registryFactory))throw new Error(t+" backend not found in registry");this.backendName===t&&null!=this.pendingBackendInit&&this.pendingBackendInitId++,t in this.registry&&(this.disposeRegisteredKernels(t),this.registry[t].dispose(),delete this.registry[t]),delete this.registryFactory[t],this.backendName===t&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)},t.prototype.getSortedBackends=function(){var t=this;if(0===Object.keys(this.registryFactory).length)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort(function(e,n){return t.registryFactory[n].priority-t.registryFactory[e].priority})},t.prototype.initializeBackendsAndReturnBest=function(){for(var t=this.getSortedBackends(),e=0;e<t.length;e++){var n=t[e],r=this.initializeBackend(n),o=r.success,a=r.asyncInit;if(a||o)return{name:n,asyncInit:a}}throw new Error("Could not initialize any backends, all backend initializations failed.")},t.prototype.moveData=function(t,e){var n=this.state.tensorInfo.get(e),r=n.backend,o=this.readSync(e);r.disposeData(e),n.backend=t,t.move(e,o,n.shape,n.dtype),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++},t.prototype.tidy=function(t,e){var n,r=this,o=null;if(null==e){if("function"!=typeof t)throw new Error("Please provide a function to tidy()");e=t}else{if("string"!=typeof t&&!(t instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!=typeof e)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");o=t}return this.scopedRun(function(){return r.startScope(o)},function(){return r.endScope(n)},function(){return(n=e())instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n})},t.prototype.scopedRun=function(t,e,n){t();try{var r=n();return e(),r}catch(t){throw e(),t}},t.prototype.nextTensorId=function(){return t.nextTensorId++},t.prototype.nextVariableId=function(){return t.nextVariableId++},t.prototype.clone=function(t){var e=this.makeTensorFromDataId(t.dataId,t.shape,t.dtype),n={x:t};return this.addTapeNode(this.state.activeScope.name,n,[e],function(t){return{x:function(){return t.toFloat()}}},[]),e},t.prototype.runKernel=function(t,e,n,r,o){return this.runKernelFunc(null,e,null,t,n,r,o)},t.prototype.shouldCheckForMemLeaks=function(){return this.ENV.getBool("IS_TEST")},t.prototype.checkKernelForMemLeak=function(t,e,n){var r=this.backend.numDataIds(),o=0;n.forEach(function(t){o+="complex64"===t.dtype?3:1});var a=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],i=r-e-o-a;if(i>0)throw new Error("Backend '"+this.backendName+"' has an internal memory leak ("+i+" data ids) after running '"+t+"'")},t.prototype.runKernelFunc=function(t,e,n,r,o,a,i){var s,u=this;void 0===a&&(a=[]),void 0===i&&(i=[]);var c,l=[],h=this.isTapeOn(),d=null!=this.state.activeScope?this.state.activeScope.name:"",f=function(t){h&&(l=t.map(function(t){return u.keep(u.clone(t))}))},v=this.state.numBytes,m=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);var g,x=p(r,this.backendName);return c=null!=x?function(){var t=u.backend.numDataIds();g=x.kernelFunc({inputs:e,attrs:o,backend:u.backend});var n=Array.isArray(g)?g:[g];u.shouldCheckForMemLeaks()&&u.checkKernelForMemLeak(d,t,n);var r=n.map(function(t){var e=t.dataId,n=t.shape,r=t.dtype;return u.makeTensorFromDataId(e,n,r)}),s=r.filter(function(t,e){return i[e]});return f(a.slice().concat(s)),r}:function(){var e=u.backend.numDataIds();g=u.tidy(function(){return t(u.backend,f)});var n=Array.isArray(g)?g:[g];return u.shouldCheckForMemLeaks()&&u.checkKernelForMemLeak(d,e,n),n},this.scopedRun(function(){return u.state.kernelDepth++},function(){return u.state.kernelDepth--},function(){s=u.ENV.getBool("DEBUG")?u.profiler.profileKernel(d,e,function(){return c()}):c()}),h&&this.addTapeNode(d,e,s,n,l),this.state.profiling&&this.state.activeProfile.kernels.push({name:d,bytesAdded:this.state.numBytes-v,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-m,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(e).map(function(t){return e[t].shape}),outputShapes:s.map(function(t){return t.shape})}),Array.isArray(g)?s:s[0]},t.prototype.makeTensor=function(t,e,n,r){if(null==t)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",r=r||this.backend;var o=t;"string"===n&&V(t[0])&&(o=t.map(function(t){return et(t)}));var a=r.write(o,e,n),i=new gt(e,n,a,this.nextTensorId());if(this.incRef(i,r),"string"===n){var s=this.state.tensorInfo.get(a),u=U(o);this.state.numBytes+=u-s.bytes,s.bytes=u}return i},t.prototype.makeTensorFromDataId=function(t,e,n,r){var o=new gt(e,n=n||"float32",t,this.nextTensorId());return this.incRef(o,r),o},t.prototype.makeVariable=function(t,e,n,r){void 0===e&&(e=!0),n=n||this.nextVariableId().toString(),null!=r&&r!==t.dtype&&(t=t.asType(r));var o=new Et(t,e,n,this.nextTensorId());if(null!=this.state.registeredVariables[o.name])throw new Error("Variable with name "+o.name+" was already registered");return this.state.registeredVariables[o.name]=o,this.incRef(o,this.backend),o},t.prototype.incRef=function(t,e){var n=this.state.tensorInfo.has(t.dataId)?this.state.tensorInfo.get(t.dataId).refCount:0;if(this.state.numTensors++,"string"===t.dtype&&this.state.numStringTensors++,0===n){this.state.numDataBuffers++;var r=0;"complex64"!==t.dtype&&"string"!==t.dtype&&(r=t.size*z(t.dtype)),this.state.tensorInfo.set(t.dataId,{backend:e||this.backend,dtype:t.dtype,shape:t.shape,bytes:r,refCount:0}),this.state.numBytes+=r}this.state.tensorInfo.get(t.dataId).refCount++,t instanceof Et||this.track(t)},t.prototype.disposeTensor=function(t){if(this.state.tensorInfo.has(t.dataId)){this.state.numTensors--,"string"===t.dtype&&this.state.numStringTensors--;var e=this.state.tensorInfo.get(t.dataId);e.refCount<=1?("complex64"!==t.dtype&&(this.state.numBytes-=e.bytes),this.state.numDataBuffers--,e.backend.disposeData(t.dataId),this.state.tensorInfo.delete(t.dataId)):this.state.tensorInfo.get(t.dataId).refCount--}},t.prototype.disposeVariables=function(){for(var t in this.state.registeredVariables){var e=this.state.registeredVariables[t];this.disposeVariable(e)}},t.prototype.disposeVariable=function(t){this.disposeTensor(t),null!=this.state.registeredVariables[t.name]&&delete this.state.registeredVariables[t.name]},t.prototype.memory=function(){var t=this.backend.memory();return t.numTensors=this.state.numTensors,t.numDataBuffers=this.state.numDataBuffers,t.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(t.unreliable=!0,null==t.reasons&&(t.reasons=[]),t.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),t},t.prototype.profile=function(t){return a(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,r,o){var a=this,i={id:this.state.nextTapeNodeId++,name:t,inputs:e,outputs:n,saved:o};null!=r&&(i.gradient=function(t){return t=t.map(function(t,e){if(null==t){var r=n[e],o=J(r.size,r.dtype);return a.makeTensor(o,r.shape,r.dtype)}return t}),r(t.length>1?t:t[0],o)}),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=Dt(t),r=new Set(n.map(function(t){return t.id})),o=0;o<this.state.activeScope.track.length;o++){var a=this.state.activeScope.track[o];a.kept||r.has(a.id)||a.dispose()}var i=this.state.scopeStack.pop();this.state.activeScope=0===this.state.scopeStack.length?null:this.state.scopeStack[this.state.scopeStack.length-1],n.forEach(function(t){t.kept||t.scopeId!==i.id||e.track(t)})},t.prototype.gradients=function(t,e,n,r){var o=this;if(void 0===r&&(r=!1),b(e.length>0,function(){return"gradients() received an empty list of xs."}),null!=n&&"float32"!==n.dtype)throw new Error("dy must have 'float32' dtype, but has '"+n.dtype+"'");var a=this.scopedRun(function(){return o.startTape()},function(){return o.endTape()},function(){return o.tidy("forward",t)});b(a instanceof gt,function(){return"The result y returned by f() must be a tensor."});var i=function(t,e,n){for(var r={},o={},a=0;a<e.length;a++)r[e[a].id]=!0;for(a=0;a<t.length;a++){var i=(f=t[a]).inputs;for(var s in i){for(var u=i[s],c=!1,l=0;l<e.length;l++)if(r[u.id]){f.outputs.forEach(function(t){return r[t.id]=!0}),c=!0,o[f.id]=!0;break}if(c)break}}var p={};p[n.id]=!0;var h={};for(a=t.length-1;a>=0;a--)for(i=(f=t[a]).inputs,l=0;l<f.outputs.length;l++)if(p[f.outputs[l].id]){for(var s in i)p[i[s].id]=!0,h[f.id]=!0;break}var d=[];for(a=0;a<t.length;a++){var f;if(o[(f=t[a]).id]&&h[f.id]){var v={};for(var s in f.inputs){var m=f.inputs[s];r[m.id]&&(v[s]=m)}var g=Object.assign({},f);g.inputs=v,g.outputs=f.outputs,d.push(g)}}return d}(this.state.activeTape,e,a);if(!r&&0===i.length&&e.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",function(){var t,r,s={};s[a.id]=null==n?(r=Q(R(t=a.shape),"float32"),_t.makeTensor(r,t,"float32")):n,function(t,e,n){for(var r=function(r){var o=e[r],a=[];if(o.outputs.forEach(function(e){var n=t[e.id];null!=n?a.push(n):a.push(null)}),null==o.gradient)throw new Error("Cannot compute gradient: gradient function not found for "+o.name+".");var i=o.gradient(a),s=function(e){if(!(e in i))throw new Error("Cannot backprop through input "+e+". Available gradients found: "+Object.keys(i)+".");var r=n(function(){return i[e]()});if("float32"!==r.dtype)throw new Error("Error in gradient for op "+o.name+". The gradient of input "+e+" must have 'float32' dtype, but has '"+r.dtype+"'");var a=o.inputs[e];if(!I(r.shape,a.shape))throw new Error("Error in gradient for op "+o.name+". The gradient of input '"+e+"' has shape '"+r.shape+"', which does not match the shape of the input '"+a.shape+"'");if(null==t[a.id])t[a.id]=r;else{var s=t[a.id];t[a.id]=s.add(r),s.dispose()}};for(var u in o.inputs)s(u)},o=e.length-1;o>=0;o--)r(o)}(s,i,function(t){return o.tidy(t)});var u=e.map(function(t){return s[t.id]});return 0===o.state.gradientDepth&&(o.state.activeTape.forEach(function(t){for(var e in t.saved)t.saved[e].dispose()}),o.state.activeTape=null),{value:a,grads:u}})},t.prototype.customGrad=function(t){var e=this;return b(K(t),function(){return"The f passed in customGrad(f) must be a function."}),function(){for(var n,r=[],o=0;o<arguments.length;o++)r[o]=arguments[o];b(r.every(function(t){return t instanceof gt}),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.runKernelFunc(function(e,o){return b((n=t.apply(void 0,r.concat([o]))).value instanceof gt,function(){return"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"}),b(K(n.gradFunc),function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."}),n.value},a,function(t,e){var o=n.gradFunc(t,e),a=Array.isArray(o)?o:[o];b(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(...)."}),b(a.every(function(t){return t instanceof gt}),function(){return"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors."});var i={};return a.forEach(function(t,e){i[e]=function(){return t}}),i})}},t.prototype.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 a(this,void 0,void 0,function(){var e,n;return i(this,function(r){switch(r.label){case 0:return e=Z(),[4,this.backend.time(t)];case 1:return(n=r.sent()).wallMs=Z()-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 Ft,this.registry)this.disposeRegisteredKernels(t),this.registry[t].dispose(),delete this.registry[t];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null},t.nextTensorId=0,t.nextVariableId=0,t}();exports.tensor_util=Tt;var _t=function(){var n=function(){if(null==Nt){var n=void 0;if("undefined"!=typeof window)n=window;else if(void 0!==t)n=t;else if(void 0!==e)n=e;else{if("undefined"==typeof self)throw new Error("Could not find a global object");n=self}Nt=n}return Nt}();if(null==n._tfengine){var r=new s(n);n._tfengine=new Ot(r)}return function(t){exports.ENV=c=t}(n._tfengine.ENV),ft=function(){return n._tfengine},n._tfengine}();function Mt(){return"undefined"!=typeof window&&null!=window.document||"undefined"!=typeof WorkerGlobalScope}var Bt=u();Bt.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.")}),Bt.registerFlag("IS_BROWSER",function(){return Mt()}),Bt.registerFlag("IS_NODE",function(){return void 0!==e&&void 0!==e.versions&&void 0!==e.versions.node}),Bt.registerFlag("IS_CHROME",function(){return"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)}),Bt.registerFlag("PROD",function(){return!1}),Bt.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",function(){return Bt.getBool("DEBUG")}),Bt.registerFlag("DEPRECATION_WARNINGS_ENABLED",function(){return!0}),Bt.registerFlag("IS_TEST",function(){return!1});var Pt,Lt,Wt,zt={},Ut={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function Vt(t,e){zt[t]=e}function Gt(t){t in zt||(zt[t]=function(t){if(1!==t&&2!==t)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");var e=Ht(t);return e.addEventListener("webglcontextlost",function(e){e.preventDefault(),delete zt[t]},!1),1===t?e.getContext("webgl",Ut)||e.getContext("experimental-webgl",Ut):e.getContext("webgl2",Ut)}(t));var e=zt[t];return e.isContextLost()?(delete zt[t],Gt(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),zt[t])}function Ht(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 qt(t,e){return[e,t]}function Kt(t){var e=R(t);return A(Math.ceil(e/4))}function jt(t,e){return[Math.max(1,Math.ceil(e/2)),Math.max(1,Math.ceil(t/2))]}function Xt(t,e){var n,r,o,a,i,s,c,l,p,h=t;return 2===u().getNumber("WEBGL_VERSION")?(n=h.R32F,r=h.R16F,o=h.RGBA16F,a=h.RGBA32F,i=h.RED,s=4,c=1,l=h.HALF_FLOAT,p=h.FLOAT):(n=t.RGBA,r=t.RGBA,o=t.RGBA,a=h.RGBA,i=t.RGBA,s=4,c=4,l=null!=e?e.HALF_FLOAT_OES:null,p=t.FLOAT),{internalFormatFloat:n,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:o,internalFormatPackedFloat:a,textureFormatFloat:i,downloadTextureFormat:t.RGBA,downloadUnpackNumChannels:s,defaultNumChannels:c,textureTypeHalfFloat:l,textureTypeFloat:p}}function $t(t,e,n){var r=n();return e&&function(t){var e=t.getError();if(e!==t.NO_ERROR)throw new Error("WebGL Error: "+Zt(t,e))}(t),r}!function(t){t[t.DENSE=0]="DENSE",t[t.SHARED_BATCH=1]="SHARED_BATCH"}(Pt||(Pt={})),function(t){t[t.RENDER=0]="RENDER",t[t.UPLOAD=1]="UPLOAD",t[t.PIXELS=2]="PIXELS",t[t.DOWNLOAD=3]="DOWNLOAD"}(Lt||(Lt={})),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"}(Wt||(Wt={}));var Yt=5.96e-8,Qt=65504;function Jt(t){return!!(u().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||0===t||Yt<Math.abs(t)&&Math.abs(t)<Qt)}function Zt(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 te(t,e,n){return Ee(t,e,function(){return t.getExtension(n)},'Extension "'+n+'" not supported on this browser.')}function ee(t,e,n){var r=Ee(t,e,function(){return t.createShader(t.VERTEX_SHADER)},"Unable to create vertex WebGLShader.");if($t(t,e,function(){return t.shaderSource(r,n)}),$t(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 ne(t,e,n){var r=Ee(t,e,function(){return t.createShader(t.FRAGMENT_SHADER)},"Unable to create fragment WebGLShader.");if($t(t,e,function(){return t.shaderSource(r,n)}),$t(t,e,function(){return t.compileShader(r)}),!1===t.getShaderParameter(r,t.COMPILE_STATUS))throw function(t,e){var n=ae.exec(e);if(null==n)return console.log("Couldn't parse line number in error: "+e),void console.log(t);for(var r=+n[1],o=t.split("\n"),a=o.length.toString().length+2,i=o.map(function(t,e){return D((e+1).toString(),a)+t}),s=0,u=0;u<i.length;u++)s=Math.max(i[u].length,s);var c=i.slice(0,r-1),l=i.slice(r-1,r),p=i.slice(r);console.log(c.join("\n")),console.log(e.split("\n")[0]),console.log("%c "+D(l[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 re,oe,ae=/ERROR: [0-9]+:([0-9]+):/g;function ie(t,e){return Ee(t,e,function(){return t.createProgram()},"Unable to create WebGLProgram.")}function se(t,e,n){if($t(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 ue(t,e,n){if($t(t,e,function(){return t.validateProgram(n)}),!1===t.getProgramParameter(n,t.VALIDATE_STATUS))throw console.log(t.getProgramInfoLog(n)),new Error("Shader program validation failed.")}function ce(t,e,n){var r=Ee(t,e,function(){return t.createBuffer()},"Unable to create WebGLBuffer");return $t(t,e,function(){return t.bindBuffer(t.ARRAY_BUFFER,r)}),$t(t,e,function(){return t.bufferData(t.ARRAY_BUFFER,n,t.STATIC_DRAW)}),r}function le(t,e,n){var r=Ee(t,e,function(){return t.createBuffer()},"Unable to create WebGLBuffer");return $t(t,e,function(){return t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,r)}),$t(t,e,function(){return t.bufferData(t.ELEMENT_ARRAY_BUFFER,n,t.STATIC_DRAW)}),r}function pe(t,e){return Ee(t,e,function(){return t.createTexture()},"Unable to create WebGLTexture.")}function he(t,e){var n=u().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(t<=0||e<=0){var r="["+t+"x"+e+"]";throw new Error("Requested texture size "+r+" is invalid.")}if(t>n||e>n)throw r="["+t+"x"+e+"]",new Error("Requested texture size "+r+" greater than WebGL maximum on this browser / GPU ["+n+"x"+n+"].")}function de(t,e){return Ee(t,e,function(){return t.createFramebuffer()},"Unable to create WebGLFramebuffer.")}function fe(t,e,n,r,o,a,i,s){var u=t.getAttribLocation(n,r);return-1!==u&&($t(t,e,function(){return t.bindBuffer(t.ARRAY_BUFFER,o)}),$t(t,e,function(){return t.vertexAttribPointer(u,a,t.FLOAT,!1,i,s)}),$t(t,e,function(){return t.enableVertexAttribArray(u)}),!0)}function ve(t,e,n,r){Re(t,r),$t(t,e,function(){return t.activeTexture(t.TEXTURE0+r)}),$t(t,e,function(){return t.bindTexture(t.TEXTURE_2D,n)})}function me(t,e,n,r){return Ee(t,e,function(){return t.getUniformLocation(n,r)},'uniform "'+r+'" not present in program.')}function ge(t,e,n){return t.getUniformLocation(e,n)}function xe(t,e,n,r,o,a){$t(t,e,function(){return ve(t,e,r,a)}),$t(t,e,function(){return t.uniform1i(o,a)})}function ye(t,e,n,r){$t(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,r)}),$t(t,e,function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0)})}function be(t,e,n){$t(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,n)}),$t(t,e,function(){return t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,null,0)})}function we(t){var e=t.checkFramebufferStatus(t.FRAMEBUFFER);if(e!==t.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+Ce(t,e))}function Ce(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 Ee(t,e,n,r){var o=$t(t,e,function(){return n()});if(null==o)throw new Error(r);return o}function Re(t,e){var n=t.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=e+t.TEXTURE0;if(r<t.TEXTURE0||r>n)throw new Error("textureUnit must be in [gl.TEXTURE0, gl.TEXTURE"+n+"].")}function Ie(t,e){return void 0===e&&(e=2),R(t.slice(0,t.length-e))}function ke(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 Se(t){var e=[1,1,1];return 0===t.length||1===t.length&&1===t[0]||(e=[Ie(t)].concat(ke(t))),e}function Ae(t,e){var n;void 0===e&&(e=!1);var r=u().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e&&(r*=2,1===(t=t.map(function(e,n){return n>=t.length-2?x(t[n]):t[n]})).length&&(t=[2,t[0]])),2!==t.length){var o=O(t);t=o.newShape}var a=R(t);if(t.length<=1&&a<=r)return[1,a];if(2===t.length&&t[0]<=r&&t[1]<=r)return t;if(3===t.length&&t[0]*t[1]<=r&&t[2]<=r)return[t[0]*t[1],t[2]];if(3===t.length&&t[0]<=r&&t[1]*t[2]<=r)return[t[0],t[1]*t[2]];if(4===t.length&&t[0]*t[1]*t[2]<=r&&t[3]<=r)return[t[0]*t[1]*t[2],t[3]];if(4===t.length&&t[0]<=r&&t[1]*t[2]*t[3]<=r)return[t[0],t[1]*t[2]*t[3]];if(e){var i=Ie(t),s=2,c=2;return t.length&&(s=(n=ke(t))[0],c=n[1]),A(a=i*(s/2)*(c/2)).map(function(t){return 2*t})}return A(a)}function De(t){return t%2==0}function Ne(t,e){if(I(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(De(n)&&De(r)&&(1===t[0]||1===e[0]))return!0}return t[1]===e[1]&&De(t[0])&&De(e[0])}function Te(t){if(null==re){var e=Gt(t);re=e.getParameter(e.MAX_TEXTURE_SIZE)}return re}function Fe(t){if(null==oe){var e=Gt(t);oe=e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,oe)}function Oe(t){if(0===t)return 0;var e=Gt(t);return _e(e,"EXT_disjoint_timer_query_webgl2")&&2===t?2:_e(e,"EXT_disjoint_timer_query")?1:0}function _e(t,e){return null!=t.getExtension(e)}function Me(t){try{if(null!=Gt(t))return!0}catch(t){return!1}return!1}function Be(t){if(0===t)return!1;var e=Gt(t);if(1===t){if(!_e(e,"OES_texture_float"))return!1}else if(!_e(e,"EXT_color_buffer_float"))return!1;return Le(e)}function Pe(t){if(0===t)return!1;var e=Gt(t);if(1!==t){if(_e(e,"EXT_color_buffer_float"))return Le(e);if(_e(e,"EXT_color_buffer_half_float")){var n=e.getExtension("EXT_color_buffer_half_float");return function(t,e){var n=Xt(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 o=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,o),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(o),a}(e,n)}return!1}return!!_e(e,"OES_texture_float")&&!!_e(e,"WEBGL_color_buffer_float")&&Le(e)}function Le(t){var e=Xt(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 o=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),o}function We(t){return 2===t&&null!=Gt(t).fenceSync}var ze=Object.freeze({callAndCheck:$t,canBeRepresented:Jt,getWebGLErrorMessage:Zt,getExtensionOrThrow:te,createVertexShader:ee,createFragmentShader:ne,createProgram:ie,linkProgram:se,validateProgram:ue,createStaticVertexBuffer:ce,createStaticIndexBuffer:le,getNumChannels:function(){return 2===u().getNumber("WEBGL_VERSION")?1:4},createTexture:pe,validateTextureSize:he,createFramebuffer:de,bindVertexBufferToProgramAttribute:fe,bindTextureUnit:ve,unbindTextureUnit:function(t,e,n){Re(t,n),$t(t,e,function(){return t.activeTexture(t.TEXTURE0+n)}),$t(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)})},getProgramUniformLocationOrThrow:me,getProgramUniformLocation:ge,bindTextureToProgramUniformSampler:xe,bindCanvasToFramebuffer:function(t,e){$t(t,e,function(){return t.bindFramebuffer(t.FRAMEBUFFER,null)}),$t(t,e,function(){return t.viewport(0,0,t.canvas.width,t.canvas.height)}),$t(t,e,function(){return t.scissor(0,0,t.canvas.width,t.canvas.height)})},bindColorTextureToFramebuffer:ye,unbindColorTextureFromFramebuffer:be,validateFramebuffer:we,getFramebufferErrorMessage:Ce,getBatchDim:Ie,getRowsCols:ke,getShapeAs3D:Se,getTextureShapeFromLogicalShape:Ae,isReshapeFree:Ne,getWebGLMaxTextureSize:Te,resetMaxTextureSize:function(){re=null},resetMaxTexturesInShader:function(){oe=null},getMaxTexturesInShader:Fe,getWebGLDisjointQueryTimerVersion:Oe,hasExtension:_e,isWebGLVersionEnabled:Me,isCapableOfRenderingToFloatTexture:Be,isDownloadFloatTextureEnabled:Pe,isWebGLFenceEnabled:We}),Ue=u();function Ve(){u().set("PROD",!0)}function Ge(){u().set("DEBUG",!0)}function He(){u().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function qe(t){u().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(t+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function Ke(){_t.disposeVariables()}function je(){return _t}function Xe(){return _t.memory()}function $e(t){return _t.profile(t)}function Ye(t,e){return _t.tidy(t,e)}function Qe(t){Dt(t).forEach(function(t){return t.dispose()})}function Je(t){return _t.keep(t)}function Ze(t){return _t.time(t)}function tn(t){return _t.setBackend(t)}function en(){return _t.ready()}function nn(){return _t.backendName}function rn(t){_t.removeBackend(t)}function on(t){return _t.findBackend(t)}function an(t){return _t.findBackendFactory(t)}function sn(t,e,n){return void 0===n&&(n=1),_t.registerBackend(t,e,n)}function un(){return _t.backend}function cn(t,e){u().setPlatform(t,e)}function ln(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];u().getBool("IS_TEST")||console.warn.apply(console,t)}function pn(t,e){var n=t;if(W(t))return"string"===e?[]:[t.length];if(!Array.isArray(t))return[];for(var r=[];Array.isArray(n)||W(n)&&"string"!==e;)r.push(n.length),n=n[0];return Array.isArray(t)&&u().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&function t(e,n,r){if(r=r||[],Array.isArray(e)||W(e)){b(n.length>0,function(){return"Element arr["+r.join("][")+"] should be a primitive, but is an array of "+e.length+" elements"}),b(e.length===n[0],function(){return"Element arr["+r.join("][")+"] should have "+n[0]+" elements, but has "+e.length+" elements"});for(var o=n.slice(1),a=0;a<e.length;++a)t(e[a],o,r.concat(a))}else b(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 hn(t,e,n,r){if(null!=t&&("numeric"!==t&&t!==e||"numeric"===t&&"string"===e))throw new Error("Argument '"+n+"' passed to '"+r+"' must be "+t+" tensor, but got "+e+" tensor")}function dn(t,e,n,r){if(void 0===r&&(r="numeric"),t instanceof gt)return hn(r,t.dtype,e,n),t;var o=q(t);if("string"!==o&&["bool","int32","float32"].indexOf(r)>=0&&(o=r),hn(r,o,e,n),null==t||!W(t)&&!Array.isArray(t)&&"number"!=typeof t&&"boolean"!=typeof t&&"string"!=typeof t){var a=null==t?"null":t.constructor.name;throw new Error("Argument '"+e+"' passed to '"+n+"' must be a Tensor or TensorLike, but got '"+a+"'")}var i=pn(t,o);W(t)||Array.isArray(t)||(t=[t]);var s="string"!==o?$(t,o,u().getBool("DEBUG")):E(t,[],!0);return _t.makeTensor(s,i,o)}function fn(t,e,n,r){if(void 0===r&&(r="numeric"),!Array.isArray(t))throw new Error("Argument "+e+" passed to "+n+" must be a `Tensor[]` or `TensorLike[]`");return t.map(function(t,r){return dn(t,e+"["+r+"]",n)},r)}function vn(t,e){for(var n=0;n<t.length;++n)if(t[t.length-n-1]!==e-1-n)return!1;return!0}function mn(t,e,n){for(var r=t.length+e.length,o=[],a=0,i=0,s=0;s<r;s++)-1===n.indexOf(s)?o.push(t[a++]):o.push(e[i++]);return o}function gn(t,e){for(var n=[],r=t.length,o=0;o<r;o++)-1===e.indexOf(o)&&n.push(t[o]);return[n,e.map(function(e){return t[e]})]}function xn(t,e){return mn(t,e.map(function(t){return 1}),e)}function yn(t,e,n){b(vn(e,n),function(){return t+" supports only inner-most axes for now. Got axes "+e+" and rank-"+n+" input."})}function bn(t,e){if(vn(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 wn(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 Cn(t,e){for(var n=[],r=e-t;r<e;++r)n.push(r);return n}function En(t,e){var n=t[0].length;t.forEach(function(t,e){b(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+")"})}),b(e>=0&&e<n,function(){return"Error in concat"+n+"D: axis must be between 0 and "+(n-1)+"."});var r=t[0];t.forEach(function(t,o){for(var a=0;a<n;a++)b(a===e||t[a]===r[a],function(){return"Error in concat"+n+"D: Shape of tensors["+o+"] ("+t+") does not match the shape of the rest ("+r+") along the non-concatenated axis "+o+"."})})}function Rn(t,e){for(var n=t[0].slice(),r=1;r<t.length;r++)n[e]+=t[r][e];return n}function In(t){var e=Object.keys(t);if(1!==e.length)throw new Error("Please provide an object with a single key (operation name) mapping to a function. Got an object with "+e.length+" keys.");var n=e[0],r=t[n];n.endsWith("_")&&(n=n.substring(0,n.length-1));var o=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];_t.startScope(n);try{var o=r.apply(void 0,t);return o instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),_t.endScope(o),o}catch(t){throw _t.endScope(null),t}};return Object.defineProperty(o,"name",{value:n,configurable:!0}),o}Ue.registerFlag("HAS_WEBGL",function(){return Ue.getNumber("WEBGL_VERSION")>0}),Ue.registerFlag("WEBGL_VERSION",function(){return Me(2)?2:Me(1)?1:0}),Ue.registerFlag("WEBGL_BUFFER_SUPPORTED",function(){return 2===Ue.get("WEBGL_VERSION")}),Ue.registerFlag("WEBGL_CPU_FORWARD",function(){return!0}),Ue.registerFlag("WEBGL_FORCE_F16_TEXTURES",function(){return!1}),Ue.registerFlag("WEBGL_PACK",function(){return Ue.getBool("HAS_WEBGL")}),Ue.registerFlag("WEBGL_PACK_NORMALIZATION",function(){return Ue.getBool("WEBGL_PACK")}),Ue.registerFlag("WEBGL_PACK_CLIP",function(){return Ue.getBool("WEBGL_PACK")}),Ue.registerFlag("WEBGL_PACK_DEPTHWISECONV",function(){return!1}),Ue.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",function(){return Ue.getBool("WEBGL_PACK")}),Ue.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",function(){return Ue.getBool("WEBGL_PACK")}),Ue.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",function(){return Ue.getBool("WEBGL_PACK")}),Ue.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",function(){return Ue.getBool("WEBGL_PACK")}),Ue.registerFlag("WEBGL_PACK_REDUCE",function(){return Ue.getBool("WEBGL_PACK")}),Ue.registerFlag("WEBGL_LAZILY_UNPACK",function(){return Ue.getBool("WEBGL_PACK")}),Ue.registerFlag("WEBGL_CONV_IM2COL",function(){return Ue.getBool("WEBGL_PACK")}),Ue.registerFlag("WEBGL_MAX_TEXTURE_SIZE",function(){return Te(Ue.getNumber("WEBGL_VERSION"))}),Ue.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",function(){return Fe(Ue.getNumber("WEBGL_VERSION"))}),Ue.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",function(){var t=Ue.getNumber("WEBGL_VERSION");return 0===t?0:Oe(t)}),Ue.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",function(){return Ue.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&(t=navigator.userAgent||navigator.vendor||window.opera,!(/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4))));var t}),Ue.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",function(){return Be(Ue.getNumber("WEBGL_VERSION"))}),Ue.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",function(){return!Ue.getBool("WEBGL_FORCE_F16_TEXTURES")&&Ue.getBool("WEBGL_RENDER_FLOAT32_CAPABLE")}),Ue.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",function(){return Pe(Ue.getNumber("WEBGL_VERSION"))}),Ue.registerFlag("WEBGL_FENCE_API_ENABLED",function(){return We(Ue.getNumber("WEBGL_VERSION"))}),Ue.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",function(){return Ue.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0}),mt=qe;var kn=In({complex_:function(t,e){var n=dn(t,"real","complex"),r=dn(e,"imag","complex");return w(n.shape,r.shape,"real and imag shapes, "+n.shape+" and "+r.shape+", must match in call to tf.complex()."),_t.runKernelFunc(function(t){return t.complex(n,r)},{$real:n,$imag:r})}}),Sn=In({real_:function(t){var e=dn(t,"input","real");return _t.runKernelFunc(function(t){return t.real(e)},{$input:e})}}),An=In({imag_:function(t){var e=dn(t,"input","imag");return _t.runKernelFunc(function(t){return t.imag(e)},{$input:e})}});function Dn(t,e,n){return Nn(t,e,pn(t,n),n)}function Nn(t,e,n,r){if(null==r&&(r=q(t)),"complex64"===r)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!W(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){tt(e);var o=R(e),a=R(n);b(o===a,function(){return"Based on the provided shape, ["+e+"], the tensor should have "+o+" values but has "+a});for(var i=0;i<n.length;++i){var s=n[i],c=i!==n.length-1||s!==R(e.slice(i));b(n[i]===e[i]||!c,function(){return"Error creating a new Tensor. Inferred shape ("+n+") does not match the provided shape ("+e+"). "})}}return W(t)||Array.isArray(t)||(t=[t]),e=e||n,t="string"!==r?$(t,r,u().getBool("DEBUG")):E(t,[],!0),_t.makeTensor(t,e,r)}function Tn(t,e){if((W(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&&W(t)&&!(t instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Nn(t,[],[],e)}function Fn(t,e){C(t);var n=pn(t,e);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Nn(t,null,n,e)}function On(t,e,n){if(C(t),null!=e&&2!==e.length)throw new Error("tensor2d() requires shape to have two numbers");var r=pn(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 Nn(t,e,r,n)}function _n(t,e,n){if(C(t),null!=e&&3!==e.length)throw new Error("tensor3d() requires shape to have three numbers");var r=pn(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 Nn(t,e,r,n)}function Mn(t,e,n){if(C(t),null!=e&&4!==e.length)throw new Error("tensor4d() requires shape to have four numbers");var r=pn(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 Nn(t,e,r,n)}function Bn(t,e,n){if(C(t),null!=e&&5!==e.length)throw new Error("tensor5d() requires shape to have five numbers");var r=pn(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 Nn(t,e,r,n)}function Pn(t,e,n){if(C(t),null!=e&&6!==e.length)throw new Error("tensor6d() requires shape to have six numbers");var r=pn(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 Nn(t,e=e||r,r,n)}function Ln(t,e,n,r){return void 0===e&&(e=!0),_t.makeVariable(t,e,n,r)}function Wn(t,e){if(void 0===e&&(e="float32"),"complex64"===e){var n=Wn(t,"float32"),r=zn(t,"float32");return kn(n,r)}var o=Q(R(t),e);return _t.makeTensor(o,t,e)}function zn(t,e){if(void 0===e&&(e="float32"),"complex64"===e){var n=zn(t,"float32"),r=zn(t,"float32");return kn(n,r)}var o=J(R(t),e);return _t.makeTensor(o,t,e)}function Un(t,e,n){return _t.runKernelFunc(function(r){return r.fill(t,e,n)},{})}function Vn(t,e,n){if(n<=0)throw new Error("The number of values should be positive.");return _t.runKernelFunc(function(r){return r.linspace(t,e,n)},{})}function Gn(t,e,n,r){if(void 0===n&&(n=1),void 0===r&&(r="float32"),0===n)throw new Error("Cannot have a step of zero");if(t===e||t<e&&n<0||e<t&&n>1)return zn([0],r);var o=J(Math.abs(Math.ceil((e-t)/n)),r);e<t&&1===n&&(n=-1),o[0]=t;for(var a=1;a<o.length;a++)o[a]=o[a-1]+n;return Fn(o,r)}exports.imag=An,exports.real=Sn,exports.complex=kn;var Hn=In({onesLike_:function(t){var e=dn(t,"x","onesLike");if("complex64"===e.dtype){var n=Hn(Sn(e)),r=qn(An(e));return kn(n,r)}return _t.runKernelFunc(function(t){return t.onesLike(e)},{$x:e},function(t,e){return{$x:function(){return qn(t)}}})}}),qn=In({zerosLike_:function(t){var e=dn(t,"x","zerosLike");return _t.runKernelFunc(function(t){return t.zerosLike(e)},{$x:e},function(t,e){return{$x:function(){return qn(t)}}})}});exports.zerosLike=qn,exports.onesLike=Hn;var Kn=In({concat_:function(t,e){void 0===e&&(e=0),b(t.length>=1,function(){return"Pass at least one tensor to concat"});var n=fn(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=F(e,n[0].shape)[0];var r=Rn(n.map(function(t){return t.shape}),e);if(0===R(r))return Dn([],r);if(1===(n=n.filter(function(t){return t.size>0})).length)return n[0];var o=n.map(function(t){return t.shape});En(o,e);var a=n,i={axis:e};return _t.runKernelFunc(function(t){return t.concat(n,e)},a,function(t){var n=o.map(function(t){return t[e]});return Qn(t,n,e).map(function(t){return function(){return t}})},"Concat",i)}}),jn=In({concat1d_:function(t){return Kn(t,0)}}),Xn=In({concat2d_:function(t,e){return Kn(t,e)}}),$n=In({concat3d_:function(t,e){return Kn(t,e)}}),Yn=In({concat4d_:function(t,e){return Kn(t,e)}}),Qn=In({split_:function(t,e,n){void 0===n&&(n=0);var r,o=dn(t,"x","split");return n=F(n,o.shape)[0],"number"==typeof e?(b(o.shape[n]%e==0,function(){return"Number of splits must evenly divide the axis."}),r=new Array(e).fill(o.shape[n]/e)):(b(o.shape[n]===e.reduce(function(t,e){return t+e}),function(){return"The sum of sizes must match the size of the axis dimension."}),r=e),_t.runKernelFunc(function(t){return t.split(o,r,n)},{$x:o},function(t){return{$x:function(){return Kn(t,n)}}})}});function Jn(t,e){return t(e={exports:{}},e.exports),e.exports}exports.split=Qn,exports.concat4d=Yn,exports.concat3d=$n,exports.concat2d=Xn,exports.concat1d=jn,exports.concat=Kn,"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:void 0!==t||"undefined"!=typeof self&&self;var Zn=Jn(function(t){!function(t,e,n){function r(t){var e,n=this,r=(e=4022871197,function(t){t=t.toString();for(var n=0;n<t.length;n++){var r=.02519603282416938*(e+=t.charCodeAt(n));r-=e=r>>>0,e=(r*=e)>>>0,e+=4294967296*(r-=e)}return 2.3283064365386963e-10*(e>>>0)});n.next=function(){var t=2091639*n.s0+2.3283064365386963e-10*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=t-(n.c=0|t)},n.c=1,n.s0=r(" "),n.s1=r(" "),n.s2=r(" "),n.s0-=r(t),n.s0<0&&(n.s0+=1),n.s1-=r(t),n.s1<0&&(n.s1+=1),n.s2-=r(t),n.s2<0&&(n.s2+=1),r=null}function o(t,e){return e.c=t.c,e.s0=t.s0,e.s1=t.s1,e.s2=t.s2,e}function a(t,e){var n=new r(t),a=e&&e.state,i=n.next;return i.int32=function(){return 4294967296*n.next()|0},i.double=function(){return i()+1.1102230246251565e-16*(2097152*i()|0)},i.quick=i,a&&("object"==typeof a&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:this.alea=a}(0,t)}),tr=Jn(function(t){!function(t,e,n){function r(t){var e=this,n="";e.x=0,e.y=0,e.z=0,e.w=0,e.next=function(){var t=e.x^e.x<<11;return e.x=e.y,e.y=e.z,e.z=e.w,e.w^=e.w>>>19^t^t>>>8},t===(0|t)?e.x=t:n+=t;for(var r=0;r<n.length+64;r++)e.x^=0|n.charCodeAt(r),e.next()}function o(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e}function a(t,e){var n=new r(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:this.xor128=a}(0,t)}),er=Jn(function(t){!function(t,e,n){function r(t){var e=this,n="";e.next=function(){var t=e.x^e.x>>>2;return e.x=e.y,e.y=e.z,e.z=e.w,e.w=e.v,(e.d=e.d+362437|0)+(e.v=e.v^e.v<<4^t^t<<1)|0},e.x=0,e.y=0,e.z=0,e.w=0,e.v=0,t===(0|t)?e.x=t:n+=t;for(var r=0;r<n.length+64;r++)e.x^=0|n.charCodeAt(r),r==n.length&&(e.d=e.x<<10^e.x>>>4),e.next()}function o(t,e){return e.x=t.x,e.y=t.y,e.z=t.z,e.w=t.w,e.v=t.v,e.d=t.d,e}function a(t,e){var n=new r(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:this.xorwow=a}(0,t)}),nr=Jn(function(t){!function(t,e,n){function r(t){var e=this;e.next=function(){var t,n,r=e.x,o=e.i;return t=r[o],n=(t^=t>>>7)^t<<24,n^=(t=r[o+1&7])^t>>>10,n^=(t=r[o+3&7])^t>>>3,n^=(t=r[o+4&7])^t<<7,t=r[o+7&7],n^=(t^=t<<13)^t<<9,r[o]=n,e.i=o+1&7,n},function(t,e){var n,r=[];if(e===(0|e))r[0]=e;else for(e=""+e,n=0;n<e.length;++n)r[7&n]=r[7&n]<<15^e.charCodeAt(n)+r[n+1&7]<<13;for(;r.length<8;)r.push(0);for(n=0;n<8&&0===r[n];++n);for(8==n?r[7]=-1:r[n],t.x=r,t.i=0,n=256;n>0;--n)t.next()}(e,t)}function o(t,e){return e.x=t.x.slice(),e.i=t.i,e}function a(t,e){null==t&&(t=+new Date);var n=new r(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,a&&(a.x&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:this.xorshift7=a}(0,t)}),rr=Jn(function(t){!function(t,e,n){function r(t){var e=this;e.next=function(){var t,n,r=e.w,o=e.X,a=e.i;return e.w=r=r+1640531527|0,n=o[a+34&127],t=o[a=a+1&127],n^=n<<13,t^=t<<17,n^=n>>>15,t^=t>>>12,n=o[a]=n^t,e.i=a,n+(r^r>>>16)|0},function(t,e){var n,r,o,a,i,s=[],u=128;for(e===(0|e)?(r=e,e=null):(e+="\0",r=0,u=Math.max(u,e.length)),o=0,a=-32;a<u;++a)e&&(r^=e.charCodeAt((a+32)%e.length)),0===a&&(i=r),r^=r<<10,r^=r>>>15,r^=r<<4,r^=r>>>13,a>=0&&(i=i+1640531527|0,o=0==(n=s[127&a]^=r+i)?o+1:0);for(o>=128&&(s[127&(e&&e.length||0)]=-1),o=127,a=512;a>0;--a)r=s[o+34&127],n=s[o=o+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,s[o]=r^n;t.w=i,t.X=s,t.i=o}(e,t)}function o(t,e){return e.i=t.i,e.w=t.w,e.X=t.X.slice(),e}function a(t,e){null==t&&(t=+new Date);var n=new r(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,a&&(a.X&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:this.xor4096=a}(0,t)}),or=Jn(function(t){!function(t,e,n){function r(t){var e=this,n="";e.next=function(){var t=e.b,n=e.c,r=e.d,o=e.a;return t=t<<25^t>>>7^n,n=n-r|0,r=r<<24^r>>>8^o,o=o-t|0,e.b=t=t<<20^t>>>12^n,e.c=n=n-r|0,e.d=r<<16^n>>>16^o,e.a=o-t|0},e.a=0,e.b=0,e.c=-1640531527,e.d=1367130551,t===Math.floor(t)?(e.a=t/4294967296|0,e.b=0|t):n+=t;for(var r=0;r<n.length+20;r++)e.b^=0|n.charCodeAt(r),e.next()}function o(t,e){return e.a=t.a,e.b=t.b,e.c=t.c,e.d=t.d,e}function a(t,e){var n=new r(t),a=e&&e.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&o(a,n),i.state=function(){return o(n,{})}),i}e&&e.exports?e.exports=a:this.tychei=a}(0,t)}),ar=Jn(function(t){!function(e,n){var r,o=this,a=256,i=6,s="random",u=n.pow(a,i),c=n.pow(2,52),l=2*c,p=a-1;function h(t,p,h){var g=[],x=v(function t(e,n){var r,o=[],a=typeof e;if(n&&"object"==a)for(r in e)try{o.push(t(e[r],n-1))}catch(t){}return o.length?o:"string"==a?e:e+"\0"}((p=1==p?{entropy:!0}:p||{}).entropy?[t,m(e)]:null==t?function(){try{var t;return r&&(t=r.randomBytes)?t=t(a):(t=new Uint8Array(a),(o.crypto||o.msCrypto).getRandomValues(t)),m(t)}catch(t){var n=o.navigator,i=n&&n.plugins;return[+new Date,o,i,o.screen,m(e)]}}():t,3),g),y=new d(g),b=function(){for(var t=y.g(i),e=u,n=0;t<c;)t=(t+n)*a,e*=a,n=y.g(1);for(;t>=l;)t/=2,e/=2,n>>>=1;return(t+n)/e};return b.int32=function(){return 0|y.g(4)},b.quick=function(){return y.g(4)/4294967296},b.double=b,v(m(y.S),e),(p.pass||h||function(t,e,r,o){return o&&(o.S&&f(o,y),t.state=function(){return f(y,{})}),r?(n[s]=t,e):t})(b,x,"global"in p?p.global:this==n,p.state)}function d(t){var e,n=t.length,r=this,o=0,i=r.i=r.j=0,s=r.S=[];for(n||(t=[n++]);o<a;)s[o]=o++;for(o=0;o<a;o++)s[o]=s[i=p&i+t[o%n]+(e=s[o])],s[i]=e;(r.g=function(t){for(var e,n=0,o=r.i,i=r.j,s=r.S;t--;)e=s[o=p&o+1],n=n*a+s[p&(s[o]=s[i=p&i+e])+(s[i]=e)];return r.i=o,r.j=i,n})(a)}function f(t,e){return e.i=t.i,e.j=t.j,e.S=t.S.slice(),e}function v(t,e){for(var n,r=t+"",o=0;o<r.length;)e[p&o]=p&(n^=19*e[p&o])+r.charCodeAt(o++);return m(e)}function m(t){return String.fromCharCode.apply(0,t)}if(n["seed"+s]=h,v(n.random(),e),t.exports){t.exports=h;try{r=require("crypto")}catch(t){}}}([],Math)});ar.alea=Zn,ar.xor128=tr,ar.xorwow=er,ar.xorshift7=nr,ar.xor4096=rr,ar.tychei=or;var ir=ar.alea,sr=function(){function t(t,e,n,r,o){this.mean=t,this.stdDev=e,this.dtype=n,this.nextVal=NaN,this.truncated=r,this.truncated&&(this.upper=this.mean+2*this.stdDev,this.lower=this.mean-2*this.stdDev);var a=o||Math.random();this.random=ir(a.toString())}return t.prototype.nextValue=function(){if(!isNaN(this.nextVal)){var t=this.nextVal;return this.nextVal=NaN,t}for(var e,n,r=!1;!r;){var o=void 0,a=void 0,i=void 0;do{i=(o=2*this.random()-1)*o+(a=2*this.random()-1)*a}while(i>=1||0===i);var s=Math.sqrt(-2*Math.log(i)/i);e=this.mean+this.stdDev*o*s,n=this.mean+this.stdDev*a*s,this.truncated&&!this.isValidTruncated(e)||(r=!0)}return this.truncated&&!this.isValidTruncated(n)||(this.nextVal=this.convertValue(n)),this.convertValue(e)},t.prototype.convertValue=function(t){return null==this.dtype||"float32"===this.dtype?t:Math.round(t)},t.prototype.isValidTruncated=function(t){return t<=this.upper&&t>=this.lower},t}(),ur=function(){function t(t,e,n,r){this.alpha=t,this.beta=1/e,this.dtype=n;var o=r||Math.random();this.randu=ir(o.toString()),this.randn=new sr(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,o,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)),(o=this.randu())<e||Math.log(o)<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}(),cr=function(){function t(t,e,n,r){var o=this;if(void 0===t&&(t=0),void 0===e&&(e=1),this.canReturnFloat=function(){return null==o.dtype||"float32"===o.dtype},this.min=t,this.range=e-t,this.dtype=n,null==r&&(r=Math.random()),"number"==typeof r&&(r=r.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error("The difference between "+t+" - "+e+" <= 1 and dtype is not float");this.random=ir(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 lr(t,e,n){return void 0===e&&(e="float32"),e=e||"float32",tt(t),new dt(t,e,n)}function pr(t,e){void 0===e&&(e=!1),console.log(t.toString(e))}var hr=In({batchToSpaceND_:function(t,e,n){var r=dn(t,"x","batchToSpaceND"),o=e.reduce(function(t,e){return t*e});return b(r.rank>=1+e.length,function(){return"input rank is "+r.rank+" but should be > than blockShape.length "+e.length}),b(n.length===e.length,function(){return"crops.length is "+n.length+" but should be equal to blockShape.length  "+e.length}),b(r.shape[0]%o==0,function(){return"input tensor batch is "+r.shape[0]+" but is not divisible by the product of the elements of blockShape "+e.join(" * ")+" === "+o}),_t.runKernelFunc(function(t){return t.batchToSpaceND(r,e,n)},{$x:r},function(t){return{$x:function(){return t.spaceToBatchND(e,n)}}})}}),dr=In({cast_:function(t,e){var n=dn(t,"x","cast");if(!P(e))throw new Error("Failed to cast to unknown dtype "+e);if("string"===e&&"string"!==n.dtype||"string"!==e&&"string"===n.dtype)throw new Error("Only strings can be casted to strings");var r={dtype:e};return _t.runKernelFunc(function(t){return t.cast(n,e)},{x:n},function(t){return{x:function(){return t.clone()}}},"Cast",r)}}),fr=In({clone_:function(t){var e=dn(t,"x","clone",null);return _t.runKernelFunc(function(){return _t.makeTensorFromDataId(e.dataId,e.shape,e.dtype)},{$x:e},function(t){return{$x:function(){return t.toFloat()}}})}}),vr=In({cumsum_:function(t,e,n,r){void 0===e&&(e=0),void 0===n&&(n=!1),void 0===r&&(r=!1);var o=dn(t,"x","cumsum"),a=bn([e|=0],o.rank),i=o;null!=a&&(i=o.transpose(a));var s=Cn(1,o.rank)[0],u=_t.runKernelFunc(function(t){return t.cumsum(i,s,n,r)},{permutedX:i},function(t){return{permutedX:function(){return t.cumsum(e,n,!r)}}});return null!=a&&(u=u.transpose(a)),u}}),mr=In({depthToSpace_:function(t,e,n){void 0===n&&(n="NHWC");var r=dn(t,"x","depthToSpace"),o="NHWC"===n?r.shape[1]:r.shape[2],a="NHWC"===n?r.shape[2]:r.shape[3],i="NHWC"===n?r.shape[3]:r.shape[1];return b(o*e>=0,function(){return"Negative dimension size caused by overflow when multiplying\n      "+o+" and "+e+"  for depthToSpace with input shape\n      "+r.shape}),b(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}),b(i%(e*e)==0,function(){return"Dimension size must be evenly divisible by "+e*e+" but is "+i+" for depthToSpace with input shape "+r.shape}),_t.runKernelFunc(function(t){return t.depthToSpace(r,e,n)},{$x:r})}}),gr=In({expandDims_:function(t,e){void 0===e&&(e=0);var n=dn(t,"x","expandDims",null);b(e<=n.rank,function(){return"Axis must be <= rank of the tensor"});var r=n.shape.slice();return e<0&&(b(-(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),Nr(n,r)}}),xr=In({eye_:function(t,e,n,r){void 0===r&&(r="float32"),null==e&&(e=t);for(var o=lr([t,e],r),a=t<=e?t:e,i=0;i<a;++i)o.set(1,i,i);var s=o.toTensor().as2D(t,e);if(null==n)return s;if(1===n.length)return _r(gr(s,0),[n[0],1,1]);if(2===n.length)return _r(gr(gr(s,0),0),[n[0],n[1],1,1]);if(3===n.length)return _r(gr(gr(gr(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.")}}),yr=In({multinomial_:function(t,e,n,r){void 0===r&&(r=!1);var o=dn(t,"logits","multinomial"),a=o.size,i=o.rank;if(a<2)throw new Error("Error in multinomial: you need at least 2 outcomes, but got "+a+".");if(i>2)throw new Error("Rank of probabilities must be 1 or 2, but is "+i);n=n||Math.random();var s=1===i?o.as2D(1,-1):o,u=_t.runKernelFunc(function(t){return t.multinomial(s,r,e,n)},{logits2D:s});return 1===i?u.as1D():u}}),br=In({oneHot_:function(t,e,n,r){if(void 0===n&&(n=1),void 0===r&&(r=0),e<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+e);var o=dn(t,"indices","oneHot","int32"),a=o.shape.concat([e]);return o=o.flatten(),_t.runKernelFunc(function(t){return t.oneHot(o,e,n,r)},{$indices:o},function(t){return{$indices:function(){return zn(o.shape,"float32")}}}).reshape(a)}}),wr=In({pad_:function(t,e,n){void 0===n&&(n=0);var r=dn(t,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");var o=e.map(function(t){return t[0]});return _t.runKernelFunc(function(t){return t.pad(r,e,n)},{$x:r},function(t){return{$x:function(){return t.slice(o,r.shape)}}})}}),Cr=In({pad1d_:function(t,e,n){return void 0===n&&(n=0),b(2===e.length,function(){return"Invalid number of paddings. Must be length of 2."}),wr(t,[e],n)}}),Er=In({pad2d_:function(t,e,n){return void 0===n&&(n=0),b(2===e.length&&2===e[0].length&&2===e[1].length,function(){return"Invalid number of paddings. Must be length of 2 each."}),wr(t,e,n)}}),Rr=In({pad3d_:function(t,e,n){return void 0===n&&(n=0),b(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."}),wr(t,e,n)}}),Ir=In({pad4d_:function(t,e,n){return void 0===n&&(n=0),b(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."}),wr(t,e,n)}}),kr=In({rand_:function(t,e,n){var r=R(t),o=null;if(null==n||"float32"===n)o=new Float32Array(r);else if("int32"===n)o=new Int32Array(r);else{if("bool"!==n)throw new Error("Unknown data type "+n);o=new Uint8Array(r)}for(var a=0;a<r;a++)o[a]=e();return _t.makeTensor(o,t,n)}}),Sr=In({randomNormal_:function(t,e,n,r,o){if(void 0===e&&(e=0),void 0===n&&(n=1),null!=r&&"bool"===r)throw new Error("Unsupported data type "+r);for(var a=new sr(e,n,r,!1,o),i=lr(t,r),s=0;s<i.values.length;s++)i.values[s]=a.nextValue();return i.toTensor()}}),Ar=In({randomGamma_:function(t,e,n,r,o){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 ur(e,n,r,o),i=lr(t,r),s=0;s<i.values.length;s++)i.values[s]=a.nextValue();return i.toTensor()}}),Dr=In({randomUniform_:function(t,e,n,r,o){void 0===e&&(e=0),void 0===n&&(n=1),void 0===r&&(r="float32");for(var a=lr(t,r),i=new cr(e,n,null,o),s=0;s<a.values.length;s++)a.values[s]=i.nextValue();return a.toTensor()}}),Nr=In({reshape_:function(t,e){var n=dn(t,"x","reshape",null);e=T(e,n.size),b(n.size===R(e),function(){return"new shape and old shape must have the same number of elements."});var r={shape:e};return _t.runKernelFunc(function(t){return t.reshape(n,e)},{x:n},function(t){return{x:function(){return t.reshape(n.shape)}}},"Reshape",r)}}),Tr=In({spaceToBatchND_:function(t,e,n){var r=dn(t,"x","spaceToBatchND");return b(r.rank>=1+e.length,function(){return"input rank "+r.rank+" should be > than [blockShape] "+e.length}),b(n.length===e.length,function(){return"paddings.shape[0] "+n.length+" must be equal to [blockShape] "+e.length}),b(r.shape.reduce(function(t,r,o){return o>0&&o<=e.length?t&&(r+n[o-1][0]+n[o-1][1])%e[o-1]==0:t},!0),function(){return"input spatial dimensions "+r.shape.slice(1)+" with paddings "+n.toString()+" must be divisible by blockShapes "+e.toString()}),_t.runKernelFunc(function(t){return t.spaceToBatchND(r,e,n)},{$x:r},function(t){return{$x:function(){return t.batchToSpaceND(e,n)}}})}}),Fr=In({squeeze_:function(t,e){var n=dn(t,"x","squeeze");return Nr(n,O(n.shape,e).newShape)}}),Or=In({stack_:function(t,e){void 0===e&&(e=0);var n=fn(t,"tensors","stack");if(b(n.length>=1,function(){return"Pass at least one tensor to tf.stack"}),1===n.length)return n[0].expandDims(e);var r=n[0].rank,o=n[0].shape,a=n[0].dtype;b(e<=r,function(){return"Axis must be <= rank of the tensor"}),n.forEach(function(t){w(o,t.shape,"All tensors passed to stack must have matching shapes")}),n.forEach(function(t){b(a===t.dtype,function(){return"All tensors passed to stack must have matching dtypes"})});var i=n.map(function(t){return t.expandDims(e)});return Kn(i,e)}}),_r=In({tile_:function(t,e){var n=dn(t,"x","tile",null);return b(n.rank===e.length,function(){return"Error in transpose: rank of input "+n.rank+" must match length of reps "+e+"."}),_t.runKernelFunc(function(t,r){var o=t.tile(n,e);return r([n]),o},{$x:n},function(t,n){var r=n[0];return{$x:function(){var n=qn(r);if(1===r.rank)for(var o=0;o<e[0];++o)n=n.add(t.slice([o*r.shape[0]],[r.shape[0]]));else if(2===r.rank)for(o=0;o<e[0];++o)for(var a=0;a<e[1];++a)n=n.add(t.slice([o*r.shape[0],a*r.shape[1]],[r.shape[0],r.shape[1]]));else if(3===r.rank)for(o=0;o<e[0];++o)for(a=0;a<e[1];++a)for(var i=0;i<e[2];++i)n=n.add(t.slice([o*r.shape[0],a*r.shape[1],i*r.shape[2]],[r.shape[0],r.shape[1],r.shape[2]]));else{if(4!==r.rank)throw new Error("Gradient for tile operation is not implemented for rank-"+r.rank+" tensors yet.");for(o=0;o<e[0];++o)for(a=0;a<e[1];++a)for(i=0;i<e[2];++i)for(var s=0;s<e[3];++s)n=n.add(t.slice([o*r.shape[0],a*r.shape[1],i*r.shape[2],s*r.shape[3]],[r.shape[0],r.shape[1],r.shape[2],r.shape[3]]))}return n}}})}}),Mr=In({truncatedNormal_:function(t,e,n,r,o){if(void 0===e&&(e=0),void 0===n&&(n=1),null!=r&&"bool"===r)throw new Error("Unsupported data type "+r);for(var a=new sr(e,n,r,!0,o),i=lr(t,r),s=0;s<i.values.length;s++)i.values[s]=a.nextValue();return i.toTensor()}}),Br=In({unstack_:function(t,e){void 0===e&&(e=0),e=e||0;var n=dn(t,"x","unstack");return b(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),_t.runKernelFunc(function(t){return t.unstack(n,e)},{$x:n},function(t){return{$x:function(){return Or(t,e)}}})}}),Pr=function(t,e){return a(this,void 0,void 0,function(){var n,r,o,a,s,u,c,l,p,h;return i(this,function(i){switch(i.label){case 0:return n=dn(t,"x","setdiff1d"),r=dn(e,"y","setdiff1d"),b(n.dtype===r.dtype,function(){return"x and y should have the same dtype, but got x ("+n.dtype+") and y ("+r.dtype+")."}),b(1===n.rank,function(){return"x should be 1D tensor, but got x ("+n.shape+")."}),b(1===r.rank,function(){return"y should be 1D tensor, but got y ("+r.shape+")."}),[4,n.data()];case 1:return o=i.sent(),[4,r.data()];case 2:for(a=i.sent(),s=new Set(a),u=0,p=0;p<o.length;p++)s.has(o[p])||u++;for(c=new dt([u],n.dtype),l=new dt([u],"int32"),p=0,h=0;p<o.length;p++)s.has(o[p])||(c.values[h]=o[p],l.values[h]=p,h++);return[2,[c.toTensor(),l.toTensor()]]}})})};function Lr(t,e,n,r){void 0===r&&(r=!0);var o=[];if(r)(o=o.concat(e.slice(0))).push(t[0]/n),o=o.concat(t.slice(1));else{o=o.concat(t[0]);for(var a=e.length,i=0;i<a;++i)o=o.concat([t[i+1]/e[i],e[i]]);o=o.concat(t.slice(a+1))}return o}function Wr(t,e,n){void 0===n&&(n=!0);var r=[];if(n){r.push(e);for(var o=e+1;o<t;++o)o<=2*e?(r.push(o),r.push(o-(e+1))):r.push(o)}else{var a=[],i=[];for(o=1;o<t;++o)o>=2*e+1||o%2==1?i.push(o):a.push(o);r.push.apply(r,a),r.push(0),r.push.apply(r,i)}return r}function zr(t,e,n,r){void 0===r&&(r=!0);var o=[];r?o.push(t[0]/n):o.push(t[0]*n);for(var a=1;a<t.length;++a)a<=e.length?r?o.push(e[a-1]*t[a]):o.push(t[a]/e[a-1]):o.push(t[a]);return o}function Ur(t,e){for(var n=[0],r=0;r<e;++r)n.push(t[r][0]);return n}function Vr(t,e,n){for(var r=t.slice(0,1),o=0;o<n;++o)r.push(t[o+1]-e[o][0]-e[o][1]);return r}function 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],o=1,a=0;a<n.length-1;++a)o*=n[a];var i=t.shape,s=n.slice();s.pop();var u=1;for(a=r;a<t.rank;++a)u*=i[a],s.push(i[a]);var c=X(t.shape).map(function(t){return t/u}).concat([1]).slice(0,r);return[s,o,u,c]}exports.setdiff1dAsync=Pr,exports.unstack=Br,exports.truncatedNormal=Mr,exports.tile=_r,exports.stack=Or,exports.squeeze=Fr,exports.spaceToBatchND=Tr,exports.reshape=Nr,exports.randomUniform=Dr,exports.randomGamma=Ar,exports.randomNormal=Sr,exports.rand=kr,exports.pad4d=Ir,exports.pad3d=Rr,exports.pad2d=Er,exports.pad1d=Cr,exports.pad=wr,exports.oneHot=br,exports.multinomial=yr,exports.eye=xr,exports.expandDims=gr,exports.depthToSpace=mr,exports.cumsum=vr,exports.clone=fr,exports.cast=dr,exports.batchToSpaceND=hr;var Hr=30;function qr(t){return t<=Hr?t:j(t,Math.floor(Math.sqrt(t)))}function Kr(t,e,n){if(e.rank<1)throw new Error("tf.scatterND() expects the indices to be rank 1 or higher, but the rank was "+e.rank+".");if(t.rank<1)throw new Error("tf.scatterND() expects the updates to be rank 1 or higher, but the rank was "+t.rank+".");if("int32"!==e.dtype)throw new Error("The dtype of 'indices' should be int32, but got dtype: "+e.dtype);if(n.length<1)throw new Error("Output rank must be greater or equal to 1, but got shape: "+n);if(0===n.length){if(0===e.size)throw new Error("Indices specified for empty output. indices shape: "+e.shape);if(0===t.size)throw new Error("Updates specified for empty output. updates shape: "+t.shape)}!function(t,e,n){var r=e.rank>1?e.shape[e.rank-1]:1,o=e.rank>1?e.rank-1:1,a="Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: "+n.shape+", indices.shape: "+e.shape+", shape: "+t+", sliceDim: "+r+", and batchDim: "+o+".";if(n.rank<o)throw new Error(a+" update.rank < "+o+". ");if(t.length<r+(n.rank-o))throw new Error(a+" Output shape length < "+(r+(n.rank-o)));if(n.rank!==o+t.length-r)throw new Error(a+" update.rank != "+(o+t.length-r));for(var i=0;i<o;++i)if(n.shape[i]!==e.shape[i])throw new Error(a+" updates.shape["+i+"] ("+n.shape[i]+") != indices.shape["+i+"] ("+e.shape[i]+").");for(i=0;i<n.rank-o;++i)if(n.shape[i+o]!==t[i+r])throw new Error(a+" updates.shape["+(i+o)+"] ("+n.shape[i+o]+") != shape["+(i+o)+"] ("+t[i+o]+")")}(n,e,t)}function jr(t,e,n){for(var r=e.rank>1?e.shape[e.rank-1]:1,o=n.length,a=1,i=r;i<o;++i)a*=n[i];var s=r<1?1:r;return{sliceRank:r,numUpdates:e.size/s,sliceSize:a,strides:X(n.slice(0,r)).concat([1]),outputSize:R(n)}}function Xr(t,e,n){b(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+")."}),b(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){b(e[r]+n[r]<=t.shape[r],function(){return"Error in slice"+t.rank+"D: begin["+r+"] + size["+r+"] ("+(e[r]+n[r])+") would overflow input.shape["+r+"] ("+t.shape[r]+")"})},o=0;o<t.rank;++o)r(o)}function $r(t){for(var e=[],n=0;t>0;)1&t&&e.push(n),t/=2,n++;return e}function Yr(t,e,n){for(var r=[],o=0;o<t.length;o++)r[o]=Math.ceil((e[o]-t[o])/n[o]);return r}function Qr(t,e,n,r,o){var a=e[o],i=n[o]||1;(t&1<<o||null==a)&&(a=i>0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);var s=r[o];return a<0&&(a+=s),g(0,a,s-1)}function Jr(t,e,n,r,o){var a=e[o],i=n[o]||1;(t&1<<o||null==a)&&(a=i>0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);var s=r[o];return a<0&&(a+=s),i>0?g(0,a,s):g(-1,a,s-1)}function Zr(t,e,n){for(var r=n.length,o=0;o<n.length;o++)if(n[o]>1){r=o;break}for(o=r+1;o<n.length;o++)if(e[o]>0||n[o]!==t[o])return!1;return!0}function to(t,e){for(var n=t.length>0?t[t.length-1]:1,r=0;r<t.length-1;r++)n+=t[r]*e[r];return n}var eo=Object.freeze({assertParamsValid:Xr,maskToAxes:$r,computeOutShape:Yr,startForAxis:Qr,stopForAxis:Jr,isSliceContinous:Zr,computeFlatOffset:to});function no(t){return b(K(t),function(){return"The f passed in grad(f) must be a function"}),function(e,n){var r=dn(e,"x","tf.grad",null),o=null!=n?dn(n,"dy","tf.grad"):null;return _t.tidy(function(){var e=_t.gradients(function(){return t(r)},[r],o),n=e.value,a=e.grads;return null!=o&&w(n.shape,o.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),uo(a),a[0]})}}function ro(t){return b(K(t),function(){return"The f passed in grads(f) must be a function"}),function(e,n){b(Array.isArray(e),function(){return"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s"});var r=fn(e,"args","tf.grads",null),o=null!=n?dn(n,"dy","tf.grads"):null;return _t.tidy(function(){var e=_t.gradients(function(){return t.apply(void 0,r)},r,o),n=e.value,a=e.grads;return null!=o&&w(n.shape,o.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),uo(a),a})}}function oo(t){return b(K(t),function(){return"The f passed in valueAndGrad(f) must be a function"}),function(e,n){b(e instanceof gt,function(){return"The x passed in valueAndGrad(f)(x) must be a tensor"}),b(null==n||n instanceof gt,function(){return"The dy passed in valueAndGrad(f)(x, dy) must be a tensor"});var r=_t.gradients(function(){return t(e)},[e],n),o=r.grads,a=r.value;return uo(o),{grad:o[0],value:a}}}function ao(t){return b(K(t),function(){return"The f passed in valueAndGrads(f) must be a function"}),function(e,n){b(Array.isArray(e)&&e.every(function(t){return t instanceof gt}),function(){return"The args passed in valueAndGrads(f)(args) must be array of tensors"}),b(null==n||n instanceof gt,function(){return"The dy passed in valueAndGrads(f)(args, dy) must be a tensor"});var r=_t.gradients(function(){return t.apply(void 0,e)},e,n);return null!=n&&w(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),uo(r.grads),r}}function io(t,e){b(K(t),function(){return"The f passed in variableGrads(f) must be a function"}),b(null==e||Array.isArray(e)&&e.every(function(t){return t instanceof Et}),function(){return"The varList passed in variableGrads(f, varList) must be an array of variables"});var n=null!=e;if(!n)for(var r in e=[],_t.registeredVariables)e.push(_t.registeredVariables[r]);var o=n?e.filter(function(t){return!t.trainable}):null,a=e.length;b((e=e.filter(function(t){return t.trainable})).length>0,function(){return"variableGrads() expects at least one of the input variables to be trainable, but none of the "+a+" variables is trainable."});var i=_t.gradients(t,e,null,!0),s=i.value,u=i.grads;b(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()."}),b(0===s.rank,function(){return"The f passed in variableGrads(f) must return a scalar, but it returned a rank-"+s.rank+" tensor"});var c={};return e.forEach(function(t,e){null!=u[e]&&(c[t.name]=u[e])}),null!=o&&o.forEach(function(t){return c[t.name]=null}),{value:s,grads:c}}function so(t){return _t.customGrad(t)}function uo(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.")}exports.slice_util=eo;var co=In({softmax_:function(t,e){void 0===e&&(e=-1);var n=dn(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 so(function(t,n){var r=t.logSumExp([e],!0),o=t.toFloat().sub(r).exp();return n([o]),{value:o,gradFunc:function(t,n){var r=n[0],o=t.mul(r);return o.sub(o.sum([e],!0).mul(r))}}})(n)}}),lo=In({logSoftmax_:function(t,e){void 0===e&&(e=-1);var n=dn(t,"logits","logSoftmax");if(-1===e&&(e=n.rank-1),e!==n.rank-1)throw Error("Log Softmax along a non-last dimension is not yet supported. Logits was rank "+n.rank+" and axis was "+e);return so(function(t,n){var r=t.max(e,!0),o=t.sub(r),a=o.toFloat().sub(o.exp().sum(e,!0).log());return n([a]),{value:a,gradFunc:function(t,n){var r=n[0].exp();return t.sub(t.sum(e,!0).mul(r))}}})(n)}}),po=function(){function t(t,e){this.backend=t,this.dataMover=e,this.data=new WeakMap,this.dataIdsCount=0}return t.prototype.get=function(t){return this.data.has(t)||this.dataMover.moveData(this.backend,t),this.data.get(t)},t.prototype.set=function(t,e){this.dataIdsCount++,this.data.set(t,e)},t.prototype.has=function(t){return this.data.has(t)},t.prototype.delete=function(t){return this.dataIdsCount--,this.data.delete(t)},t.prototype.numDataIds=function(){return this.dataIdsCount},t}(),ho=function(){function t(){}return t.prototype.time=function(t){return fo("time")},t.prototype.read=function(t){return fo("read")},t.prototype.readSync=function(t){return fo("readSync")},t.prototype.numDataIds=function(){return fo("numDataIds")},t.prototype.disposeData=function(t){return fo("disposeData")},t.prototype.fromPixels=function(t,e){return fo("fromPixels")},t.prototype.write=function(t,e,n){return fo("write")},t.prototype.move=function(t,e,n,r){return fo("move")},t.prototype.memory=function(){return fo("memory")},t.prototype.floatPrecision=function(){return fo("floatPrecision")},t.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4},t.prototype.batchMatMul=function(t,e,n,r){return fo("batchMatMul")},t.prototype.fusedBatchMatMul=function(t){return t.a,t.b,t.transposeA,t.transposeB,t.bias,t.activation,t.preluActivationWeights,fo("fusedBatchMatMul")},t.prototype.slice=function(t,e,n){return fo("slice")},t.prototype.stridedSlice=function(t,e,n,r){return fo("stridedSlice")},t.prototype.unstack=function(t,e){return fo("unstack")},t.prototype.reverse=function(t,e){return fo("reverse")},t.prototype.concat=function(t,e){return fo("concat")},t.prototype.neg=function(t){return fo("neg")},t.prototype.add=function(t,e){return fo("add")},t.prototype.addN=function(t){return fo("addN")},t.prototype.subtract=function(t,e){return fo("subtract")},t.prototype.multiply=function(t,e){return fo("multiply")},t.prototype.realDivide=function(t,e){return fo("realDivide")},t.prototype.floorDiv=function(t,e){return fo("floorDiv")},t.prototype.sum=function(t,e){return fo("sum")},t.prototype.prod=function(t,e){return fo("prod")},t.prototype.unsortedSegmentSum=function(t,e,n){return fo("unsortedSegmentSum")},t.prototype.argMin=function(t,e){return fo("argMin")},t.prototype.argMax=function(t,e){return fo("argMax")},t.prototype.equal=function(t,e){return fo("equal")},t.prototype.notEqual=function(t,e){return fo("notEqual")},t.prototype.less=function(t,e){return fo("less")},t.prototype.lessEqual=function(t,e){return fo("lessEqual")},t.prototype.greater=function(t,e){return fo("greater")},t.prototype.greaterEqual=function(t,e){return fo("greaterEqual")},t.prototype.logicalNot=function(t){return fo("logicalNot")},t.prototype.logicalAnd=function(t,e){return fo("logicalAnd")},t.prototype.logicalOr=function(t,e){return fo("logicalOr")},t.prototype.where=function(t){return fo("where")},t.prototype.select=function(t,e,n){return fo("select")},t.prototype.topk=function(t,e,n){return fo("topk")},t.prototype.min=function(t,e){return fo("min")},t.prototype.minimum=function(t,e){return fo("minimum")},t.prototype.mod=function(t,e){return fo("mod")},t.prototype.max=function(t,e){return fo("max")},t.prototype.maximum=function(t,e){return fo("maximum")},t.prototype.all=function(t,e){return fo("all")},t.prototype.any=function(t,e){return fo("any")},t.prototype.squaredDifference=function(t,e){return fo("squaredDifference")},t.prototype.ceil=function(t){return fo("ceil")},t.prototype.floor=function(t){return fo("floor")},t.prototype.round=function(t){return fo("round")},t.prototype.sign=function(t){return fo("sign")},t.prototype.isNaN=function(t){return fo("isNaN")},t.prototype.isInf=function(t){return fo("isInf")},t.prototype.isFinite=function(t){return fo("isFinite")},t.prototype.pow=function(t,e){return fo("pow")},t.prototype.exp=function(t){return fo("exp")},t.prototype.expm1=function(t){return fo("expm1")},t.prototype.log=function(t){return fo("log")},t.prototype.log1p=function(t){return fo("log1p")},t.prototype.sqrt=function(t){return fo("sqrt")},t.prototype.rsqrt=function(t){return fo("rsqrt")},t.prototype.square=function(t){return fo("square")},t.prototype.reciprocal=function(t){return fo("reciprocal")},t.prototype.relu=function(t){return fo("relu")},t.prototype.relu6=function(t){return fo("relu6")},t.prototype.prelu=function(t,e){return fo("prelu")},t.prototype.elu=function(t){return fo("elu")},t.prototype.eluDer=function(t,e){return fo("eluDer")},t.prototype.selu=function(t){return fo("selu")},t.prototype.int=function(t){return fo("int")},t.prototype.clip=function(t,e,n){return fo("clip")},t.prototype.abs=function(t){return fo("abs")},t.prototype.complexAbs=function(t){return fo("complexAbs")},t.prototype.sigmoid=function(t){return fo("sigmoid")},t.prototype.softplus=function(t){return fo("softplus")},t.prototype.sin=function(t){return fo("sin")},t.prototype.cos=function(t){return fo("cos")},t.prototype.tan=function(t){return fo("tan")},t.prototype.asin=function(t){return fo("asin")},t.prototype.acos=function(t){return fo("acos")},t.prototype.atan=function(t){return fo("atan")},t.prototype.atan2=function(t,e){return fo("atan2")},t.prototype.sinh=function(t){return fo("sinh")},t.prototype.cosh=function(t){return fo("cosh")},t.prototype.tanh=function(t){return fo("tanh")},t.prototype.asinh=function(t){return fo("asinh")},t.prototype.acosh=function(t){return fo("acosh")},t.prototype.atanh=function(t){return fo("atanh")},t.prototype.erf=function(t){return fo("erf")},t.prototype.step=function(t,e){return fo("step")},t.prototype.fusedConv2d=function(t){return t.input,t.filter,t.convInfo,t.bias,t.activation,t.preluActivationWeights,fo("fusedConv2d")},t.prototype.conv2d=function(t,e,n){return fo("conv2d")},t.prototype.conv2dDerInput=function(t,e,n){return fo("conv2dDerInput")},t.prototype.conv2dDerFilter=function(t,e,n){return fo("conv2dDerFilter")},t.prototype.fusedDepthwiseConv2D=function(t){return t.input,t.filter,t.convInfo,t.bias,t.activation,t.preluActivationWeights,fo("fusedDepthwiseConv2D")},t.prototype.depthwiseConv2D=function(t,e,n){return fo("depthwiseConv2D")},t.prototype.depthwiseConv2DDerInput=function(t,e,n){return fo("depthwiseConv2DDerInput")},t.prototype.depthwiseConv2DDerFilter=function(t,e,n){return fo("depthwiseConv2DDerFilter")},t.prototype.conv3d=function(t,e,n){return fo("conv3d")},t.prototype.conv3dDerInput=function(t,e,n){return fo("conv3dDerInput")},t.prototype.conv3dDerFilter=function(t,e,n){return fo("conv3dDerFilter")},t.prototype.maxPool=function(t,e){return fo("maxPool")},t.prototype.maxPoolBackprop=function(t,e,n,r){return fo("maxPoolBackprop")},t.prototype.avgPool=function(t,e){return fo("avgPool")},t.prototype.avgPoolBackprop=function(t,e,n){return fo("avgPoolBackprop")},t.prototype.avgPool3d=function(t,e){return fo("avgPool3d")},t.prototype.avgPool3dBackprop=function(t,e,n){return fo("avgPool3dBackprop")},t.prototype.maxPool3d=function(t,e){return fo("maxPool3d")},t.prototype.maxPool3dBackprop=function(t,e,n,r){return fo("maxPool3dBackprop")},t.prototype.reshape=function(t,e){return fo("reshape")},t.prototype.cast=function(t,e){return fo("cast")},t.prototype.tile=function(t,e){return fo("tile")},t.prototype.pad=function(t,e,n){return fo("pad")},t.prototype.transpose=function(t,e){return fo("transpose")},t.prototype.gather=function(t,e,n){return fo("gather")},t.prototype.gatherND=function(t,e){return fo("gatherND")},t.prototype.scatterND=function(t,e,n){return fo("scatterND")},t.prototype.batchToSpaceND=function(t,e,n){return fo("batchToSpaceND")},t.prototype.spaceToBatchND=function(t,e,n){return fo("spaceToBatchND")},t.prototype.resizeBilinear=function(t,e,n,r){return fo("resizeBilinear")},t.prototype.resizeBilinearBackprop=function(t,e,n){return fo("resizeBilinearBackprop")},t.prototype.resizeNearestNeighbor=function(t,e,n,r){return fo("resizeNearestNeighbor")},t.prototype.resizeNearestNeighborBackprop=function(t,e,n){return fo("resizeNearestNeighborBackprop")},t.prototype.batchNormalization=function(t,e,n,r,o,a){return fo("batchNormalization")},t.prototype.localResponseNormalization4D=function(t,e,n,r,o){return fo("localResponseNormalization4D")},t.prototype.LRNGrad=function(t,e,n,r,o,a,i){return fo("LRNGrad")},t.prototype.multinomial=function(t,e,n,r){return fo("multinomial")},t.prototype.oneHot=function(t,e,n,r){return fo("oneHot")},t.prototype.cumsum=function(t,e,n,r){return fo("cumsum")},t.prototype.nonMaxSuppression=function(t,e,n,r,o){return fo("nonMaxSuppression")},t.prototype.fft=function(t){return fo("fft")},t.prototype.ifft=function(t){return fo("ifft")},t.prototype.complex=function(t,e){return fo("complex")},t.prototype.real=function(t){return fo("real")},t.prototype.imag=function(t){return fo("imag")},t.prototype.cropAndResize=function(t,e,n,r,o,a){return fo("cropAndResize")},t.prototype.depthToSpace=function(t,e,n){return fo("depthToSpace")},t.prototype.split=function(t,e,n){return fo("split")},t.prototype.sparseToDense=function(t,e,n,r){return fo("sparseToDense")},t.prototype.diag=function(t){return fo("diag")},t.prototype.fill=function(t,e,n){return fo("fill")},t.prototype.onesLike=function(t){return fo("onesLike")},t.prototype.zerosLike=function(t){return fo("zerosLike")},t.prototype.linspace=function(t,e,n){return fo("linspace")},t.prototype.dispose=function(){return fo("dispose")},t}();function fo(t){throw new Error("'"+t+"' not yet implemented or not found in the registry. Did you forget to import the kernel?")}function vo(t,e){for(var n=t.length,r=[],o=0;o<n;o++){var a=n-1-o,i=t[a]||1;(e[e.length-1-o]||1)>1&&1===i&&r.unshift(a)}return r}function mo(t,e){for(var n=[],r=0;r<e.length;r++){var o=t[t.length-r-1],a=e.length-r-1,i=e[a];(null==o||1===o&&i>1)&&n.unshift(a)}return n}function go(t,e){for(var n=[],r=Math.max(t.length,e.length),o=0;o<r;o++){var a=t[t.length-o-1];null==a&&(a=1);var i=e[e.length-o-1];if(null==i&&(i=1),1===a)n.unshift(i);else if(1===i)n.unshift(a);else{if(a!==i)throw Error("Operands could not be broadcast together with shapes "+t+" and "+e+".");n.unshift(a)}}return n}function xo(t,e,n,r,o,a,i){void 0===i&&(i="channelsLast");var s,u=Eo(e),c=u[0],l=u[1];if("channelsLast"===i)s=[c,l,t[3],t[3]];else{if("channelsFirst"!==i)throw new Error("Unknown dataFormat "+i);s=[c,l,t[1],t[1]]}return bo(t,s,n,r,o,a,!1,i)}function yo(t,e,n,r,o,a,i){void 0===i&&(i="NDHWC");var s,u,c=Ro(e),l=c[0],p=c[1],h=c[2];if("NDHWC"===i)u="channelsLast",s=[l,p,h,t[4],t[4]];else{if("NCDHW"!==i)throw new Error("Unknown dataFormat "+i);u="channelsFirst",s=[l,p,h,t[1],t[1]]}return wo(t,s,n,r,o,!1,u,a)}function bo(t,e,n,r,o,a,i,s){void 0===i&&(i=!1),void 0===s&&(s="channelsLast");var u=[-1,-1,-1,-1],c=u[0],l=u[1],p=u[2],h=u[3];if("channelsLast"===s)c=t[0],l=t[1],p=t[2],h=t[3];else{if("channelsFirst"!==s)throw new Error("Unknown dataFormat "+s);c=t[0],h=t[1],l=t[2],p=t[3]}var d,f=e[0],v=e[1],m=e[3],g=Eo(n),x=g[0],y=g[1],w=Eo(r),C=w[0],E=w[1],R=Io(f,C),I=Io(v,E),S=function(t,e,n,r,o,a,i,s){var u,c,l;if("number"==typeof t){u={top:t,bottom:t,left:t,right:t,type:0===t?"VALID":"NUMBER"};var p=function(t,e,n,r,o){null==r&&(r=Co(t,e,n));var a=t[1],i=ko((t[0]-e+2*r)/n+1,o);b(k(i),function(){return"The output # of rows ("+i+") must be an integer. Change the stride and/or zero pad parameters"});var s=ko((a-e+2*r)/n+1,o);return b(k(s),function(){return"The output # of columns ("+s+") must be an integer. Change the stride and/or zero pad parameters"}),[i,s]}([e,n],a,r,t,s);c=p[0],l=p[1]}else if("same"===t){c=Math.ceil(e/r),l=Math.ceil(n/o);var h=Math.max(0,(c-1)*r+a-e),d=Math.max(0,(l-1)*o+i-n),f=Math.floor(h/2),v=h-f,m=Math.floor(d/2);u={top:f,bottom:v,left:m,right:d-m,type:"SAME"}}else{if("valid"!==t)throw Error("Unknown padding parameter: "+t);u={top:0,bottom:0,left:0,right:0,type:"VALID"},c=Math.ceil((e-a+1)/r),l=Math.ceil((n-i+1)/o)}return{padInfo:u,outHeight:c,outWidth:l}}(o,l,p,x,y,R,I,a),A=S.padInfo,D=S.outHeight,N=S.outWidth,T=i?m*h:m;return"channelsFirst"===s?d=[c,T,D,N]:"channelsLast"===s&&(d=[c,D,N,T]),{batchSize:c,dataFormat:s,inHeight:l,inWidth:p,inChannels:h,outHeight:D,outWidth:N,outChannels:T,padInfo:A,strideHeight:x,strideWidth:y,filterHeight:f,filterWidth:v,effectiveFilterHeight:R,effectiveFilterWidth:I,dilationHeight:C,dilationWidth:E,inShape:t,outShape:d,filterShape:e}}function wo(t,e,n,r,o,a,i,s){void 0===a&&(a=!1),void 0===i&&(i="channelsLast");var u=[-1,-1,-1,-1,-1],c=u[0],l=u[1],p=u[2],h=u[3],d=u[4];if("channelsLast"===i)c=t[0],l=t[1],p=t[2],h=t[3],d=t[4];else{if("channelsFirst"!==i)throw new Error("Unknown dataFormat "+i);c=t[0],d=t[1],l=t[2],p=t[3],h=t[4]}var f,v=e[0],m=e[1],g=e[2],x=e[4],y=Ro(n),w=y[0],C=y[1],E=y[2],R=Ro(r),I=R[0],S=R[1],A=R[2],D=Io(v,I),N=Io(m,S),T=Io(g,A),F=function(t,e,n,r,o,a,i,s,u,c,l){var p,h,d,f;if("number"==typeof t){p={top:t,bottom:t,left:t,right:t,front:t,back:t,type:0===t?"VALID":"NUMBER"};var v=function(t,e,n,r,o,a){null==o&&(o=Co(t,e,r));var i=t[1],s=t[2],u=ko((t[0]-e+2*o)/r+1,a);b(k(u),function(){return"The output # of depths ("+u+") must be an integer. Change the stride and/or zero pad parameters"});var c=ko((i-e+2*o)/r+1,a);b(k(c),function(){return"The output # of rows ("+c+") must be an integer. Change the stride and/or zero pad parameters"});var l=ko((s-e+2*o)/r+1,a);return b(k(l),function(){return"The output # of columns ("+l+") must be an integer. Change the stride and/or zero pad parameters"}),[u,c,l,1]}([e,n,r,1],s,0,o,t,l);h=v[0],d=v[1],f=v[2]}else if("same"===t){var m=((h=Math.ceil(e/o))-1)*o+s-e,g=((d=Math.ceil(n/a))-1)*a+u-n,x=((f=Math.ceil(r/i))-1)*i+c-r,y=Math.floor(m/2),w=m-y,C=Math.floor(g/2),E=g-C,R=Math.floor(x/2);p={top:C,bottom:E,left:R,right:x-R,front:y,back:w,type:"SAME"}}else{if("valid"!==t)throw Error("Unknown padding parameter: "+t);p={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},h=Math.ceil((e-s+1)/o),d=Math.ceil((n-u+1)/a),f=Math.ceil((r-c+1)/i)}return{padInfo:p,outDepth:h,outHeight:d,outWidth:f}}(o,l,p,h,w,C,E,D,N,T,s),O=F.padInfo,_=F.outDepth,M=F.outHeight,B=F.outWidth,P=a?x*d:x;return"channelsFirst"===i?f=[c,P,_,M,B]:"channelsLast"===i&&(f=[c,_,M,B,P]),{batchSize:c,dataFormat:i,inDepth:l,inHeight:p,inWidth:h,inChannels:d,outDepth:_,outHeight:M,outWidth:B,outChannels:P,padInfo:O,strideDepth:w,strideHeight:C,strideWidth:E,filterDepth:v,filterHeight:m,filterWidth:g,effectiveFilterDepth:D,effectiveFilterHeight:N,effectiveFilterWidth:T,dilationDepth:I,dilationHeight:S,dilationWidth:A,inShape:t,outShape:f,filterShape:e}}function Co(t,e,n,r){void 0===r&&(r=1);var o=Io(e,r);return Math.floor((t[0]*(n-1)-n+o)/2)}function Eo(t){return"number"==typeof t?[t,t,t]:2===t.length?[t[0],t[1],1]:t}function Ro(t){return"number"==typeof t?[t,t,t]:t}function Io(t,e){return e<=1?t:t+(t-1)*(e-1)}function ko(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 So(t){var e=Eo(t),n=e[0],r=e[1],o=e[2];return 1===n&&1===r&&1===o}function Ao(t,e){return So(t)||So(e)}function Do(t){if("NHWC"===t)return"channelsLast";if("NCHW"===t)return"channelsFirst";throw new Error("Unknown dataFormat "+t)}function No(t,e,n){if("complex64"===e){if("complex64"===t.dtype)return t.clone();var r=zn(t.shape),o=t.toFloat(),a=n.complex(o,r);return r.dispose(),o.dispose(),a}if(!L(t.dtype,e))return _t.makeTensorFromDataId(t.dataId,t.shape,e);if("complex64"===t.dtype){var i=n.real(t);return a=i.cast(e),i.dispose(),a}if("int32"===e)return n.int(t);if("bool"===e){var s=Tn(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 To(t,e){return _t.makeTensorFromDataId(t.dataId,e,t.dtype)}function Fo(t,e,n){var r=(e-t)/(n-1),o=J(n,"float32");o[0]=t;for(var a=1;a<o.length;a++)o[a]=o[a-1]+r;return Fn(o,"float32")}exports.KernelBackend=ho,exports.DataStorage=po,exports.logSoftmax=lo,exports.softmax=co;var Oo=Object.freeze({castTensor:No,reshapeTensor:To,linspaceImpl:Fo,upcastType:It,axesAreInnerMostDims:vn,combineLocations:mn,computeOutAndReduceShapes:gn,expandShapeToKeepDim:xn,assertAxesAreInnerMostDims:yn,getAxesPermutation:bn,getUndoAxesPermutation:wn,getInnerMostAxes:Cn,getBroadcastDims:vo,getReductionAxes:mo,assertAndGetBroadcastShape:go,assertParamsConsistent:En,computeOutShape:Rn,computePool2DInfo:xo,computePool3DInfo:yo,computeConv2DInfo:bo,computeConv3DInfo:wo,computeDefaultPad:Co,tupleValuesAreOne:So,eitherStridesOrDilationsAreOne:Ao,convertConv2DDataFormat:Do});function _o(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 Mo(t,e){return{real:t[2*e],imag:t[2*e+1]}}function Bo(t,e,n,r){t[2*r]=e,t[2*r+1]=n}function Po(t,e,n){var r=(n?2:-2)*Math.PI*(t/e);return{real:Math.cos(r),imag:Math.sin(r)}}function Lo(t,e,n,r,o){for(var a=Array.from(e).map(function(t,e){return{score:t,boxIndex:e}}).filter(function(t){return t.score>o}).sort(function(t,e){return e.score-t.score}),i=[],s=0;s<a.length;s++){var u=a[s],c=u.score,l=u.boxIndex;if(c<o)break;for(var p=!1,h=i.length-1;h>=0;--h)if(Wo(t,l,i[h])>=r){p=!0;break}if(!p&&(i.push(l),i.length>=n))break}return Fn(i,"int32")}function Wo(t,e,n){var r=t.subarray(4*e,4*e+4),o=t.subarray(4*n,4*n+4),a=Math.min(r[0],r[2]),i=Math.min(r[1],r[3]),s=Math.max(r[0],r[2]),u=Math.max(r[1],r[3]),c=Math.min(o[0],o[2]),l=Math.min(o[1],o[3]),p=Math.max(o[0],o[2]),h=Math.max(o[1],o[3]),d=(s-a)*(u-i),f=(p-c)*(h-l);if(d<=0||f<=0)return 0;var v=Math.max(a,c),m=Math.max(i,l),g=Math.min(s,p),x=Math.min(u,h),y=Math.max(g-v,0)*Math.max(x-m,0);return y/(d+f-y)}function zo(t,e,n){var r=new Array(t.rank).fill(0),o=t.shape.slice();return e.map(function(e){o[n]=e;var a=t.slice(r,o);return r[n]+=e,a})}function Uo(t,e){for(var n=new Array(t.rank),r=0;r<n.length;r++)n[r]=t.shape[r]*e[r];var o=lr(n,t.dtype);for(r=0;r<o.values.length;++r){for(var a=o.indexToLoc(r),i=new Array(t.rank),s=0;s<i.length;s++)i[s]=a[s]%t.shape[s];var u=t.locToIndex(i);o.values[r]=t.values[u]}return o.toTensor()}function Vo(t,e,n,r,o){for(var a=e[e.length-1],i=[t.length/a,a],s=i[0],u=i[1],c=_(n,s*r),l=_("int32",s*r),p=0;p<s;p++){for(var h=p*u,d=t.subarray(h,h+u),f=[],v=0;v<d.length;v++)f.push({value:d[v],index:v});f.sort(function(t,e){return e.value-t.value});var m=p*r,g=c.subarray(m,m+r),x=l.subarray(m,m+r);for(v=0;v<r;v++)g[v]=f[v].value,x[v]=f[v].index}var y=e.slice();return y[y.length-1]=r,[Dn(c,y,n),Dn(l,y,"int32")]}function Go(t,e){for(var n=[],r=0;r<e.length;r++)e[r]&&n.push(r);var o=lr(t,"int32"),a=lr([n.length,t.length],"int32");for(r=0;r<n.length;r++){var i=o.indexToLoc(n[r]),s=r*t.length;a.values.set(i,s)}return a.toTensor()}exports.backend_util=Oo;var Ho=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    "},qo=function(t,e){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.variableNames=e.map(function(t,e){return"T"+e});var n=[];this.variableNames.forEach(function(t){n.push("vec4 v"+t+" = get"+t+"AtOutCoords();")});var r=this.variableNames.map(function(t){return"v"+t}).join(" + ");this.userCode="\n      void main() {\n        "+n.join("\n        ")+"\n\n        vec4 result = "+r+";\n        setOutput(result);\n      }\n    "},Ko=function(t,e,n){this.variableNames=["A"];var r=t.windowSize,o=t.batchSize,a=t.inSize,i=Math.ceil(a/r);n||this.variableNames.push("bestIndicesA"),this.outputShape=[o,i];var s="max"===e?">":"<",u=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode="\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int batch = coords[0];\n        int outIdx = coords[1];\n        int inOffset = outIdx * "+r+";\n\n        int bestIndex = inOffset;\n        float bestValue = getA(batch, bestIndex);\n\n        for (int i = 0; i < "+r+"; i++) {\n          int inIdx = "+u+";\n          float candidate = getA(batch, inIdx);\n          if (candidate "+s+" bestValue) {\n            bestValue = candidate;\n            bestIndex = inIdx;\n          }\n        }\n        setOutput(float(bestIndex));\n      }\n    "};function jo(t,e){return["x","y","z","w","u","v"].slice(0,e).map(function(e){return t+"."+e})}function Xo(t,e){return 1===e?[t]:jo(t,e)}function $o(){var t,e,n,r,o,a,i,s,c,l;return 2===u().getNumber("WEBGL_VERSION")?(t="#version 300 es",e="in",n="out",r="in",o="texture",a="outputColor",i="out vec4 outputColor;",s="\n      bool isnan_custom(float val) {\n        return (val > 0.0 || val < 0.0) ? false : val != 0.0;\n      }\n\n      bvec4 isnan_custom(vec4 val) {\n        return bvec4(isnan_custom(val.x),\n          isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));\n      }\n\n      #define isnan(value) isnan_custom(value)\n    ",c="",l="\n      #define round(value) newRound(value)\n      int newRound(float value) {\n        return int(floor(value + 0.5));\n      }\n\n      ivec4 newRound(vec4 value) {\n        return ivec4(floor(value + vec4(0.5)));\n      }\n    "):(t="",e="attribute",n="varying",r="varying",o="texture2D",a="gl_FragColor",i="",s="\n      #define isnan(value) isnan_custom(value)\n      bool isnan_custom(float val) {\n        return (val > 0. || val < 1. || val == 0.) ? false : true;\n      }\n      bvec4 isnan_custom(vec4 val) {\n        return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\n      }\n    ",c="\n      uniform float INFINITY;\n\n      bool isinf(float val) {\n        return abs(val) == INFINITY;\n      }\n      bvec4 isinf(vec4 val) {\n        return equal(abs(val), vec4(INFINITY));\n      }\n    ",l="\n      int round(float value) {\n        return int(floor(value + 0.5));\n      }\n\n      ivec4 round(vec4 value) {\n        return ivec4(floor(value + vec4(0.5)));\n      }\n    "),{version:t,attribute:e,varyingVs:n,varyingFs:r,texture2D:o,output:a,defineOutput:i,defineSpecialNaN:s,defineSpecialInf:c,defineRound:l}}function Yo(t,e,n){void 0===n&&(n="index");var r=X(e);return r.map(function(e,o){return"int "+t[o]+" = "+n+" / "+e+"; "+(o===r.length-1?"int "+t[o+1]+" = "+n+" - "+t[o]+" * "+e:"index -= "+t[o]+" * "+e)+";"}).join("")}function Qo(t){var e=X(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 Jo="\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 Zo(t,e,n,r){var o=[];t.forEach(function(t){var e=R(t.shapeInfo.logicalShape);t.shapeInfo.isUniform?o.push("uniform float "+t.name+(e>1?"["+e+"]":"")+";"):(o.push("uniform sampler2D "+t.name+";"),o.push("uniform int offset"+t.name+";"))});var a,i,s=o.join("\n"),u=t.map(function(t){return function(t,e,n){void 0===n&&(n=!1);var r="";r+=n?ea(t):ta(t);var o=t.shapeInfo.logicalShape,a=e.logicalShape;return o.length<=a.length&&(r+=n?function(t,e){var n,r=t.name,o=r.charAt(0).toUpperCase()+r.slice(1),a="get"+o+"AtOutCoords",i=t.shapeInfo.logicalShape.length,s=e.logicalShape.length,u=vo(t.shapeInfo.logicalShape,e.logicalShape),c=ua(s),l=s-i,p=["x","y","z","w","u","v"];n=0===i?"":s<2&&u.length>=1?"coords = 0;":u.map(function(t){return"coords."+p[t+l]+" = 0;"}).join("\n");var h;h=s<2&&i>0?"coords":t.shapeInfo.logicalShape.map(function(t,e){return"coords."+p[e+l]}).join(", ");var d="return outputValue;",f=1===R(t.shapeInfo.logicalShape),v=1===R(e.logicalShape);if(1!==i||f||v){if(f&&!v)d=1===s?"\n        return vec4(outputValue.x, outputValue.x, 0., 0.);\n      ":"\n        return vec4(outputValue.x);\n      ";else if(u.length){var m=i-2,g=i-1;u.indexOf(m)>-1&&u.indexOf(g)>-1?d="return vec4(outputValue.x);":u.indexOf(m)>-1?d="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":u.indexOf(g)>-1&&(d="return vec4(outputValue.xx, outputValue.zz);")}}else d="\n      return vec4(outputValue.xy, outputValue.xy);\n    ";return"\n    vec4 "+a+"() {\n      "+c+" coords = getOutputCoords();\n      "+n+"\n      vec4 outputValue = get"+o+"("+h+");\n      "+d+"\n    }\n  "}(t,e):function(t,e){var n=t.name,r=n.charAt(0).toUpperCase()+n.slice(1),o="get"+r+"AtOutCoords",a=e.texShape,i=t.shapeInfo.texShape,s=t.shapeInfo.logicalShape.length,u=e.logicalShape.length;if(!t.shapeInfo.isUniform&&s===u&&null==t.shapeInfo.flatOffset&&I(i,a))return"\n      float "+o+"() {\n        return sampleTexture("+n+", resultUV);\n      }\n    ";var c=ua(u),l=vo(t.shapeInfo.logicalShape,e.logicalShape),p=u-s,h=["x","y","z","w","u","v"];return"\n    float "+o+"() {\n      "+c+" coords = getOutputCoords();\n      "+(0===s?"":u<2&&l.length>=1?"coords = 0;":l.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"),c=e.texShape,l=$o(),p="\n    float sampleTexture(sampler2D textureSampler, vec2 uv) {\n      return "+l.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    "+na+"\n    "+ra+"\n    "+oa+"\n  "}(l);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(I(t,e))return"\n      ivec2 getOutputCoords() {\n        return 2 * ivec2(resultUV.yx * vec2("+n[0]+", "+n[1]+"));\n      }\n    ";var r=Math.ceil(t[1]/2);return"\n    ivec2 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2("+n[0]+", "+n[1]+"));\n\n      int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n      int r = 2 * (index / "+r+");\n      int c = imod(index, "+r+") * 2;\n\n      return ivec2(r, c);\n    }\n  "}(t,e);case 3:return n=t,r=e,o=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],i=(a=Math.ceil(n[2]/2))*Math.ceil(n[1]/2),"\n    ivec3 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2("+o[0]+", "+o[1]+"));\n      int index = resTexRC.x * "+o[1]+" + resTexRC.y;\n\n      int b = index / "+i+";\n      index -= b * "+i+";\n\n      int r = 2 * (index / "+a+");\n      int c = imod(index, "+a+") * 2;\n\n      return ivec3(b, r, c);\n    }\n  ";default:return function(t,e){for(var n=[Math.ceil(e[0]/2),Math.ceil(e[1]/2)],r=Math.ceil(t[t.length-1]/2),o=r*Math.ceil(t[t.length-2]/2),a=o,i="",s="b, r, c",u=2;u<t.length-1;u++)i="\n      int b"+u+" = index / "+(a*=t[t.length-u-1])+";\n      index -= b"+u+" * "+a+";\n    "+i,s="b"+u+", "+s;return"\n    ivec"+t.length+" getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2("+n[0]+", "+n[1]+"));\n      int index = resTexRC.x * "+n[1]+" + resTexRC.y;\n\n      "+i+"\n\n      int b = index / "+o+";\n      index -= b * "+o+";\n\n      int r = 2 * (index / "+r+");\n      int c = imod(index, "+r+") * 2;\n\n      return ivec"+t.length+"("+s+");\n    }\n  "}(t,e)}var n,r,o,a,i}(e.logicalShape,c),i="\n    void setOutput(vec4 val) {\n      "+l.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 I(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=Yo(["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=Yo(["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=Yo(["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=Yo(["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,c),i="\n    void setOutput(float val) {\n      "+l.output+" = vec4(val, 0, 0, 0);\n    }\n  "),r&&(h+=aa),[h,p,i,s,a,u,n].join("\n")}function ta(t){var e=t.shapeInfo.logicalShape;switch(e.length){case 0:return function(t){var e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1);if(t.shapeInfo.isUniform)return"float "+n+"() {return "+e+";}";var r=t.shapeInfo.texShape,o=r[0],a=r[1];if(1===o&&1===a)return"\n      float "+n+"() {\n        return sampleTexture("+e+", halfCR);\n      }\n    ";var i=t.shapeInfo.texShape;return"\n    float "+n+"() {\n      vec2 uv = uvFromFlat("+i[0]+", "+i[1]+", "+ia(e)+");\n      return sampleTexture("+e+", uv);\n    }\n  "}(t);case 1:return function(t){var e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1);if(t.shapeInfo.isUniform)return"\n      float "+n+"(int index) {\n        "+sa(t)+"\n      }\n    ";var r=t.shapeInfo.texShape,o=r[0],a=r[1];if(1===a&&1===o)return"\n      float "+n+"(int index) {\n        return sampleTexture("+e+", halfCR);\n      }\n    ";var i=ia(e);return 1===a?"\n      float "+n+"(int index) {\n        vec2 uv = vec2(0.5, (float(index + "+i+") + 0.5) / "+o+".0);\n        return sampleTexture("+e+", uv);\n      }\n    ":1===o?"\n      float "+n+"(int index) {\n        vec2 uv = vec2((float(index + "+i+") + 0.5) / "+a+".0, 0.5);\n        return sampleTexture("+e+", uv);\n      }\n    ":"\n    float "+n+"(int index) {\n      vec2 uv = uvFromFlat("+o+", "+a+", index + "+i+");\n      return sampleTexture("+e+", uv);\n    }\n  "}(t);case 2:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=t.shapeInfo.texShape;if(null!=o&&I(e,o)){var a=o[0];return"\n    float "+r+"(int row, int col) {\n      vec2 uv = (vec2(col, row) + halfCR) / vec2("+o[1]+".0, "+a+".0);\n      return sampleTexture("+n+", uv);\n    }\n  "}var i=O(e),s=i.newShape,u=i.keptDims,c=s;if(c.length<e.length)return"\n      "+ta(ca(t,c))+"\n      float "+r+"(int row, int col) {\n        return "+r+"("+la(["row","col"],u)+");\n      }\n    ";if(t.shapeInfo.isUniform)return"\n      float "+r+"(int row, int col) {\n        int index = round(dot(vec2(row, col), vec2("+e[1]+", 1)));\n        "+sa(t)+"\n      }\n    ";var l=o[0],p=o[1],h=ia(n);return 1===p?"\n    float "+r+"(int row, int col) {\n      float index = dot(vec3(row, col, "+h+"), vec3("+e[1]+", 1, 1));\n      vec2 uv = vec2(0.5, (index + 0.5) / "+l+".0);\n      return sampleTexture("+n+", uv);\n    }\n  ":1===l?"\n    float "+r+"(int row, int col) {\n      float index = dot(vec3(row, col, "+h+"), vec3("+e[1]+", 1, 1));\n      vec2 uv = vec2((index + 0.5) / "+p+".0, 0.5);\n      return sampleTexture("+n+", uv);\n    }\n  ":"\n  float "+r+"(int row, int col) {\n    // Explicitly use integer operations as dot() only works on floats.\n    int index = row * "+e[1]+" + col + "+h+";\n    vec2 uv = uvFromFlat("+l+", "+p+", index);\n    return sampleTexture("+n+", uv);\n  }\n"}(t);case 3:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=e[1]*e[2],a=e[2],i=O(e),s=i.newShape,u=i.keptDims,c=s;if(c.length<e.length)return"\n        "+ta(ca(t,c))+"\n        float "+r+"(int row, int col, int depth) {\n          return "+r+"("+la(["row","col","depth"],u)+");\n        }\n      ";if(t.shapeInfo.isUniform)return"\n      float "+r+"(int row, int col, int depth) {\n        int index = round(dot(vec3(row, col, depth),\n                          vec3("+o+", "+a+", 1)));\n        "+sa(t)+"\n      }\n    ";var l=t.shapeInfo.texShape,p=l[0],h=l[1],d=t.shapeInfo.flatOffset;return h===o&&null==d?"\n        float "+r+"(int row, int col, int depth) {\n          float texR = float(row);\n          float texC = dot(vec2(col, depth), vec2("+a+", 1));\n          vec2 uv = (vec2(texC, texR) + halfCR) /\n                     vec2("+h+".0, "+p+".0);\n          return sampleTexture("+n+", uv);\n        }\n      ":h===a&&null==d?"\n    float "+r+"(int row, int col, int depth) {\n      float texR = dot(vec2(row, col), vec2("+e[1]+", 1));\n      float texC = float(depth);\n      vec2 uv = (vec2(texC, texR) + halfCR) / vec2("+h+".0, "+p+".0);\n      return sampleTexture("+n+", uv);\n    }\n  ":"\n      float "+r+"(int row, int col, int depth) {\n        // Explicitly use integer operations as dot() only works on floats.\n        int index = row * "+o+" + col * "+a+" + depth + "+ia(n)+";\n        vec2 uv = uvFromFlat("+p+", "+h+", index);\n        return sampleTexture("+n+", uv);\n      }\n  "}(t);case 4:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=e[3],a=e[2]*o,i=e[1]*a,s=O(e),u=s.newShape,c=s.keptDims;if(u.length<e.length)return"\n      "+ta(ca(t,u))+"\n      float "+r+"(int row, int col, int depth, int depth2) {\n        return "+r+"("+la(["row","col","depth","depth2"],c)+");\n      }\n    ";if(t.shapeInfo.isUniform)return"\n      float "+r+"(int row, int col, int depth, int depth2) {\n        int index = round(dot(vec4(row, col, depth, depth2),\n                          vec4("+i+", "+a+", "+o+", 1)));\n        "+sa(t)+"\n      }\n    ";var l=t.shapeInfo.flatOffset,p=t.shapeInfo.texShape,h=p[0],d=p[1];return d===i&&null==l?"\n      float "+r+"(int row, int col, int depth, int depth2) {\n        float texR = float(row);\n        float texC =\n            dot(vec3(col, depth, depth2),\n                vec3("+a+", "+o+", 1));\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                   vec2("+d+".0, "+h+".0);\n        return sampleTexture("+n+", uv);\n      }\n    ":d===o&&null==l?"\n      float "+r+"(int row, int col, int depth, int depth2) {\n        float texR = dot(vec3(row, col, depth),\n                         vec3("+e[1]*e[2]+", "+e[2]+", 1));\n        float texC = float(depth2);\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                  vec2("+d+".0, "+h+".0);\n        return sampleTexture("+n+", uv);\n      }\n    ":"\n    float "+r+"(int row, int col, int depth, int depth2) {\n      // Explicitly use integer operations as dot() only works on floats.\n      int index = row * "+i+" + col * "+a+" +\n          depth * "+o+" + depth2;\n      vec2 uv = uvFromFlat("+h+", "+d+", index + "+ia(n)+");\n      return sampleTexture("+n+", uv);\n    }\n  "}(t);case 5:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=e[4],a=e[3]*o,i=e[2]*a,s=e[1]*i,u=O(e),c=u.newShape,l=u.keptDims;if(c.length<e.length)return"\n      "+ta(ca(t,c))+"\n      float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n        return "+r+"("+la(["row","col","depth","depth2","depth3"],l)+");\n      }\n    ";if(t.shapeInfo.isUniform)return"\n      float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n        float index = dot(\n          vec4(row, col, depth, depth2),\n          vec4("+s+", "+i+", "+a+", "+o+")) +\n          depth3;\n        "+sa(t)+"\n      }\n    ";var p=t.shapeInfo.flatOffset,h=t.shapeInfo.texShape,d=h[0],f=h[1];return f===s&&null==p?"\n      float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n        int texR = row;\n        float texC = dot(vec4(col, depth, depth2, depth3),\n                         vec4("+i+", "+a+", "+o+", 1));\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                   vec2("+f+".0, "+d+".0);\n        return sampleTexture("+n+", uv);\n      }\n    ":f===o&&null==p?"\n      float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n        float texR = dot(\n          vec4(row, col, depth, depth2),\n          vec4("+e[1]*e[2]*e[3]+",\n               "+e[2]*e[3]+", "+e[3]+", 1));\n        int texC = depth3;\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                  vec2("+f+".0, "+d+".0);\n        return sampleTexture("+n+", uv);\n      }\n    ":"\n    float "+r+"(int row, int col, int depth, int depth2, int depth3) {\n      // Explicitly use integer operations as dot() only works on floats.\n      int index = row * "+s+" + col * "+i+" + depth * "+a+" +\n          depth2 * "+o+" + depth3 + "+ia(n)+";\n      vec2 uv = uvFromFlat("+d+", "+f+", index);\n      return sampleTexture("+n+", uv);\n    }\n  "}(t);case 6:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=O(e),a=o.newShape,i=o.keptDims;if(a.length<e.length)return"\n      "+ta(ca(t,a))+"\n      float "+r+"(int row, int col, int depth,\n                    int depth2, int depth3, int depth4) {\n        return "+r+"("+la(["row","col","depth","depth2","depth3","depth4"],i)+");\n      }\n    ";var s=e[5],u=e[4]*s,c=e[3]*u,l=e[2]*c,p=e[1]*l;if(t.shapeInfo.isUniform)return"\n      float "+r+"(int row, int col, int depth,\n                  int depth2, int depth3, int depth4) {\n        int index = round(dot(\n          vec4(row, col, depth, depth2),\n          vec4("+p+", "+l+", "+c+", "+u+")) +\n          dot(\n            vec2(depth3, depth4),\n            vec2("+s+", 1)));\n        "+sa(t)+"\n      }\n    ";var h=t.shapeInfo.flatOffset,d=t.shapeInfo.texShape,f=d[0],v=d[1];return v===p&&null==h?"\n      float "+r+"(int row, int col, int depth,\n                    int depth2, int depth3, int depth4) {\n        int texR = row;\n        float texC = dot(vec4(col, depth, depth2, depth3),\n          vec4("+l+", "+c+", "+u+", "+s+")) +\n               float(depth4);\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                   vec2("+v+".0, "+f+".0);\n        return sampleTexture("+n+", uv);\n      }\n    ":v===s&&null==h?"\n      float "+r+"(int row, int col, int depth,\n                    int depth2, int depth3, int depth4) {\n        float texR = dot(vec4(row, col, depth, depth2),\n          vec4("+e[1]*e[2]*e[3]*e[4]+",\n               "+e[2]*e[3]*e[4]+",\n               "+e[3]*e[4]+",\n               "+e[4]+")) + float(depth3);\n        int texC = depth4;\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                  vec2("+v+".0, "+f+".0);\n        return sampleTexture("+n+", uv);\n      }\n    ":"\n    float "+r+"(int row, int col, int depth,\n                  int depth2, int depth3, int depth4) {\n      // Explicitly use integer operations as dot() only works on floats.\n      int index = row * "+p+" + col * "+l+" + depth * "+c+" +\n          depth2 * "+u+" + depth3 * "+s+" + depth4 + "+ia(n)+";\n      vec2 uv = uvFromFlat("+f+", "+v+", index);\n      return sampleTexture("+n+", uv);\n    }\n  "}(t);default:throw new Error(e.length+"-D input sampling is not yet supported")}}function ea(t){var e;switch(t.shapeInfo.logicalShape.length){case 0:return"\n    vec4 "+("get"+(e=t.name).charAt(0).toUpperCase()+e.slice(1))+"() {\n      return "+$o().texture2D+"("+e+", halfCR);\n    }\n  ";case 1:return function(t){var e=t.name,n="get"+e.charAt(0).toUpperCase()+e.slice(1),r=t.shapeInfo.texShape,o=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)],a=$o();return"\n    vec4 "+n+"(int index) {\n      vec2 uv = packedUVfrom1D(\n        "+o[0]+", "+o[1]+", index);\n      return "+a.texture2D+"("+e+", uv);\n    }\n  "}(t);case 2:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=t.shapeInfo.texShape,a=o[0],i=o[1],s=$o();if(null!=o&&I(e,o))return"\n      vec4 "+r+"(int row, int col) {\n        vec2 uv = (vec2(col, row) + halfCR) / vec2("+i+".0, "+a+".0);\n\n        return "+s.texture2D+"("+n+", uv);\n      }\n    ";var u=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)];return"\n    vec4 "+r+"(int row, int col) {\n      vec2 uv = packedUVfrom2D("+Math.ceil(e[1]/2)+", "+u[0]+", "+u[1]+", row, col);\n      return "+s.texture2D+"("+n+", uv);\n    }\n  "}(t);case 3:return function(t){var e=t.shapeInfo.logicalShape,n=t.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),o=t.shapeInfo.texShape,a=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)];if(1===e[0])return"\n        "+ea(ca(t,e.slice(1)))+"\n        vec4 "+r+"(int b, int row, int col) {\n          return "+r+"("+la(["b","row","col"],[1,2])+");\n        }\n      ";var i=a[0],s=a[1],u=Math.ceil(e[2]/2);return"\n    vec4 "+r+"(int b, int row, int col) {\n      vec2 uv = packedUVfrom3D(\n        "+i+", "+s+", "+u*Math.ceil(e[1]/2)+", "+u+", b, row, col);\n      return "+$o().texture2D+"("+n+", uv);\n    }\n  "}(t);default:return function(t){for(var e=t.shapeInfo.logicalShape,n=e.length,r=t.name,o="get"+r.charAt(0).toUpperCase()+r.slice(1),a=t.shapeInfo.texShape,i=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],s=i[0],u=i[1],c=Math.ceil(e[n-1]/2),l=c*Math.ceil(e[n-2]/2),p="int b, int row, int col",h="b * "+l+" + (row / 2) * "+c+" + (col / 2)",d=2;d<n-1;d++)p="int b"+d+", "+p,h="b"+d+" * "+(l*=e[n-d-1])+" + "+h;return"\n    vec4 "+o+"("+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 "+$o().texture2D+"("+r+", uv);\n    }\n  "}(t)}}var na="\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",ra="\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",oa="\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",aa="\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 ia(t){return"offset"+t}function sa(t){var e=t.name,n=R(t.shapeInfo.logicalShape);return n<2?"return "+e+";":"\n    for (int i = 0; i < "+n+"; i++) {\n      if (i == index) {\n        return "+e+"[i];\n      }\n    }\n  "}function ua(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 ca(t,e){var n=JSON.parse(JSON.stringify(t));return n.shapeInfo.logicalShape=e,n}function la(t,e){return e.map(function(e){return t[e]}).join(", ")}var pa=function(t,e,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,b(t.length>2,function(){return"Packed arg"+(n.charAt(0).toUpperCase()+n.slice(1))+" supports only inputs with rank above 2."});var o=t[t.length-1],a=Math.ceil(o/e);this.outputShape=t.slice(0,-1),a>1&&this.outputShape.push(a),r||this.variableNames.push("bestIndicesA");var i,s,u=this.outputShape,c=u.length,l=ua(c),p=Xo("coords",c);if(1===a){var h=ua(s=c+1);i="\n        "+h+" sourceLocR = "+h+"("+p.join()+", 0);\n        ++"+p[c-1]+";\n        "+h+" sourceLocG = "+h+"("+p.join()+", 0);\n        ++"+p[c-2]+";\n        "+h+" sourceLocA = "+h+"("+p.join()+", 0);\n        --"+p[c-1]+";\n        "+h+" sourceLocB = "+h+"("+p.join()+", 0);\n        --"+p[c-2]+";"}else s=c,i="\n        "+l+" sourceLocR = coords;\n        ++"+p[c-1]+";\n        "+l+" sourceLocG = coords;\n        ++"+p[c-2]+";\n        "+l+" sourceLocA = coords;\n        --"+p[c-1]+";\n        "+l+" sourceLocB = coords;\n        --"+p[c-2]+";";var d=["x","y","z","w","u","v"].slice(0,s),f="."+d[s-1],v=d.map(function(t){return"int "+t}),m=Xo("sourceLocR",s-1).concat("inIdx.r"),g=Xo("sourceLocG",s-1).concat("inIdx.g"),x=Xo("sourceLocB",s-1).concat("inIdx.b"),y=Xo("sourceLocA",s-1).concat("inIdx.a"),w="max"===n?"greaterThan":"lessThan",C=r?"":"\n          inIdx = round(vec4(getBestIndicesAChannel("+m.join()+"),\n                             getBestIndicesAChannel("+g.join()+"),\n                             getBestIndicesAChannel("+x.join()+"),\n                             getBestIndicesAChannel("+y.join()+")));",E="vec4(\n            getAChannel("+m.join()+"),\n            hasNextCol ? getAChannel("+g.join()+") : 0.,\n            hasNextRow ? getAChannel("+x.join()+") : 0.,\n            hasNextRow && hasNextCol ? getAChannel("+y.join()+") : 0.)",R=r?"":"\n      float getBestIndicesAChannel("+v.join()+") {\n        return getChannel(getBestIndicesA("+d.join()+"),\n                                          vec2("+d.slice(-2).join()+"));\n      }";this.userCode="\n      float getAChannel("+v.join()+") {\n        return getChannel(getA("+d.join()+"),\n                               vec2("+d.slice(-2).join()+"));\n      }\n      "+R+"\n      void main() {\n        "+l+" coords = getOutputCoords();\n        bool hasNextCol = "+p[c-1]+" < "+(u[c-1]-1)+";\n        bool hasNextRow = "+p[c-2]+" < "+(u[c-2]-1)+";\n        "+i+"\n        ivec4 srcIdx = ivec4(sourceLocR"+f+", sourceLocG"+f+",\n          sourceLocB"+f+", sourceLocA"+f+") * "+e+";\n        ivec4 inIdx = srcIdx;\n        vec4 bestIndex = vec4(inIdx);\n        vec4 bestValue = "+E+";\n\n        for (int i = 0; i < "+e+"; i++) {\n          inIdx = srcIdx;\n          "+C+"\n          vec4 candidate = "+E+";\n          bvec4 nan = isnan(candidate);\n          bvec4 replace = bvec4(\n            vec4("+w+"(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));\n\n          bestValue = vec4(replace.x  ? candidate.x : bestValue.x,\n                           replace.y  ? candidate.y : bestValue.y,\n                           replace.z  ? candidate.z : bestValue.z,\n                           replace.w  ? candidate.w : bestValue.w);\n          bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));\n          srcIdx++;\n        }\n        setOutput(bestIndex);\n      }\n    "},ha=function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,o=t.strideWidth,a=t.dilationHeight,i=t.dilationWidth,s=t.effectiveFilterHeight,u=t.effectiveFilterWidth,c=s-1-t.padInfo.top,l=u-1-t.padInfo.left,p=1/(e*n);this.userCode="\n      const ivec2 pads = ivec2("+c+", "+l+");\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+= "+i+") {\n            float dyC = float(dyCCorner + wC) / "+o+".0;\n\n            if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n                fract(dyC) > 0.0) {\n              continue;\n            }\n            int idyC = int(dyC);\n\n            float dyValue = getDy(b, idyR, idyC, d);\n\n            dotProd += dyValue * avgMultiplier;\n          }\n        }\n        setOutput(dotProd);\n      }\n    "},da=function(t){this.variableNames=["dy"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,r=t.filterWidth,o=t.strideDepth,a=t.strideHeight,i=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,c=t.dilationWidth,l=t.effectiveFilterDepth,p=t.effectiveFilterHeight,h=t.effectiveFilterWidth,d=l-1-t.padInfo.front,f=p-1-t.padInfo.top,v=h-1-t.padInfo.left,m=1/(e*n*r);this.userCode="\n      const ivec3 pads = ivec3("+d+", "+f+", "+v+");\n      const float avgMultiplier = float("+m+");\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 < "+l+";\n            wD += "+s+") {\n          float dyD = float(dyDCorner + wD) / "+o+".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 += "+c+") {\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(batch, idyD, idyR, idyC, ch);\n\n              dotProd += dyValue * avgMultiplier;\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    "},fa=function(t,e,n,r,o,a){this.outputShape=[],this.variableNames=["x","mean","variance"],go(t,e),go(t,n);var i="0.0";null!=r&&(go(t,r),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");var s="1.0";null!=o&&(go(t,o),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n      void main() {\n        float x = getXAtOutCoords();\n        float mean = getMeanAtOutCoords();\n        float variance = getVarianceAtOutCoords();\n        float offset = "+i+";\n        float scale = "+s+";\n        float inv = scale * inversesqrt(variance + float("+a+"));\n        setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n      }\n    "},va=function(t,e,n,r,o,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],go(t,e),go(t,n);var i="vec4(0.0)";null!=r&&(go(t,r),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");var s="vec4(1.0)";null!=o&&(go(t,o),this.variableNames.push("scale"),s="getScaleAtOutCoords()"),this.outputShape=t,this.userCode="\n      void main() {\n        vec4 offset = "+i+";\n        vec4 scale = "+s+";\n\n        vec4 x = getXAtOutCoords();\n        vec4 mean = getMeanAtOutCoords();\n        vec4 variance = getVarianceAtOutCoords();\n\n        vec4 inv = scale * inversesqrt(variance + vec4("+a+"));\n\n        setOutput((x - mean) * inv + offset);\n      }\n    "},ma="return areal * breal - aimag * bimag;",ga="return areal * bimag + aimag * breal;",xa=function(t,e,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=go(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    "},ya="return a + b;",ba="return a - b;",wa="return a * b;",Ca="return (a < 0.) ? b * a : a;",Ea=function(t,e,n){this.variableNames=["A","B"],this.outputShape=go(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    "},Ra="\n  vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n  return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n",Ia=function(t,e,n,r){void 0===r&&(r=!1),this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=go(e,n);var o=this.outputShape.length,a="";if(r)if(0===o||1===R(this.outputShape))a="\n          result.y = 0.;\n          result.z = 0.;\n          result.w = 0.;\n        ";else if(a="\n          "+ua(o)+" coords = getOutputCoords();\n        ",1===o)a+="\n            result.y = (coords + 1) >= "+this.outputShape[0]+" ? 0. : result.y;\n            result.z = 0.;\n            result.w = 0.;\n          ";else{var i=Xo("coords",o);a+="\n            bool nextRowOutOfBounds =\n              ("+i[o-2]+" + 1) >= "+this.outputShape[o-2]+";\n            bool nextColOutOfBounds =\n              ("+i[o-1]+" + 1) >= "+this.outputShape[o-1]+";\n            result.y = nextColOutOfBounds ? 0. : result.y;\n            result.z = nextRowOutOfBounds ? 0. : result.z;\n            result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n          "}this.userCode="\n      vec4 binaryOperation(vec4 a, vec4 b) {\n        "+t+"\n      }\n\n      void main() {\n        vec4 a = getAAtOutCoords();\n        vec4 b = getBAtOutCoords();\n\n        vec4 result = binaryOperation(a, b);\n        "+a+"\n\n        setOutput(result);\n      }\n    "},ka=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,o){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(o,"minVal"),n.maxLoc=r.getUniformLocationNoThrow(o,"maxVal")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e)}},t}(),Sa=function(){function t(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.userCode="\n      uniform float minVal;\n      uniform float maxVal;\n\n      void main() {\n        vec4 value = getAAtOutCoords();\n\n        if (any(isnan(value))) {\n          setOutput(value);\n          return;\n        }\n\n        setOutput(clamp(value, vec4(minVal), vec4(maxVal)));\n      }\n    "}return t.prototype.getCustomSetupFunc=function(t,e){var n=this;return function(r,o){null==n.minLoc&&(n.minLoc=r.getUniformLocationNoThrow(o,"minVal"),n.maxLoc=r.getUniformLocationNoThrow(o,"maxVal")),r.gl.uniform1f(n.minLoc,t),r.gl.uniform1f(n.maxLoc,e)}},t}(),Aa=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    "},Da=function(t){this.outputShape=[],this.outputShape=Rn(t,1),this.variableNames=t.map(function(t,e){return"T"+e});var e=new Array(t.length-1);e[0]=t[0][1];for(var n=1;n<e.length;n++)e[n]=e[n-1]+t[n][1];var r=["if (yC < "+e[0]+") setOutput(getT0(yR, yC));"];for(n=1;n<e.length;n++){var o=e[n-1];r.push("else if (yC < "+e[n]+") setOutput(getT"+n+"(yR, yC-"+o+"));")}var a=e.length,i=e[e.length-1];r.push("else setOutput(getT"+a+"(yR, yC-"+i+"));"),this.userCode="\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int yR = coords.x;\n        int yC = coords.y;\n\n        "+r.join("\n        ")+"\n      }\n    "},Na=function(t,e){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=Rn(t,e);var n=this.outputShape,r=n.length,o=ua(r),a=Xo("coords",r),i=["x","y","z","w","u","v"].slice(0,r);this.variableNames=t.map(function(t,e){return"T"+e});var s=new Array(t.length-1);s[0]=t[0][e];for(var u=1;u<s.length;u++)s[u]=s[u-1]+t[u][e];var c=i[e],l=i.slice(-2),p=i.join(),h="if ("+c+" < "+s[0]+") {\n        return getChannel(\n            getT0("+p+"), vec2("+l.join()+"));\n        }";for(u=1;u<s.length;u++){var d=s[u-1];h+="\n        if ("+c+" < "+s[u]+"  && "+c+" >= "+s[u-1]+") {\n          return getChannel(\n            getT"+u+"("+Ta(i,c,d)+"),\n            vec2("+Ta(l,c,d)+"));\n        }"}var f=s.length,v=s[s.length-1];h+="\n        return getChannel(\n          getT"+f+"("+Ta(i,c,v)+"),\n          vec2("+Ta(l,c,v)+"));",this.userCode="\n      float getValue("+i.map(function(t){return"int "+t})+") {\n        "+h+"\n      }\n\n      void main() {\n        "+o+" 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 Ta(t,e,n){var r=t.indexOf(e);return t.map(function(t,e){return e===r?t+" - "+n:t}).join()}var Fa=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,n=t.strideWidth,r=t.padInfo.top,o=t.padInfo.left,a="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+" - "+o+";\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    "},Oa=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,o=t.strideWidth,a="channelsLast"===t.dataFormat,i=e-1-t.padInfo.top,s=n-1-t.padInfo.left,u=a?1:2,c=a?2:3,l=a?3:1;this.userCode="\n      const ivec2 pads = ivec2("+i+", "+s+");\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d1 = coords["+l+"];\n\n        ivec2 dyCorner = ivec2(coords["+u+"], coords["+c+"]) - pads;\n        int dyRCorner = dyCorner.x;\n        int dyCCorner = dyCorner.y;\n\n        // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        for (int wR = 0; wR < "+e+"; wR++) {\n          float dyR = float(dyRCorner + wR) / "+r+".0;\n\n          if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          int wRPerm = "+e+" - 1 - wR;\n\n          for (int wC = 0; wC < "+n+"; wC++) {\n            float dyC = float(dyCCorner + wC) / "+o+".0;\n\n            if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n                fract(dyC) > 0.0) {\n              continue;\n            }\n            int idyC = int(dyC);\n\n            int wCPerm = "+n+" - 1 - wC;\n\n            for (int d2 = 0; d2 < "+t.outChannels+"; d2++) {\n\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    "},_a=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideDepth,n=t.strideHeight,r=t.strideWidth,o=t.padInfo.front,a=t.padInfo.top,i=t.padInfo.left;this.userCode="\n      void main() {\n        ivec5 coords = getOutputCoords();\n        int wF = coords.x;\n        int wR = coords.y;\n        int wC = coords.z;\n        int d1 = coords.w;\n        int d2 = coords.u;\n\n        float dotProd = 0.0;\n\n        for (int b = 0; b < "+t.batchSize+"; b++) {\n          for (int yF = 0; yF < "+t.outDepth+"; yF++) {\n            int xF = wF + yF * "+e+" - "+o+";\n\n            if (xF < 0 || xF >= "+t.inDepth+") {\n              continue;\n            }\n\n            for (int yR = 0; yR < "+t.outHeight+"; yR++) {\n              int xR = wR + yR * "+n+" - "+a+";\n\n              if (xR < 0 || xR >= "+t.inHeight+") {\n                continue;\n              }\n\n              for (int yC = 0; yC < "+t.outWidth+"; yC++) {\n                int xC = wC + yC * "+r+" - "+i+";\n\n                if (xC < 0 || xC >= "+t.inWidth+") {\n                  continue;\n                }\n\n                float dyValue = getDy(b, yF, yR, yC, d2);\n                float xValue = getX(b, xF, xR, xC, d1);\n                dotProd += (xValue * dyValue);\n              }\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    "},Ma=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterDepth,n=t.filterHeight,r=t.filterWidth,o=t.strideDepth,a=t.strideHeight,i=t.strideWidth,s=e-1-t.padInfo.front,u=n-1-t.padInfo.top,c=r-1-t.padInfo.left;this.userCode="\n      const ivec3 pads = ivec3("+s+", "+u+", "+c+");\n\n      void main() {\n        ivec5 coords = getOutputCoords();\n        int batch = coords.x;\n        int d1 = coords.u;\n\n\n        ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n        int dyFCorner = dyCorner.x;\n        int dyRCorner = dyCorner.y;\n        int dyCCorner = dyCorner.z;\n\n        float dotProd = 0.0;\n        for (int wF = 0; wF < "+e+"; wF++) {\n          float dyF = float(dyFCorner + wF) / "+o+".0;\n\n          if (dyF < 0.0 || dyF >= "+t.outDepth+".0 || fract(dyF) > 0.0) {\n            continue;\n          }\n          int idyF = int(dyF);\n\n          int wFPerm = "+e+" - 1 - wF;\n\n          for (int wR = 0; wR < "+n+"; wR++) {\n            float dyR = float(dyRCorner + wR) / "+a+".0;\n\n            if (dyR < 0.0 || dyR >= "+t.outHeight+".0 ||\n              fract(dyR) > 0.0) {\n              continue;\n            }\n            int idyR = int(dyR);\n\n            int wRPerm = "+n+" - 1 - wR;\n\n            for (int wC = 0; wC < "+r+"; wC++) {\n              float dyC = float(dyCCorner + wC) / "+i+".0;\n\n              if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n                  fract(dyC) > 0.0) {\n                continue;\n              }\n              int idyC = int(dyC);\n\n              int wCPerm = "+r+" - 1 - wC;\n\n              for (int d2 = 0; d2 < "+t.outChannels+"; d2++) {\n                float xValue = getDy(batch, idyF, idyR, idyC, d2);\n                float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);\n                dotProd += xValue * wValue;\n              }\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    "},Ba=function(t){this.variableNames=["x","dy"],this.outputShape=t.filterShape;var e=t.strideHeight,n=t.strideWidth,r=t.padInfo.top,o=t.padInfo.left,a=t.outChannels/t.inChannels;this.userCode="\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int wR = coords.x;\n        int wC = coords.y;\n        int d1 = coords.z;\n        int dm = coords.w;\n        int d2 = d1 * "+a+" + dm;\n\n        float dotProd = 0.0;\n\n        // 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+" - "+o+";\n\n              if (xC < 0 || xC >= "+t.inWidth+") {\n                continue;\n              }\n\n              float dyValue = getDy(b, yR, yC, d2);\n              float xValue = getX(b, xR, xC, d1);\n              dotProd += (xValue * dyValue);\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    "},Pa=function(t){this.variableNames=["dy","W"],this.outputShape=t.inShape;var e=t.filterHeight,n=t.filterWidth,r=t.strideHeight,o=t.strideWidth,a=e-1-t.padInfo.top,i=n-1-t.padInfo.left,s=t.outChannels/t.inChannels;this.userCode="\n      const ivec2 pads = ivec2("+a+", "+i+");\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d1 = coords[3];\n        ivec2 dyCorner = coords.yz - pads;\n        int dyRCorner = dyCorner.x;\n        int dyCCorner = dyCorner.y;\n\n        float dotProd = 0.0;\n\n        for (int wR = 0; wR < "+e+"; wR++) {\n          float dyR = float(dyRCorner + wR) / "+r+".0;\n\n          if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          int wRPerm = "+e+" - 1 - wR;\n\n          for (int wC = 0; wC < "+n+"; wC++) {\n            float dyC = float(dyCCorner + wC) / "+o+".0;\n\n            if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n                fract(dyC) > 0.0) {\n              continue;\n            }\n            int idyC = int(dyC);\n\n            int wCPerm = "+n+" - 1 - wC;\n\n            // 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    "},La=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 o=t.padInfo.top,a=t.padInfo.left,i=t.strideHeight,s=t.strideWidth,u=t.dilationHeight,c=t.dilationWidth,l=t.filterHeight,p=t.filterWidth,h=4*Math.floor(t.inChannels/4),d=t.inChannels%4,f="channelsLast"===t.dataFormat,v=f?1:2,m=f?2:3,g=f?3:1,x="",y="";n&&(x=r?"float activation(float a) {\n          float b = getPreluActivationWeightsAtOutCoords();\n          "+n+"\n        }":"\n          float activation(float x) {\n            "+n+"\n          }\n        ",y="result = activation(result);");var b=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode="\n      "+x+"\n\n      const ivec2 strides = ivec2("+i+", "+s+");\n      const ivec2 pads = ivec2("+o+", "+a+");\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d2 = coords["+g+"];\n\n        ivec2 xRCCorner =\n            ivec2(coords["+v+"], coords["+m+"]) * 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 < "+l+"; 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 * "+c+";\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 ("+f+") {\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===d)+") {\n\n              if ("+f+") {\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===d)+") {\n              vec2 wValues = vec2(\n                getW(wR, wC, "+h+", d2),\n                getW(wR, wC, "+h+" + 1, d2)\n              );\n\n              if ("+f+") {\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===d)+") {\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 ("+f+") {\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        "+b+"\n        "+y+"\n        setOutput(result);\n      }\n    "},Wa=function(t){this.variableNames=["x","W"],this.outputShape=t.outShape;var e=t.padInfo.front,n=t.padInfo.top,r=t.padInfo.left,o=t.strideDepth,a=t.strideHeight,i=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,c=t.dilationWidth,l=t.filterDepth,p=t.filterHeight,h=t.filterWidth,d=4*Math.floor(t.inChannels/4),f=t.inChannels%4;this.userCode="\n      const ivec3 strides = ivec3("+o+", "+a+", "+i+");\n      const ivec3 pads = ivec3("+e+", "+n+", "+r+");\n\n      void main() {\n        ivec5 coords = getOutputCoords();\n        int batch = coords.x;\n        int d2 = coords.u;\n\n        ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n        int xFCorner = xFRCCorner.x;\n        int xRCorner = xFRCCorner.y;\n        int xCCorner = xFRCCorner.z;\n\n        // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get\n        // y(yF, yR, yC, d2). ? = to be determined. : = across all\n        // values in that axis.\n        float dotProd = 0.0;\n        for (int wF = 0; wF < "+l+"; 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 * "+c+";\n\n              if (xC < 0 || xC >= "+t.inWidth+") {\n                continue;\n              }\n\n              for (int d1 = 0; d1 < "+d+"; 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===f)+") {\n                dotProd +=\n                  getX(batch, xF, xR, xC, "+d+") *\n                  getW(wF, wR, wC, "+d+", d2);\n              } else if ("+(2===f)+") {\n                vec2 xValues = vec2(\n                  getX(batch, xF, xR, xC, "+d+"),\n                  getX(batch, xF, xR, xC, "+d+" + 1)\n                );\n                vec2 wValues = vec2(\n                  getW(wF, wR, wC, "+d+", d2),\n                  getW(wF, wR, wC, "+d+" + 1, d2)\n                );\n                dotProd += dot(xValues, wValues);\n              } else if ("+(3===f)+") {\n                vec3 xValues = vec3(\n                  getX(batch, xF, xR, xC, "+d+"),\n                  getX(batch, xF, xR, xC, "+d+" + 1),\n                  getX(batch, xF, xR, xC, "+d+" + 2)\n                );\n                vec3 wValues = vec3(\n                  getW(wF, wR, wC, "+d+", d2),\n                  getW(wF, wR, wC, "+d+" + 1, d2),\n                  getW(wF, wR, wC, "+d+" + 2, d2)\n                );\n                dotProd += dot(xValues, wValues);\n              }\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    "},za=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 o=t.inHeight,a=t.inWidth,i=t.padInfo.top,s=t.padInfo.left,u=t.strideHeight,c=t.strideWidth,l=t.dilationHeight,p=t.dilationWidth,h=t.filterHeight,d=t.filterWidth,f=t.outChannels/t.inChannels,v="",m="";n&&(v=r?"float activation(float a) {\n          float b = getPreluActivationWeightsAtOutCoords();\n          "+n+"\n        }":"\n          float activation(float x) {\n            "+n+"\n          }\n        ",m="result = activation(result);");var g=e?"result += getBiasAtOutCoords();":"";e&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.userCode="\n      "+v+"\n\n      const ivec2 strides = ivec2("+u+", "+c+");\n      const ivec2 pads = ivec2("+i+", "+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 / "+f+";\n        int q = d2 - d1 * "+f+";\n\n        int xRCorner = xRCCorner.x;\n        int xCCorner = xRCCorner.y;\n\n        // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        // 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 * "+l+";\n\n          if (xR < 0 || xR >= "+o+") {\n            continue;\n          }\n\n          for (int wC = 0; wC < "+d+"; 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        "+g+"\n        "+m+"\n        setOutput(result);\n      }\n    "},Ua=function(t,e,n,r){void 0===e&&(e=!1),void 0===n&&(n=null),void 0===r&&(r=!1),this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.outShape;for(var o=t.inHeight,a=t.inWidth,i=t.padInfo.top,s=t.padInfo.left,u=t.strideHeight,c=t.strideWidth,l=t.dilationHeight,p=t.dilationWidth,h=t.filterHeight,d=t.filterWidth,f=d,v="int xR; int xC; int xCOffset;",m=0;m<h;m++)for(var g=0;g<d;g++)v+="\n          vec4 xTexelR"+m+"C"+2*g+" = vec4(0.);\n          vec4 wR"+m+"C"+g+" = vec4(0.);\n          vec4 xR"+m+"C"+g+" = vec4(0.);";for(m=0;m<h;m++)for(var y=0;y<f;y++){if(v+="\n          xR = xRCorner + "+m*l+";\n          xC = xCCorner + "+(g=2*y)*p+";\n        ",1===c){if(g<d&&(v+=s%2==1?"\n                xCOffset = xC + 1;\n                if(xR >= 0 && xR < "+o+" && xCOffset >= 0 && xCOffset < "+a+") {\n                  xTexelR"+m+"C"+g+" = getX(batch, xR, xCOffset, d1);\n                } else {\n                  xTexelR"+m+"C"+g+" = vec4(0.);\n                }\n\n                xCOffset = xC + 1 - 2;\n                if(xR >= 0 && xR < "+o+" && xCOffset >= 0 && xCOffset < "+a+") {\n                  vec4 previous = getX(batch, xR, xCOffset, d1);\n                  xR"+m+"C"+g+" = vec4(previous.zw, xTexelR"+m+"C"+g+".xy);\n                } else {\n                  xR"+m+"C"+g+" = vec4(0, 0, xTexelR"+m+"C"+g+".xy);\n                }\n              ":"\n                if(xR >= 0 && xR < "+o+" && xC >= 0 && xC < "+a+") {\n                  xTexelR"+m+"C"+g+" = getX(batch, xR, xC, d1);\n                } else {\n                  xTexelR"+m+"C"+g+" = vec4(0.);\n                }\n\n                xR"+m+"C"+g+" = xTexelR"+m+"C"+g+";\n              ",g+1<d)){var b=s%2==0?x(p):p;p%2==0&&s%2==1||p%2!=0&&s%2!=1?(v+="\n                  xCOffset = xC + "+s%2+" + "+b+";\n\n                  if(xR >= 0 && xR < "+o+" &&\n                    xCOffset >= 0 && xCOffset < "+a+") {\n                    xTexelR"+m+"C"+(g+2)+" = getX(batch, xR, xCOffset, d1);\n                  }\n                ",p>1&&(v+="\n                    xCOffset -= 2;\n                    if(xR >= 0 && xR < "+o+" &&\n                      xCOffset >= 0 && xCOffset < "+a+") {\n                      xTexelR"+m+"C"+g+" = getX(batch, xR, xCOffset, d1);\n                    } else {\n                      xTexelR"+m+"C"+g+" = vec4(0.);\n                    }\n                  "),v+="\n                  xR"+m+"C"+(g+1)+" = vec4(\n                    xTexelR"+m+"C"+g+".zw, xTexelR"+m+"C"+(g+2)+".xy);\n                "):v+="\n                  xCOffset = xC + "+b+";\n\n                  if(xR >= 0 && xR < "+o+" &&\n                    xCOffset >= 0 && xCOffset < "+a+") {\n                    xTexelR"+m+"C"+(g+2)+" = getX(batch, xR, xCOffset, d1);\n                  }\n\n                  xR"+m+"C"+(g+1)+" = xTexelR"+m+"C"+(g+2)+";\n                "}}else g<d&&(v+="\n              if(xR >= 0 && xR < "+o+") {\n            ",s%2==1?(v+="\n                xCOffset = xC + 1 - "+c+";\n                if(xCOffset >= 0 && xCOffset < "+a+") {\n                  xTexelR"+m+"C"+g+" = getX(batch, xR, xCOffset, d1);\n                } else {\n                  xTexelR"+m+"C"+g+" = vec4(0.);\n                }\n\n                if(xC + 1 >= 0 && xC + 1 < "+a+") {\n                  xTexelR"+m+"C"+(g+2)+" = getX(batch, xR, xC + 1, d1);\n                } else {\n                  xTexelR"+m+"C"+(g+2)+" = vec4(0.);\n                }\n\n                xR"+m+"C"+g+" = vec4(\n                  xTexelR"+m+"C"+g+".zw, xTexelR"+m+"C"+(g+2)+".zw);\n              ",g+1<d&&(v+="\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"+m+"C"+(g+1)+" = vec4(xTexelR"+m+"C"+(g+2)+".xy, final.xy);\n                ")):(v+="\n                if(xC >= 0 && xC < "+a+") {\n                  xTexelR"+m+"C"+g+" = getX(batch, xR, xC, d1);\n                } else {\n                  xTexelR"+m+"C"+g+" = vec4(0.);\n                }\n\n                xCOffset = xC + "+c+";\n                if(xCOffset >= 0 && xCOffset < "+a+") {\n                  xTexelR"+m+"C"+(g+2)+" = getX(batch, xR, xCOffset, d1);\n                } else {\n                  xTexelR"+m+"C"+(g+2)+" = vec4(0.);\n                }\n\n                xR"+m+"C"+g+" = vec4(\n                  xTexelR"+m+"C"+g+".xy, xTexelR"+m+"C"+(g+2)+".xy);\n              ",g+1<d&&(v+="\n                  xR"+m+"C"+(g+1)+" = vec4(\n                    xTexelR"+m+"C"+g+".zw, xTexelR"+m+"C"+(g+2)+".zw);\n                ")),v+="}");g<d&&(v+="\n            vec4 wTexelR"+m+"C"+g+" = getW("+m+", "+g+", d1, q);\n            wR"+m+"C"+g+" = vec4(wTexelR"+m+"C"+g+".xz, wTexelR"+m+"C"+g+".xz);\n          ",g+1<d&&(v+="\n              vec4 wTexelR"+m+"C"+(g+1)+" = getW("+m+", "+(g+1)+", d1, q);\n              wR"+m+"C"+(g+1)+" =\n                vec4(wTexelR"+m+"C"+(g+1)+".xz, wTexelR"+m+"C"+(g+1)+".xz);"))}for(m=0;m<h;m++)for(g=0;g<d;g++)v+="dotProd += xR"+m+"C"+g+" * wR"+m+"C"+g+";";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 E=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("+i+", "+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        "+v+"\n\n        vec4 result = dotProd;\n        "+E+"\n        "+C+"\n        setOutput(result);\n      }\n    "},Va=function(t,e,n,r,o){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];var a=t[0],i=t[1],s=t[2],u=t[3],c=e[0],l=n[0],p=n[1];this.outputShape=[c,l,p,u];var h="bilinear"===r?1:0,d=[i-1+".0",s-1+".0"],f=d[0],v=d[1],m=l>1?[""+(i-1)/(l-1),"(y2-y1) * height_ratio","y1*"+f+" + float(y)*(height_scale)"]:["0.0","0.0","0.5 * (y1+y2) * "+f],g=m[0],x=m[1],y=m[2],b=p>1?[""+(s-1)/(p-1),"(x2-x1) * width_ratio","x1*"+v+" + float(x)*(width_scale)"]:["0.0","0.0","0.5 * (x1+x2) * "+v],w=b[0],C=b[1],E=b[2];this.userCode="\n      const float height_ratio = float("+g+");\n      const float width_ratio = float("+w+");\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int y = coords[1];\n        int x = coords[2];\n        int d = coords[3];\n\n        // get box vals\n        float y1 = getBoxes(b,0);\n        float x1 = getBoxes(b,1);\n        float y2 = getBoxes(b,2);\n        float x2 = getBoxes(b,3);\n\n        // get image in batch index\n        int bInd = round(getBoxInd(b));\n        if(bInd < 0 || bInd >= "+a+") {\n          return;\n        }\n\n        float height_scale = "+x+";\n        float width_scale = "+C+";\n\n        float in_y = "+y+";\n        if( in_y < 0.0 || in_y > "+f+" ) {\n          setOutput(float("+o+"));\n          return;\n        }\n        float in_x = "+E+";\n        if( in_x < 0.0 || in_x > "+v+" ) {\n          setOutput(float("+o+"));\n          return;\n        }\n\n        vec2 sourceFracIndexCR = vec2(in_x,in_y);\n        if("+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    "},Ga=function(t,e,n){this.variableNames=["x"],this.outputShape=t;var r=t.length,o=t[t.length-1],a=n?"<":">";this.userCode="\n      int getIndex(int i) {\n        "+(n?"return "+o+" -i - 1;":"return i;")+"\n      }\n\n      void main() {\n        "+ua(r)+" coords = getOutputCoords();\n        int end = "+Ha(r,"coords")+";\n        float val = 0.0;\n        for (int i = "+o+" - 1; i >= 0; i -= 1) {\n          int idx = getIndex(i);\n          if (idx "+a+" end) {\n            continue;\n          }\n          if (idx == end && "+e+") {\n            continue;\n          }\n          "+Ha(r,"coords")+" = idx;\n          val += getX("+function(t,e){if(1===r)return""+e;if(2===r)return e+".x, "+e+".y";if(3===r)return e+".x, "+e+".y, "+e+".z";if(4===r)return e+".x, "+e+".y, "+e+".z, "+e+".w";throw Error("Cumulative sum for rank "+r+" is not yet supported")}(0,"coords")+");\n        }\n        setOutput(val);\n      }\n    "};function Ha(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 qa=function(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=Pt.DENSE;var e=Kt(t),n=$o();this.outputShape=t,this.userCode="\n      ivec3 outCoordsFromFlatIndex(int index) {\n        "+Yo(["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    "},Ka=function(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=Pt.DENSE;var e=Kt(t),n=$o();this.outputShape=t,this.userCode="\n      ivec3 outCoordsFromFlatIndex(int index) {\n        "+Yo(["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    "},ja=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}(),Xa=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    "},$a=function(t){this.variableNames=["A"],this.outTexUsage=Lt.DOWNLOAD;var e=$o();this.outputShape=t,this.userCode="\n      "+Jo+"\n\n      void main() {\n        float x = getAAtOutCoords();\n        "+e.output+" = encode_float(x);\n      }\n    "},Ya=function(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=Lt.DOWNLOAD;var e=$o();this.outputShape=t,this.userCode="\n      "+Jo+"\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    "},Qa=function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"];var r=$o(),o=e[0],a=e[1];this.outputShape=t;var i="result";n&&(i="floor(result * 255. + 0.5)"),this.userCode="\n      "+Qo(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, "+o+".0);\n        vec4 values = "+r.texture2D+"(A, uv);\n\n        float result;\n\n        if(offset == 0) {\n          result = values[0];\n        } else if(offset == 1) {\n          result = values[1];\n        } else if(offset == 2) {\n          result = values[2];\n        } else {\n          result = values[3];\n        }\n\n        "+r.output+" = vec4("+i+", 0., 0., 0.);\n      }\n    "},Ja=function(t,e,n){void 0===n&&(n=!1),this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var r=$o(),o=e[0],a=e[1];this.outputShape=t;var i="",s="result";n&&(s="floor(result * 255. + 0.5)");for(var u=0;u<=1;u++)for(var c=0;c<=1;c++){var l=2*u+c;i+="\n          localCoords = coords;\n          if(localCoords[2] + "+c+" < "+t[2]+") {\n            localCoords[2] += "+c+";\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, "+o+".0);\n              values = "+r.texture2D+"(A, uv);\n\n              if(offset == 0) {\n                result["+l+"] = values[0];\n              } else if(offset == 1) {\n                result["+l+"] = values[1];\n              } else if(offset == 2) {\n                result["+l+"] = values[2];\n              } else {\n                result["+l+"] = values[3];\n              }\n            }\n          }\n        "}this.userCode="\n      "+Qo(t)+"\n\n      void main() {\n        ivec3 coords = getOutputCoords();\n\n        vec4 result = vec4(0.);\n        int flatIndex, r, c, offset;\n        ivec3 localCoords;\n        vec2 uv;\n        vec4 values;\n\n        "+i+"\n\n        "+r.output+" = "+s+";\n      }\n    "},Za="return real * expR - imag * expI;",ti="return real * expI + imag * expR;",ei=function(t,e,n){this.variableNames=["real","imag"];var r=e[1];this.outputShape=e;var o=n?"2.0 * "+Math.PI:"-2.0 * "+Math.PI,a=n?r+".0":"1.0";this.userCode="\n      const float exponentMultiplier = "+o+";\n\n      float unaryOpComplex(float real, float expR, float imag, float expI) {\n        "+t+"\n      }\n\n      float mulMatDFT(int batch, int index) {\n        float indexRatio = float(index) / float("+r+");\n        float exponentMultiplierTimesIndexRatio =\n            exponentMultiplier * indexRatio;\n\n        float result = 0.0;\n\n        for (int i = 0; i < "+r+"; i++) {\n          // x = (-2|2 * PI / N) * index * i;\n          float x = exponentMultiplierTimesIndexRatio * float(i);\n          float expR = cos(x);\n          float expI = sin(x);\n          float real = getReal(batch, i);\n          float imag = getImag(batch, i);\n\n          result +=\n              unaryOpComplex(real, expR, imag, expI) / "+a+";\n        }\n\n        return result;\n      }\n\n      void main() {\n        ivec2 coords = getOutputCoords();\n        setOutput(mulMatDFT(coords[0], coords[1]));\n      }\n    "},ni=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}(),ri=function(t){this.variableNames=["A"];var e=$o(),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    "},oi=function(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;var e=$o(),n=t[0],r=t[1];this.outputShape=t,this.userCode="\n      void main() {\n        ivec3 coords = getOutputCoords();\n        int texR = coords[0];\n        int texC = coords[1];\n        int depth = coords[2];\n\n        vec4 result = vec4(0.);\n\n        for(int row=0; row<=1; row++) {\n          for(int col=0; col<=1; col++) {\n            texC = coords[1] + row;\n            depth = coords[2] + col;\n\n            vec2 uv = (vec2(texC, texR) + halfCR) /\n                       vec2("+r+".0, "+n+".0);\n            vec4 values = "+e.texture2D+"(A, uv);\n            float value;\n            if (depth == 0) {\n              value = values.r;\n            } else if (depth == 1) {\n              value = values.g;\n            } else if (depth == 2) {\n              value = values.b;\n            } else if (depth == 3) {\n              value = values.a;\n            }\n\n            result[row * 2 + col] = floor(value * 255.0 + 0.5);\n          }\n        }\n\n        "+e.output+" = result;\n      }\n    "},ai=function(t,e,n){this.variableNames=["A","indices"];var r=t.slice();r[n]=e,this.outputShape=r,this.rank=r.length;var o=ua(this.rank),a=function(t,e){var n=t.length;if(n>4)throw Error("Gather for rank "+n+" is not yet supported");if(1===n)return"int(getIndices(resRC))";for(var r=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[],a=0;a<t.length;a++)a===e?o.push("int(getIndices("+r[a]+"))"):o.push(""+r[a]);return o.join()}(t,n);this.userCode="\n      void main() {\n        "+o+" resRC = getOutputCoords();\n        setOutput(getA("+a+"));\n      }\n    "},ii=function(t,e,n){this.sliceDim=t,this.strides=e,this.variableNames=["x","indices"],this.outputShape=n;var r=ua(e.length),o=ua(n.length),a=this.sliceDim>1?"strides[j]":"strides";this.userCode="\n        "+r+" strides = "+r+"("+this.strides+");\n         void main() {\n          "+o+" coords = getOutputCoords();\n          int flattenIndex = 0;\n          for (int j = 0; j < "+this.sliceDim+"; j++) {\n            int index = round(getIndices(coords[0], j));\n            flattenIndex += index * "+a+";\n          }\n          setOutput(getX(flattenIndex, coords[1]));\n        }\n      "};function si(t,e){var n=$o();return ee(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 ui(t,e){return ce(t,e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function ci(t,e){return le(t,e,new Uint16Array([0,1,2,2,1,3]))}function li(t,e,n,r,o,a,i){he(n,r);var s=pe(t,e),u=t.TEXTURE_2D;return $t(t,e,function(){return t.bindTexture(u,s)}),$t(t,e,function(){return t.texParameteri(u,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE)}),$t(t,e,function(){return t.texParameteri(u,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE)}),$t(t,e,function(){return t.texParameteri(u,t.TEXTURE_MIN_FILTER,t.NEAREST)}),$t(t,e,function(){return t.texParameteri(u,t.TEXTURE_MAG_FILTER,t.NEAREST)}),$t(t,e,function(){return t.texImage2D(u,0,o,n,r,0,a,i,null)}),$t(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)}),s}function pi(t,e,n,r,o){var a=qt(n,r);return li(t,e,a[0],a[1],o.internalFormatFloat,o.textureFormatFloat,t.FLOAT)}function hi(t,e,n,r,o){var a=qt(n,r);return li(t,e,a[0],a[1],o.internalFormatHalfFloat,o.textureFormatFloat,o.textureTypeHalfFloat)}function di(t,e,n,r,o){var a=qt(n,r);return li(t,e,a[0],a[1],t.RGBA,t.RGBA,t.UNSIGNED_BYTE)}function fi(t,e,n,r,o){var a=jt(n,r);return li(t,e,a[0],a[1],o.internalFormatPackedFloat,t.RGBA,t.FLOAT)}function vi(t,e,n,r,o){var a=jt(n,r);return li(t,e,a[0],a[1],o.internalFormatPackedHalfFloat,t.RGBA,o.textureTypeHalfFloat)}function mi(t,e,n,r){return $t(t,e,function(){return t.bindBuffer(t.ARRAY_BUFFER,r)}),fe(t,e,n,"clipSpacePos",r,3,20,0)&&fe(t,e,n,"uv",r,2,20,12)}function gi(t,e,n,r,o,a,i){var s,u,c;$t(t,e,function(){return t.bindTexture(t.TEXTURE_2D,n)}),a instanceof Uint8Array?(s=new Uint8Array(r*o*4),u=t.UNSIGNED_BYTE,c=t.RGBA):(s=new Float32Array(r*o*4),u=t.FLOAT,c=i.internalFormatPackedFloat),s.set(a),$t(t,e,function(){return t.texImage2D(t.TEXTURE_2D,0,c,r,o,0,t.RGBA,u,s)}),$t(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)})}function xi(t,e,n,r){$t(t,e,function(){return t.bindTexture(t.TEXTURE_2D,n)}),r.data instanceof Uint8Array?$t(t,e,function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,r.width,r.height,0,t.RGBA,t.UNSIGNED_BYTE,r.data)}):$t(t,e,function(){return t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,r)}),$t(t,e,function(){return t.bindTexture(t.TEXTURE_2D,null)})}function yi(t,e,n,r,o){var a=t.createBuffer();$t(t,e,function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,a)});var i=16*n*r;return $t(t,e,function(){return t.bufferData(t.PIXEL_PACK_BUFFER,i,t.STREAM_READ)}),$t(t,e,function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,0)}),$t(t,e,function(){return t.bindBuffer(t.PIXEL_PACK_BUFFER,null)}),a}function bi(t,e,n){var r=t,o=new Float32Array(n);return r.bindBuffer(r.PIXEL_PACK_BUFFER,e),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,o),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),o}function wi(t,e,n,r,o){var a=qt(n,r),i=a[0],s=a[1],u=new Uint8Array(n*r*4);return $t(t,e,function(){return t.readPixels(0,0,i,s,o.downloadTextureFormat,t.UNSIGNED_BYTE,u)}),new Float32Array(u.buffer)}function Ci(t,e,n,r,o,a,i,s){var u=t,c=new Float32Array(function(t,e){var n=jt(a,i);return n[0]*n[1]*4}());return u.bindBuffer(u.PIXEL_PACK_BUFFER,e),u.getBufferSubData(u.PIXEL_PACK_BUFFER,0,c),u.bindBuffer(u.PIXEL_PACK_BUFFER,null),c}function Ei(t,e,n,r){var o=new Float32Array(n*r*4);return $t(t,e,function(){return t.readPixels(0,0,r,n,t.RGBA,t.FLOAT,o)}),o}var Ri=Object.freeze({createVertexShader:si,createVertexBuffer:ui,createIndexBuffer:ci,createFloat32MatrixTexture:pi,createFloat16MatrixTexture:hi,createUnsignedBytesMatrixTexture:di,createPackedMatrixTexture:fi,createFloat16PackedMatrixTexture:vi,bindVertexProgramAttributeStreams:mi,uploadDenseMatrixToTexture:gi,uploadPixelDataToTexture:xi,createBufferFromOutputTexture:yi,downloadFloat32MatrixFromBuffer:bi,downloadByteEncodedFloatMatrixFromOutputTexture:wi,downloadPackedMatrixFromBuffer:Ci,downloadMatrixFromPackedOutputTexture:Ei}),Ii=function(){function t(t){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];var e=u().getNumber("WEBGL_VERSION");if(null!=t?(this.gl=t,Vt(e,t)):this.gl=Gt(e),1===u().getNumber("WEBGL_VERSION"))this.textureFloatExtension=te(this.gl,this.debug,"OES_texture_float"),this.colorBufferFloatExtension=this.gl.getExtension("WEBGL_color_buffer_float"),this.textureHalfFloatExtension=te(this.gl,this.debug,"OES_texture_half_float"),this.colorBufferHalfFloatExtension=this.gl.getExtension("EXT_color_buffer_half_float");else if(_e(this.gl,"EXT_color_buffer_float"))this.colorBufferFloatExtension=this.gl.getExtension("EXT_color_buffer_float");else{if(!_e(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=ui(this.gl,this.debug),this.indexBuffer=ci(this.gl,this.debug),this.framebuffer=de(this.gl,this.debug),this.textureConfig=Xt(this.gl,this.textureHalfFloatExtension)}return Object.defineProperty(t.prototype,"debug",{get:function(){return u().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;$t(e,this.debug,function(){return e.finish()}),$t(e,this.debug,function(){return e.bindFramebuffer(e.FRAMEBUFFER,null)}),$t(e,this.debug,function(){return e.deleteFramebuffer(t.framebuffer)}),$t(e,this.debug,function(){return e.bindBuffer(e.ARRAY_BUFFER,null)}),$t(e,this.debug,function(){return e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)}),$t(e,this.debug,function(){return e.deleteBuffer(t.indexBuffer)}),this.disposed=!0}},t.prototype.createFloat32MatrixTexture=function(t,e){return this.throwIfDisposed(),pi(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createFloat16MatrixTexture=function(t,e){return this.throwIfDisposed(),hi(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createUnsignedBytesMatrixTexture=function(t,e){return this.throwIfDisposed(),di(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.uploadPixelDataToTexture=function(t,e){this.throwIfDisposed(),xi(this.gl,this.debug,t,e)},t.prototype.uploadDenseMatrixToTexture=function(t,e,n,r){this.throwIfDisposed(),gi(this.gl,this.debug,t,e,n,r,this.textureConfig)},t.prototype.createFloat16PackedMatrixTexture=function(t,e){return this.throwIfDisposed(),vi(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.createPackedMatrixTexture=function(t,e){return this.throwIfDisposed(),fi(this.gl,this.debug,t,e,this.textureConfig)},t.prototype.deleteMatrixTexture=function(t){var e=this;this.throwIfDisposed(),this.outputTexture===t&&(be(this.gl,this.debug,this.framebuffer),this.outputTexture=null),$t(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 wi(r.gl,r.debug,e,n,r.textureConfig)})},t.prototype.downloadPackedMatrixFromBuffer=function(t,e,n,r,o,a){return Ci(this.gl,t,0,0,0,o,a,this.textureConfig)},t.prototype.downloadFloat32MatrixFromBuffer=function(t,e){return bi(this.gl,t,e)},t.prototype.createBufferFromTexture=function(t,e,n){this.bindTextureToFrameBuffer(t);var r=yi(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(u().getBool("WEBGL_FENCE_API_ENABLED")){var o=t,a=o.fenceSync(o.SYNC_GPU_COMMANDS_COMPLETE,0);t.flush(),n=function(){var t=o.clientWaitSync(a,0,0);return t===o.ALREADY_SIGNALED||t===o.CONDITION_SATISFIED},e=a}else u().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(e=this.beginQuery(),this.endQuery(),n=function(){return r.isQueryAvailable(e,u().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 Ei(r.gl,r.debug,e,n)})},t.prototype.createProgram=function(t){this.throwIfDisposed();var e=this.gl,n=ne(e,this.debug,t),r=si(e,this.debug),o=ie(e,this.debug);return $t(e,this.debug,function(){return e.attachShader(o,r)}),$t(e,this.debug,function(){return e.attachShader(o,n)}),se(e,this.debug,o),this.debug&&ue(e,this.debug,o),this.vertexAttrsAreBound||(this.setProgram(o),this.vertexAttrsAreBound=mi(e,this.debug,this.program,this.vertexBuffer)),o},t.prototype.deleteProgram=function(t){var e=this;this.throwIfDisposed(),t===this.program&&(this.program=null),null!=t&&$t(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&&ue(this.gl,this.debug,this.program),$t(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?me(this.gl,this.debug,t,e):ge(this.gl,t,e)},t.prototype.getAttributeLocation=function(t,e){var n=this;return this.throwIfDisposed(),$t(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(),xe(this.gl,this.debug,this.program,t,e,n)},t.prototype.setOutputMatrixTexture=function(t,e,n){this.setOutputMatrixTextureDriver(t,n,e)},t.prototype.setOutputPackedMatrixTexture=function(t,e,n){this.throwIfDisposed();var r=jt(e,n),o=r[0],a=r[1];this.setOutputMatrixTextureDriver(t,o,a)},t.prototype.setOutputMatrixWriteRegion=function(t,e,n,r){this.setOutputMatrixWriteRegionDriver(n,t,r,e)},t.prototype.setOutputPackedMatrixWriteRegion=function(t,e,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")},t.prototype.debugValidate=function(){null!=this.program&&ue(this.gl,this.debug,this.program),we(this.gl)},t.prototype.executeProgram=function(){this.throwIfDisposed(),this.throwIfNoProgram();var t=this.gl;this.debug&&this.debugValidate(),$t(t,this.debug,function(){return t.drawElements(t.TRIANGLES,6,t.UNSIGNED_SHORT,0)})},t.prototype.blockUntilAllProgramsCompleted=function(){var t=this;this.throwIfDisposed(),$t(this.gl,this.debug,function(){return t.gl.finish()})},t.prototype.getQueryTimerExtension=function(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=te(this.gl,this.debug,2===u().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===u().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){var t=this.gl,e=this.getQueryTimerExtensionWebGL2(),n=t.createQuery();return t.beginQuery(e.TIME_ELAPSED_EXT,n),n}var r=this.getQueryTimerExtensionWebGL1(),o=r.createQueryEXT();return r.beginQueryEXT(r.TIME_ELAPSED_EXT,o),o},t.prototype.endQuery=function(){if(2!==u().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 a(this,void 0,void 0,function(){var e=this;return i(this,function(n){switch(n.label){case 0:return[4,N(function(){return e.disposed||e.isQueryAvailable(t,u().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))})];case 1:return n.sent(),[2,this.getQueryTime(t,u().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))]}})})},t.prototype.getQueryTime=function(t,e){if(0===e)return null;if(2===e){var n=this.gl;return n.getQueryParameter(t,n.QUERY_RESULT)/1e6}var r=this.getQueryTimerExtensionWebGL1();return r.getQueryObjectEXT(t,r.QUERY_RESULT_EXT)/1e6},t.prototype.isQueryAvailable=function(t,e){if(0===e)return!0;if(2===e){var n=this.gl,r=this.getQueryTimerExtensionWebGL2(),o=n.getQueryParameter(t,n.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),o&&!this.disjoint}return o=(r=this.getQueryTimerExtensionWebGL1()).getQueryObjectEXT(t,r.QUERY_RESULT_AVAILABLE_EXT),null==this.disjoint&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),o&&!this.disjoint},t.prototype.pollFence=function(t){var e=this;return new Promise(function(n){e.addItemToPoll(function(){return t.isFencePassed()},function(){return n()})})},t.prototype.pollItems=function(){for(var t=function(t){for(var e=0;e<t.length;++e){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||N(function(){return n.pollItems(),0===n.itemsToPoll.length})},t.prototype.bindTextureToFrameBuffer=function(t){this.throwIfDisposed(),ye(this.gl,this.debug,t,this.framebuffer),this.debug&&we(this.gl)},t.prototype.unbindTextureToFrameBuffer=function(){null!=this.outputTexture?(ye(this.gl,this.debug,this.outputTexture,this.framebuffer),this.debug&&we(this.gl)):be(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;ye(r,this.debug,t,this.framebuffer),this.debug&&we(r),this.outputTexture=t,$t(r,this.debug,function(){return r.viewport(0,0,e,n)}),$t(r,this.debug,function(){return r.scissor(0,0,e,n)})},t.prototype.setOutputMatrixWriteRegionDriver=function(t,e,n,r){var o=this;this.throwIfDisposed(),$t(this.gl,this.debug,function(){return o.gl.scissor(t,e,n,r)})},t.prototype.throwIfDisposed=function(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")},t.prototype.throwIfNoProgram=function(){if(null==this.program)throw new Error("No GPU program is currently set.")},t}();function ki(t,e){if(t.length!==e.length)throw Error("Binary was compiled with "+t.length+" inputs, but was executed with "+e.length+" inputs");t.forEach(function(t,n){var r=t.logicalShape,o=e[n],a=o.shape;if(!I(r,a))throw Error("Binary was compiled with different shapes than the current args. Shapes "+r+" and "+a+" must match");if(!t.isUniform||!o.isUniform){var i=t.texShape,s=o.isUniform?null:o.texData.texShape;if(!I(i,s))throw Error("Binary was compiled with different texture shapes than the current args. Shape "+i+" and "+s+" must match")}})}var Si=function(t,e,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;for(var r=n.filterWidth,o=n.inChannels,a=n.strideWidth,i=n.strideHeight,s=n.padInfo,u=n.outWidth,c=n.dilationWidth,l=n.dilationHeight,p=n.dataFormat,h=s.left,d=s.top,f=o*r,v=$o(),m="channelsLast"===p,g=m?0:1,x=m?1:2,y="",b=0;b<=1;b++)for(var w=0;w<=1;w++)y+="\n          blockIndex = rc.y + "+w+";\n          pos = rc.x + "+b+";\n\n          if(blockIndex < "+t[1]+" && pos < "+t[0]+") {\n            offsetY = int(blockIndex / ("+u+")) * "+i+" - "+d+";\n            d0 = offsetY + "+l+" * (pos / "+f+");\n\n            if(d0 < "+e[g]+" && d0 >= 0) {\n\n              offsetX = int(mod(float(blockIndex), "+u+".) * "+a+". - "+h+".);\n              d1 = offsetX + "+c+" * (int(mod(float(pos), "+f+".) / "+o+".));\n\n              if(d1 < "+e[x]+" && d1 >= 0) {\n\n                ch = int(mod(float(pos), "+o+".));\n\n                if ("+m+") {\n                  innerDims = vec2(d1, ch);\n                  result["+(2*b+w)+"] = getChannel(\n                    getA(d0, int(innerDims.x),\n                    int(innerDims.y)), innerDims);\n                } else {\n                  innerDims = vec2(d0, d1);\n                  result["+(2*b+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        "+y+"\n\n        "+v.output+" = result;\n      }\n    "},Ai=function(t,e,n,r,o){this.variableNames=["x"],this.outputShape=[];var a,i=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";a=.5===o?"inversesqrt("+u+")":1===o?"1.0/("+u+")":"exp(log("+u+") * float(-"+o+"));",this.userCode="\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int r = coords[1];\n        int c = coords[2];\n        int d = coords[3];\n        float x = getX(b, r, c, d);\n        float sum = 0.0;\n        for (int j = -"+i+"; j <= "+i+"; j++) {\n          int idx = d + j;\n          if (idx >= 0 && idx <=  "+s+") {\n            float z = getX(b, r, c, idx);\n            sum += z * z;\n          }\n        }\n        float val = x * "+a+";\n        setOutput(val);\n      }\n    "},Di=function(t,e,n,r,o){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=t,this.depth=t[3],this.depthRadius=e,this.bias=n,this.alpha=r,this.beta=o,this.userCode="\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int r = coords[1];\n        int c = coords[2];\n\n        float result = 0.0;\n        for (int d = 0; d < "+this.depth+"; ++d) {\n          int depthBegin = int(max(0.0, float(d - "+e+")));\n          int depthEnd = int(min(float("+this.depth+"),\n              float(d + "+e+" + 1)));\n\n          const int MIN_DEPTH_BEGIN = 0;\n          const int MAX_DEPTH_END = "+this.depth+";\n\n          float norm = 0.0;\n          for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {\n            if (k < depthBegin){\n              continue;\n            }\n            else if (k >= depthBegin && k < depthEnd) {\n              norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);\n            }\n            else {\n              break;\n            }\n          }\n\n          norm = float("+r+") * norm + float("+n+");\n\n          for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){\n            if (k < depthBegin){\n              continue;\n            }\n            else if (k >= depthBegin && k < depthEnd){\n              float dyi = -2.0 * float("+r+")\n                * float("+o+")\n                * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)\n                / norm;\n              if (k == d) {\n                dyi += pow(norm, -1.0 * "+o+");\n              }\n              if (k == coords[3]) {\n                dyi *= getDy(b, r, c, d);\n                result += dyi;\n              }\n            }\n            else {\n              break;\n            }\n          }\n      }\n      setOutput(result);\n      }\n    "},Ni=function(t,e,n,r,o){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;var a,i=e,s=t[3]-1;this.outputShape=t;var u="float("+n+") + float("+r+") * sum";a=.5===o?"inversesqrt("+u+")":1===o?"1.0/("+u+")":"exp(log("+u+") * float(-"+o+"));",this.userCode="\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords.x;\n        int r = coords.y;\n        int c = coords.z;\n        int d = coords.w;\n\n        bool hasNextCol = d < "+this.outputShape[3]+";\n        bool hasNextRow = c < "+this.outputShape[2]+";\n\n        vec4 sum = vec4(0.);\n        vec4 xFragAtOutputCoords = getX(b, r, c, d);\n\n        vec4 xAtOutputCoords = vec4(\n          getChannel(xFragAtOutputCoords, vec2(c, d)),\n          hasNextCol ?\n            getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,\n          hasNextRow ?\n            getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0\n        );\n\n        int firstChannel = d - "+i+";\n        vec2 cache = vec2(0.);\n        if(firstChannel >= 0){\n          vec4 firstChannelFrag = getX(b, r, c, firstChannel);\n          cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));\n            if(hasNextRow){\n              cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));\n            }\n        }\n\n        ivec2 depth = ivec2(d, d + 1);\n        for (int j = - "+i+"; j <= "+i+"; j++) {\n          ivec2 idx = depth + j;\n          bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\n          bvec2 belowUpperBound = lessThanEqual(idx, ivec2("+s+"));\n\n          bool depthInRange = aboveLowerBound.x && belowUpperBound.x;\n          bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;\n\n          if(depthInRange || depthPlusOneInRange){\n            vec4 z = vec4(0.);\n            vec4 xFragAtCurrentDepth;\n            z.xz = cache.xy;\n            if(depthPlusOneInRange && hasNextCol){\n              xFragAtCurrentDepth = idx.y != d ?\n                getX(b, r, c, idx.y) : xFragAtOutputCoords;\n              z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));\n              if(hasNextRow){\n                z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));\n              }\n            }\n            cache.xy = z.yw;\n            sum += z * z;\n          }\n        }\n        vec4 result = xAtOutputCoords * "+a+";\n        setOutput(result);\n      }\n    "},Ti=function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideHeight,n=t.strideWidth,r=t.dilationHeight,o=t.effectiveFilterHeight,a=t.effectiveFilterWidth,i=o-1-t.padInfo.top,s=a-1-t.padInfo.left,u=o*a-1;this.userCode="\n      const ivec2 pads = ivec2("+i+", "+s+");\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n\n        ivec2 dyRCCorner = coords.yz - pads;\n        int dyRCorner = dyRCCorner.x;\n        int dyCCorner = dyRCCorner.y;\n\n        // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        for (int wR = 0; wR < "+o+";\n          wR += "+r+") {\n          float dyR = float(dyRCorner + wR) / "+e+".0;\n\n          if (dyR < 0.0 || dyR >= "+t.outHeight+".0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          for (int wC = 0; wC < "+a+"; wC++) {\n            float dyC = float(dyCCorner + wC) / "+n+".0;\n\n            if (dyC < 0.0 || dyC >= "+t.outWidth+".0 ||\n                fract(dyC) > 0.0) {\n              continue;\n            }\n            int idyC = int(dyC);\n\n            float dyValue = getDy(b, idyR, idyC, d);\n            int maxPosValue = "+u+" - int(getMaxPos(b, idyR, idyC, d));\n\n            // Get the current value, check it against the value from the\n            // position matrix.\n            int curPosValue = wR * "+a+" + wC;\n            float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n            dotProd += dyValue * mask;\n          }\n        }\n        setOutput(dotProd);\n      }\n    "},Fi=function(t){this.variableNames=["dy","maxPos"],this.outputShape=t.inShape;var e=t.strideDepth,n=t.strideHeight,r=t.strideWidth,o=t.dilationDepth,a=t.dilationHeight,i=t.dilationWidth,s=t.effectiveFilterDepth,u=t.effectiveFilterHeight,c=t.effectiveFilterWidth,l=s-1-t.padInfo.front,p=u-1-t.padInfo.top,h=c-1-t.padInfo.left,d=s*u*c-1;this.userCode="\n      const ivec3 pads = ivec3("+l+", "+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 += "+o+") {\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 < "+c+";\n                wC += "+i+") {\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 = "+d+" -\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+" * "+c+" +\n                  wR * "+c+" + wC;\n              float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n              dotProd += dyValue * mask;\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    "},Oi=function(t,e,n,r,o,a,i){void 0===n&&(n=!1),void 0===r&&(r=!1),void 0===o&&(o=!1),void 0===a&&(a=null),void 0===i&&(i=!1),this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;var s=n?t[1]:t[2],u=Math.ceil(s/2),c=n?"i * 2, rc.y":"rc.y, i * 2",l=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"],d="",f="";a&&(d=i?"vec4 activation(vec4 a) {\n          vec4 b = getPreluActivationWeightsAtOutCoords();\n          "+a+"\n        }":"vec4 activation(vec4 x) {\n          "+a+"\n        }",f="result = activation(result);");var v=o?"result += getBiasAtOutCoords();":"";o&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),this.userCode="\n      "+d+"\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, "+c+");\n          vec4 b = getMatrixB(rc.x, "+l+");\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        "+v+"\n\n        "+f+"\n\n        setOutput(result);\n      }\n    "},_i=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}(),Mi=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    "},Bi=function(t){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=t;var e=t.length;if(0===e)this.userCode="\n        void main() {\n          setOutput(vec4(getA(), 0., 0., 0.));\n        }\n      ";else{var n=Xo("rc",e),r=ua(e),o=function(t,e,n){if(1===t)return"rc > "+e[0];for(var r="",o=t-2;o<t;o++)r+=n[o]+" >= "+e[o],o<t-1&&(r+="||");return r}(e,t,n),a=function(t,e,n,r){if(1===t)return"";var o=r.slice(-2);return"\n    int r = "+o[0]+";\n    int c = "+o[1]+";\n    int rp1 = r + 1;\n    int cp1 = c + 1;\n\n    bool cEdge = cp1 >= "+e+";\n    bool rEdge = rp1 >= "+n+";\n  "}(e,t[t.length-1],t[t.length-2],n),i=function(t,e){var n=t.length,r=function(t,e){for(var n=[],r=0;r<=1;r++)for(var o=0;o<=1;o++){for(var a=(0===r?"r":"rp1")+", "+(0===o?"c":"cp1"),i=2;i<t;i++)a=e[e.length-1-i]+","+a;n.push(a)}return n}(n,e);return 1===n?"getA(rc),\n            rc + 1 >= "+t[0]+" ? 0. : getA(rc + 1),\n            0, 0":"getA("+r[0]+"),\n          cEdge ? 0. : getA("+r[1]+"),\n          rEdge ? 0. : getA("+r[2]+"),\n          rEdge || cEdge ? 0. : getA("+r[3]+")"}(t,n);this.userCode="\n        void main() {\n          "+r+" rc = getOutputCoords();\n\n          if("+o+") {\n            setOutput(vec4(0));\n          } else {\n            "+a+"\n\n            setOutput(vec4("+i+"));\n          }\n        }\n      "}},Pi=function(t,e,n){this.variableNames=["x"],this.outputShape=e.map(function(e,n){return e[0]+t[n]+e[1]});var r=t.length,o=ua(r),a=e.map(function(t){return t[0]}).join(","),i=e.map(function(e,n){return e[0]+t[n]}).join(","),s=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);this.userCode=1!==r?"\n      "+o+" start = "+o+"("+a+");\n      "+o+" end = "+o+"("+i+");\n\n      void main() {\n        "+o+" outC = getOutputCoords();\n        if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n          setOutput(float("+n+"));\n        } else {\n          "+o+" coords = outC - start;\n          setOutput(getX("+s+"));\n        }\n      }\n    ":"\n        int start = "+a+";\n        int end = "+i+";\n\n        void main() {\n          int outC = getOutputCoords();\n          if (outC < start || outC >= end) {\n            setOutput(float("+n+"));\n          } else {\n            setOutput(getX(outC - start));\n          }\n        }\n      "},Li=function(t,e,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.map(function(e,n){return e[0]+t[n]+e[1]});for(var r=t.length,o=ua(r),a=e.map(function(t){return t[0]}).join(","),i=e.map(function(e,n){return e[0]+t[n]}).join(","),s=Xo("rc",r),u=Xo("source",r),c=s[r-1]+" < "+this.outputShape[r-1],l=1===r?"source":"vec2("+u.slice(-2).join()+")",p=[o+" rc = outputLoc;",s[r-1]+" += 1;\n       if("+c+") {\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("+c+") {"],h=1===r?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",d="",f=0,v=1===r?2:4;f<v;f++)d+="\n        "+p[f]+"\n        if ("+h+") {\n          result["+f+"] = float("+n+");\n        } else {\n          "+o+" source = rc - start;\n          result["+f+"] = getChannel(getX("+u.join()+"), "+l+");\n        }\n      ";d+=1===r?"} ":"}}",this.userCode="\n      const "+o+" start = "+o+"("+a+");\n      const "+o+" end = "+o+"("+i+");\n\n      void main() {\n        "+o+" outputLoc = getOutputCoords();\n        vec4 result = vec4(0.);\n        "+d+"\n        setOutput(result);\n      }\n    "},Wi=function(t,e,n){if(this.variableNames=["x"],"avg"===e&&n)throw new Error("Cannot compute positions for average pool.");var r=t.filterWidth,o=t.strideHeight,a=t.strideWidth,i=t.dilationHeight,s=t.dilationWidth,u=t.effectiveFilterHeight,c=t.effectiveFilterWidth,l=t.padInfo.top,p=t.padInfo.left;this.outputShape=t.outShape;var h="avg"===e,d="0.0";if(h||(d="-1.0 / 1e-20"),n)this.userCode="\n        const ivec2 strides = ivec2("+o+", "+a+");\n        const ivec2 pads = ivec2("+l+", "+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 += "+i+") {\n            int xR = xRCorner + wR;\n\n            if (xR < 0 || xR >= "+t.inHeight+") {\n              continue;\n            }\n\n            for (int wC = 0; wC < "+c+";\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 * "+c+" + wC;\n              }\n            }\n          }\n          setOutput(float(minMaxPosition));\n        }\n      ";else{var f=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===e&&(f="avgValue / count");var v=4*Math.floor(r/4),m=r%4,g="\n      if ("+h+") {\n        avgValue += dot(values, ones);\n      } else {\n        minMaxValue = max(values, minMaxValue);\n      }\n    ";this.userCode="\n      const ivec2 strides = ivec2("+o+", "+a+");\n      const ivec2 pads = ivec2("+l+", "+p+");\n      const float initializationValue = "+d+";\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("+d+");\n        float avgValue = 0.0;\n        count = 0.0;\n\n        for (int wR = 0; wR < "+u+";\n            wR += "+i+") {\n          int xR = xRCorner + wR;\n\n          if (xR < 0 || xR >= "+t.inHeight+") {\n            continue;\n          }\n\n          for (int wC = 0; wC < "+v+"; wC += 4) {\n            int xC = xCCorner + wC * "+s+";\n\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              getValue(batch, xR, xC + "+s+", d),\n              getValue(batch, xR, xC + 2 * "+s+", d),\n              getValue(batch, xR, xC + 3 * "+s+", d)\n            );\n\n            "+g+"\n          }\n\n          int xC = xCCorner + "+v+";\n          if ("+(1===m)+") {\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              initializationValue,\n              initializationValue,\n              initializationValue\n            );\n\n            "+g+"\n          } else if ("+(2===m)+") {\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              getValue(batch, xR, xC + "+s+", d),\n              initializationValue,\n              initializationValue\n            );\n\n            "+g+"\n          } else if ("+(3===m)+") {\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              getValue(batch, xR, xC + "+s+", d),\n              getValue(batch, xR, xC + 2 * "+s+", d),\n              initializationValue\n            );\n\n            "+g+"\n          }\n        }\n        setOutput("+f+");\n      }\n    "}},zi=function(t,e,n){if(this.variableNames=["x"],"avg"===e&&n)throw new Error("Cannot compute positions for average pool.");var r=t.filterWidth,o=t.strideDepth,a=t.strideHeight,i=t.strideWidth,s=t.dilationDepth,u=t.dilationHeight,c=t.dilationWidth,l=t.effectiveFilterDepth,p=t.effectiveFilterHeight,h=t.effectiveFilterWidth,d=t.padInfo.front,f=t.padInfo.top,v=t.padInfo.left;this.outputShape=t.outShape;var m="avg"===e,g="0.0";if(m||(g="-1.0 / 1e-20"),n)this.userCode="\n        const ivec3 strides =\n            ivec3("+o+", "+a+", "+i+");\n        const ivec3 pads = ivec3("+d+", "+f+", "+v+");\n\n        void main() {\n          ivec5 coords = getOutputCoords();\n          int batch = coords.x;\n          int ch = coords.u;\n\n          ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n          int xDCorner = xCorner.x;\n          int xRCorner = xCorner.y;\n          int xCCorner = xCorner.z;\n\n          // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).\n          // ? = to be determined\n          float minMaxValue = 0.0;\n          float minMaxValueFound = 0.0;\n          int minMaxPosition = 0;\n\n          for (int wD = 0; wD < "+l+";\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 += "+c+") {\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 x=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"avg"===e&&(x="avgValue / count");var y=4*Math.floor(r/4),b=r%4,w="\n      if ("+m+") {\n        avgValue += dot(values, ones);\n      } else {\n        minMaxValue = max(values, minMaxValue);\n      }\n    ";this.userCode="\n      const ivec3 strides =\n        ivec3("+o+", "+a+", "+i+");\n      const ivec3 pads = ivec3("+d+", "+f+", "+v+");\n      const float initializationValue = "+g+";\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("+g+");\n        float avgValue = 0.0;\n        count = 0.0;\n\n        for (int wD = 0; wD < "+l+";\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 < "+y+"; wC += 4) {\n              int xC = xCCorner + wC * "+c+";\n\n              vec4 values = vec4(\n                getValue(batch, xD, xR, xC, ch),\n                getValue(batch, xD, xR, xC + "+c+", ch),\n                getValue(batch, xD, xR, xC + 2 * "+c+", ch),\n                getValue(batch, xD, xR, xC + 3 * "+c+", ch)\n              );\n\n              "+w+"\n            }\n\n            int xC = xCCorner + "+y+";\n            if ("+(1===b)+") {\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===b)+") {\n              vec4 values = vec4(\n                getValue(batch, xD, xR, xC, ch),\n                getValue(batch, xD, xR, xC + "+c+", ch),\n                initializationValue,\n                initializationValue\n              );\n\n              "+w+"\n            } else if ("+(3===b)+") {\n              vec4 values = vec4(\n                getValue(batch, xD, xR, xC, ch),\n                getValue(batch, xD, xR, xC + "+c+", ch),\n                getValue(batch, xD, xR, xC + 2 * "+c+", ch),\n                initializationValue\n              );\n\n              "+w+"\n            }\n          }\n          setOutput("+x+");\n        }\n      }\n    "}},Ui=function(t,e){this.variableNames=["x"];var n=t.windowSize,r=t.batchSize,o=t.inSize,a=Math.ceil(o/n);this.outputShape=[r,a];var i="0.0",s="";"prod"===e?i="1.0":"min"===e?(i="1.0 / 1e-20",s="min"):"max"===e&&(i="-1.0 / 1e-20",s="max");var u=e+"("+e+"("+e+"(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])";"sum"===e?u="sumValue":"prod"===e?u="prodValue":"all"===e?u="allValue":"any"===e&&(u="anyValue");var c=4*Math.floor(n/4),l=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?(i="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&&(i="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 d="";o%n>0&&(d="\n        if (inIdx < 0 || inIdx >= "+o+") {\n          return initializationValue;\n        }\n      "),this.userCode="\n      const float initializationValue = "+i+";\n      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n      float getValue(int batch, int inIdx) {\n        "+d+"\n        return getX(batch, inIdx);\n      }\n\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int batch = coords[0];\n        int outIdx = coords[1];\n        int inOffset = outIdx * "+n+";\n\n        vec4 minMaxValue = vec4("+i+");\n        float prodValue = 1.0;\n        float sumValue = 0.0;\n        float allValue = 1.0;\n        float anyValue = 0.0;\n\n        for (int i = 0; i < "+c+"; 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 + "+c+";\n        if ("+(1===l)+") {\n          "+h+" values = "+h+"(\n            getValue(batch, inIdx),\n            initializationValue,\n            initializationValue,\n            initializationValue\n          );\n\n          "+p+"\n        } else if ("+(2===l)+") {\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===l)+") {\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    "},Vi=function(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t;for(var n="",r=0;r<4;r++){var o="thisRC = rc;";r%2==1&&(o+="thisRC.z += 1;"),r>1&&(o+="thisRC.y += 1;"),n+="\n        "+o+"\n        "+(r>0?"if(thisRC.y < rows && thisRC.z < cols){":"")+"\n          int flatIndex = getFlatIndex(thisRC);\n\n          ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);\n          vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n          result["+r+"] =\n            getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n        "+(r>0?"}":"")+"\n      "}this.userCode="\n      \n    ivec3 inputCoordsFromReshapedOutCoords(int index) {\n      "+Yo(["r","c","d"],e)+"\n      return ivec3(r, c, d);\n    }\n  \n      "+Qo(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    "},Gi=function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,o=r[1],a=r[2],i=t.shape,s=i[1],u=i[2],c=[n&&s>1?o-1:o,n&&u>1?a-1:a],l=[n&&s>1?s-1:s,n&&u>1?u-1:u],p=c[0]/l[0],h=c[1]/l[1],d=1/p,f=1/h,v=2*Math.ceil(d)+2,m=2*Math.ceil(f)+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("+d+");\n        const float invWidthScale = float("+f+");\n\n        const int winHeight = int("+v+");\n        const int winWidth = int("+m+");\n\n        // Compute bounds for where in dy we will look\n        float startRLerp = floor(float(r) * invHeightScale);\n        int startDyR = int(startRLerp - float(winHeight / 2));\n\n        float startCLerp = floor(float(c) * invWidthScale);\n        int startDyC = int(startCLerp - float(winWidth / 2));\n\n        // Loop over dy\n        for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n          int dyR = dyROffset + startDyR;\n\n          // Guard against the window exceeding the bounds of dy\n          if (dyR < 0 || dyR >= "+s+") {\n            continue;\n          }\n\n          for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n            int dyC = dyCOffset + startDyC;\n\n            // Guard against the window exceeding the bounds of dy\n            if (dyC < 0 || dyC >= "+u+") {\n              continue;\n            }\n\n            float dxR = float(dyR) * heightScale;\n            int topDxRIndex = int(floor(dxR));\n            int bottomDxRIndex = int(min(ceil(dxR), "+(o-1)+".0));\n            float dxRLerp = dxR - float(topDxRIndex);\n            float inverseDxRLerp = 1.0 - dxRLerp;\n\n            float dxC = float(dyC) * widthScale;\n            int leftDxCIndex = int(floor(dxC));\n            int rightDxCIndex = int(min(ceil(dxC), "+(a-1)+".0));\n            float dxCLerp = dxC - float(leftDxCIndex);\n            float inverseDxCLerp = 1.0 - dxCLerp;\n\n            if (r == topDxRIndex && c == leftDxCIndex) {\n              // topLeft\n              accumulator +=\n                getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;\n            }\n\n            if (r == topDxRIndex && c == rightDxCIndex) {\n              // topRight\n              accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;\n            }\n\n            if (r == bottomDxRIndex && c == leftDxCIndex) {\n              // bottomLeft\n              accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;\n            }\n\n            if (r == bottomDxRIndex && c == rightDxCIndex) {\n              // bottomRight\n              accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;\n            }\n          }\n        }\n        // End loop over dy\n\n        setOutput(accumulator);\n      }\n    "},Hi=function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var o=t[0],a=t[1],i=t[2],s=t[3];this.outputShape=[o,e,n,s];var u=[r&&e>1?a-1:a,r&&n>1?i-1:i],c=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n      const vec2 effectiveInputOverOutputRatioRC = vec2(\n          "+u[0]/c[0]+",\n          "+u[1]/c[1]+");\n      const vec2 inputShapeRC = vec2("+a+".0, "+i+".0);\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n        ivec2 yRC = coords.yz;\n\n        // Fractional source index.\n        vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n        // Compute the four integer indices.\n        ivec2 sourceFloorRC = ivec2(sourceFracIndexRC);\n        ivec2 sourceCeilRC = ivec2(\n          min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n        float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\n        float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\n        float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\n        float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n        vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n        float top = topLeft + (topRight - topLeft) * fracRC.y;\n        float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n        float newValue = top + (bottom - top) * fracRC.x;\n\n        setOutput(newValue);\n      }\n    "},qi=function(t,e,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];var o=t[0],a=t[1],i=t[2],s=t[3];this.outputShape=[o,e,n,s];var u=[r&&e>1?a-1:a,r&&n>1?i-1:i],c=[r&&e>1?e-1:e,r&&n>1?n-1:n];this.userCode="\n      const vec3 effectiveInputOverOutputRatioRC = vec3(\n          "+u[0]/c[0]+",\n          "+u[1]/c[1]+",\n          "+u[1]/c[1]+");\n      const vec3 inputShapeRC = vec3("+a+".0, "+i+".0,\n                                     "+i+".0);\n\n      float getAValue(int b, int r, int c, int d) {\n        return getChannel(getA(b, r, c, d), vec2(c, d));\n      }\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n        // Calculate values for next column in yRC.z.\n        ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n        // Fractional source index.\n        vec3 sourceFracIndexRC = vec3(yRC) * effectiveInputOverOutputRatioRC;\n\n        // Compute the four integer indices.\n        ivec3 sourceFloorRC = ivec3(sourceFracIndexRC);\n        ivec3 sourceCeilRC = ivec3(\n          min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n        // Should we calculate next column and row elements in 2x2 packed cell.\n        bool hasNextCol = d < "+(s-1)+";\n        bool hasNextRow = coords.z < "+(n-1)+";\n\n        // In parallel, construct four corners for all four components in\n        // packed 2x2 cell.\n        vec4 topLeft = vec4(\n          getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),\n          hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)\n                     : 0.0,\n          hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)\n                     : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n        vec4 bottomLeft = vec4(\n          getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),\n          hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)\n                     : 0.0,\n          hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)\n                     : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n        vec4 topRight = vec4(\n          getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),\n          hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)\n                     : 0.0,\n          hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)\n                     : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n        vec4 bottomRight = vec4(\n          getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),\n          hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)\n                     : 0.0,\n          hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)\n                     : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n        vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);\n\n        vec4 top = mix(topLeft, topRight, fracRC.yyzz);\n        vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);\n        vec4 newValue = mix(top, bottom, fracRC.x);\n\n        setOutput(newValue);\n      }\n    "},Ki=function(t,e,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=e.shape;var r=e.shape,o=r[1],a=r[2],i=t.shape,s=i[1],u=i[2],c=[n&&s>1?o-1:o,n&&u>1?a-1:a],l=[n&&s>1?s-1:s,n&&u>1?u-1:u],p=c[0]/l[0],h=c[1]/l[1],d=1/p,f=1/h,v=2*Math.ceil(d)+2,m=2*Math.ceil(f)+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("+d+");\n        const float invWidthScale = float("+f+");\n\n        const int winHeight = int("+v+");\n        const int winWidth = int("+m+");\n\n        // Compute bounds for where in dy we will look\n        float startRLerp = floor(float(r) * invHeightScale);\n        int startDyR = int(floor(startRLerp - float(winHeight / 2)));\n\n        float startCLerp = floor(float(c) * invWidthScale);\n        int startDyC = int(floor(startCLerp - float(winWidth / 2)));\n\n        // Loop over dy\n        for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n          int dyR = dyROffset + startDyR;\n\n          // Guard against the window exceeding the bounds of dy\n          if (dyR < 0 || dyR >= "+s+") {\n            continue;\n          }\n\n          for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n            int dyC = dyCOffset + startDyC;\n\n            // Guard against the window exceeding the bounds of dy\n            if (dyC < 0 || dyC >= "+u+") {\n              continue;\n            }\n\n            float sourceFracRow =\n              float("+c[0]+") *\n                (float(dyR) / float("+l[0]+"));\n\n            float sourceFracCol =\n                float("+c[1]+") *\n                  (float(dyC) / float("+l[1]+"));\n\n            int sourceNearestRow = int(min(\n                float(int("+o+") - 1),\n                "+n+" ? float(round(sourceFracRow)) :\n                                  float(floor(sourceFracRow))));\n\n            int sourceNearestCol = int(min(\n                float(int("+a+") - 1),\n                "+n+" ? float(round(sourceFracCol)) :\n                                  float(floor(sourceFracCol))));\n\n            if (r == sourceNearestRow && c == sourceNearestCol) {\n              accumulator += getDy(b, dyR, dyC, d);\n            }\n          }\n        }\n        // End loop over dy\n\n        setOutput(accumulator);\n      }\n    "},ji=function(t,e,n,r){this.variableNames=["A"],this.outputShape=[];var o=t[0],a=t[1],i=t[2],s=t[3];this.outputShape=[o,e,n,s];var u=[r&&e>1?a-1:a,r&&n>1?i-1:i],c=[r&&e>1?e-1:e,r&&n>1?n-1:n],l=r?"0.5":"0.0";this.userCode="\n      const vec2 effectiveInputOverOutputRatioRC = vec2(\n          "+u[0]/c[0]+",\n          "+u[1]/c[1]+");\n      const vec2 inputShapeRC = vec2("+a+".0, "+i+".0);\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n        ivec2 yRC = coords.yz;\n\n        // Fractional source index.\n        vec2 sourceFracIndexRC = vec2(yRC) * effectiveInputOverOutputRatioRC;\n\n        // Compute the coordinators of nearest neighbor point.\n        ivec2 sourceNearestRC = ivec2(\n          min(inputShapeRC - 1.0, floor(sourceFracIndexRC + "+l+")));\n\n        float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n        setOutput(newValue);\n      }\n    "},Xi=function(t,e){this.variableNames=["x"];var n=t.length;if(n>4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");if(this.outputShape=t,1!==n){var r=t.map(function(n,r){return function(n){return-1!==e.indexOf(n)&&1!==t[n]?t[n]+" - coords["+n+"] - 1":"coords["+n+"]"}(r)}).join(","),o=ua(n);this.userCode="\n      void main() {\n        "+o+" coords = getOutputCoords();\n        setOutput(getX("+r+"));\n      }\n    "}else this.userCode="\n        void main() {\n          int coord = getOutputCoords();\n          setOutput(getX("+t[0]+" - coord - 1));\n        }\n      "},$i=function(t,e){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;var n=t.length;if(n>4)throw new Error("WebGL backend: Reverse of rank-"+n+" tensor is not yet supported");this.outputShape=t;var r=Xo("rc",n),o=r[n-1]+" + 1 < "+this.outputShape[n-1],a=r[n-2]+" + 1 < "+this.outputShape[n-2],i=ua(n);function s(n){var r=t.map(function(r,o){return function(n,r){return-1!==e.indexOf(n)&&1!==t[n]?t[n]+" - "+r[n]+" - 1":""+r[n]}(o,n)});return"getChannel(getX("+r.join(",")+"), vec2("+r.slice(-2).join(",")+"))"}this.userCode=1===n?"\n        void main(){\n          int rc = getOutputCoords();\n          vec4 result = vec4(0.);\n          result.r = getChannel(getX("+t[0]+" - rc - 1),\n            "+t[0]+" - rc - 1);\n          if("+o+"){\n              result.g = getChannel(getX("+t[0]+" - (rc  + 1) - 1),\n                "+t[0]+" - (rc  + 1) - 1);\n          }\n          setOutput(result);\n        }\n      ":"\n        void main() {\n          "+i+" rc = getOutputCoords();\n          vec4 result = vec4(0.);\n          result.r = "+s(r.slice())+";\n          if("+o+"){\n            result.g = "+function(t){return t[n-1]="("+t[n-1]+" + 1)",s(t)}(r.slice())+";\n          }\n          if("+a+") {\n            result.b = "+function(t){return t[n-2]="("+t[n-2]+" + 1)",s(t)}(r.slice())+";\n            if("+o+") {\n              result.a = "+function(t){return t[n-1]="("+t[n-1]+" + 1)",t[n-2]="("+t[n-2]+" + 1)",s(t)}(r.slice())+";\n            }\n          }\n          setOutput(result);\n        }\n    "},Yi=function(t,e,n,r,o,a,i){void 0===i&&(i=!0),this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;var s=ua(o.length),u=ua(a.length),c="";1===n?c="i":2===n&&(c="i, j");var l="getIndices("+c+")",p="";1===r?p="i":2===r&&(p="i, coords[1]");var h="getUpdates("+p+")",d=e>1?"strides[j]":"strides";this.userCode="\n        "+s+" strides = "+s+"("+o+");\n\n        void main() {\n          "+u+" coords = getOutputCoords();\n          float sum = 0.0;\n          bool found = false;\n          for (int i = 0; i < "+t+"; i++) {\n            int flattenedIndex = 0;\n            for (int j = 0; j < "+e+"; j++) {\n              int index = round("+l+");\n              flattenedIndex += index * "+d+";\n            }\n            if (flattenedIndex == coords[0]) {\n              sum += "+h+";\n              found = true;\n            }\n          }\n          setOutput(mix(getDefaultValue(), sum, float(found)));\n        }\n      "},Qi=function(t,e){this.variableNames=["x","segmentIds"];var n=t.windowSize,r=t.batchSize,o=t.inSize,a=t.numSegments,i=a*Math.ceil(o/n);this.outputShape=[r,i];var s=4*Math.floor(n/4),u=n%4,c="\n        sumValue += dot(values, segFilter);\n    ",l="";o%n>0&&(l="\n        if (inIdx < 0 || inIdx >= "+o+") {\n          return initializationValue;\n        }\n      ");var p="";o%n>0&&(p="\n        if (inIdx < 0 || inIdx >= "+o+") {\n          return -1.0;\n        }\n      "),this.userCode="\n      const float initializationValue = 0.0;\n\n      float getValue(int batch, int inIdx) {\n        "+l+"\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          "+c+"\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          "+c+"\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          "+c+"\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          "+c+"\n        }\n        setOutput(sumValue);\n      }\n    "},Ji=function(t,e,n){var r,o;if(this.variableNames=["c","a","b"],this.outputShape=e,n>4)throw Error("Where for rank "+n+" is not yet supported");if(1===n)o="resRC",r="resRC";else{for(var a=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],s=[],u=0;u<e.length;u++)s.push(""+a[u]),u<t&&i.push(""+a[u]);r=i.join(),o=s.join()}var c=ua(n);this.userCode="\n      void main() {\n        "+c+" resRC = getOutputCoords();\n        float cVal = getC("+r+");\n        if (cVal >= 1.0) {\n          setOutput(getA("+o+"));\n        } else {\n          setOutput(getB("+o+"));\n        }\n      }\n    "},Zi=function(){function t(t){this.variableNames=["source"],this.outputShape=t,this.rank=t.length;var e,n=ua(this.rank),r="uniform int start["+this.rank+"];",o=function(t){if(1===t)return"sourceLoc";if(t<=6)return ts.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."+ts[e]+" = start["+e+"] + coords."+ts[e]+";"}).join("\n")+"\n      ",this.userCode="\n      "+r+"\n      void main() {\n        "+e+"\n        setOutput(getSource("+o+"));\n      }\n    "}return t.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+t.length+")");return function(n,r){null==e.startLoc&&(e.startLoc=n.getUniformLocationNoThrow(r,"start"),null==e.startLoc)||n.gl.uniform1iv(e.startLoc,t)}},t}(),ts=["x","y","z","w","u","v"],es=function(){function t(t){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.rank=t.length;var e=ua(this.rank),n=Xo("coords",this.rank),r=Xo("sourceLoc",this.rank),o=1===this.rank?"sourceLoc":"vec2("+r.slice(-2).join()+")",a="getChannel(getSource("+r.join()+"), "+o+")",i="\n      result.x = "+a+";\n      if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n        ++"+r[this.rank-1]+";\n        result.y = "+a+";\n        --"+r[this.rank-1]+";\n      }\n    ",s=1===this.rank?"":"\n      --"+n[this.rank-1]+";\n      if (++"+n[this.rank-2]+" < "+t[this.rank-2]+") {\n        ++"+r[this.rank-2]+";\n        result.z = "+a+";\n        if (++"+n[this.rank-1]+" < "+t[this.rank-1]+") {\n          ++"+r[this.rank-1]+";\n          result.w = "+a+";\n        }\n      }\n    ",u=this.rank<=4?"sourceLoc = coords +\n            "+e+"("+t.map(function(t,e){return"start["+e+"]"}).join()+");":t.map(function(t,e){return r[e]+" = "+n[e]+" + start["+e+"];"}).join("\n");this.userCode="\n      uniform int start["+this.rank+"];\n      void main() {\n        "+e+" coords = getOutputCoords();\n        "+e+" sourceLoc;\n        "+u+"\n        vec4 result = vec4(0.);\n        "+i+"\n        "+s+"\n        setOutput(result);\n      }\n    "}return t.prototype.getCustomSetupFunc=function(t){var e=this;if(t.length!==this.rank)throw Error("The rank ("+this.rank+") of the program must match the length of start ("+t.length+")");return function(n,r){null==e.startLoc&&(e.startLoc=n.getUniformLocationNoThrow(r,"start"),null==e.startLoc)||n.gl.uniform1iv(e.startLoc,t)}},t}(),ns=function(t,e,n){this.variableNames=["x"],this.outputShape=n;var r=n.length,o=ua(n.length),a=ua(n.length),i="";if(1===r)i="coords * strides + begin";else{var s=0;i=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      "+o+" begin = "+o+"("+t+");\n      "+o+" strides = "+o+"("+e+");\n\n      void main() {\n        "+a+" coords = getOutputCoords();\n        setOutput(getX("+i+"));\n      }\n    "},rs=function(){function t(t){this.gpgpu=t,this.numUsedTextures=0,this.numFreeTextures=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}return t.prototype.acquireTexture=function(t,e,n){var r,o=os(e,n),a=as(t,o,n);if(a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]),this.freeTextures[a].length>0){this.numFreeTextures--,this.numUsedTextures++,this.log();var i=this.freeTextures[a].shift();return this.usedTextures[a].push(i),i}return this.numUsedTextures++,this.log(),o===Wt.PACKED_2X2_FLOAT32?r=this.gpgpu.createPackedMatrixTexture(t[0],t[1]):o===Wt.PACKED_2X2_FLOAT16?r=this.gpgpu.createFloat16PackedMatrixTexture(t[0],t[1]):o===Wt.UNPACKED_FLOAT32?r=this.gpgpu.createFloat32MatrixTexture(t[0],t[1]):o===Wt.UNPACKED_FLOAT16?r=this.gpgpu.createFloat16MatrixTexture(t[0],t[1]):o===Wt.PACKED_4X1_UNSIGNED_BYTE&&(r=this.gpgpu.createUnsignedBytesMatrixTexture(t[0],t[1])),this.usedTextures[a].push(r),r},t.prototype.releaseTexture=function(t,e,n,r){if(null!=this.freeTextures){var o=as(e,os(n,r),r);o in this.freeTextures||(this.freeTextures[o]=[]),this.freeTextures[o].push(t),this.numFreeTextures++,this.numUsedTextures--;var a=this.usedTextures[o],i=a.indexOf(t);if(i<0)throw new Error("Cannot release a texture that was never provided by this texture manager");a.splice(i,1),this.log()}},t.prototype.log=function(){if(this.logEnabled){var t=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",this.numFreeTextures+" / "+this.numUsedTextures,"("+t+")")}},t.prototype.getNumUsedTextures=function(){return this.numUsedTextures},t.prototype.getNumFreeTextures=function(){return this.numFreeTextures},t.prototype.dispose=function(){var t=this;if(null!=this.freeTextures){for(var e in this.freeTextures)this.freeTextures[e].forEach(function(e){t.gpgpu.deleteMatrixTexture(e)});for(var e in this.usedTextures)this.usedTextures[e].forEach(function(e){t.gpgpu.deleteMatrixTexture(e)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0}},t}();function os(t,e){if(t===Lt.UPLOAD)return Wt.PACKED_2X2_FLOAT32;if(t===Lt.RENDER||null==t)return function(t){return u().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?t?Wt.PACKED_2X2_FLOAT32:Wt.UNPACKED_FLOAT32:t?Wt.PACKED_2X2_FLOAT16:Wt.UNPACKED_FLOAT16}(e);if(t===Lt.DOWNLOAD||t===Lt.PIXELS)return Wt.PACKED_4X1_UNSIGNED_BYTE;throw new Error("Unknown logical texture type "+t)}function as(t,e,n){return t[0]+"_"+t[1]+"_"+e+"_"+n}var is=function(t,e){this.variableNames=["A"];for(var n=new Array(t.length),r=0;r<n.length;r++)n[r]=t[r]*e[r];this.outputShape=n,this.rank=n.length;var o=ua(this.rank),a=function(t){var e=t.length;if(e>5)throw Error("Tile for rank "+e+" is not yet supported");if(1===e)return"imod(resRC, "+t[0]+")";for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],r=[],o=0;o<t.length;o++)r.push("imod("+n[o]+", "+t[o]+")");return r.join()}(t);this.userCode="\n      void main() {\n        "+o+" resRC = getOutputCoords();\n        setOutput(getA("+a+"));\n      }\n    "},ss=function(t,e){this.variableNames=["A"];for(var n=new Array(t.length),r=0;r<n.length;r++)n[r]=t[e[r]];this.outputShape=n,this.rank=n.length;var o=ua(this.rank),a=function(t){var e=t.length;if(e>6)throw Error("Transpose for rank "+e+" is not yet supported");for(var n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(e),o=0;o<t.length;o++)r[t[o]]=n[o];return r.join()}(e);this.userCode="\n    void main() {\n      "+o+" resRC = getOutputCoords();\n      setOutput(getA("+a+"));\n    }\n    "},us=function(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;for(var n=new Array(t.length),r=0;r<n.length;r++)n[r]=t[e[r]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error("Packed transpose for rank "+this.rank+" is not yet supported.");var o=ua(this.rank),a=jo("rc",this.rank),i=new Array(this.rank);for(r=0;r<e.length;r++)i[e[r]]=a[r];var s="vec2("+i.slice(-2).join()+")",u="++"+a[this.rank-1]+" < "+n[this.rank-1],c="getChannel(getA("+i.join()+"), "+s+")";this.userCode="\n    void main() {\n      "+o+" rc = getOutputCoords();\n      vec4 result = vec4(0.);\n      result[0] = "+c+";\n      if("+u+") {\n        result[1] = "+c+";\n      }\n      --"+a[this.rank-1]+";\n      if(++"+a[this.rank-2]+" < "+n[this.rank-2]+") {\n        result[2] = "+c+";\n        if("+u+") {\n          result[3] = "+c+";\n        }\n      }\n      setOutput(result);\n    }\n    "},cs=1.7580993408473768,ls=1.0507009873554805,ps=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    "},hs="if (isnan(x)) return x;",ds="return x;",fs="return abs(x);",vs=hs+"\n  return (x < 0.0) ? 0.0 : x;\n",ms=hs+"\n  return (x < 0.0) ? 0.0 : min(6.0, x);\n",gs="return (x >= 0.0) ? x : (exp(x) - 1.0);",xs="\n  // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n  // see: https://arxiv.org/abs/1706.02515\n  float scaleAlpha = "+cs+";\n  float scale = "+ls+";\n  return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n",ys="return -x;",bs="return ceil(x);",ws="return floor(x);",Cs="return exp(x);",Es="return exp(x) - 1.0;",Rs=hs+"\n  return sin(x);\n",Is=hs+"\n  return cos(x);\n",ks=hs+"\n  if (abs(x) > 1.) {\n    return NAN;\n  }\n  return asin(x);\n",Ss=hs+"\n  if (abs(x) > 1.) {\n    return NAN;\n  }\n  return acos(x);\n",As=hs+"\n  return atan(x);\n",Ds=hs+"return log(x + sqrt(x * x + 1.0));",Ns=hs+"\n  if (x < 1.0) return NAN;\n  return log(x + sqrt(x * x - 1.0));",Ts=hs+"\n  if ((x < -1.0) || (x > 1.0)) return NAN;\n  return (log(1.0 + x) - log(1.0 - x)) / 2.0;",Fs="return x;",Os="return x;",_s="\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",Ms="\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",Bs="\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",Ps=function(t,e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t,this.userCode="\n      vec4 unaryOperation(vec4 x) {\n        "+e+"\n      }\n\n      void main() {\n        vec4 x = getAAtOutCoords();\n        vec4 y = unaryOperation(x);\n\n        setOutput(y);\n      }\n    "},Ls=function(t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=t;var e=t.length,n=Xo("rc",e),r=ua(e),o=function(t,e){if(1===t)return"rc";for(var n="",r=0;r<t;r++)n+=e[r],r<t-1&&(n+=",");return n}(e,n),a=n.slice(-2),i=e<=1?"rc":"vec2("+a.join(",")+")";this.userCode="\n      void main() {\n        "+r+" rc = getOutputCoords();\n        vec4 packedInput = getA("+o+");\n\n        setOutput(getChannel(packedInput, "+i+"));\n      }\n    "},Ws={};function zs(t,e){if(void 0===e&&(e=!1),"linear"===t)return e?Os:ds;if("relu"===t)return e?_s:vs;if("elu"===t)return e?Bs:gs;if("relu6"===t)return e?Ms:ms;if("prelu"===t)return e?Ra:Ca;throw new Error("Activation "+t+" has not been implemented for the WebGL backend.")}var Us=600,Vs=function(t){function e(e){var n,r=t.call(this)||this;if(r.gpgpu=e,r.pendingRead=new WeakMap,r.pendingDisposal=new WeakSet,r.dataRefCount=new WeakMap,r.numBytesInGPU=0,r.uploadWaitMs=0,r.downloadWaitMs=0,r.warnedAboutMemory=!1,r.pendingDeletes=0,r.disposed=!1,!u().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(null==e){var o=Gt(u().getNumber("WEBGL_VERSION"));r.binaryCache=(n=u().getNumber("WEBGL_VERSION"))in Ws?Ws[n]:(Ws[n]={},Ws[n]),r.gpgpu=new Ii(o),r.canvas=o.canvas,r.gpgpuCreatedLocally=!0}else r.binaryCache={},r.gpgpuCreatedLocally=!1,r.canvas=e.gl.canvas;return r.textureManager=new rs(r.gpgpu),r.numMBBeforeWarning=null==u().global.screen?1024:u().global.screen.height*u().global.screen.width*window.devicePixelRatio*Us/1024/1024,r.texData=new po(r,_t),r}return o(e,t),e.prototype.numDataIds=function(){return this.texData.numDataIds()+(this.cpuBackend?this.cpuBackend.numDataIds():0)-this.pendingDeletes},e.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,o="undefined"!=typeof ImageData&&t instanceof ImageData,a="undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement,i="undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement,s=a?[t.videoWidth,t.videoHeight]:[t.width,t.height],c=s[0],l=s[1],p=[l,c],h=[l,c,e];if(!(n||r||o||a||i))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);(i||a)&&(null==this.fromPixels2DContext&&(this.fromPixels2DContext=Ht(u().getNumber("WEBGL_VERSION")).getContext("2d")),this.fromPixels2DContext.canvas.width=c,this.fromPixels2DContext.canvas.height=l,this.fromPixels2DContext.drawImage(t,0,0,c,l),t=this.fromPixels2DContext.canvas);var d,f,v=this.makeTensorInfo(p,"int32");return this.texData.get(v.dataId).usage=Lt.PIXELS,this.gpgpu.uploadPixelDataToTexture(this.getTexture(v.dataId),t),u().getBool("WEBGL_PACK")?(d=new oi(h),f=this.compileAndRun(d,[v])):(d=new ri(h),f=this.compileAndRun(d,[v])),this.disposeData(v.dataId),f},e.prototype.write=function(t,e,n){if(u().getBool("DEBUG")&&this.checkNumericalProblems(t),"complex64"===n&&null!=t)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");var r={};return this.texData.set(r,{shape:e,dtype:n,values:t,usage:Lt.UPLOAD}),r},e.prototype.move=function(t,e,n,r){if(u().getBool("DEBUG")&&this.checkNumericalProblems(e),"complex64"===r)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(t,{shape:n,dtype:r,values:e,usage:Lt.UPLOAD})},e.prototype.readSync=function(t){var e=this.texData.get(t),n=e.values,r=e.dtype,o=e.complexTensors,a=e.slice,i=e.shape,s=e.isPacked;if(null!=a){var u;u=s?new Ps(i,Fs):new ps(i,Fs);var c=this.runWebGLProgram(u,[{dataId:t,shape:i,dtype:r}],r),l=this.readSync(c.dataId);return this.disposeData(c.dataId),l}if(null!=n)return this.convertAndCacheOnCPU(t);if("string"===r)return n;var p,h,d=null!=this.activeTimers;return d&&(p=Z()),h="complex64"===r?_o(o.real.dataSync(),o.imag.dataSync()):this.getValuesFromTexture(t),d&&(this.downloadWaitMs+=Z()-p),this.convertAndCacheOnCPU(t,h)},e.prototype.read=function(t){return a(this,void 0,void 0,function(){var e,n,r,o,a,s,c,l,p,h,d,f,v,m,g,x,y,b,w,C,E,I;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,o=n.shape,a=n.slice,s=n.dtype,c=n.complexTensors,l=n.isPacked,null!=a)return void 0,p=l?new Ps(o,Fs):new ps(o,Fs),h=this.runWebGLProgram(p,[{dataId:t,shape:o,dtype:s}],s),d=this.read(h.dataId),this.disposeData(h.dataId),[2,d];if(null!=r)return[2,this.convertAndCacheOnCPU(t)];if(!u().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===u().getNumber("WEBGL_VERSION"))throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");return f=null,"complex64"!==s&&u().get("WEBGL_BUFFER_SUPPORTED")&&(v=this.decode(t),m=this.texData.get(v.dataId),f=(I=this.gpgpu).createBufferFromTexture.apply(I,[m.texture].concat(Kt(o)))),this.pendingRead.set(t,[]),"complex64"===s?[3,2]:[4,this.gpgpu.createAndWaitForFence()];case 1:i.sent(),i.label=2;case 2:return"complex64"!==s?[3,4]:[4,Promise.all([c.real.data(),c.imag.data()])];case 3:return x=i.sent(),y=x[0],b=x[1],g=_o(y,b),[3,5];case 4:null==f?g=this.getValuesFromTexture(t):(w=R(o),g=this.gpgpu.downloadFloat32MatrixFromBuffer(f,w)),i.label=5;case 5:return null!=v&&this.disposeData(v.dataId),C=this.convertAndCacheOnCPU(t,g),E=this.pendingRead.get(t),this.pendingRead.delete(t),E.forEach(function(t){return t(C)}),this.pendingDisposal.has(t)&&(this.pendingDisposal.delete(t),this.disposeData(t),this.pendingDeletes--),[2,C]}})})},e.prototype.checkNumericalProblems=function(t){if(null!=t)for(var e=0;e<t.length;e++){var n=t[e];if(!Jt(n)){if(u().getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))throw Error("The value "+n+" cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'");throw Error("The value "+n+" cannot be represented on this device.")}}},e.prototype.getValuesFromTexture=function(t){var e,n=this.texData.get(t),r=n.shape,o=n.dtype,a=n.isPacked,i=R(r);if(u().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){var s=this.decode(t),c=this.texData.get(s.dataId),l=(e=this.gpgpu).downloadMatrixFromPackedTexture.apply(e,[c.texture].concat(Kt(r))).subarray(0,i);return this.disposeData(s.dataId),l}var p=u().getBool("WEBGL_PACK")&&!0===a,h=p?Se(r):r,d=p?new Ya(h):new $a(h),f=this.runWebGLProgram(d,[{shape:h,dtype:o,dataId:t}],"float32"),v=this.texData.get(f.dataId),m=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(v.texture,v.texShape[0],v.texShape[1]).subarray(0,i);return this.disposeData(f.dataId),m},e.prototype.time=function(t){return a(this,void 0,void 0,function(){var e,n,r,o,a,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(),o=E(this.activeTimers.map(function(t){return t.query})).filter(function(t){return null!=t}),a=E(this.activeTimers.map(function(t){return t.name})).filter(function(t){return null!=t}),this.activeTimers=e,r&&(this.programTimersStack=null),[4,Promise.all(o)];case 1:return s=i.sent(),u={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:y(s),getExtraProfileInfo:function(){return s.map(function(t,e){return{name:a[e],ms:t}}).map(function(t){return t.name+": "+t.ms}).join(", ")},wallMs:null},this.uploadWaitMs=0,this.downloadWaitMs=0,[2,u]}})})},e.prototype.memory=function(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU}},e.prototype.startTimer=function(){return u().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?this.gpgpu.beginQuery():{startMs:Z(),endMs:null}},e.prototype.endTimer=function(t){return u().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(this.gpgpu.endQuery(),t):(t.endMs=Z(),t)},e.prototype.getQueryTime=function(t){return a(this,void 0,void 0,function(){var e;return i(this,function(n){return u().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?[2,this.gpgpu.waitForQueryAndGetTime(t)]:[2,(e=t).endMs-e.startMs]})})},e.prototype.disposeData=function(t){if(!this.pendingDisposal.has(t)){if(this.pendingRead.has(t))return this.pendingDisposal.add(t),void this.pendingDeletes++;if(this.texData.has(t)){this.releaseGPUData(t);var e=this.texData.get(t).complexTensors;null!=e&&(e.real.dispose(),e.imag.dispose()),this.texData.delete(t)}}},e.prototype.releaseGPUData=function(t){var e=this.texData.get(t),n=e.texture,r=e.dtype,o=e.texShape,a=e.usage,i=e.isPacked,s=e.slice,u=s&&s.origDataId||t,c=this.dataRefCount.get(u);c>1?this.dataRefCount.set(u,c-1):(this.dataRefCount.delete(u),null!=n&&(this.numBytesInGPU-=this.computeBytes(o,r),this.textureManager.releaseTexture(n,o,a,i)));var l=this.texData.get(t);l.texture=null,l.texShape=null,l.isPacked=!1,l.slice=null},e.prototype.getTexture=function(t){return this.uploadToGPU(t),this.texData.get(t).texture},e.prototype.getDataInfo=function(t){return this.texData.get(t)},e.prototype.getCPUBackend=function(){return u().getBool("WEBGL_CPU_FORWARD")?(null==this.cpuBackend&&(this.cpuBackend=_t.findBackend("cpu")),this.cpuBackend):null},e.prototype.shouldExecuteOnCPU=function(t,e){var n=this;return void 0===e&&(e=128),null!=this.getCPUBackend()&&t.every(function(t){return null==n.texData.get(t.dataId).texture&&t.size<e})},e.prototype.getGPGPUContext=function(){return this.gpgpu},e.prototype.complex=function(t,e){var n=this.makeOutput(t.shape,"complex64");return this.texData.get(n.dataId).complexTensors={real:_t.keep(t.clone()),imag:_t.keep(e.clone())},n},e.prototype.real=function(t){return this.texData.get(t.dataId).complexTensors.real.clone()},e.prototype.imag=function(t){return this.texData.get(t.dataId).complexTensors.imag.clone()},e.prototype.slice=function(t,e,n){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.slice(t,e,n);if(0===R(n))return Dn([],n,t.dtype);var r=this.texData.get(t.dataId).isPacked,o=Zr(t.shape,e,n);if(r||!o){var a=u().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new es(n):new Zi(n),i=a.getCustomSetupFunc(e);return this.compileAndRun(a,[t],null,i)}return this.uploadToGPU(t.dataId),this.shallowSlice(t,e,n)},e.prototype.shallowSlice=function(t,e,n){var r=this.texData.get(t.dataId),o=this.makeOutput(n,t.dtype),a=this.texData.get(o.dataId);Object.assign(a,r),a.shape=n,a.dtype=t.dtype;var i=to(e,t.strides);r.slice&&(i+=r.slice.flatOffset),a.slice={flatOffset:i,origDataId:r.slice&&r.slice.origDataId||t.dataId};var s=this.dataRefCount.get(a.slice.origDataId)||1;return this.dataRefCount.set(a.slice.origDataId,s+1),o},e.prototype.stridedSlice=function(t,e,n,r){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.stridedSlice(t,e,n,r);var o=Yr(e,n,r);if(o.some(function(t){return 0===t}))return Dn([],o);var a=new ns(e,r,o);return this.compileAndRun(a,[t])},e.prototype.reverse=function(t,e){var n=u().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new $i(t.shape,e):new Xi(t.shape,e);return this.compileAndRun(n,[t])},e.prototype.concat=function(t,e){if("complex64"===t[0].dtype){var n=t.map(function(t){return Sn(t)}),r=t.map(function(t){return An(t)});return kn(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>u().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){var o=Math.floor(t.length/2),a=this.concat(t.slice(0,o),e),i=this.concat(t.slice(o),e);return this.concat([a,i],e)}if(u().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&t[0].rank>1){var s=new Na(t.map(function(t){return t.shape}),e);return this.compileAndRun(s,t)}var c=Rn(t.map(function(t){return t.shape}),e),l=t.map(function(t){return t.as2D(-1,R(t.shape.slice(e)))}),p=new Da(l.map(function(t){return t.shape}));return this.compileAndRun(p,l).reshape(c)},e.prototype.neg=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.neg(t);if(u().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,ys,t.dtype);var e=new ps(t.shape,ys);return this.compileAndRun(e,[t])},e.prototype.batchMatMul=function(t,e,n,r){var o=n?t.shape[2]:t.shape[1],a=r?e.shape[1]:e.shape[2],i=n?t.shape[1]:t.shape[2],s=t.shape[0];if((1===o||1===a)&&i>1e3){n&&(t=t.transpose([0,2,1])),r&&(e=e.transpose([0,2,1]));var u=1===a?t:t.as3D(s,i,1),c=1===a?2:1,l=1===a?e.as3D(s,1,i):e;return this.multiply(u,l).sum(c,!0)}var p=It(t.dtype,e.dtype),h=new Oi(t.shape,[s,o,a],n,r);return this.compileAndRun(h,[t,e],p)},e.prototype.fusedBatchMatMul=function(t){var e=t.a,n=t.b,r=t.transposeA,o=t.transposeB,a=t.bias,i=t.activation,s=t.preluActivationWeights,u=r?e.shape[2]:e.shape[1],c=o?n.shape[1]:n.shape[2],l=e.shape[0],p=It(e.dtype,n.dtype),h=null!=a,d=null!=s,f=i?zs(i,!0):null,v=new Oi(e.shape,[l,u,c],r,o,h,f,d),m=[e,n];return a&&m.push(a),s&&m.push(s),this.compileAndRun(v,m,p)},e.prototype.multiply=function(t,e){if("complex64"===t.dtype){var n=this.texData.get(t.dataId),r=this.texData.get(e.dataId),o=new xa(ma,t.shape,e.shape),a=new xa(ga,t.shape,e.shape),i=[this.makeComplexComponentTensorInfo(t,n.complexTensors.real),this.makeComplexComponentTensorInfo(t,n.complexTensors.imag),this.makeComplexComponentTensorInfo(e,r.complexTensors.real),this.makeComplexComponentTensorInfo(e,r.complexTensors.imag)],s=this.compileAndRun(o,i),c=this.compileAndRun(a,i),l=this.complex(s,c);return s.dispose(),c.dispose(),l}if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.multiply(t,e);if(u().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,wa,t.dtype);var p=new Ea(wa,t.shape,e.shape);return this.compileAndRun(p,[t,e],t.dtype)},e.prototype.batchNormalization=function(t,e,n,r,o,a){var i=[t,e,n],s=null;null!=a&&(s=a.shape,i.push(a));var c=null;if(null!=o&&(c=o.shape,i.push(o)),u().getBool("WEBGL_PACK_NORMALIZATION")){var l=new va(t.shape,e.shape,n.shape,s,c,r);return this.compileAndRun(l,i)}var p=new fa(t.shape,e.shape,n.shape,s,c,r);return this.compileAndRun(p,i)},e.prototype.localResponseNormalization4D=function(t,e,n,r,o){var a=u().getBool("WEBGL_PACK_NORMALIZATION")?new Ni(t.shape,e,n,r,o):new Ai(t.shape,e,n,r,o);return this.compileAndRun(a,[t])},e.prototype.LRNGrad=function(t,e,n,r,o,a,i){var s=new Di(e.shape,r,o,a,i);return this.compileAndRun(s,[e,n,t])},e.prototype.tile=function(t,e){if("string"===t.dtype){var n=this.readSync(t.dataId).map(function(t){return nt(t)});return Uo(lr(t.shape,t.dtype,n),e)}var r=new is(t.shape,e);return this.compileAndRun(r,[t])},e.prototype.pad=function(t,e,n){var r=u().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Li(t.shape,e,n):new Pi(t.shape,e,n);return this.compileAndRun(r,[t])},e.prototype.transpose=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.transpose(t,e);var n=u().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new us(t.shape,e):new ss(t.shape,e);return this.compileAndRun(n,[t])},e.prototype.gather=function(t,e,n){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.gather(t,e,n);var r=new ai(t.shape,e.size,n);return this.compileAndRun(r,[t,e])},e.prototype.batchToSpaceND=function(t,e,n){b(t.rank<=4,function(){return"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"});var r=e.reduce(function(t,e){return t*e}),o=Lr(t.shape,e,r),a=Wr(o.length,e.length),i=zr(t.shape,e,r),s=Ur(n,e.length),u=Vr(i,n,e.length);return t.reshape(o).transpose(a).reshape(i).slice(s,u)},e.prototype.spaceToBatchND=function(t,e,n){b(t.rank<=4,function(){return"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"});var r=e.reduce(function(t,e){return t*e}),o=[[0,0]];o.push.apply(o,n);for(var a=1+e.length;a<t.shape.length;++a)o.push([0,0]);var i=t.pad(o),s=Lr(i.shape,e,r,!1),u=Wr(s.length,e.length,!1),c=zr(i.shape,e,r,!1);return i.reshape(s).transpose(u).reshape(c)},e.prototype.reduce=function(t,e,n){var r=t.shape[0],o=t.shape[1],a=qr(o),i=new Ui({windowSize:a,inSize:o,batchSize:r},e),s=this.compileAndRun(i,[t],n);return 1===s.shape[1]?s:this.reduce(s,e,n)},e.prototype.argReduce=function(t,e,n){void 0===n&&(n=null);var r=t.shape[0],o=t.shape[1];null!=n&&(r=n.shape[0],o=n.shape[1]);var a=qr(o),i=new Ko({windowSize:a,inSize:o,batchSize:r},e,null==n),s=[t];null!=n&&s.push(n);var u=this.compileAndRun(i,s,"int32");return 1===u.shape[1]?u:this.argReduce(t,e,u)},e.prototype.argReducePacked=function(t,e,n){void 0===n&&(n=null);var r=null!=n?n.shape:t.shape,o=qr(r[r.length-1]),a=new pa(r,o,e,null==n),i=null==n?[t]:[t,n],s=this.compileAndRun(a,i,"int32");return s.rank===t.rank?this.argReducePacked(t,e,s):s},e.prototype.sum=function(t,e){yn("sum",e,t.rank);var n=gn(t.shape,e),r=n[0],o=R(n[1]),a=t.as2D(-1,o),i=kt(t.dtype);return this.reduce(a,"sum",i).reshape(r)},e.prototype.prod=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.prod(t,e);var n=gn(t.shape,e),r=n[0],o=R(n[1]),a=t.as2D(-1,o),i=kt(t.dtype);return this.reduce(a,"prod",i).reshape(r)},e.prototype.unsortedSegmentSum=function(t,e,n){var r=0,o=bn([r],t.rank),a=t;null!=o&&(a=t.transpose(o),r=Cn(1,t.rank)[0]);var i=function(t,e,n){for(var r=[],o=t.length,a=0;a<o;a++)a!==e?r.push(t[a]):r.push(n);return r}(a.shape,r,n),s=R([a.shape[r]]),u=a.as2D(-1,s),c=kt(t.dtype),l=this.segOpCompute(u,"unsortedSegmentSum",e,c,n).reshape(i);return null!=o&&(l=l.transpose(wn(o))),l},e.prototype.segOpCompute=function(t,e,n,r,o){var a=t.shape[0],i=t.shape[1],s=function(t,e){var n,r=!1;for(t<=Hr?(n=t,r=!0):n=j(t,Math.floor(Math.sqrt(t)));!r;)n>e||n===t?r=!0:n=j(t,n+1);return n}(i,o),u=new Qi({windowSize:s,inSize:i,batchSize:a,numSegments:o},e),c=this.compileAndRun(u,[t,n],r);return c.shape[1]===o?c:(n=Gn(0,o).tile([i/s]),this.segOpCompute(c,e,n,r,o))},e.prototype.argMinMaxReduce=function(t,e,n){var r=[e];if(yn("arg"+n.charAt(0).toUpperCase()+n.slice(1),r,t.rank),!u().getBool("WEBGL_PACK_REDUCE")||t.rank<=2){var o=gn(t.shape,r),a=o[0],i=R(o[1]),s=t.as2D(-1,i);return this.argReduce(s,n).reshape(a)}return this.argReducePacked(t,n)},e.prototype.argMin=function(t,e){return this.argMinMaxReduce(t,e,"min")},e.prototype.argMax=function(t,e){return this.argMinMaxReduce(t,e,"max")},e.prototype.cumsum=function(t,e,n,r){if(e!==t.rank-1)throw new Error("WebGL cumsum shader expects an inner-most axis="+(t.rank-1)+" but got axis="+e);var o=new Ga(t.shape,n,r);return this.compileAndRun(o,[t])},e.prototype.equal=function(t,e){if(u().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  return vec4(equal(a, b));\n","bool");var n=new Ea("return float(a == b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.notEqual=function(t,e){if(u().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  return vec4(notEqual(a, b));\n","bool");var n=new Ea("return float(a != b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.less=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.less(t,e);if(u().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  return vec4(lessThan(a, b));\n","bool");var n=new Ea("return float(a < b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.lessEqual=function(t,e){if(u().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  return vec4(lessThanEqual(a, b));\n","bool");var n=new Ea("return float(a <= b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.greater=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.greater(t,e);if(u().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  return vec4(greaterThan(a, b));\n","bool");var n=new Ea("return float(a > b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.greaterEqual=function(t,e){if(u().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,"\n  return vec4(greaterThanEqual(a, b));\n","bool");var n=new Ea("return float(a >= b);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.logicalNot=function(t){var e=new ps(t.shape,"return float(!(x >= 1.0));");return this.compileAndRun(e,[t])},e.prototype.logicalAnd=function(t,e){if(u().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 Ea("return float(a >= 1.0 && b >= 1.0);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.logicalOr=function(t,e){if(u().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 Ea("return float(a >= 1.0 || b >= 1.0);",t.shape,e.shape);return this.compileAndRun(n,[t,e],"bool")},e.prototype.select=function(t,e,n){var r=new Ji(t.rank,e.shape,e.rank);return this.compileAndRun(r,[t,e,n],It(e.dtype,n.dtype))},e.prototype.where=function(t){ln("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");var e=t.dataSync();return Go(t.shape,e)},e.prototype.topk=function(t,e,n){return Vo(t.dataSync(),t.shape,t.dtype,e)},e.prototype.min=function(t,e){yn("min",e,t.rank);var n=gn(t.shape,e),r=n[0],o=R(n[1]),a=t.as2D(-1,o);return this.reduce(a,"min",a.dtype).reshape(r)},e.prototype.minimum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.minimum(t,e);var n=u().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ia("\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 Ea("\n  if (isnan(a)) return a;\n  if (isnan(b)) return b;\n\n  return min(a, b);\n",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.mod=function(t,e){var n=u().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ia("\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 Ea("if (b == 0.0) return NAN;\n  return mod(a, b);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.max=function(t,e){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.max(t,e);yn("max",e,t.rank);var n=gn(t.shape,e),r=n[0],o=R(n[1]),a=t.as2D(-1,o);return this.reduce(a,"max",a.dtype).reshape(r)},e.prototype.maximum=function(t,e){if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.maximum(t,e);var n=u().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ia("\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 Ea("\n  if (isnan(a)) return a;\n  if (isnan(b)) return b;\n\n  return max(a, b);\n",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.all=function(t,e){yn("all",e,t.rank);var n=gn(t.shape,e),r=n[0],o=R(n[1]),a=t.as2D(-1,o);return this.reduce(a,"all",a.dtype).reshape(r)},e.prototype.any=function(t,e){yn("any",e,t.rank);var n=gn(t.shape,e),r=n[0],o=R(n[1]),a=t.as2D(-1,o);return this.reduce(a,"any",a.dtype).reshape(r)},e.prototype.squaredDifference=function(t,e){var n=u().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ia("return (a - b) * (a - b);",t.shape,e.shape):new Ea("return (a - b) * (a - b);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.realDivide=function(t,e){if(u().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 Ea("\nif (a == b) {\n  return 1.0;\n};\nreturn a / b;",t.shape,e.shape);return this.compileAndRun(n,[t,e],"float32")},e.prototype.floorDiv=function(t,e){if(u().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 Ea("\n  float s = sign(a) * sign(b);\n  int ia = round(a);\n  int ib = round(b);\n  if (ib != 0) {\n    // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n    return float(idiv(ia, ib, s));\n  } else {\n    return NAN;\n  }\n",t.shape,e.shape);return this.compileAndRun(n,[t,e],"int32")},e.prototype.add=function(t,e){if("complex64"===t.dtype&&"complex64"===e.dtype)return this.complexSeparableBinaryOp(t,e,ya);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.add(t,e);var n=It(t.dtype,e.dtype);if(u().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,ya,n);var r=new Ea(ya,t.shape,e.shape);return this.compileAndRun(r,[t,e],n)},e.prototype.packedUnaryOp=function(t,e,n){var r=new Ps(t.shape,e);return this.compileAndRun(r,[t],n)},e.prototype.packedBinaryOp=function(t,e,n,r,o){void 0===o&&(o=!1);var a=new Ia(n,t.shape,e.shape,o);return this.compileAndRun(a,[t,e],r)},e.prototype.complexSeparableBinaryOp=function(t,e,n){var r=this,o=this.texData.get(t.dataId),a=this.texData.get(e.dataId),i=[[o.complexTensors.real,a.complexTensors.real],[o.complexTensors.imag,a.complexTensors.imag]].map(function(o){var a=o[0],i=o[1],s=r.makeComplexComponentTensorInfo(t,a),u=r.makeComplexComponentTensorInfo(e,i),c=new Ea(n,t.shape,e.shape);return r.compileAndRun(c,[s,u],It(a.dtype,i.dtype))}),s=i[0],u=i[1],c=this.complex(s,u);return s.dispose(),u.dispose(),c},e.prototype.makeComplexComponentTensorInfo=function(t,e){return{dataId:e.dataId,dtype:e.dtype,shape:t.shape}},e.prototype.addN=function(t){if(1===t.length)return t[0];if(t.length>u().get("WEBGL_MAX_TEXTURES_IN_SHADER")){var e=Math.floor(t.length/2),n=this.addN(t.slice(0,e)),r=this.addN(t.slice(e));return this.addN([n,r])}var o=t.map(function(t){return t.dtype}).reduce(function(t,e){return It(t,e)}),a=t.map(function(t){return t.shape}),i=u().getBool("WEBGL_PACK")?new qo(t[0].shape,a):new Ho(t[0].shape,a);return this.compileAndRun(i,t,o)},e.prototype.subtract=function(t,e){if("complex64"===t.dtype&&"complex64"===e.dtype)return this.complexSeparableBinaryOp(t,e,ba);if(this.shouldExecuteOnCPU([t,e]))return this.cpuBackend.subtract(t,e);var n=It(t.dtype,e.dtype);if(u().getBool("WEBGL_PACK_BINARY_OPERATIONS"))return this.packedBinaryOp(t,e,ba,t.dtype);var r=new Ea(ba,t.shape,e.shape);return this.compileAndRun(r,[t,e],n)},e.prototype.pow=function(t,e){var n=u().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ia("\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 Ea("\nif(a < 0.0 && floor(b) < b){\n  return NAN;\n}\nif (b == 0.0) {\n  return 1.0;\n}\nreturn (round(mod(b, 2.0)) != 1) ?\n    pow(abs(a), b) : sign(a) * pow(abs(a), b);\n",t.shape,e.shape),r=It(t.dtype,e.dtype);return this.compileAndRun(n,[t,e],r)},e.prototype.ceil=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.ceil(t);if(u().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,bs,t.dtype);var e=new ps(t.shape,bs);return this.compileAndRun(e,[t])},e.prototype.floor=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.floor(t);if(u().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,ws,t.dtype);var e=new ps(t.shape,ws);return this.compileAndRun(e,[t])},e.prototype.sign=function(t){var e=new ps(t.shape,"\n  if (isnan(x)) { return 0.0; }\n  return sign(x);\n");return this.compileAndRun(e,[t])},e.prototype.isNaN=function(t){var e=new ps(t.shape,"return float(isnan(x));");return this.compileAndRun(e,[t],"bool")},e.prototype.isInf=function(t){var e=new ps(t.shape,"return float(isinf(x));");return this.compileAndRun(e,[t],"bool")},e.prototype.isFinite=function(t){var e=new ps(t.shape,"return float(!isnan(x) && !isinf(x));");return this.compileAndRun(e,[t],"bool")},e.prototype.round=function(t){var e=new ps(t.shape,"\n  // OpenGL ES does not support round function.\n  // The algorithm is based on banker's rounding.\n  float base = floor(x);\n  if ((x - base) < 0.5) {\n    return floor(x);\n  } else if ((x - base) > 0.5) {\n    return ceil(x);\n  } else {\n    if (mod(base, 2.0) == 0.0) {\n      return base;\n    } else {\n      return base + 1.0;\n    }\n  }\n");return this.compileAndRun(e,[t])},e.prototype.exp=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.exp(t);if(u().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,Cs,t.dtype);var e=new ps(t.shape,Cs);return this.compileAndRun(e,[t])},e.prototype.expm1=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.expm1(t);if(u().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,Es,t.dtype);var e=new ps(t.shape,Es);return this.compileAndRun(e,[t])},e.prototype.log=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.log(t);if(u().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 ps(t.shape,"if (x < 0.0) return NAN;\n  return log(x);");return this.compileAndRun(e,[t])},e.prototype.log1p=function(t){var e=new ps(t.shape,"return log(1.0 + x);");return this.compileAndRun(e,[t])},e.prototype.sqrt=function(t){var e=new ps(t.shape,"return sqrt(x);");return this.compileAndRun(e,[t])},e.prototype.rsqrt=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.rsqrt(t);var e=new ps(t.shape,"return inversesqrt(x);");return this.compileAndRun(e,[t])},e.prototype.reciprocal=function(t){var e=new ps(t.shape,"return 1.0 / x;");return this.compileAndRun(e,[t])},e.prototype.relu=function(t){var e;return e=u().getBool("WEBGL_PACK")?new Ps(t.shape,_s):new ps(t.shape,vs),this.compileAndRun(e,[t])},e.prototype.relu6=function(t){var e;return e=u().getBool("WEBGL_PACK")?new Ps(t.shape,Ms):new ps(t.shape,ms),this.compileAndRun(e,[t])},e.prototype.prelu=function(t,e){var n=u().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ia(Ra,t.shape,e.shape):new Ea(Ca,t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.elu=function(t){if(u().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,Bs,t.dtype);var e=new ps(t.shape,gs);return this.compileAndRun(e,[t])},e.prototype.eluDer=function(t,e){var n=u().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ia("\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 Ea("return (b >= 1.0) ? a : a * (b + 1.0);",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.selu=function(t){var e=new ps(t.shape,xs);return this.compileAndRun(e,[t])},e.prototype.int=function(t){var e=new ps(t.shape,"return float(int(x));");return this.compileAndRun(e,[t],"int32")},e.prototype.clip=function(t,e,n){var r,o=(r=u().getBool("WEBGL_PACK_CLIP")?new Sa(t.shape):new ka(t.shape)).getCustomSetupFunc(e,n);return this.compileAndRun(r,[t],null,o)},e.prototype.abs=function(t){if(this.shouldExecuteOnCPU([t]))return this.cpuBackend.abs(t);if(u().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(t,fs,t.dtype);var e=new ps(t.shape,fs);return this.compileAndRun(e,[t])},e.prototype.complexAbs=function(t){var e=this.texData.get(t.dataId),n=new Aa(t.shape),r=[this.makeComplexComponentTensorInfo(t,e.complexTensors.real),this.makeComplexComponentTensorInfo(t,e.complexTensors.imag)];return this.compileAndRun(n,r)},e.prototype.sigmoid=function(t){var e=new ps(t.shape,"return 1.0 / (1.0 + exp(-1.0 * x));");return this.compileAndRun(e,[t])},e.prototype.softplus=function(t){var e=new ps(t.shape,"\n  float epsilon = 1.1920928955078125e-7;\n  float threshold = log(epsilon) + 2.0;\n\n  bool too_large = x > -threshold;\n  bool too_small = x < threshold;\n\n  float result;\n  float exp_x = exp(x);\n\n  if (too_large){\n    result = x;\n  }\n  else if (too_small){\n    result = exp_x;\n  }\n  else{\n    result = log(exp_x + 1.0);\n  }\n  return result;\n");return this.compileAndRun(e,[t])},e.prototype.sin=function(t){var e=new ps(t.shape,Rs);return this.compileAndRun(e,[t])},e.prototype.cos=function(t){var e=new ps(t.shape,Is);return this.compileAndRun(e,[t])},e.prototype.tan=function(t){var e=new ps(t.shape,"return tan(x);");return this.compileAndRun(e,[t])},e.prototype.asin=function(t){var e=new ps(t.shape,ks);return this.compileAndRun(e,[t])},e.prototype.acos=function(t){var e=new ps(t.shape,Ss);return this.compileAndRun(e,[t])},e.prototype.atan=function(t){var e=new ps(t.shape,As);return this.compileAndRun(e,[t])},e.prototype.atan2=function(t,e){var n=u().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Ia("\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 Ea("\n  if (isnan(a)) return a;\n  if (isnan(b)) return b;\n\n  return atan(a, b);\n",t.shape,e.shape);return this.compileAndRun(n,[t,e])},e.prototype.sinh=function(t){var e=new ps(t.shape,"\n  float e2x = exp(x);\n  return (e2x - 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t])},e.prototype.cosh=function(t){var e=new ps(t.shape,"\n  float e2x = exp(-x);\n  return (e2x + 1.0 / e2x) / 2.0;\n");return this.compileAndRun(e,[t])},e.prototype.tanh=function(t){var e=new ps(t.shape,"\n  float e2x = exp(-2.0 * abs(x));\n  return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n");return this.compileAndRun(e,[t])},e.prototype.asinh=function(t){var e=new ps(t.shape,Ds);return this.compileAndRun(e,[t])},e.prototype.acosh=function(t){var e=new ps(t.shape,Ns);return this.compileAndRun(e,[t])},e.prototype.atanh=function(t){var e=new ps(t.shape,Ts);return this.compileAndRun(e,[t])},e.prototype.erf=function(t){var e=new ps(t.shape,'\n  // Error function is calculated approximately with elementary function.\n  // See "Handbook of Mathematical Functions with Formulas,\n  // Graphs, and Mathematical Tables", Abramowitz and Stegun.\n  float p = 0.3275911;\n  float a1 = 0.254829592;\n  float a2 = -0.284496736;\n  float a3 = 1.421413741;\n  float a4 = -1.453152027;\n  float a5 = 1.061405429;\n\n  float sign = sign(x);\n  x = abs(x);\n  float t = 1.0 / (1.0 + p * x);\n  return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));\n');return this.compileAndRun(e,[t])},e.prototype.step=function(t,e){var n=new ps(t.shape,function(t){return void 0===t&&(t=0),hs+"\n    return x > 0.0 ? 1.0 : float("+t+");\n  "}(e));return this.compileAndRun(n,[t])},e.prototype.conv2dByMatMul=function(t,e,n,r,o,a){var i=t.shape,s=this.texData.get(t.dataId),c=n.inChannels,l=i[0]*i[1]*i[2],p=n.outChannels,h="channelsLast"===n.dataFormat,d=(1===l||1===p)&&c>1e3,f=i[2]%2!=0&&!!s.isPacked;if(d||!u().getBool("WEBGL_LAZILY_UNPACK")||!u().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!f){var v=h?i[0]*i[1]*i[2]:i[0]*i[2]*i[3],m=this.reshape(t,[1,v,n.inChannels]),g=this.reshape(e,[1,n.inChannels,n.outChannels]);return this.reshape(this.fusedBatchMatMul({a:m,b:g,transposeA:!1,transposeB:!1,bias:r,activation:o,preluActivationWeights:a}),n.outShape)}var x=h?i[0]*i[1]*(i[2]+1):i[0]*i[2]*(i[3]+1),y={dataId:t.dataId,shape:[1,x,n.inChannels],dtype:t.dtype},w=s.shape;s.shape=s.shape.slice(),s.shape[s.shape.length-2]++,b(Ne(s.shape,y.shape),function(){return"packed reshape "+s.shape+" to "+y.shape+" isn't free"});var C=this.reshape(e,[1,n.inChannels,n.outChannels]),E=this.fusedBatchMatMul({a:y,b:C,transposeA:!1,transposeB:!1,bias:r,activation:o,preluActivationWeights:a}),R=this.texData.get(E.dataId);return b(R.isPacked,function(){return"batchMatMul result is expected to be packed"}),s.shape=w,R.shape=n.outShape,_t.makeTensorFromDataId(E.dataId,n.outShape,E.dtype)},e.prototype.conv2dWithIm2Row=function(t,e,n,r,o,a){var i=n.filterWidth,s=n.filterHeight,u=n.inChannels,c=n.outWidth,l=n.outHeight,p="channelsLast"===n.dataFormat,h=i*s*u,d=l*c,f=[h,d],v=t.squeeze([0]),m=e.reshape([1,h,-1]),g=new Si(f,v.shape,n),x=this.compileAndRun(g,[v]).reshape([1,f[0],f[1]]),y=null!=r,b=null!=a,w=o?zs(o,!0):null,C=new Oi(x.shape,[1,d,n.outChannels],!0,!1,y,w,b),E=[x,m];r&&E.push(r),b&&E.push(a);var R=this.compileAndRun(C,E);return p?R.reshape([1,l,c,n.outChannels]):R.reshape([1,n.outChannels,l,c])},e.prototype.fusedConv2d=function(t){var e=t.input,n=t.filter,r=t.convInfo,o=t.bias,a=t.activation,i=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,o,a,i);if(u().getBool("WEBGL_CONV_IM2COL")&&1===e.shape[0])return this.conv2dWithIm2Row(e,n,r,o,a,i);var s=null!=o,c=null!=i,l=a?zs(a,!1):null,p=new La(r,s,l,c),h=[e,n];return o&&h.push(o),i&&h.push(i),this.compileAndRun(p,h)},e.prototype.conv2d=function(t,e,n){if(1===n.filterHeight&&1===n.filterWidth&&1===n.dilationHeight&&1===n.dilationWidth&&1===n.strideHeight&&1===n.strideWidth&&("SAME"===n.padInfo.type||"VALID"===n.padInfo.type))return this.conv2dByMatMul(t,e,n);if(u().getBool("WEBGL_CONV_IM2COL")&&1===t.shape[0])return this.conv2dWithIm2Row(t,e,n);var r=new La(n);return this.compileAndRun(r,[t,e])},e.prototype.conv2dDerInput=function(t,e,n){var r=new Oa(n);return this.compileAndRun(r,[t,e])},e.prototype.conv2dDerFilter=function(t,e,n){var r=new Fa(n);return this.compileAndRun(r,[t,e])},e.prototype.fusedDepthwiseConv2D=function(t){var e,n=t.input,r=t.filter,o=t.convInfo,a=t.bias,i=t.activation,s=t.preluActivationWeights,c=u().getBool("WEBGL_PACK_DEPTHWISECONV")&&o.strideWidth<=2&&o.outChannels/o.inChannels==1,l=i?zs(i,c):null,p=[n,r],h=null!=a,d=null!=s;return h&&p.push(a),d&&p.push(s),c?(e=new Ua(o,h,l,d),this.compileAndRun(e,p)):(e=new za(o,h,l,d),this.compileAndRun(e,p))},e.prototype.depthwiseConv2D=function(t,e,n){var r;return u().getBool("WEBGL_PACK_DEPTHWISECONV")&&n.strideWidth<=2&&n.outChannels/n.inChannels==1?(r=new Ua(n),this.compileAndRun(r,[t,e])):(r=new za(n),this.compileAndRun(r,[t,e]))},e.prototype.depthwiseConv2DDerInput=function(t,e,n){var r=new Pa(n);return this.compileAndRun(r,[t,e])},e.prototype.depthwiseConv2DDerFilter=function(t,e,n){var r=new Ba(n);return this.compileAndRun(r,[t,e])},e.prototype.conv3d=function(t,e,n){var r=new Wa(n);return this.compileAndRun(r,[t,e])},e.prototype.conv3dDerInput=function(t,e,n){var r=new Ma(n);return this.compileAndRun(r,[t,e])},e.prototype.conv3dDerFilter=function(t,e,n){var r=new _a(n);return this.compileAndRun(r,[t,e])},e.prototype.maxPool=function(t,e){var n=new Wi(e,"max",!1);return this.compileAndRun(n,[t])},e.prototype.avgPool=function(t,e){var n=new Wi(e,"avg",!1);return this.compileAndRun(n,[t],"float32")},e.prototype.maxPoolBackprop=function(t,e,n,r){var o=new Wi(r,"max",!0),a=this.compileAndRun(o,[e]),i=new Ti(r),s=this.compileAndRun(i,[t,a],e.dtype);return a.dispose(),s},e.prototype.avgPoolBackprop=function(t,e,n){var r=new ha(n);return this.compileAndRun(r,[t],e.dtype)},e.prototype.cast=function(t,e){return No(t,e,this)},e.prototype.unstack=function(t,e){for(var n=t.shape[e],r=new Array(t.rank-1),o=0,a=0;a<t.rank;a++)a!==e&&(r[o++]=t.shape[a]);var i=new Array(t.rank).fill(0),s=t.shape.slice();s[e]=1;var u=new Array(n);for(a=0;a<u.length;a++)i[e]=a,u[a]=this.slice(t,i,s).reshape(r);return u},e.prototype.avgPool3d=function(t,e){var n=new zi(e,"avg",!1);return this.compileAndRun(n,[t],"float32")},e.prototype.avgPool3dBackprop=function(t,e,n){var r=new da(n);return this.compileAndRun(r,[t],e.dtype)},e.prototype.maxPool3d=function(t,e){var n=new zi(e,"max",!1);return this.compileAndRun(n,[t],"float32")},e.prototype.maxPool3dBackprop=function(t,e,n,r){var o=new zi(r,"max",!0),a=this.compileAndRun(o,[e]),i=new Fi(r),s=this.compileAndRun(i,[t,a],e.dtype);return a.dispose(),s},e.prototype.reshape=function(t,e){var n=this.texData.get(t.dataId);if(n.isPacked&&!Ne(t.shape,e)&&(null===n.texture||!Ne(n.shape,e))){var r=this.packedReshape(t,e);return _t.makeTensorFromDataId(r.dataId,r.shape,r.dtype)}return To(t,e)},e.prototype.resizeBilinear=function(t,e,n,r){var o=u().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new qi(t.shape,e,n,r):new Hi(t.shape,e,n,r);return this.compileAndRun(o,[t])},e.prototype.resizeBilinearBackprop=function(t,e,n){var r=new Gi(t,e,n);return this.compileAndRun(r,[t])},e.prototype.resizeNearestNeighbor=function(t,e,n,r){var o=new ji(t.shape,e,n,r);return this.compileAndRun(o,[t])},e.prototype.resizeNearestNeighborBackprop=function(t,e,n){var r=new Ki(t,e,n);return this.compileAndRun(r,[t])},e.prototype.multinomial=function(t,e,n,r){var o=e?t:co(t),a=o.shape[0],i=o.shape[1],s=new _i(a,i,n),u=s.getCustomSetupFunc(r);return this.compileAndRun(s,[o],"int32",u)},e.prototype.oneHot=function(t,e,n,r){var o=new Mi(t.size,e,n,r);return this.compileAndRun(o,[t])},e.prototype.diag=function(t){var e=new Xa(t.size);return this.compileAndRun(e,[t])},e.prototype.nonMaxSuppression=function(t,e,n,r,o){return ln("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead"),Lo(t.dataSync(),e.dataSync(),n,r,o)},e.prototype.cropAndResize=function(t,e,n,r,o,a){var i=new Va(t.shape,e.shape,r,o,a);return this.compileAndRun(i,[t,e,n])},e.prototype.depthToSpace=function(t,e,n){b(e>1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+e});var r=t.shape[0],o="NHWC"===n?t.shape[1]:t.shape[2],a="NHWC"===n?t.shape[2]:t.shape[3],i="NHWC"===n?t.shape[3]:t.shape[1],s=o*e,u=a*e,c=i/(e*e),l=new ja("NHWC"===n?[r,s,u,c]:[r,c,s,u],e,n);return this.compileAndRun(l,[t])},e.prototype.split=function(t,e,n){return zo(t,e,n)},e.prototype.scatterND=function(t,e,n){var r=jr(0,t,n),o=r.sliceRank,a=r.numUpdates,i=r.sliceSize,s=r.strides,u=r.outputSize,c=[u/i,i],l=t.reshape([a,o]),p=e.reshape([a,i]);if(0===u)return To(Dn([]),n);var h=Tn(0),d=new Yi(a,o,l.rank,p.rank,s,c);return this.compileAndRun(d,[p,l,h]).reshape(n)},e.prototype.sparseToDense=function(t,e,n,r){var o=jr(0,t,n),a=o.sliceRank,i=o.numUpdates,s=o.strides,u=o.outputSize,c=new Yi(i,a,t.rank,e.rank,s,[u,1],!1);return this.compileAndRun(c,[e,t,r]).reshape(n)},e.prototype.fft=function(t){return this.fftImpl(t,!1)},e.prototype.ifft=function(t){return this.fftImpl(t,!0)},e.prototype.fftImpl=function(t,e){var n=this.texData.get(t.dataId),r=new ei(Za,t.shape,e),o=new ei(ti,t.shape,e),a=[this.makeComplexComponentTensorInfo(t,n.complexTensors.real),this.makeComplexComponentTensorInfo(t,n.complexTensors.imag)],i=this.compileAndRun(r,a),s=this.compileAndRun(o,a),u=this.complex(i,s).as2D(t.shape[0],t.shape[1]);return i.dispose(),s.dispose(),u},e.prototype.gatherND=function(t,e){var n=e.shape,r=n[n.length-1],o=Gr(t,e),a=o[0],i=o[1],s=o[2],u=o[3],c=e.reshape([i,r]),l=t.reshape([t.size/s,s]),p=new ii(r,u,[i,s]);return this.compileAndRun(p,[l,c]).reshape(a)},e.prototype.fill=function(t,e,n){if("string"===(n=n||q(e))){var r=M(n,R(t));return r.fill(e),_t.makeTensor(r,t,n,this)}var o=new ni(t,e),a=o.getCustomSetupFunc(e);return this.compileAndRun(o,[],n,a)},e.prototype.onesLike=function(t){if("string"===t.dtype)throw new Error("onesLike is not supported under string dtype");return this.fill(t.shape,1,t.dtype)},e.prototype.zerosLike=function(t){return this.fill(t.shape,"string"===t.dtype?"":0,t.dtype)},e.prototype.linspace=function(t,e,n){return Fo(t,e,n)},e.prototype.makeTensorInfo=function(t,e){var n=this.write(null,t,e);return this.texData.get(n).usage=null,{dataId:n,shape:t,dtype:e}},e.prototype.makeOutput=function(t,e){var n=this.makeTensorInfo(t,e).dataId;return _t.makeTensorFromDataId(n,t,e,this)},e.prototype.unpackTensor=function(t){var e=new Ls(t.shape);return this.runWebGLProgram(e,[t],t.dtype)},e.prototype.packTensor=function(t){var e=new Bi(t.shape);return this.runWebGLProgram(e,[t],t.dtype,null,!0)},e.prototype.packedReshape=function(t,e){var n=[Ie(t.shape)].concat(ke(t.shape)),r={dtype:t.dtype,shape:n,dataId:t.dataId},o=[Ie(e)].concat(ke(e)),a=new Vi(o,n),i=this.runWebGLProgram(a,[r],t.dtype,null,!0);return{dataId:i.dataId,shape:e,dtype:i.dtype}},e.prototype.decode=function(t){var e,n=this.texData.get(t),r=n.isPacked,o=n.shape,a=n.dtype,i=Se(o);return e=r?new Ka(i):new qa(i),{dtype:a,shape:o,dataId:this.runWebGLProgram(e,[{shape:i,dtype:a,dataId:t}],a,null,!0).dataId}},e.prototype.runWebGLProgram=function(t,e,n,r,o){var a=this;void 0===o&&(o=!1);var i=this.makeTensorInfo(t.outputShape,n),s=this.texData.get(i.dataId);if(t.packedOutput&&(s.isPacked=!0),t.outPackingScheme===Pt.DENSE){var c=Kt(t.outputShape);s.texShape=c.map(function(t){return 2*t})}if(null!=t.outTexUsage&&(s.usage=t.outTexUsage),0===R(i.shape))return s.values=_(i.dtype,0),i;var l=[],p=e.map(function(e){if("complex64"===e.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");var n=a.texData.get(e.dataId);if(null==n.texture){if(!t.packedInputs&&R(e.shape)<=u().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:e.shape,texData:null,isUniform:!0,uniformValues:n.values};t.packedInputs&&(n.isPacked=!0,n.shape=e.shape)}else if(!!n.isPacked!=!!t.packedInputs)e=n.isPacked?a.unpackTensor(e):a.packTensor(e),l.push(e),n=a.texData.get(e.dataId);else if(n.isPacked&&!Ne(n.shape,e.shape)){var r=e,o=e.shape;e.shape=n.shape,e=a.packedReshape(e,o),l.push(e),n=a.texData.get(e.dataId),r.shape=o}return a.uploadToGPU(e.dataId),{shape:e.shape,texData:n,isUniform:!1}});this.uploadToGPU(i.dataId);var h,d={shape:i.shape,texData:s,isUniform:!1},f=function(t,e,n){var r="";p.concat(n).forEach(function(t){var e=null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0,n=t.isUniform?"uniform":t.texData.texShape;r+=t.shape+"_"+n+"_"+e});var o=t.userCode;return t.constructor.name+"_"+r+"_"+o}(t,0,d),v=this.getAndSaveBinary(f,function(){return function(t,e,n,r){var o=e.userCode,a=n.map(function(t,n){var r={logicalShape:t.shape,texShape:t.isUniform?null:t.texData.texShape,isUniform:t.isUniform,isPacked:!t.isUniform&&t.texData.isPacked,flatOffset:null};return null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0&&(r.flatOffset=t.texData.slice.flatOffset),{name:e.variableNames[n],shapeInfo:r}}),i=a.map(function(t){return t.shapeInfo}),s={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},c=Zo(a,s,o,e.packedInputs),l=t.createProgram(c),p=null,h=t.getUniformLocation(l,"NAN",!1);1===u().getNumber("WEBGL_VERSION")&&(p=t.getUniformLocation(l,"INFINITY",!1));for(var d={},f=0;f<e.variableNames.length;f++){var v=e.variableNames[f];d[v]=t.getUniformLocation(l,v,!1),d["offset"+v]=t.getUniformLocation(l,"offset"+v,!1)}return{program:e,source:c,webGLProgram:l,uniformLocations:d,inShapeInfos:i,outShapeInfo:s,infLoc:p,nanLoc:h}}(a.gpgpu,t,p,d)}),m=null!=this.activeTimers;if(m&&(h=this.startTimer()),function(t,e,n,r,o){ki(e.inShapeInfos,n),ki([e.outShapeInfo],[r]);var a=r.texData.texture,i=r.texData.texShape;r.texData.isPacked?t.setOutputPackedMatrixTexture(a,i[0],i[1]):t.setOutputMatrixTexture(a,i[0],i[1]),t.setProgram(e.webGLProgram),1===u().getNumber("WEBGL_VERSION")&&null!==e.infLoc&&t.gl.uniform1f(e.infLoc,1/0),null!==e.nanLoc&&t.gl.uniform1f(e.nanLoc,NaN),n.forEach(function(n,r){var o=e.program.variableNames[r],a=e.uniformLocations[o],i=e.uniformLocations["offset"+o];if(null!=a)if(n.isUniform)if(R(n.shape)<2)t.gl.uniform1f(a,n.uniformValues[0]);else{var s=n.uniformValues;s instanceof Float32Array||(s=new Float32Array(s)),t.gl.uniform1fv(a,s)}else null!=n.texData.slice&&null!=i&&t.gl.uniform1i(i,n.texData.slice.flatOffset),t.setInputMatrixTexture(n.texData.texture,a,r)}),null!=o&&o(t,e.webGLProgram),t.executeProgram()}(this.gpgpu,v,p,d,r),l.forEach(function(t){return a.disposeData(t.dataId)}),m&&(h=this.endTimer(h),this.activeTimers.push({name:t.constructor.name,query:this.getQueryTime(h)})),!u().getBool("WEBGL_LAZILY_UNPACK")&&s.isPacked&&!1===o){var g=this.unpackTensor(i);return this.disposeData(i.dataId),g}return i},e.prototype.compileAndRun=function(t,e,n,r,o){void 0===o&&(o=!1),n=n||e[0].dtype;var a=this.runWebGLProgram(t,e,n,r,o);return _t.makeTensorFromDataId(a.dataId,a.shape,a.dtype)},e.prototype.getAndSaveBinary=function(t,e){return t in this.binaryCache||(this.binaryCache[t]=e()),this.binaryCache[t]},e.prototype.getTextureManager=function(){return this.textureManager},e.prototype.dispose=function(){this.disposed||(this.textureManager.dispose(),null!=this.canvas&&"undefined"!=typeof HTMLCanvasElement&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,null!=this.fromPixels2DContext&&this.fromPixels2DContext.canvas.remove&&this.fromPixels2DContext.canvas.remove(),this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)},e.prototype.floatPrecision=function(){var t=this;return null==this.floatPrecisionValue&&(this.floatPrecisionValue=Ye(function(){if(!u().get("WEBGL_RENDER_FLOAT32_ENABLED")){var e=u().getBool("DEBUG");u().set("DEBUG",!1);var n=t.abs(Tn(1e-8)).dataSync()[0];if(u().set("DEBUG",e),n>0)return 32}return 16})),this.floatPrecisionValue},e.prototype.epsilon=function(){return 32===this.floatPrecision()?1e-7:1e-4},e.prototype.uploadToGPU=function(t){var e,n=this.texData.get(t),r=n.shape,o=n.dtype,a=n.values,i=n.texture,s=n.usage,u=n.isPacked;if(null==i){var c,l=null!=this.activeTimers;l&&(c=Z());var p=n.texShape;if(null==p&&(p=Ae(r,u),n.texShape=p),null!=a){var h=Se(r),d=void 0,f=p[1],v=p[0],m=a instanceof Uint8Array;u?(f=(e=jt(p[0],p[1]))[0],v=e[1],d=new Ja(h,[v,f],m)):d=new Qa(h,[v,f],m);var g=this.makeTensorInfo([v,f],o);this.texData.get(g.dataId).usage=m?Lt.PIXELS:Lt.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(g.dataId),f,v,a);var x=this.runWebGLProgram(d,[g],o,null,!0),y=this.texData.get(x.dataId);n.texture=y.texture,n.texShape=y.texShape,n.isPacked=y.isPacked,n.usage=y.usage,this.disposeData(g.dataId),this.texData.delete(x.dataId),n.values=null,l&&(this.uploadWaitMs+=Z()-c)}else{var b=this.acquireTexture(p,s,o,u);n.texture=b}}},e.prototype.convertAndCacheOnCPU=function(t,e){var n=this.texData.get(t),r=n.dtype;return this.releaseGPUData(t),null!=e&&(n.values=function(t,e){if("float32"===e||"complex64"===e)return t;if("int32"===e||"bool"===e){for(var n="int32"===e?new Int32Array(t.length):new Uint8Array(t.length),r=0;r<n.length;++r)n[r]=Math.round(t[r]);return n}throw new Error("Unknown dtype "+e)}(e,r)),n.values},e.prototype.acquireTexture=function(t,e,n,r){if(this.numBytesInGPU+=this.computeBytes(t,n),!this.warnedAboutMemory&&this.numBytesInGPU>1024*this.numMBBeforeWarning*1024){var o=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn("High memory usage in GPU: "+o+" MB, most likely due to a memory leak")}return this.textureManager.acquireTexture(t,e,r)},e.prototype.computeBytes=function(t,e){return t[0]*t[1]*z(e)},e}(ho);Mt()&&_t.registerBackend("webgl",function(){return new Vs},2);var Gs=In({square_:function(t){var e=dn(t,"x","square"),n=[e];return _t.runKernelFunc(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))}}},"Square",{},n,[])}});exports.square=Gs;var Hs=In({abs_:function(t){var e=dn(t,"x","abs");return"complex64"===e.dtype?_t.runKernelFunc(function(t){return t.complexAbs(e)},{$x:e}):_t.runKernelFunc(function(t,n){var r=t.abs(e);return n([e]),r},{x:e},function(t,e){var n=e[0];return{x:function(){return t.mul(n.toFloat().step(-1))}}},"Abs")}}),qs=In({acos_:function(t){var e=dn(t,"x","acos");return _t.runKernelFunc(function(t,n){var r=t.acos(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(Tn(1).sub(n.toFloat().square()).sqrt()).neg()}}})}}),Ks=In({acosh_:function(t){var e=dn(t,"x","acosh");return _t.runKernelFunc(function(t,n){var r=t.acosh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(n.toFloat().square().sub(1).sqrt())}}})}}),js=In({asin_:function(t){var e=dn(t,"x","asin");return _t.runKernelFunc(function(t,n){var r=t.asin(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(Tn(1).sub(n.toFloat().square()).sqrt())}}})}}),Xs=In({asinh_:function(t){var e=dn(t,"x","asinh");return _t.runKernelFunc(function(t,n){var r=t.asinh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.divStrict(Tn(1).add(n.toFloat().square()).sqrt())}}})}}),$s=In({atan_:function(t){var e=dn(t,"x","atan");return _t.runKernelFunc(function(t,n){var r=t.atan(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.toFloat().square().add(1))}}})}}),Ys=In({atanh_:function(t){var e=dn(t,"x","atanh");return _t.runKernelFunc(function(t,n){var r=t.atanh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(Tn(1).sub(n.toFloat().square()))}}})}}),Qs=In({ceil_:function(t){var e=dn(t,"x","ceil");return _t.runKernelFunc(function(t){return t.ceil(e)},{$x:e},function(t){return{$x:function(){return qn(t)}}})}}),Js=In({clipByValue_:function(t,e,n){var r=dn(t,"x","clipByValue");return b(e<=n,function(){return"Error in clip: min ("+e+") must be less than or equal to max ("+n+")."}),_t.runKernelFunc(function(t,o){var a=t.clip(r,e,n);return o([r]),a},{$x:r},function(t,r){var o=r[0];return{$x:function(){return t.where(o.greaterEqual(e).logicalAnd(o.lessEqual(n)),qn(t))}}})}}),Zs=In({cos_:function(t){var e=dn(t,"x","cos");return _t.runKernelFunc(function(t,n){var r=t.cos(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return n.toFloat().sin().neg().mul(t)}}})}}),tu=In({cosh_:function(t){var e=dn(t,"x","cosh");return _t.runKernelFunc(function(t,n){var r=t.cosh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return n.toFloat().sinh().mulStrict(t)}}})}}),eu=In({erf_:function(t){var e=dn(t,"x","erf");return b("int32"===e.dtype||"float32"===e.dtype,function(){return"Input dtype must be `int32` or `float32`."}),"int32"===e.dtype&&(e=e.toFloat()),_t.runKernelFunc(function(t,n){var r=t.erf(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.square().neg().exp().mul(2/Math.sqrt(Math.PI)))}}})}}),nu=In({exp_:function(t){var e=dn(t,"x","exp");return _t.runKernelFunc(function(t,n){var r=t.exp(e);return n([r]),r},{$x:e},function(t,e){return{$x:function(){return t.mulStrict(e[0])}}})}}),ru=In({expm1_:function(t){var e=dn(t,"x","expm1");return _t.runKernelFunc(function(t,n){var r=t.expm1(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.exp())}}})}}),ou=In({floor_:function(t){var e=dn(t,"x","floor");return _t.runKernelFunc(function(t){return t.floor(e)},{$x:e},function(t){return{$x:function(){return qn(t)}}})}}),au=In({log_:function(t){var e=dn(t,"x","log");return _t.runKernelFunc(function(t,n){var r=t.log(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.toFloat())}}})}}),iu=In({log1p_:function(t){var e=dn(t,"x","log1p");return _t.runKernelFunc(function(t,n){var r=t.log1p(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.add(1))}}})}}),su=In({logSigmoid_:function(t){var e=dn(t,"x","logSigmoid");return _t.runKernelFunc(function(t,n){var r=t.softplus(e.neg()).neg();return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.neg().sigmoid())}}})}}),uu=In({neg_:function(t){var e=dn(t,"x","neg");return _t.runKernelFunc(function(t){return t.neg(e)},{$x:e},function(t){return{$x:function(){return t.neg()}}})}}),cu=In({reciprocal_:function(t){var e=dn(t,"x","reciprocal");return _t.runKernelFunc(function(t,n){var r=t.reciprocal(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.square().neg())}}})}}),lu=In({round_:function(t){var e=dn(t,"x","round");return _t.runKernelFunc(function(t){return t.round(e)},{$x:e},function(t){return{$x:function(){return qn(t)}}})}}),pu=In({rsqrt_:function(t){var e=dn(t,"x","rsqrt");return _t.runKernelFunc(function(t,n){var r=t.rsqrt(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.pow(1.5).mul(2)).neg()}}})}}),hu=In({sigmoid_:function(t){var e=dn(t,"x","sigmoid");return _t.runKernelFunc(function(t,n){var r=t.sigmoid(e);return n([r]),r},{x:e},function(t,e){var n=e[0];return{x:function(){return t.mul(n.mul(Tn(1).sub(n)))}}},"Sigmoid")}}),du=In({sign_:function(t){var e=dn(t,"x","sign");return _t.runKernelFunc(function(t){return t.sign(e)},{$x:e},function(t){return{$x:function(){return qn(t)}}})}}),fu=In({isNaN_:function(t){var e=dn(t,"x","isNaN");return _t.runKernelFunc(function(t){return t.isNaN(e)},{$x:e},function(t){return{$x:function(){return qn(t)}}})}}),vu=In({isInf_:function(t){var e=dn(t,"x","isInf");return _t.runKernelFunc(function(t){return t.isInf(e)},{$x:e},function(t){return{$x:function(){return qn(t)}}})}}),mu=In({isFinite_:function(t){var e=dn(t,"x","isFinite");return _t.runKernelFunc(function(t){return t.isFinite(e)},{$x:e},function(t){return{$x:function(){return qn(t)}}})}}),gu=In({sin_:function(t){var e=dn(t,"x","sin");return _t.runKernelFunc(function(t,n){var r=t.sin(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return n.toFloat().cos().mul(t)}}})}}),xu=In({sinh_:function(t){var e=dn(t,"x","sinh");return _t.runKernelFunc(function(t,n){var r=t.sinh(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return n.toFloat().cosh().mulStrict(t)}}})}}),yu=In({softplus_:function(t){var e=dn(t,"x","softplus");return _t.runKernelFunc(function(t,n){var r=t.softplus(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mul(n.sigmoid())}}})}}),bu=In({sqrt_:function(t){var e=dn(t,"x","sqrt");return _t.runKernelFunc(function(t,n){var r=t.sqrt(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.toFloat().sqrt().mul(2))}}})}}),wu=In({step_:function(t,e){void 0===e&&(e=0);var n=dn(t,"x","step");return _t.runKernelFunc(function(t){return t.step(n,e)},{$x:n},function(t){return{$x:function(){return qn(t)}}})}}),Cu=In({tan_:function(t){var e=dn(t,"x","tan");return _t.runKernelFunc(function(t,n){var r=t.tan(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.div(n.cos().square())}}})}}),Eu=In({tanh_:function(t){var e=dn(t,"x","tanh");return _t.runKernelFunc(function(t,n){var r=t.tanh(e);return n([r]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return Tn(1).sub(n.square()).mulStrict(t)}}})}});function Ru(t,e,n,r,o,a){var i,s,u=dn(t,"x","batchNorm"),c=dn(e,"mean","batchNorm"),l=dn(n,"variance","batchNorm");return null!=o&&(i=dn(o,"scale","batchNorm")),null!=r&&(s=dn(r,"offset","batchNorm")),b(2===u.rank,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."}),b(2===c.rank||1===c.rank,function(){return"Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank "+c.rank+"."}),b(2===l.rank||1===l.rank,function(){return"Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank "+l.rank+"."}),null!=i&&b(2===i.rank||1===i.rank,function(){return"Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank "+i.rank+"."}),null!=s&&b(2===s.rank||1===s.rank,function(){return"Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank "+s.rank+"."}),Su(u,c,l,s,i,a)}function Iu(t,e,n,r,o,a){var i,s,u=dn(t,"x","batchNorm"),c=dn(e,"mean","batchNorm"),l=dn(n,"variance","batchNorm");return null!=o&&(i=dn(o,"scale","batchNorm")),null!=r&&(s=dn(r,"offset","batchNorm")),b(3===u.rank,function(){return"Error in batchNorm3D: x must be rank 3 but got rank "+u.rank+"."}),b(3===c.rank||1===c.rank,function(){return"Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank "+c.rank+"."}),b(3===l.rank||1===l.rank,function(){return"Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank "+l.rank+"."}),null!=i&&b(3===i.rank||1===i.rank,function(){return"Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank "+i.rank+"."}),null!=s&&b(3===s.rank||1===s.rank,function(){return"Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank "+s.rank+"."}),Su(u,c,l,s,i,a)}function ku(t,e,n,r,o,a){var i,s,u=dn(t,"x","batchNorm"),c=dn(e,"mean","batchNorm"),l=dn(n,"variance","batchNorm");return null!=o&&(i=dn(o,"scale","batchNorm")),null!=r&&(s=dn(r,"offset","batchNorm")),b(4===u.rank,function(){return"Error in batchNorm4D: x must be rank 4 but got rank "+u.rank+"."}),b(4===c.rank||1===c.rank,function(){return"Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank "+c.rank+"."}),b(4===l.rank||1===l.rank,function(){return"Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank "+l.rank+"."}),null!=i&&b(4===i.rank||1===i.rank,function(){return"Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank "+i.rank+"."}),null!=s&&b(4===s.rank||1===s.rank,function(){return"Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank "+s.rank+"."}),Su(u,c,l,s,i,a)}function Su(t,e,n,r,o,a){null==a&&(a=.001);var i,s,u,c=dn(t,"x","batchNorm"),l=dn(e,"mean","batchNorm"),p=dn(n,"variance","batchNorm");null!=o&&(i=dn(o,"scale","batchNorm")),null!=r&&(s=dn(r,"offset","batchNorm")),b(l.rank===p.rank,function(){return"Batch normalization gradient requires mean and variance to have equal ranks."}),b(null==s||l.rank===s.rank,function(){return"Batch normalization gradient requires mean and offset to have equal ranks."}),b(null==i||l.rank===i.rank,function(){return"Batch normalization gradient requires mean and scale to have equal ranks."}),u=0===c.rank||1===c.rank?c.as4D(1,1,1,c.size):2===c.rank?c.as4D(1,1,c.shape[0],c.shape[1]):3===c.rank?c.as4D(1,c.shape[0],c.shape[1],c.shape[2]):c;var h=[c,l,p,i];return _t.runKernelFunc(function(t,e){var n=t.batchNormalization(u,Au(l),Au(p),a,Au(i),Au(s));return e([c,l,p,i]),n},{x:c,mean:l,variance:p,scale:i,offset:s},function(t,e){var n=e,r=n[0],o=n[1],i=n[2],s=n[3],c=null==s?Tn(1):s,l=mo(o.shape,u.shape),p=[];if(1===o.rank){for(var h=0;h<u.shape.length-1;++h)p.push(u.shape[h]);p.push(1)}var d=r.sub(o),f=t.mul(c),v=pu(i.add(Tn(a))),m=v.mul(v).mul(v).mul(Tn(-.5));return{x:function(){return 1===o.rank?t.mul(_r(v.as4D(1,1,1,o.shape[0]),p)).mul(c).reshape(r.shape):t.mul(v).mul(c).reshape(r.shape)},mean:function(){var t=v.mul(Tn(-1)).mul(f);return 1===o.rank&&(t=t.sum(l)),t.reshape(o.shape)},variance:function(){var t=m.mul(d).mul(f);return 1===o.rank&&(t=t.sum(l)),t.reshape(o.shape)},scale:function(){var e=d.mul(v),n=t.mul(e);return 1===o.rank&&(n=n.sum(l)),n.reshape(o.shape)},offset:function(){var e=t;return 1===o.rank&&(e=e.sum(l)),e.reshape(o.shape)}}},"BatchNormalization",{varianceEpsilon:a},h).reshape(c.shape)}function Au(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 Du(){qe("tf.batchNormalization() is going away. Use tf.batchNorm() instead, and note the positional argument change of scale, offset, and varianceEpsilon")}exports.tanh=Eu,exports.tan=Cu,exports.step=wu,exports.sqrt=bu,exports.softplus=yu,exports.sinh=xu,exports.sin=gu,exports.isFinite=mu,exports.isInf=vu,exports.isNaN=fu,exports.sign=du,exports.sigmoid=hu,exports.rsqrt=pu,exports.round=lu,exports.reciprocal=cu,exports.neg=uu,exports.logSigmoid=su,exports.log1p=iu,exports.log=au,exports.floor=ou,exports.expm1=ru,exports.exp=nu,exports.erf=eu,exports.cosh=tu,exports.cos=Zs,exports.clipByValue=Js,exports.ceil=Qs,exports.atanh=Ys,exports.atan=$s,exports.asinh=Xs,exports.asin=js,exports.acosh=Ks,exports.acos=qs,exports.abs=Hs;var Nu=In({batchNormalization2d_:function(t,e,n,r,o,a){return void 0===r&&(r=.001),Du(),Ru(t,e,n,a,o,r)}}),Tu=In({batchNormalization3d_:function(t,e,n,r,o,a){return void 0===r&&(r=.001),Du(),Iu(t,e,n,a,o,r)}}),Fu=In({batchNormalization4d_:function(t,e,n,r,o,a){return void 0===r&&(r=.001),Du(),ku(t,e,n,a,o,r)}}),Ou=In({batchNormalization_:function(t,e,n,r,o,a){return void 0===r&&(r=.001),Du(),Su(t,e,n,a,o,r)}}),_u=In({batchNorm_:Su}),Mu=In({batchNorm2d_:Ru}),Bu=In({batchNorm3d_:Iu}),Pu=In({batchNorm4d_:ku});exports.batchNorm4d=Pu,exports.batchNorm3d=Bu,exports.batchNorm2d=Mu,exports.batchNorm=_u,exports.batchNormalization=Ou,exports.batchNormalization4d=Fu,exports.batchNormalization3d=Tu,exports.batchNormalization2d=Nu;var Lu=In({logicalAnd_:function(t,e){var n=dn(t,"a","logicalAnd","bool"),r=dn(e,"b","logicalAnd","bool");return go(n.shape,r.shape),_t.runKernelFunc(function(t){return t.logicalAnd(n,r)},{$a:n,$b:r})}}),Wu=In({logicalNot_:function(t){var e=dn(t,"x","logicalNot","bool");return _t.runKernelFunc(function(t){return t.logicalNot(e)},{$x:e})}}),zu=In({logicalOr_:function(t,e){var n=dn(t,"a","logicalOr","bool"),r=dn(e,"b","logicalOr","bool");return go(n.shape,r.shape),_t.runKernelFunc(function(t){return t.logicalOr(n,r)},{$a:n,$b:r})}}),Uu=In({logicalXor_:function(t,e){var n=dn(t,"a","logicalXor","bool"),r=dn(e,"b","logicalXor","bool");return go(n.shape,r.shape),zu(t,e).logicalAnd(Lu(t,e).logicalNot())}}),Vu=In({where_:function(t,e,n){var r=dn(e,"a","where"),o=dn(n,"b","where"),a=dn(t,"condition","where","bool");return w(r.shape,o.shape,"Error in where: "),1===a.rank?b(a.shape[0]===r.shape[0],function(){return"The first dimension of `a` must match the size of `condition`."}):w(a.shape,o.shape,"Error in where: "),_t.runKernelFunc(function(t,e){var n=t.select(a,r,o);return e([a]),n},{$condition:a,$a:r,$b:o},function(t,e){var n=e[0];return{$condition:function(){return qn(n).toFloat()},$a:function(){return t.mul(n.cast(t.dtype))},$b:function(){return t.mul(n.logicalNot().cast(t.dtype))}}})}}),Gu=function(t){return a(this,void 0,void 0,function(){var e,n,r;return i(this,function(o){switch(o.label){case 0:return[4,(e=dn(t,"condition","whereAsync","bool")).data()];case 1:return n=o.sent(),r=Go(e.shape,n),t!==e&&e.dispose(),[2,r]}})})};exports.whereAsync=Gu,exports.where=Vu,exports.logicalXor=Uu,exports.logicalOr=zu,exports.logicalNot=Wu,exports.logicalAnd=Lu;var Hu=In({add_:function(t,e){var n,r=dn(t,"a","add"),o=dn(e,"b","add");n=St(r,o),r=n[0],o=n[1];var a=go(r.shape,o.shape);return _t.runKernelFunc(function(t){return t.add(r,o)},{a:r,b:o},function(t){return{a:function(){var e=t,n=mo(r.shape,a);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)},b:function(){var e=t,n=mo(o.shape,a);return n.length>0&&(e=e.sum(n)),e.reshape(o.shape)}}},"Add")}}),qu=In({addN_:function(t){b(Array.isArray(t),function(){return"The argument passed to tf.addN() must be a list of tensors"}),b(t.length>=1,function(){return"Must pass at least one tensor to tf.addN(), but got "+t.length});var e=t.map(function(t,e){return dn(t,"tensors"+e,"addN")}),n=e[0];e.forEach(function(t){if(t.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),e.forEach(function(t){if(!I(t.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});var r=e;return _t.runKernelFunc(function(t){return t.addN(e)},r,function(t){var n={};return e.forEach(function(e,r){n[r]=function(){return t.clone()}}),n})}}),Ku=In({addStrict_:function(t,e){var n=dn(t,"a","addStrict"),r=dn(e,"b","addStrict");return w(n.shape,r.shape,"Error in addStrict: "),n.add(r)}}),ju=In({atan2_:function(t,e){var n,r=dn(t,"a","atan2"),o=dn(e,"b","atan2");n=St(r,o),r=n[0],o=n[1];var a=go(r.shape,o.shape);return _t.runKernelFunc(function(t,e){var n=t.atan2(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=Hu(n.square(),r.square()),o=t.mul(r.div(e)),i=mo(n.shape,a);return i.length>0&&(o=o.sum(i)),o.reshape(n.shape)},$b:function(){var e=Hu(n.square(),r.square()),o=uu(t.mul(n.div(e))),i=mo(r.shape,a);return i.length>0&&(o=o.sum(i)),o.reshape(r.shape)}}})}}),Xu=In({div_:function(t,e){var n,r=dn(t,"a","div"),o=dn(e,"b","div");if(n=St(r,o),r=n[0],o=n[1],"int32"===r.dtype&&"int32"===o.dtype)return Qu(r,o);var a=go(r.shape,o.shape);return _t.runKernelFunc(function(t,e){var n=t.realDivide(r,o);return e([r,o]),n},{a:r,b:o},function(t,e){var n=e[0],r=e[1];return{a:function(){var e=t.div(r.toFloat()),o=mo(n.shape,a);return o.length>0?e.sum(o).reshape(n.shape):e},b:function(){var e=t.mul(n.toFloat()),o=mo(r.shape,a);o.length>0&&(e=e.sum(o).reshape(r.shape));var i=r.square();return e.div(i.toFloat()).neg()}}},"Div")}}),$u=In({divNoNan_:function(t,e){var n,r=dn(t,"a","div"),o=dn(e,"b","div");r=(n=St(r,o))[0],o=n[1];var a=Xu(r,o),i=qn(a),s=o.equal(i);return Vu(s,i,a)}}),Yu=In({divStrict_:function(t,e){var n=dn(t,"a","div"),r=dn(e,"b","div");return w(n.shape,r.shape,"Error in divideStrict: "),n.div(r)}}),Qu=In({floorDiv_:function(t,e){var n,r=dn(t,"a","floorDiv"),o=dn(e,"b","floorDiv");n=St(r,o),r=n[0],o=n[1];var a=go(r.shape,o.shape);return _t.runKernelFunc(function(t,e){var n=t.floorDiv(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=t.div(r.toFloat()),o=mo(n.shape,a);return o.length>0?e.sum(o).reshape(n.shape):e},$b:function(){var e=t.mul(n.toFloat()),o=mo(r.shape,a);o.length>0&&(e=e.sum(o).reshape(r.shape));var i=r.square();return e.div(i.toFloat()).neg()}}})}}),Ju=In({maximum_:function(t,e){var n,r=dn(t,"a","maximum"),o=dn(e,"b","maximum");return n=St(r,o),r=n[0],o=n[1],"bool"===r.dtype&&(r=r.toInt(),o=o.toInt()),go(r.shape,o.shape),_t.runKernelFunc(function(t,e){var n=t.maximum(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return{$a:function(){return t.mul(n.greaterEqual(r).toFloat())},$b:function(){return t.mul(n.less(r).toFloat())}}})}}),Zu=In({maximumStrict_:function(t,e){var n=dn(t,"a","maximumStrict"),r=dn(e,"b","maximumStrict");return w(n.shape,r.shape,"Error in maximumStrict: "),n.maximum(r)}}),tc=In({minimum_:function(t,e){var n,r=dn(t,"a","minimum"),o=dn(e,"b","minimum");return n=St(r,o),r=n[0],o=n[1],"bool"===r.dtype&&(r=r.toInt(),o=o.toInt()),go(r.shape,o.shape),_t.runKernelFunc(function(t,e){var n=t.minimum(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return{$a:function(){return t.mul(n.lessEqual(r).toFloat())},$b:function(){return t.mul(n.greater(r).toFloat())}}})}}),ec=In({minimumStrict_:function(t,e){var n=dn(t,"a","minimumStrict"),r=dn(e,"b","minimumStrict");return w(n.shape,r.shape,"Error in minimumStrict: "),n.minimum(r)}}),nc=In({mod_:function(t,e){var n,r=dn(t,"a","mod"),o=dn(e,"b","mod");n=St(r,o),r=n[0],o=n[1];var a=go(r.shape,o.shape);return _t.runKernelFunc(function(t,e){var n=t.mod(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return{$a:function(){var e=mo(n.shape,a);return e.length>0?t.sum(e).reshape(n.shape):t},$b:function(){var e=t.mul(n.div(r).floor().neg()),o=mo(r.shape,a);return o.length>0?e.sum(o).reshape(r.shape):e}}})}}),rc=In({modStrict_:function(t,e){var n=dn(t,"a","modStrict"),r=dn(e,"b","modStrict");return w(n.shape,r.shape,"Error in modStrict: "),n.mod(r)}}),oc=In({mul_:function(t,e){var n,r=dn(t,"a","mul"),o=dn(e,"b","mul");n=St(r,o),r=n[0],o=n[1];var a=go(r.shape,o.shape);return _t.runKernelFunc(function(t,e){var n=t.multiply(r,o);return e([r,o]),n},{a:r,b:o},function(t,e){var n=e[0],r=e[1];return{a:function(){var e=t.mul(r.toFloat()),o=mo(n.shape,a);return o.length>0?e.sum(o).reshape(n.shape):e},b:function(){var e=t.mul(n.toFloat()),o=mo(r.shape,a);return o.length>0?e.sum(o).reshape(r.shape):e}}},"Mul")}}),ac=In({mulStrict_:function(t,e){var n=dn(t,"a","mul"),r=dn(e,"b","mul");return w(n.shape,r.shape,"Error in multiplyStrict: "),n.mul(r)}}),ic=In({pow_:function(t,e){var n=dn(t,"base","pow"),r=dn(e,"exp","pow"),o=go(n.shape,r.shape);return t=n.cast(It(n.dtype,r.dtype)),e=r.cast(It(n.dtype,r.dtype)),_t.runKernelFunc(function(t,e){var o=t.pow(n,r);return e([n,r,o]),o},{$base:n,$exp:r},function(t,e){var n=e[0],r=e[1],a=e[2];return{$base:function(){var e=r.toFloat(),a=t.mul(e.mul(n.pow(e.sub(Tn(1))))),i=mo(n.shape,o);return i.length>0&&(a=a.sum(i)),a.reshape(n.shape)},$exp:function(){var e=n.greater(0),i=n.log().where(e,qn(n)),s=t.mul(a.mul(i)),u=mo(r.shape,o);return u.length>0&&(s=s.sum(u)),s.reshape(r.shape)}}})}}),sc=In({powStrict_:function(t,e){return w(t.shape,e.shape,"Error in powStrict: "),t.pow(e)}}),uc=In({squaredDifference_:function(t,e){var n,r=dn(t,"a","squaredDifference"),o=dn(e,"b","squaredDifference");return n=St(r,o),r=n[0],o=n[1],go(r.shape,o.shape),_t.runKernelFunc(function(t,e){var n=t.squaredDifference(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1],o=Tn(2);return{$a:function(){return t.mul(n.sub(r).mul(o))},$b:function(){return t.mul(r.sub(n).mul(o))}}})}}),cc=In({squaredDifferenceStrict_:function(t,e){var n=dn(t,"a","squaredDifferenceStrict"),r=dn(e,"b","squaredDifferenceStrict");return w(n.shape,r.shape,"Error in squaredDifferenceStrict: "),n.squaredDifference(r)}}),lc=In({sub_:function(t,e){var n,r=dn(t,"a","sub"),o=dn(e,"b","sub");n=St(r,o),r=n[0],o=n[1];var a=go(r.shape,o.shape);return _t.runKernelFunc(function(t){return t.subtract(r,o)},{a:r,b:o},function(t){return{a:function(){var e=t,n=mo(r.shape,a);return n.length>0&&(e=e.sum(n)),e.reshape(r.shape)},b:function(){var e=t,n=mo(o.shape,a);return n.length>0&&(e=e.sum(n)),e.neg().reshape(o.shape)}}},"Sub")}}),pc=In({subStrict_:function(t,e){var n=dn(t,"a","subStrict"),r=dn(e,"b","subStrict");return w(n.shape,r.shape,"Error in subStrict: "),n.sub(r)}});exports.subStrict=pc,exports.sub=lc,exports.squaredDifferenceStrict=cc,exports.squaredDifference=uc,exports.powStrict=sc,exports.pow=ic,exports.mulStrict=ac,exports.mul=oc,exports.modStrict=rc,exports.mod=nc,exports.minimumStrict=ec,exports.minimum=tc,exports.maximumStrict=Zu,exports.maximum=Ju,exports.floorDiv=Qu,exports.divStrict=Yu,exports.divNoNan=$u,exports.div=Xu,exports.atan2=ju,exports.addStrict=Ku,exports.addN=qu,exports.add=Hu;var hc=In({equal_:function(t,e){var n,r=dn(t,"a","equal"),o=dn(e,"b","equal");return n=St(r,o),r=n[0],o=n[1],go(r.shape,o.shape),_t.runKernelFunc(function(t){return t.equal(r,o)},{$a:r,$b:o})}}),dc=In({equalStrict_:function(t,e){var n=dn(t,"a","equalStrict"),r=dn(e,"b","equalStrict");return w(n.shape,r.shape,"Error in equalStrict: "),n.equal(r)}}),fc=In({greater_:function(t,e){var n,r=dn(t,"a","greater"),o=dn(e,"b","greater");return n=St(r,o),r=n[0],o=n[1],go(r.shape,o.shape),_t.runKernelFunc(function(t){return t.greater(r,o)},{$a:r,$b:o})}}),vc=In({greaterEqual_:function(t,e){var n,r=dn(t,"a","greaterEqual"),o=dn(e,"b","greaterEqual");return n=St(r,o),r=n[0],o=n[1],go(r.shape,o.shape),_t.runKernelFunc(function(t,e){var n=t.greaterEqual(r,o);return e([r,o]),n},{$a:r,$b:o},function(t,e){var n=e[0],r=e[1];return{$a:function(){return qn(n)},$b:function(){return qn(r)}}})}}),mc=In({greaterEqualStrict_:function(t,e){var n=dn(t,"a","greaterEqualStrict"),r=dn(e,"b","greaterEqualStrict");return w(n.shape,r.shape,"Error in greaterEqualStrict: "),n.greaterEqual(r)}}),gc=In({greaterStrict_:function(t,e){var n=dn(t,"a","greaterStrict"),r=dn(e,"b","greaterStrict");return w(n.shape,r.shape,"Error in greaterStrict: "),n.greater(r)}}),xc=In({less_:function(t,e){var n,r=dn(t,"a","less"),o=dn(e,"b","less");return n=St(r,o),r=n[0],o=n[1],go(r.shape,o.shape),_t.runKernelFunc(function(t){return t.less(r,o)},{$a:r,$b:o})}}),yc=In({lessEqual_:function(t,e){var n,r=dn(t,"a","lessEqual"),o=dn(e,"b","lessEqual");return n=St(r,o),r=n[0],o=n[1],go(r.shape,o.shape),_t.runKernelFunc(function(t){return t.lessEqual(r,o)},{$a:r,$b:o})}}),bc=In({lessEqualStrict_:function(t,e){var n=dn(t,"a","lessEqualStrict"),r=dn(e,"b","lessEqualStrict");return w(n.shape,r.shape,"Error in lessEqualStrict: "),n.lessEqual(r)}}),wc=In({lessStrict_:function(t,e){var n=dn(t,"a","lessStrict"),r=dn(e,"b","lessStrict");return w(n.shape,r.shape,"Error in lessStrict: "),n.less(r)}}),Cc=In({notEqual_:function(t,e){var n,r=dn(t,"a","notEqual"),o=dn(e,"b","notEqual");return n=St(r,o),r=n[0],o=n[1],go(r.shape,o.shape),_t.runKernelFunc(function(t){return t.notEqual(r,o)},{$a:r,$b:o})}}),Ec=In({notEqualStrict_:function(t,e){var n=dn(t,"a","notEqualStrict"),r=dn(e,"b","notEqualStrict");return w(n.shape,r.shape,"Error in notEqualStrict: "),n.notEqual(r)}});function Rc(t,e){for(var n=[],r=t;r<e;++r)n.push(r);return n}function Ic(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}exports.notEqualStrict=Ec,exports.notEqual=Cc,exports.lessStrict=wc,exports.lessEqualStrict=bc,exports.lessEqual=yc,exports.less=xc,exports.greaterStrict=gc,exports.greaterEqualStrict=mc,exports.greaterEqual=vc,exports.greater=fc,exports.equalStrict=dc,exports.equal=hc;var kc=In({gather_:function(t,e,n){void 0===n&&(n=0);var r=dn(t,"x","gather"),o=dn(e,"indices","gather","int32");n=F(n,r.shape)[0];var a=function(t,e,n){for(var r=t.shape[n],o=[],a=1,i=1,s=0;s<n;s++)o.push(t.shape[s]),a*=t.shape[s];for(s=0;s<e.rank;s++)o.push(e.shape[s]);for(s=n+1;s<t.rank;s++)o.push(t.shape[s]),i*=t.shape[s];return{batchSize:a,sliceSize:i,dimSize:r,outputShape:o}}(r,o,n);return _t.runKernelFunc(function(t,e){var a=t.gather(r,o.flatten(),n);return e([o]),a},{$x:r},function(t,e){var o=e[0];return{$x:function(){var e=r.shape,a=o.size,i=e.slice(0,n),s=i.length,u=e.slice(n,e.length).slice(1),c=u.length,l=Rc(0,s),p=Rc(s+1,s+1+c),h=Ic([i,[a],u]),d=t.reshape(h),f=o.reshape([a]),v=Ic([[s],l,p]),m=d.transpose(v),g=Sc(m,f,r.shape[n]),x=wn(v);return g.transpose(x)}}}).reshape(a.outputShape)}}),Sc=In({unsortedSegmentSum_:function(t,e,n){var r=dn(t,"x","unsortedSegmentSum"),o=dn(e,"segmentIds","unsortedSegmentSum","int32");return b(k(n),function(){return"numSegments must be of dtype int"}),_t.runKernelFunc(function(t,e){var a=t.unsortedSegmentSum(r,o,n);return e([o]),a},{$x:r},function(t,e){var n=e[0];return{$x:function(){return function(t,e){for(var n=Ju(e,qn(e)),r=kc(t,n),o=vc(e,Tn(0,"int32")),a=r.rank-o.rank,i=0;i<a;++i)o=gr(o,i+1);o=Lu(o,Wn(r.shape,"bool"));var s=qn(r);return Vu(o,r,s)}(t,n)}}})}});exports.unsortedSegmentSum=Sc,exports.gather=kc;var Ac=function(t,e,n){return a(this,void 0,void 0,function(){var r,o,a,s,u,c,l,p,h,d,f,v,m;return i(this,function(i){switch(i.label){case 0:for(r=dn(t,"tensor","boolMask"),o=dn(e,"mask","boolMask","bool"),a=null==n?0:n,s=o.rank,u=r.shape,b(s>0,function(){return"mask cannot be scalar"}),w(u.slice(a,a+s),o.shape,"mask's shape must match the first K dimensions of tensor's shape,"),c=1,l=a;l<a+s;l++)c*=u[l];return p=u.slice(0,a).concat([c],u.slice(a+s)),h=r.reshape(p),d=o.reshape([-1]),[4,Gu(d)];case 1:return f=i.sent(),v=f.squeeze([1]),m=kc(h,v,a),t!==r&&r.dispose(),e!==o&&o.dispose(),v.dispose(),h.dispose(),d.dispose(),f.dispose(),[2,m]}})})};function Dc(t,e,n,r,o,a,i){void 0===a&&(a="NHWC"),b(t.length===e.rank,function(){return"Length of inShape ("+t.length+") and rank of dy ("+e.rank+") must match"});var s=t,u=e,c=!1;3===e.rank&&(c=!0,u=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]),s=[1,t[0],t[1],t[2]]),b(4===s.length,function(){return"Error in conv2dDerInput: inShape must be length 4, but got length "+s.length+"."}),b(4===u.rank,function(){return"Error in conv2dDerInput: dy must be rank 4, but got rank "+u.rank}),b(4===n.rank,function(){return"Error in conv2dDerInput: filter must be rank 4, but got rank "+n.rank});var l="NHWC"===a?s[3]:s[1],p="NHWC"===a?u.shape[3]:u.shape[1];b(l===n.shape[2],function(){return"Error in conv2dDerInput: depth of input ("+l+") must match input depth for filter "+n.shape[2]+"."}),b(p===n.shape[3],function(){return"Error in conv2dDerInput: depth of output ("+p+") must match output depth for filter "+n.shape[3]+"."}),null!=i&&b(k(o),function(){return"Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+o+"."});var h=Do(a),d=bo(s,n.shape,r,1,o,i,!1,h),f=_t.runKernelFunc(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 Oc(t,n,r,o,a,1,i)},filter:function(){return Mc(t,s,n.shape,r,o,a,i)}}});return c?f.as3D(f.shape[1],f.shape[2],f.shape[3]):f}function Nc(t){var e=function(t){return"number"==typeof t?[t,t,t]:2===t.length?[t[0],t[1],1]:t}(t),n=e[0],r=e[1],o=e[2];return 1===n&&1===r&&1===o}function Tc(t,e,n,r,o){b(t.length===e.rank,function(){return"Length of inShape ("+t.length+") and rank of dy ("+e.rank+") must match"});var a=t,i=e,s=!1;4===e.rank&&(s=!0,i=e.as5D(1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]),a=[1,t[0],t[1],t[2],t[3]]);var u=a[4],c=i.shape[4];b(5===a.length,function(){return"Error in conv3dDerInput: inShape must be length 5, but got length "+a.length+"."}),b(5===i.rank,function(){return"Error in conv3dDerInput: dy must be rank 5, but got rank "+i.rank}),b(5===n.rank,function(){return"Error in conv3dDerInput: filter must be rank 5, but got rank "+n.rank}),b(u===n.shape[3],function(){return"Error in conv3dDerInput: depth of input ("+u+") must match input depth for filter "+n.shape[3]+"."}),b(c===n.shape[4],function(){return"Error in conv3dDerInput: depth of output ("+c+") must match output depth for filter "+n.shape[4]+"."});var l=wo(a,n.shape,r,1,o),p=_t.runKernelFunc(function(t){return t.conv3dDerInput(i,n,l)},{dy5D:i});return s?p.as4D(p.shape[1],p.shape[2],p.shape[3],p.shape[4]):p}exports.booleanMaskAsync=Ac;var Fc=In({conv1d_:function(t,e,n,r,o,a,i){void 0===o&&(o="NWC"),void 0===a&&(a=1);var s=dn(t,"x","conv1d"),u=dn(e,"filter","conv1d"),c=s,l=!1;2===s.rank&&(l=!0,c=s.as3D(1,s.shape[0],s.shape[1])),b(3===c.rank,function(){return"Error in conv1d: input must be rank 3, but got rank "+c.rank+"."}),b(3===u.rank,function(){return"Error in conv1d: filter must be rank 3, but got rank "+u.rank+"."}),null!=i&&b(k(r),function(){return"Error in conv1d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+r+"."}),b(c.shape[2]===u.shape[1],function(){return"Error in conv1d: depth of input ("+c.shape[2]+") must match input depth for filter "+u.shape[1]+"."}),b(Ao(n,a),function(){return"Error in conv1D: Either stride or dilation must be 1. Got stride "+n+" and dilation '"+a+"'"}),b("NWC"===o,function(){return"Error in conv1d: got dataFormat of "+o+" but only NWC is currently supported."});var p=u.as4D(1,u.shape[0],u.shape[1],u.shape[2]),h=c.as4D(c.shape[0],1,c.shape[1],c.shape[2]),d=Oc(h,p,[1,n],r,"NHWC",[1,a],i);return l?d.as2D(d.shape[2],d.shape[3]):d.as3D(d.shape[0],d.shape[2],d.shape[3])}}),Oc=In({conv2d_:function(t,e,n,r,o,a,i){void 0===o&&(o="NHWC"),void 0===a&&(a=[1,1]);var s=dn(t,"x","conv2d"),u=dn(e,"filter","conv2d"),c=s,l=!1;3===s.rank&&(l=!0,c=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),b(4===c.rank,function(){return"Error in conv2d: input must be rank 4, but got rank "+c.rank+"."}),b(4===u.rank,function(){return"Error in conv2d: filter must be rank 4, but got rank "+u.rank+"."}),null!=i&&b(k(r),function(){return"Error in conv2d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+r+"."});var p="NHWC"===o?c.shape[3]:c.shape[1];b(p===u.shape[2],function(){return"Error in conv2d: depth of input ("+p+") must match input depth for filter "+u.shape[2]+"."}),b(Ao(n,a),function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+a+"'"});var h=Do(o),d=bo(c.shape,u.shape,n,a,r,i,!1,h),f=[u,c],v=_t.runKernelFunc(function(t,e){var n=t.conv2d(c,u,d);return e([u,c]),n},{x:c,filter:u},function(t,e){var i=e,s=i[0],u=i[1];return b(So(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 Bc(u.shape,t,s,n,r,o)},filter:function(){return Mc(u,t,s.shape,n,r,o)}}},"Conv2D",d,f);return l?v.as3D(v.shape[1],v.shape[2],v.shape[3]):v}}),_c=In({conv3d_:function(t,e,n,r,o,a){void 0===o&&(o="NDHWC"),void 0===a&&(a=[1,1,1]);var i=dn(t,"x","conv3d"),s=dn(e,"filter","conv3d"),u=i,c=!1;4===i.rank&&(c=!0,u=i.as5D(1,i.shape[0],i.shape[1],i.shape[2],i.shape[3])),b(5===u.rank,function(){return"Error in conv3d: input must be rank 5, but got rank "+u.rank+"."}),b(5===s.rank,function(){return"Error in conv3d: filter must be rank 5, but got rank "+s.rank+"."}),b(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]+"."}),b(function(t,e){return Nc(n)||Nc(e)}(0,a),function(){return"Error in conv3D: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+a+"'"}),b("NDHWC"===o,function(){return"Error in conv3d: got dataFormat of "+o+" but only NDHWC is currently supported."});var l=wo(u.shape,s.shape,n,a,r),p=_t.runKernelFunc(function(t,e){var n=t.conv3d(u,s,l);return e([u,s]),n},{x:u,$filter:s},function(t,e){b(Nc(a),function(){return"Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+a+"'"});var o=e[0],i=e[1];return{x:function(){return Tc(o.shape,t,i,n,r)},$filter:function(){return function(t,e,n,r,o){var a=t;4===t.rank&&(a=t.as5D(1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]));var i=e;4===i.rank&&(i=e.as5D(1,e.shape[0],e.shape[1],e.shape[2],e.shape[3])),b(5===a.rank,function(){return"Error in conv3dDerFilter: input must be rank 5, but got shape "+a.shape+"."}),b(5===i.rank,function(){return"Error in conv3dDerFilter: dy must be rank 5, but got shape "+i.shape+"."}),b(5===n.length,function(){return"Error in conv3dDerFilter: filterShape must be length 5, but got "+n+"."}),b(a.shape[4]===n[3],function(){return"Error in conv3dDerFilter: depth of input "+a.shape[4]+") must match input depth in filter ("+n[3]+"."}),b(i.shape[4]===n[4],function(){return"Error in conv3dDerFilter: depth of dy ("+i.shape[4]+") must match output depth for filter ("+n[4]+")."});var s=wo(a.shape,n,r,1,o);return _t.runKernelFunc(function(t){return t.conv3dDerFilter(a,i,s)},{x5D:a,dy5D:i})}(o,t,i.shape,n,r)}}});return c?p.as4D(p.shape[1],p.shape[2],p.shape[3],p.shape[4]):p}}),Mc=In({conv2dDerFilter_:function(t,e,n,r,o,a,i){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])),b(4===s.rank,function(){return"Error in conv2dDerFilter: input must be rank 4, but got shape "+s.shape+"."}),b(4===u.rank,function(){return"Error in conv2dDerFilter: dy must be rank 4, but got shape "+u.shape+"."}),b(4===n.length,function(){return"Error in conv2dDerFilter: filterShape must be length 4, but got "+n+"."});var c="NHWC"===a?s.shape[3]:s.shape[1],l="NHWC"===a?u.shape[3]:u.shape[1];b(c===n[2],function(){return"Error in conv2dDerFilter: depth of input "+c+") must match input depth in filter ("+n[2]+"."}),b(l===n[3],function(){return"Error in conv2dDerFilter: depth of dy ("+l+") must match output depth for filter ("+n[3]+")."}),null!=i&&b(k(o),function(){return"Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+o+"."});var p=Do(a),h=bo(s.shape,n,r,1,o,i,!1,p);return _t.runKernelFunc(function(t){return t.conv2dDerFilter(s,u,h)},{x4D:s,dy4D:u})}}),Bc=In({conv2dDerInput_:Dc}),Pc=In({depthwiseConv2d_:function(t,e,n,r,o,a,i){void 0===o&&(o="NHWC"),void 0===a&&(a=[1,1]);var s=dn(t,"x","depthwiseConv2d"),u=dn(e,"filter","depthwiseConv2d"),c=s,l=!1;3===s.rank&&(l=!0,c=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),b(4===c.rank,function(){return"Error in depthwiseConv2d: input must be rank 4, but got rank "+c.rank+"."}),b(4===u.rank,function(){return"Error in depthwiseConv2d: filter must be rank 4, but got rank "+u.rank+"."}),b(c.shape[3]===u.shape[2],function(){return"Error in depthwiseConv2d: number of input channels ("+c.shape[3]+") must match the inChannels dimension in filter "+u.shape[2]+"."}),null==a&&(a=[1,1]),b(Ao(n,a),function(){return"Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+a+"'"}),null!=i&&b(k(r),function(){return"Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+r+"."});var p=bo(c.shape,u.shape,n,a,r,i,!0),h=_t.runKernelFunc(function(t,e){var n=t.depthwiseConv2D(c,u,p);return e([c,u]),n},{x:c,$filter:u},function(t,e){b(So(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 Lc(n.shape,t,r,p)},$filter:function(){return Wc(n,t,r.shape,p)}}});return l?h.as3D(h.shape[1],h.shape[2],h.shape[3]):h}}),Lc=In({depthwiseConv2dDerInput_:function(t,e,n,r){var o=e,a=!1;3===e.rank&&(a=!0,o=e.as4D(1,e.shape[0],e.shape[1],e.shape[2]));var i=_t.runKernelFunc(function(t){return t.depthwiseConv2DDerInput(o,n,r)},{dy4D:o});return a?i.as3D(i.shape[1],i.shape[2],i.shape[3]):i}}),Wc=In({depthwiseConv2dDerFilter_:function(t,e,n,r){var o=t;3===t.rank&&(o=t.as4D(1,t.shape[0],t.shape[1],t.shape[2]));var a=e;return 3===a.rank&&(a=e.as4D(1,e.shape[0],e.shape[1],e.shape[2])),_t.runKernelFunc(function(t){return t.depthwiseConv2DDerFilter(o,a,r)},{x4D:o,dy4D:a})}}),zc=In({separableConv2d_:function(t,e,n,r,o,a,i){void 0===a&&(a=[1,1]),void 0===i&&(i="NHWC");var s=dn(t,"x","separableConv2d"),u=dn(e,"depthwiseFilter","separableConv2d"),c=dn(n,"pointwiseFilter","separableConv2d"),l=s,p=!1;if(3===s.rank&&(p=!0,l=s.as4D(1,s.shape[0],s.shape[1],s.shape[2])),"NCHW"===i)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");b(4===l.rank,function(){return"Error in separableConv2d: input must be rank 4, but got rank "+l.rank+"."}),b(4===u.rank,function(){return"Error in separableConv2d: depthwise filter must be rank 4, but got rank "+u.rank+"."}),b(4===c.rank,function(){return"Error in separableConv2d: pointwise filter must be rank 4, but got rank "+u.rank+"."}),b(1===c.shape[0],function(){return"Error in separableConv2d: the first dimension of pointwise filter  must be 1, but got "+c.shape[0]+"."}),b(1===c.shape[1],function(){return"Error in separableConv2d: the second dimension of pointwise filter must be 1, but got "+c.shape[1]+"."});var h=u.shape[2],d=u.shape[3];b(c.shape[2]===h*d,function(){return"Error in separableConv2d: the third dimension of pointwise filter must be "+h*d+", but got "+c.shape[2]+"."});var f=Pc(l,u,r,o,i,a),v=Oc(f,c,1,"valid",i);return p?v.as3D(v.shape[1],v.shape[2],v.shape[3]):v}}),Uc=In({conv2dTranspose_:function(t,e,n,r,o,a){return Dc(n,dn(t,"x","conv2dTranspose"),dn(e,"filter","conv2dTranspose"),r,o,"NHWC",a)}}),Vc=In({conv3dTranspose_:function(t,e,n,r,o){return Tc(n,dn(t,"x","conv3dTranspose"),dn(e,"filter","conv3dTranspose"),r,o)}});exports.conv3dTranspose=Vc,exports.conv2dTranspose=Uc,exports.separableConv2d=zc,exports.depthwiseConv2d=Pc,exports.conv3d=_c,exports.conv2d=Oc,exports.conv1d=Fc;var Gc=In({matMul_:function(t,e,n,r){var o;void 0===n&&(n=!1),void 0===r&&(r=!1);var a=dn(t,"a","matMul"),i=dn(e,"b","matMul");o=St(a,i),a=o[0],i=o[1];var s=n?a.shape[a.rank-2]:a.shape[a.rank-1],u=r?i.shape[i.rank-1]:i.shape[i.rank-2],c=n?a.shape[a.rank-1]:a.shape[a.rank-2],l=r?i.shape[i.rank-2]:i.shape[i.rank-1],p=a.shape.slice(0,-2),h=i.shape.slice(0,-2),d=R(p),f=R(h);b(a.rank>=2&&i.rank>=2&&a.rank===i.rank,function(){return"Error in matMul: inputs must have the same rank of at least 2, got ranks "+a.rank+" and "+i.rank+"."}),b(I(p,h),function(){return"Error in matMul: outer dimensions ("+p+") and ("+h+") of Tensors with shapes "+a.shape+" and "+i.shape+" must match."}),b(s===u,function(){return"Error in matMul: inner shapes ("+s+") and ("+u+") of Tensors with shapes "+a.shape+" and "+i.shape+" and transposeA="+n+" and transposeB="+r+" must match."});var v=a.shape.slice(0,-2).concat([c,l]),m=n?a.as3D(d,s,c):a.as3D(d,c,s),g=r?i.as3D(f,l,u):i.as3D(f,u,l),x={transposeA:n,transposeB:r};return _t.runKernelFunc(function(t,e){var o=t.batchMatMul(m,g,n,r);return e([m,g]),o},{a:m,b:g},function(t,e){var o=e,a=o[0],i=o[1];return n||r?!n&&r?{a:function(){return t.matMul(i,!1,!1)},b:function(){return t.matMul(a,!0,!1)}}:n&&!r?{a:function(){return i.matMul(t,!1,!0)},b:function(){return a.matMul(t,!1,!1)}}:{a:function(){return i.matMul(t,!0,!0)},b:function(){return t.matMul(a,!0,!0)}}:{a:function(){return t.matMul(i,!1,!0)},b:function(){return a.matMul(t,!0,!1)}}},"BatchMatMul",x).reshape(v)}}),Hc=In({dot_:function(t,e){var n=dn(t,"t1","dot"),r=dn(e,"t2","dot");b(!(1!==n.rank&&2!==n.rank||1!==r.rank&&2!==r.rank),function(){return"Error in dot: inputs must all be rank 1 or 2, but got ranks "+n.rank+" and "+r.rank+"."});var o=1===n.rank?n.size:n.shape[1],a=1===r.rank?r.size:r.shape[0];return b(o===a,function(){return"Error in dot: inner dimensions of inputs must match, but got "+o+" and "+a+"."}),1===n.rank&&1===r.rank?n.as2D(1,-1).matMul(r.as2D(-1,1)).asScalar():1===n.rank&&2===r.rank?n.as2D(1,-1).matMul(r.as2D(r.shape[0],r.shape[1])).as1D():2===n.rank&&1===r.rank?n.matMul(r.as2D(-1,1)).as1D():n.matMul(r.as2D(r.shape[0],r.shape[1]))}}),qc=In({outerProduct_:function(t,e){var n=dn(t,"v1","outerProduct"),r=dn(e,"v2","outerProduct");return b(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))}});exports.outerProduct=qc,exports.dot=Hc,exports.matMul=Gc;var Kc=In({reverse_:function(t,e){var n=dn(t,"x","reverse");if(0===n.rank)return n.clone();var r=F(e,n.shape);return _t.runKernelFunc(function(t){return t.reverse(n,r)},{$x:n},function(t){return{$x:function(){return t.reverse(r)}}}).reshapeAs(n)}}),jc=In({reverse1d_:function(t){var e=dn(t,"x","reverse");return b(1===e.rank,function(){return"Error in reverse1D: x must be rank 1 but got rank "+e.rank+"."}),Kc(e,0)}}),Xc=In({reverse2d_:function(t,e){var n=dn(t,"x","reverse");return b(2===n.rank,function(){return"Error in reverse2D: x must be rank 2 but got rank "+n.rank+"."}),Kc(n,e)}}),$c=In({reverse3d_:function(t,e){var n=dn(t,"x","reverse");return b(3===n.rank,function(){return"Error in reverse3D: x must be rank 3 but got rank "+n.rank+"."}),Kc(n,e)}}),Yc=In({reverse4d_:function(t,e){var n=dn(t,"x","reverse");return b(4===n.rank,function(){return"Error in reverse4D: x must be rank 4 but got rank "+n.rank+"."}),Kc(n,e)}});function Qc(t,e,n,r,o,a){var i=dn(t,"x","maxPool"),s=i,u=!1;3===i.rank&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),null==r&&(r=[1,1]),b(4===s.rank,function(){return"Error in maxPool: input must be rank 4 but got rank "+s.rank+"."}),b(Ao(n,r),function(){return"Error in maxPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"}),null!=a&&b(k(o),function(){return"Error in maxPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+o+"."});var c=xo(s.shape,e,n,r,o,a),l=_t.runKernelFunc(function(t,e){var n=t.maxPool(s,c);return e([s,n]),n},{x:s},function(t,a){var i=a[0],s=a[1];return{x:function(){return function(t,e,n,r,o,a,i,s){var u=dn(t,"dy","maxPoolBackprop"),c=dn(e,"input","maxPoolBackprop"),l=dn(n,"output","maxPoolBackprop");b(c.rank===u.rank,function(){return"Rank of input ("+c.rank+") does not match rank of dy ("+u.rank+")"}),null==a&&(a=[1,1]),b(Ao(o,a),function(){return"Error in maxPoolBackProp: Either strides or dilations must be 1. Got strides "+o+" and dilations '"+a+"'"}),b(4===u.rank,function(){return"Error in maxPoolBackprop: dy must be rank 4 but got rank "+u.rank+"."}),b(4===c.rank,function(){return"Error in maxPoolBackprop: input must be rank 4 but got rank "+c.rank+"."});var p=xo(c.shape,r,o,a,i,s);return _t.runKernelFunc(function(t){return t.maxPoolBackprop(u,c,l,p)},{$dy:u,$input:c})}(t,i,s,e,n,r,o)}}});return u?l.as3D(l.shape[1],l.shape[2],l.shape[3]):l}function Jc(t,e,n,r,o,a){var i=dn(t,"x","avgPool","float32");null==r&&(r=[1,1]),b(Ao(n,r),function(){return"Error in avgPool: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+r+"'"});var s=i,u=!1;3===i.rank&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),b(4===s.rank,function(){return"Error in avgPool: x must be rank 4 but got rank "+s.rank+"."}),null!=a&&b(k(o),function(){return"Error in avgPool: pad must be an integer when using, dimRoundingMode "+a+" but got pad "+o+"."});var c=xo(s.shape,e,n,r,o,a),l=_t.runKernelFunc(function(t){return t.avgPool(s,c)},{x:s},function(t){return{x:function(){return function(t,e,n,r,o,a){var i=dn(t,"dy","avgPoolBackprop"),s=dn(e,"input","avgPoolBackprop");b(s.rank===i.rank,function(){return"Rank of input ("+s.rank+") does not match rank of dy ("+i.rank+")"}),null==o&&(o=[1,1]),b(Ao(r,o),function(){return"Error in avgPoolBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+o+"'"});var u=s,c=i,l=!1;3===s.rank&&(l=!0,u=s.as4D(1,s.shape[0],s.shape[1],s.shape[2]),c=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),b(4===c.rank,function(){return"Error in avgPoolBackprop: dy must be rank 4 but got rank "+c.rank+"."}),b(4===u.rank,function(){return"Error in avgPoolBackprop: input must be rank 4 but got rank "+u.rank+"."});var p=xo(u.shape,n,r,o,a),h=_t.runKernelFunc(function(t){return t.avgPoolBackprop(c,u,p)},{dy4D:c,input4D:u});return l?h.as3D(h.shape[1],h.shape[2],h.shape[3]):h}(t,s,e,n,r,o)}}});return l=l.cast(i.dtype),u?l.as3D(l.shape[1],l.shape[2],l.shape[3]):l}exports.reverse4d=Yc,exports.reverse3d=$c,exports.reverse2d=Xc,exports.reverse1d=jc,exports.reverse=Kc;var Zc=In({maxPool_:function(t,e,n,r,o){return Qc(t,e,n,1,r,o)}}),tl=In({avgPool_:function(t,e,n,r,o){return Jc(t,e,n,1,r,o)}}),el=In({pool_:function(t,e,n,r,o,a){null==o&&(o=[1,1]),null==a&&(a=1),0===r&&(r="valid");var i=dn(t,"x","maxPool"),s=i,u=!1;3===i.rank&&(u=!0,s=i.as4D(1,i.shape[0],i.shape[1],i.shape[2])),b(Ao(a,o),function(){return"Error in pool: Either strides or dilations must be 1. Got strides "+a+" and dilations '"+o+"'"});var c,l=xo(s.shape,e,a,o,r),p=[l.dilationHeight,l.dilationWidth];c="same"===r?function(t,e){var n=t.map(function(t,n){return t+(t-1)*(e[n]-1)}).map(function(t){return t-1}),r=n.map(function(t){return Math.floor(t/2)}),o=n.map(function(t,e){return t-r[e]});return n.map(function(t,e){return[r[e],o[e]]})}([l.filterHeight,l.filterWidth],p):[[0,0],[0,0]];var h=1===p[0]&&1===p[1],d=function(t,e,n){var r=n.map(function(t){return t[0]}),o=n.map(function(t){return t[1]}),a=t.concat(r,o),i=e.map(function(t,e){return(t-a[e]%t)%t}),s=o.map(function(t,e){return t+i[e]});return[e.map(function(t,e){return[r[e],s[e]]}),e.map(function(t,e){return[0,i[e]]})]}([l.inHeight,l.inWidth],p,c),f=d[0],v=d[1],m=h?r:"valid",g=h?s:Tr(s,p,f),x=("avg"===n?function(){return Jc(g,e,a,1,m)}:function(){return Qc(g,e,a,1,m)})(),y=h?x:hr(x,p,v);return u?y.as3D(y.shape[1],y.shape[2],y.shape[3]):y}}),nl=In({maxPool3d_:function(t,e,n,r,o,a,i){void 0===a&&(a="NDHWC");var s=dn(t,"x","maxPool3d"),u=s,c=!1;4===s.rank&&(c=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),null==i&&(i=[1,1,1]),b(5===u.rank,function(){return"Error in maxPool3d: x must be rank 5 but got rank "+u.rank+"."}),b("NDHWC"===a,function(){return"Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of "+a}),b(Ao(n,i),function(){return"Error in maxPool3d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+i+"'"}),null!=o&&b(k(r),function(){return"Error in maxPool3d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+"."});var l=yo(u.shape,e,n,i,r,o,a),p=_t.runKernelFunc(function(t,e){var n=t.maxPool3d(u,l);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,o,a,i,s){var u=dn(t,"dy","maxPool3dBackprop"),c=dn(e,"input","maxPool3dBackprop"),l=dn(n,"output","maxPool3dBackprop"),p=u,h=c,d=l,f=!1;4===c.rank&&(f=!0,p=u.as5D(1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]),h=c.as5D(1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]),d=l.as5D(1,l.shape[0],l.shape[1],l.shape[2],l.shape[3])),b(5===p.rank,function(){return"Error in maxPool3dBackprop: dy must be rank 5 but got rank "+p.rank+"."}),b(5===h.rank,function(){return"Error in maxPool3dBackprop: input must be rank 5 but got rank "+h.rank+"."}),b(5===d.rank,function(){return"Error in maxPool3dBackprop: output must be rank 5 but got rank "+d.rank+"."}),null==a&&(a=[1,1,1]),b(Ao(o,a),function(){return"Error in maxPool3dBackprop: Either strides or dilations must be 1. Got strides "+o+" and dilations '"+a+"'"}),null!=s&&b(k(i),function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+s+" but got pad "+i+"."});var v=yo(h.shape,r,o,a,i,s),m=_t.runKernelFunc(function(t){return t.maxPool3dBackprop(p,h,d,v)},{dy5D:p,input5D:h});return f?m.as4D(m.shape[1],m.shape[2],m.shape[3],m.shape[4]):m}(t,s,u,e,n,i,r,o)}}});return c?p.as4D(p.shape[1],p.shape[2],p.shape[3],p.shape[4]):p}}),rl=In({avgPool3d_:function(t,e,n,r,o,a,i){void 0===a&&(a="NDHWC");var s=dn(t,"x","avgPool3d","float32"),u=s,c=!1;4===s.rank&&(c=!0,u=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3])),null==i&&(i=[1,1,1]),b(5===u.rank,function(){return"Error in avgPool3d: x must be rank 5 but got rank "+u.rank+"."}),b("NDHWC"===a,function(){return"Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of "+a}),b(Ao(n,i),function(){return"Error in avgPool3d: Either strides or dilations must be 1. Got strides "+n+" and dilations '"+i+"'"}),null!=o&&b(k(r),function(){return"Error in avgPool3d: pad must be an integer when using, dimRoundingMode "+o+" but got pad "+r+"."});var l=yo(u.shape,e,n,i,r,o,a),p=_t.runKernelFunc(function(t){return t.avgPool3d(u,l)},{x:u},function(t){return{x:function(){return function(t,e,n,r,o,a,i){var s=dn(t,"dy","avgPool3dBackprop"),u=dn(e,"input","avgPool3dBackprop"),c=s,l=u,p=!1;4===u.rank&&(p=!0,c=s.as5D(1,s.shape[0],s.shape[1],s.shape[2],s.shape[3]),l=u.as5D(1,u.shape[0],u.shape[1],u.shape[2],u.shape[3])),b(5===c.rank,function(){return"Error in avgPool3dBackprop: dy must be rank 5 but got rank "+c.rank+"."}),b(5===l.rank,function(){return"Error in avgPool3dBackprop: input must be rank 5 but got rank "+l.rank+"."}),null==o&&(o=[1,1,1]),b(Ao(r,o),function(){return"Error in avgPool3dBackprop: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+o+"'"}),null!=i&&b(k(a),function(){return"Error in maxPool3dBackprop: pad must be an integer when using, dimRoundingMode "+i+" but got pad "+a+"."});var h=yo(l.shape,n,r,o,a,i),d=_t.runKernelFunc(function(t){return t.avgPool3dBackprop(c,l,h)},{dy5D:c,input5D:l});return p?d.as4D(d.shape[1],d.shape[2],d.shape[3],d.shape[4]):d}(t,u,e,n,i,r,o)}}});return p=p.cast(u.dtype),c?p.as4D(p.shape[1],p.shape[2],p.shape[3],p.shape[4]):p}});exports.avgPool3d=rl,exports.maxPool3d=nl,exports.pool=el,exports.avgPool=tl,exports.maxPool=Zc;var ol=In({slice_:function(t,e,n){var r,o,a=dn(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){b(-1!==t,function(){return"slice() does not support negative begin indexing."})}),o=(o=null==n?new Array(a.rank).fill(-1):"number"==typeof n?[n].concat(new Array(a.rank-1).fill(-1)):n.length<a.rank?n.concat(new Array(a.rank-n.length).fill(-1)):n).map(function(t,e){return t>=0?t:(b(-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])}),Xr(a,r,o);var i=a.shape,s={begin:r,size:o};return _t.runKernelFunc(function(t){return t.slice(a,r,o)},{x:a},function(t){for(var e=[],n=0;n<t.rank;n++)e.push([r[n],i[n]-r[n]-o[n]]);return{x:function(){return t.pad(e)}}},"Slice",s)}}),al=In({slice1d_:function(t,e,n){var r=dn(t,"x","slice1d");return b(1===r.rank,function(){return"slice1d expects a rank-1 tensor, but got a rank-"+r.rank+" tensor"}),ol(r,[e],[n])}}),il=In({slice2d_:function(t,e,n){var r=dn(t,"x","slice2d");return b(2===r.rank,function(){return"slice2d expects a rank-2 tensor, but got a rank-"+r.rank+" tensor"}),ol(r,e,n)}}),sl=In({slice3d_:function(t,e,n){var r=dn(t,"x","slice3d");return b(3===r.rank,function(){return"slice3d expects a rank-3 tensor, but got a rank-"+r.rank+" tensor"}),ol(r,e,n)}}),ul=In({slice4d_:function(t,e,n){var r=dn(t,"x","slice4d");return b(4===r.rank,function(){return"slice4d expects a rank-4 tensor, but got a rank-"+r.rank+" tensor"}),ol(r,e,n)}});function cl(t,e,n,r,o){return e.rank<n.rank&&(e=e.reshape(xn(e.shape,r))),t.rank<n.rank&&(t=t.reshape(xn(t.shape,r))),{x:function(){var r=t.mul(n.equal(e).cast(t.dtype));return null==o?r:r.transpose(o)}}}exports.slice4d=ul,exports.slice3d=sl,exports.slice2d=il,exports.slice1d=al,exports.slice=ol;var ll=In({all_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=dn(t,"x","all","bool"),o=F(e,r.shape),a=o,i=bn(a,r.rank);null!=i&&(r=r.transpose(i),a=Cn(a.length,r.rank));var s=_t.runKernelFunc(function(t){return t.all(r,a)},{$x:r});if(n){var u=xn(s.shape,o);return s.reshape(u)}return s}}),pl=In({any_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=dn(t,"x","any","bool"),o=F(e,r.shape),a=o,i=bn(a,r.rank);null!=i&&(r=r.transpose(i),a=Cn(a.length,r.rank));var s=_t.runKernelFunc(function(t){return t.any(r,a)},{$x:r});if(n){var u=xn(s.shape,o);return s.reshape(u)}return s}}),hl=In({argMax_:function(t,e){void 0===e&&(e=0);var n=dn(t,"x","argMax");null==e&&(e=0);var r=F(e,n.shape),o=bn(r,n.rank);return null!=o&&(n=n.transpose(o),r=Cn(r.length,n.rank)),_t.runKernelFunc(function(t,e){var o=t.argMax(n,r[0]);return e([n]),o},{$x:n},function(t,e){var n=e[0];return{$x:function(){return qn(n)}}})}}),dl=In({argMin_:function(t,e){void 0===e&&(e=0);var n=dn(t,"x","argMin");null==e&&(e=0);var r=F(e,n.shape),o=bn(r,n.rank);return null!=o&&(n=n.transpose(o),r=Cn(r.length,n.rank)),_t.runKernelFunc(function(t,e){var o=t.argMin(n,r[0]);return e([n]),o},{$x:n},function(t,e){var n=e[0];return{$x:function(){return qn(n)}}})}}),fl=In({logSumExp_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=dn(t,"x","logSumExp"),o=F(e,r.shape),a=r.max(o,!0),i=r.sub(a).exp().sum(o).log(),s=a.reshape(i.shape).add(i);if(n){var u=xn(s.shape,o);return s.reshape(u)}return s}}),vl=In({max_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=dn(t,"x","max"),o=r,a=F(e,r.shape),i=a,s=bn(i,r.rank);null!=s&&(r=r.transpose(s),i=Cn(i.length,r.rank));var u=[r],c=_t.runKernelFunc(function(t,e){var n=t.max(r,i);return e([o,n]),n},{x:r},function(t,e){return cl(t,e[1],e[0],a,s)},"Max",{axes:i},u,[!0]);if(n){var l=xn(c.shape,a);c=c.reshape(l)}return c}}),ml=In({mean_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=dn(t,"x","mean"),o=F(e,r.shape),a=R(gn(r.shape,o)[1]);return so(function(t){var r=Tn(a);return{value:(r.dtype===t.dtype?t:t.cast(r.dtype)).div(r).sum(e,n),gradFunc:function(e){var n=t.shape.slice();return o.forEach(function(t){n[t]=1}),e.reshape(n).mul(Wn(t.shape,"float32")).div(a)}}})(r)}}),gl=In({min_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=dn(t,"x","min"),o=r,a=F(e,r.shape),i=a,s=bn(i,r.rank);null!=s&&(r=r.transpose(s),i=Cn(i.length,r.rank));var u=[r],c=_t.runKernelFunc(function(t,e){var n=t.min(r,i);return e([o,n]),n},{x:r},function(t,e){return cl(t,e[1],e[0],a,s)},"Min",{axes:i},u,[!0]);if(n){var l=xn(c.shape,a);c=c.reshape(l)}return c}}),xl=In({moments_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=F(e,(t=dn(t,"x","moments")).shape),o=t.mean(r,n),a=o.shape;n||(a=xn(o.shape,r));var i=t.toFloat().sub(o.reshape(a)).square();return{mean:o,variance:i.mean(r,n)}}}),yl=In({sum_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=dn(t,"x","sum");"bool"===r.dtype&&(r=r.toInt());var o=F(e,r.shape);return so(function(t){var e=bn(o,t.rank),r=o,a=t;null!=e&&(a=t.transpose(e),r=Cn(r.length,t.rank));var i=_t.runKernelFunc(function(t){return t.sum(a,r)},{permutedX:a});if(n){var s=xn(i.shape,o);i=i.reshape(s)}return{value:i,gradFunc:function(e){var n=t.shape.slice();return o.forEach(function(t){n[t]=1}),e.reshape(n).mul(Wn(t.shape,"float32"))}}})(r)}}),bl=In({prod_:function(t,e,n){void 0===e&&(e=null),void 0===n&&(n=!1);var r=dn(t,"x","prod");"bool"===r.dtype&&(r=r.toInt());var o=F(e,r.shape),a=bn(o,r.rank),i=o,s=r;null!=a&&(s=r.transpose(a),i=Cn(i.length,r.rank));var u=_t.runKernelFunc(function(t){return t.prod(s,i)},{permutedX:s});if(n){var c=xn(u.shape,o);u=u.reshape(c)}return u}});exports.prod=bl,exports.sum=yl,exports.moments=xl,exports.min=gl,exports.mean=ml,exports.max=vl,exports.logSumExp=fl,exports.argMin=dl,exports.argMax=hl,exports.any=pl,exports.all=ll;var wl=In({elu_:function(t){var e=dn(t,"x","elu");return _t.runKernelFunc(function(t,n){var r=t.elu(e);return n([r]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return _t.runKernelFunc(function(e){return e.eluDer(t,n)},{dy:t,y:n})}}})}}),Cl=In({leakyRelu_:function(t,e){void 0===e&&(e=.2);var n=dn(t,"x","leakyRelu");return Ju(Tn(e).mul(n),n)}}),El=In({prelu_:function(t,e){var n=dn(t,"x","prelu"),r=dn(e,"alpha","prelu");return _t.runKernelFunc(function(t,e){var o=t.prelu(n,r);return e([n,r]),o},{x:n,alpha:r},function(t,e){var n=e[0],r=e[1],o=n.greater(0);return{x:function(){return Vu(o,t,t.mul(r))},alpha:function(){var e=Vu(o,qn(t),t.mul(n)),a=mo(r.shape,t.shape);return a.length>0&&(e=e.sum(a)),e.reshape(r.shape)}}},"Prelu")}}),Rl=In({relu_:function(t){var e=dn(t,"x","relu");return"bool"===e.dtype?e.toInt():_t.runKernelFunc(function(t,n){var r=t.relu(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){return t.mulStrict(n.step().toFloat())}}})}}),Il=In({relu6_:function(t){var e=dn(t,"x","relu6");return"bool"===e.dtype?e.toInt():_t.runKernelFunc(function(t,n){var r=t.relu6(e);return n([e]),r},{$x:e},function(t,e){var n=e[0],r=n.lessEqual(6).mul(n.step());return{$x:function(){return t.mulStrict(r.toFloat())}}})}}),kl=In({selu_:function(t){var e=dn(t,"x","selu");return _t.runKernelFunc(function(t,n){var r=t.selu(e);return n([e]),r},{$x:e},function(t,e){var n=e[0];return{$x:function(){var e=n.greater(Tn(0)),r=Tn(cs),o=Tn(ls),a=t.mul(o),i=t.mul(r).mul(n.toFloat().exp());return Vu(e,a,i)}}})}});exports.selu=kl,exports.relu6=Il,exports.relu=Rl,exports.prelu=El,exports.leakyRelu=Cl,exports.elu=wl;var Sl=In({transpose_:function(t,e){var n=dn(t,"x","transpose");if(null==e&&(e=n.shape.map(function(t,e){return e}).reverse()),b(n.rank===e.length,function(){return"Error in transpose: rank of input "+n.rank+" must match length of perm "+e+"."}),e.forEach(function(t){b(t>=0&&t<n.rank,function(){return"All entries in 'perm' must be between 0 and "+(n.rank-1)+" but got "+e})}),n.rank<=1)return n.clone();var r={perm:e};return _t.runKernelFunc(function(t){return t.transpose(n,e)},{x:n},function(t){var n=wn(e);return{x:function(){return t.transpose(n)}}},"Transpose",r)}});exports.transpose=Sl;var Al=In({localResponseNormalization_:function(t,e,n,r,o){void 0===e&&(e=5),void 0===n&&(n=1),void 0===r&&(r=1),void 0===o&&(o=.5);var a=dn(t,"x","localResponseNormalization");b(4===a.rank||3===a.rank,function(){return"Error in localResponseNormalization: x must be rank 3 or 4 but got\n               rank "+a.rank+"."}),b(k(e),function(){return"Error in localResponseNormalization: depthRadius must be an integer but got depthRadius "+e+"."});var i=a,s=!1;3===a.rank&&(s=!0,i=a.as4D(1,a.shape[0],a.shape[1],a.shape[2]));var u=_t.runKernelFunc(function(t,a){var s=t.localResponseNormalization4D(i,e,n,r,o);return a([i,s]),s},{x4D:i},function(t,a){var i=a[0],s=a[1];return{x4D:function(){return _t.runKernelFunc(function(a){return a.LRNGrad(t,i,s,e,n,r,o)},{})}}});return s?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}});exports.localResponseNormalization=Al;var Dl=In({norm_:function(t,e,n,r){void 0===e&&(e="euclidean"),void 0===n&&(n=null),void 0===r&&(r=!1);var o=function t(e,n,r){if(void 0===r&&(r=null),0===e.rank)return e.abs();if(1!==e.rank&&null===r)return t(e.reshape([-1]),n,r);if(1===e.rank||"number"==typeof r||Array.isArray(r)&&1===r.length){if(1===n)return e.abs().sum(r);if(n===1/0)return e.abs().max(r);if(n===-1/0)return e.abs().min(r);if("euclidean"===n||2===n)return e.abs().pow(Tn(2,"int32")).sum(r).sqrt();throw new Error("Error in norm: invalid ord value: "+n)}if(Array.isArray(r)&&2===r.length){if(1===n)return e.abs().sum(r[0]).max(r[1]-1);if(n===1/0)return e.abs().sum(r[1]).max(r[0]);if(n===-1/0)return e.abs().sum(r[1]).min(r[0]);if("fro"===n||"euclidean"===n)return e.square().sum(r).sqrt();throw new Error("Error in norm: invalid ord value: "+n)}throw new Error("Error in norm: invalid axis: "+r)}(t=dn(t,"x","norm"),e,n),a=o.shape;if(r){var i=F(n,t.shape);a=xn(o.shape,i)}return o.reshape(a)}});exports.norm=Dl;var Nl=In({basicLSTMCell_:function(t,e,n,r,o,a){var i=dn(t,"forgetBias","basicLSTMCell"),s=dn(e,"lstmKernel","basicLSTMCell"),u=dn(n,"lstmBias","basicLSTMCell"),c=dn(r,"data","basicLSTMCell"),l=dn(o,"c","basicLSTMCell"),p=dn(a,"h","basicLSTMCell"),h=c.concat(p,1).matMul(s).add(u),d=h.shape[0],f=h.shape[1]/4,v=[d,f],m=h.slice([0,0],v),g=h.slice([0,f],v),x=h.slice([0,2*f],v),y=h.slice([0,3*f],v),b=m.sigmoid().mulStrict(g.tanh()).addStrict(l.mulStrict(i.add(x).sigmoid())),w=b.tanh().mulStrict(y.sigmoid());return[b,w]}}),Tl=In({multiRNNCell_:function(t,e,n,r){for(var o=dn(e,"data","multiRNNCell"),a=fn(n,"c","multiRNNCell"),i=fn(r,"h","multiRNNCell"),s=o,u=[],c=0;c<t.length;c++){var l=t[c](s,a[c],i[c]);u.push(l[0]),u.push(l[1]),s=l[1]}var p=[],h=[];for(c=0;c<u.length;c+=2)p.push(u[c]),h.push(u[c+1]);return[p,h]}});exports.multiRNNCell=Tl,exports.basicLSTMCell=Nl;var Fl=In({movingAverage_:function(t,e,n,r,o){void 0===o&&(o=!0);var a=dn(t,"v","movingAverage"),i=dn(e,"x","movingAverage"),s=dn(n,"decay","movingAverage");At(a,i),b(I(a.shape,i.shape),function(){return"Shape mismatch in v and x"});var u=Tn(1),c=u.sub(s),l=i.sub(a).mul(c);if(o){b(null!=r,function(){return"When using zeroDebias: true, step is required."});var p=dn(r,"step","movingAverage");l=l.div(u.sub(ic(s,p)))}return a.add(l)}});exports.movingAverage=Fl;var Ol=In({stridedSlice_:function(t,e,n,r,o,a,i,s,u){if(void 0===o&&(o=0),void 0===a&&(a=0),void 0===i&&(i=0),void 0===s&&(s=0),void 0===u&&(u=0),null==r&&(r=new Array(e.length)),0!==i)throw new Error("ellipsis mask is not yet supported");var c=dn(t,"x","stridedSlice"),l=$r(s),p=c.shape.slice();l.forEach(function(t){e[t]=0,n[t]=1,p.splice(t,0,1)}),c=c.reshape(p);for(var h=0;h<c.rank;h++)e[h]=Qr(o,e,r,c.shape,h),n[h]=Jr(a,n,r,c.shape,h),r[h]=r[h]||1;var d=$r(u);d.forEach(function(t){n[t]=e[t]+1,r[t]=1});var f=Yr(e,n,r),v=f.filter(function(t,e){return-1===d.indexOf(e)});return r.every(function(t){return 1===t})?ol(c,e,f).reshape(v):_t.runKernelFunc(function(t){return t.stridedSlice(c,e,n,r)},{$x:c}).reshape(v)}});exports.stridedSlice=Ol;var _l=In({topk_:function(t,e,n){void 0===e&&(e=1),void 0===n&&(n=!0);var r=dn(t,"x","topk");if(0===r.rank)throw new Error("topk() expects the input to be of rank 1 or higher");var o=r.shape[r.shape.length-1];if(e>o)throw new Error("'k' passed to topk() must be <= the last dimension ("+o+") but got "+e);var a=_t.runKernelFunc(function(t){return t.topk(r,e,n)},{$x:r});return{values:a[0],indices:a[1]}}});exports.topk=_l;var Ml=In({scatterND_:function(t,e,n){var r=dn(t,"indices","scatterND","int32"),o=dn(e,"updates","scatterND");return Kr(o,r,n),_t.runKernelFunc(function(t){return t.scatterND(r,o,n)},{$indices:r,$updates:o})}});exports.scatterND=Ml;var Bl=In({fft_:function(t){b("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 _t.runKernelFunc(function(t){return t.fft(r)},{input:t}).reshape(t.shape)}}),Pl=In({ifft_:function(t){b("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 _t.runKernelFunc(function(t){return t.ifft(r)},{input:t}).reshape(t.shape)}}),Ll=In({rfft_:function(t,e){b("float32"===t.dtype,function(){return"The dtype for rfft() must be real value but got "+t.dtype});var n,r=t.shape[t.shape.length-1],o=t.size/r;if(null!=e&&e<r){var a=t.shape.map(function(t){return 0}),i=t.shape.map(function(t){return t});i[t.shape.length-1]=e,n=t.slice(a,i),r=e}else if(null!=e&&e>r){var s=t.shape.map(function(t){return t});s[t.shape.length-1]=e-r,n=t.concat(zn(s),t.shape.length-1),r=e}else n=t;var u=n.zerosLike(),c=kn(n,u).as2D(o,r),l=Bl(c),p=Math.floor(r/2)+1,h=Sn(l),d=An(l),f=h.split([p,r-p],h.shape.length-1),v=d.split([p,r-p],d.shape.length-1),m=n.shape.slice();return m[n.shape.length-1]=p,kn(f[0],v[0]).reshape(m)}}),Wl=In({irfft_:function(t){var e=t.shape[t.shape.length-1],n=t.size/e;if(e<=2){var r=t.as2D(n,e),o=Pl(r);return Sn(o)}var a=[n,2*(e-1)],i=Sn(t).as2D(n,e),s=An(t).as2D(n,e),u=i.slice([0,1],[n,e-2]).reverse(1),c=s.slice([0,1],[n,e-2]).reverse(1).mul(Tn(-1)),l=i.concat(u,1),p=s.concat(c,1);return r=kn(l,p).as2D(a[0],a[1]),o=Pl(r),Sn(o)}}),zl=Object.freeze({fft:Bl,ifft:Pl,rfft:Ll,irfft:Wl});exports.spectral=zl,exports.irfft=Wl,exports.rfft=Ll,exports.ifft=Pl,exports.fft=Bl;var Ul=In({sparseToDense_:function(t,e,n,r){void 0===r&&(r=0);var o=dn(t,"sparseIndices","sparseToDense","int32"),a=dn(e,"sparseValues","sparseToDense"),i=dn(r,"defaultValue","sparseToDense",a.dtype);return function(t,e,n,r){if("int32"!==t.dtype)throw new Error("tf.sparseToDense() expects the indices to be int32 type, but the dtype was "+t.dtype+".");if(t.rank>2)throw new Error("sparseIndices should be a scalar, vector, or matrix, but got shape "+t.shape+".");var o=t.rank>0?t.shape[0]:1,a=t.rank>1?t.shape[1]:1;if(n.length!==a)throw new Error("outputShape has incorrect number of elements:, "+n.length+", should be: "+a+".");var i=e.size;if(0!==e.rank&&(1!==e.rank||i!==o))throw new Error("sparseValues has incorrect shape "+e.shape+", should be [] or ["+o+"]");if(e.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(o,a,n,i),_t.runKernelFunc(function(t){return t.sparseToDense(o,a,n,i)},{$sparseIndices:o,$sparseValues:a,$defaultValue:i})}});exports.sparseToDense=Ul;var Vl=In({gatherND_:function(t,e){var n=dn(e,"indices","gatherND","int32"),r=dn(t,"x","gatherND");return _t.runKernelFunc(function(t){return t.gatherND(r,n)},{$x:r,$indices:n})}});exports.gatherND=Vl;var Gl=In({diag_:function(t){var e=dn(t,"x","diag").flatten(),n=t.shape.concat(t.shape);return _t.runKernelFunc(function(t){return t.diag(e)},{$x:e}).reshape(n)}});exports.diag=Gl;var Hl=In({dropout_:function(t,e,n,r){var o=dn(t,"x","dropout");if(b("float32"===o.dtype,function(){return"x has to be a floating point tensor since it's going to be scaled, but got a "+o.dtype+" tensor instead."}),b(e>=0&&e<1,function(){return"rate must be a float in the range [0, 1), but got "+e+"."}),0===e)return t instanceof gt?o.clone():o;var a=function(t,e){if(null==e)return t.shape.slice();if(I(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}(o,n),i=1-e,s=Dr(a,0,1,"float32",r).add(i).floor().div(i);return o.mul(s)}});function ql(t,e,n){for(var r=1-t%2,o=new Float32Array(t),a=0;a<t;++a){var i=2*Math.PI*a/(t+r-1);o[a]=e-n*Math.cos(i)}return Fn(o,"float32")}exports.dropout=Hl;var Kl=In({hannWindow_:function(t){return ql(t,.5,.5)}}),jl=In({hammingWindow_:function(t){return ql(t,.54,.46)}}),Xl=In({frame_:function(t,e,n,r,o){void 0===r&&(r=!1),void 0===o&&(o=0);for(var a=0,i=[];a+e<=t.size;)i.push(ol(t,a,e)),a+=n;if(r)for(;a<t.size;){var s=a+e-t.size,u=Kn([ol(t,a,e-s),Un([s],o)]);i.push(u),a+=n}return 0===i.length?On([],[0,e]):Kn(i).as2D(i.length,e)}}),$l=In({stft_:function(t,e,n,r,o){var a;void 0===o&&(o=Kl),null==r&&(a=e,r=Math.floor(Math.pow(2,Math.ceil(Math.log(a)/Math.log(2)))));for(var i=Xl(t,e,n),s=oc(i,o(e)),u=[],c=0;c<i.shape[0];c++)u.push(Ll(s.slice([c,0],[1,e]),r));return Kn(u)}}),Yl=Object.freeze({hannWindow:Kl,hammingWindow:jl,frame:Xl,stft:$l});exports.signal=Yl,exports.stft=$l,exports.frame=Xl,exports.hammingWindow=jl,exports.hannWindow=Kl;var Ql,Jl=function(t,e,n){return void 0===n&&(n=1),a(this,void 0,void 0,function(){var r,o,a,s,u,c,l,p,h,d,f,v,m,g;return i(this,function(i){switch(i.label){case 0:return r=dn(t,"predictions","inTopK"),o=dn(e,"targets","inTopK"),b(r.rank>1,function(){return"inTopK() expects the predictions to be of rank 2 or higher, but got "+r.rank}),b(r.rank-1===o.rank,function(){return"predictions rank should be 1 larger than targets rank, but got predictions rank "+r.rank+" and targets rank "+o.rank}),w(r.shape.slice(0,r.shape.length-1),o.shape,"predictions's shape should be align with the targets' shape, except the last dimension."),a=r.shape[r.shape.length-1],b(n>0&&n<=a,function(){return"'k' passed to inTopK() must be > 0 && <= the predictions last dimension ("+a+"), but got "+n}),[4,r.data()];case 1:return s=i.sent(),[4,o.data()];case 2:for(u=i.sent(),c=[s.length/a,a],p=c[1],h=_("bool",l=c[0]),d=0;d<l;d++){for(f=d*p,v=s.subarray(f,f+p),m=[],g=0;g<v.length;g++)m.push({value:v[g],index:g});for(m.sort(function(t,e){return e.value-t.value}),h[d]=0,g=0;g<n;g++)if(m[g].index===u[d]){h[d]=1;break}}return t!==r&&r.dispose(),e!==o&&o.dispose(),[2,Dn(h,o.shape,"bool")]}})})};exports.inTopKAsync=Jl,exports.Reduction=Ql,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"}(Ql||(exports.Reduction=Ql={}));var Zl=In({absoluteDifference_:function(t,e,n,r){void 0===r&&(r=Ql.SUM_BY_NONZERO_WEIGHTS);var o=dn(t,"labels","absoluteDifference"),a=dn(e,"predictions","absoluteDifference"),i=null;null!=n&&(i=dn(n,"weights","absoluteDifference")),w(o.shape,a.shape,"Error in absoluteDifference: ");var s=o.sub(a).abs();return tp(s,i,r)}}),tp=In({computeWeightedLoss_:function(t,e,n){void 0===n&&(n=Ql.SUM_BY_NONZERO_WEIGHTS);var r=dn(t,"losses","computeWeightedLoss"),o=null;null!=e&&(o=dn(e,"weights","computeWeightedLoss"));var a=null==o?r:r.mul(o);if(n===Ql.NONE)return a;if(n===Ql.SUM)return a.sum();if(n===Ql.MEAN){if(null==o)return a.mean();var i=r.size/o.size,s=a.sum().div(o.sum());return i>1?s.div(Tn(i)):s}if(n===Ql.SUM_BY_NONZERO_WEIGHTS){if(null==o)return a.sum().div(Tn(r.size));var u=o.mul(Wn(r.shape)).notEqual(Tn(0)).sum().toFloat();return a.sum().div(u)}throw Error("Unknown reduction: "+n)}}),ep=In({cosineDistance_:function(t,e,n,r,o){void 0===o&&(o=Ql.SUM_BY_NONZERO_WEIGHTS);var a=dn(t,"labels","cosineDistance"),i=dn(e,"predictions","cosineDistance"),s=null;null!=r&&(s=dn(r,"weights","cosineDistance")),w(a.shape,i.shape,"Error in cosineDistance: ");var u=Tn(1).sub(a.mul(i).sum(n,!0));return tp(u,s,o)}}),np=In({hingeLoss_:function(t,e,n,r){void 0===r&&(r=Ql.SUM_BY_NONZERO_WEIGHTS);var o=dn(t,"labels","hingeLoss"),a=dn(e,"predictions","hingeLoss"),i=null;null!=n&&(i=dn(n,"weights","hingeLoss")),w(o.shape,a.shape,"Error in hingeLoss: ");var s=Tn(1);o=Tn(2).mul(o).sub(s);var u=s.sub(o.mul(a)).relu();return tp(u,i,r)}}),rp=In({huberLoss_:function(t,e,n,r,o){void 0===r&&(r=1),void 0===o&&(o=Ql.SUM_BY_NONZERO_WEIGHTS);var a=dn(t,"labels","huberLoss"),i=dn(e,"predictions","huberLoss"),s=null;null!=n&&(s=dn(n,"weights","huberLoss")),w(a.shape,i.shape,"Error in huberLoss: ");var u=Tn(r),c=i.sub(a).abs(),l=tc(c,u),p=c.sub(l),h=Tn(.5).mul(l.square()).add(u.mul(p));return tp(h,s,o)}}),op=In({logLoss_:function(t,e,n,r,o){void 0===r&&(r=1e-7),void 0===o&&(o=Ql.SUM_BY_NONZERO_WEIGHTS);var a=dn(t,"labels","logLoss"),i=dn(e,"predictions","logLoss"),s=null;null!=n&&(s=dn(n,"weights","logLoss")),w(a.shape,i.shape,"Error in logLoss: ");var u=Tn(1),c=Tn(r),l=a.mul(i.add(c).log()).neg().sub(u.sub(a).mul(u.sub(i).add(c).log()));return tp(l,s,o)}}),ap=In({meanSquaredError_:function(t,e,n,r){void 0===r&&(r=Ql.SUM_BY_NONZERO_WEIGHTS);var o=dn(t,"labels","meanSquaredError"),a=dn(e,"predictions","meanSquaredError"),i=null;null!=n&&(i=dn(n,"weights","meanSquaredError")),w(o.shape,a.shape,"Error in meanSquaredError: ");var s=o.squaredDifference(a);return tp(s,i,r)}}),ip=In({sigmoidCrossEntropy_:function(t,e,n,r,o){void 0===r&&(r=0),void 0===o&&(o=Ql.SUM_BY_NONZERO_WEIGHTS);var a=dn(t,"multiClassLabels","sigmoidCrossEntropy"),i=dn(e,"logits","sigmoidCrossEntropy"),s=null;if(null!=n&&(s=dn(n,"weights","sigmoidCrossEntropy")),w(a.shape,i.shape,"Error in sigmoidCrossEntropy: "),r>0){var u=Tn(r),c=Tn(1),l=Tn(.5);a=a.mul(c.sub(u)).add(l.mul(u))}var p=function(t,e){var n=dn(t,"labels","sigmoidCrossEntropyWithLogits"),r=dn(e,"logits","sigmoidCrossEntropyWithLogits");w(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");var o=r.relu(),a=r.mul(n),i=r.abs().neg().exp().log1p();return o.sub(a).add(i)}(a,i);return tp(p,s,o)}}),sp=In({softmaxCrossEntropy_:function(t,e,n,r,o){void 0===r&&(r=0),void 0===o&&(o=Ql.SUM_BY_NONZERO_WEIGHTS);var a=dn(t,"onehotLabels","softmaxCrossEntropy"),i=dn(e,"logits","softmaxCrossEntropy"),s=null;if(null!=n&&(s=dn(n,"weights","softmaxCrossEntropy")),w(a.shape,i.shape,"Error in softmaxCrossEntropy: "),r>0){var u=Tn(r),c=Tn(1),l=Tn(a.shape[1]);a=a.mul(c.sub(u)).add(u.div(l))}var p=function(t,e,n){if(void 0===n&&(n=-1),-1===n&&(n=e.rank-1),n!==e.rank-1)throw Error("Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank "+e.rank+" and dim was "+n);return so(function(t,e,r){var o=e.logSumExp([n],!0),a=e.toFloat().sub(o);return r([t,a]),{value:a.mul(t).neg().sum([n]),gradFunc:function(t,e){var r=e[0],o=e[1],a=xn(t.shape,[n]);return[t.reshape(a).mul(r.toFloat().sub(o.exp())),t.reshape(a).mul(o.exp().sub(r.toFloat()))]}}})(t,e)}(a,i);return tp(p,s,o)}}),up=Object.freeze({get Reduction(){return Ql},absoluteDifference:Zl,computeWeightedLoss:tp,cosineDistance:ep,hingeLoss:np,huberLoss:rp,logLoss:op,meanSquaredError:ap,sigmoidCrossEntropy:ip,softmaxCrossEntropy:sp});function cp(t,e){return void 0===e&&(e=!1),_t.tidy(function(){if(2!==t.shape.length)throw new Error("qr2d() requires a 2D Tensor, but got a "+t.shape.length+"D Tensor.");for(var n=t.shape[0],r=t.shape[1],o=xr(n),a=t.clone(),i=On([[1]],[1,1]),s=i.clone(),u=n>=r?r:n,c=function(t){var e,u=a,c=s,l=o;e=_t.tidy(function(){var e=a.slice([t,t],[n-t,1]),u=e.norm(),c=a.slice([t,t],[1,1]),l=On([[-1]]).where(c.greater(0),On([[1]])),p=c.sub(l.mul(u)),h=e.div(p);s=1===h.shape[0]?i.clone():i.concat(h.slice([1,0],[h.shape[0]-1,h.shape[1]]),0);var d=l.matMul(p).div(u).neg(),f=a.slice([t,0],[n-t,r]),v=d.mul(s);if(0===t)a=f.sub(v.matMul(s.transpose().matMul(f)));else{var m=f.sub(v.matMul(s.transpose().matMul(f)));a=a.slice([0,0],[t,r]).concat(m,0)}var g=o.slice([0,t],[n,o.shape[1]-t]);if(0===t)o=g.sub(g.matMul(s).matMul(v.transpose()));else{var x=g.sub(g.matMul(s).matMul(v.transpose()));o=o.slice([0,0],[n,t]).concat(x,1)}return[s,a,o]}),s=e[0],a=e[1],o=e[2],Qe([u,c,l])},l=0;l<u;++l)c(l);return!e&&n>r&&(o=o.slice([0,0],[n,r]),a=a.slice([0,0],[r,r])),[o,a]})}exports.losses=up;var lp=In({gramSchmidt_:function(t){var e;if(Array.isArray(t)){e=!1,b(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){b(t[e].shape[0]===n,function(){return"Gram-Schmidt: Non-unique lengths found in the input vectors: ("+t[e].shape[0]+" vs. "+n+")"})},o=1;o<t.length;++o)r(o)}else e=!0,t=Qn(t,t.shape[0],0).map(function(t){return Fr(t,[0])});b(t.length<=t[0].shape[0],function(){return"Gram-Schmidt: Number of vectors ("+t.length+") exceeds number of dimensions ("+t[0].shape[0]+")."});var a=[],i=t,s=function(t){a.push(_t.tidy(function(){var e=i[t];if(t>0)for(var n=0;n<t;++n){var r=yl(a[n].mulStrict(e)).mul(a[n]);e=e.sub(r)}return e.div(Dl(e,"euclidean"))}))};for(o=0;o<t.length;++o)s(o);return e?Or(a,0):a}}),pp=In({qr_:function(t,e){if(void 0===e&&(e=!1),t.rank<2)throw new Error("qr() requires input tensor to have a rank >= 2, but got rank "+t.rank);if(2===t.rank)return cp(t,e);var n=t.shape.slice(0,t.shape.length-2).reduce(function(t,e){return t*e}),r=Br(t.reshape([n,t.shape[t.shape.length-2],t.shape[t.shape.length-1]]),0),o=[],a=[];return r.forEach(function(t){var n=cp(t,e),r=n[0],i=n[1];o.push(r),a.push(i)}),[Or(o,0).reshape(t.shape),Or(a,0).reshape(t.shape)]}}),hp=Object.freeze({gramSchmidt:lp,qr:pp});function dp(t,e,n,r,o){null==r&&(r=.5),null==o&&(o=Number.NEGATIVE_INFINITY);var a=t.shape[0];return n=Math.min(n,a),b(0<=r&&r<=1,function(){return"iouThreshold must be in [0, 1], but was '"+r+"'"}),b(2===t.rank,function(){return"boxes must be a 2D tensor, but was of rank '"+t.rank+"'"}),b(4===t.shape[1],function(){return"boxes must have 4 columns, but 2nd dimension was "+t.shape[1]}),b(1===e.rank,function(){return"scores must be a 1D tensor"}),b(e.shape[0]===a,function(){return"scores has incompatible shape with boxes. Expected "+a+", but was "+e.shape[0]}),{maxOutputSize:n,iouThreshold:r,scoreThreshold:o}}exports.linalg=hp;var fp=In({resizeBilinear_:function(t,e,n){void 0===n&&(n=!1);var r=dn(t,"images","resizeBilinear");b(3===r.rank||4===r.rank,function(){return"Error in resizeBilinear: x must be rank 3 or 4, but got rank "+r.rank+"."}),b(2===e.length,function(){return"Error in resizeBilinear: new shape must 2D, but got shape "+e+"."});var o=r,a=!1;3===r.rank&&(a=!0,o=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var i=e[0],s=e[1],u=_t.runKernelFunc(function(t,e){return e([o]),t.resizeBilinear(o,i,s,n)},{batchImages:o},function(t,e){return{batchImages:function(){return _t.runKernelFunc(function(r){return r.resizeBilinearBackprop(t,e[0],n)},{})}}});return a?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),vp=In({resizeNearestNeighbor_:function(t,e,n){void 0===n&&(n=!1);var r=dn(t,"images","resizeNearestNeighbor");b(3===r.rank||4===r.rank,function(){return"Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank "+r.rank+"."}),b(2===e.length,function(){return"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+e+"."}),b("float32"===r.dtype||"int32"===r.dtype,function(){return"`images` must have `int32` or `float32` as dtype"});var o=r,a=!1;3===r.rank&&(a=!0,o=r.as4D(1,r.shape[0],r.shape[1],r.shape[2]));var i=e[0],s=e[1],u=_t.runKernelFunc(function(t,e){return e([o]),t.resizeNearestNeighbor(o,i,s,n)},{batchImages:o},function(t,e){return{batchImages:function(){return _t.runKernelFunc(function(r){return r.resizeNearestNeighborBackprop(t,e[0],n)},{})}}});return a?u.as3D(u.shape[1],u.shape[2],u.shape[3]):u}}),mp=In({nonMaxSuppression_:function(t,e,n,r,o){void 0===r&&(r=.5),void 0===o&&(o=Number.NEGATIVE_INFINITY);var a=dn(t,"boxes","nonMaxSuppression"),i=dn(e,"scores","nonMaxSuppression"),s=dp(a,i,n,r,o);return n=s.maxOutputSize,r=s.iouThreshold,o=s.scoreThreshold,_t.runKernelFunc(function(t){return t.nonMaxSuppression(a,i,n,r,o)},{$boxes:a})}}),gp=function(t,e,n,r,o){return void 0===r&&(r=.5),void 0===o&&(o=Number.NEGATIVE_INFINITY),a(this,void 0,void 0,function(){var a,s,u,c,l,p,h;return i(this,function(i){switch(i.label){case 0:return a=dn(t,"boxes","nonMaxSuppressionAsync"),s=dn(e,"scores","nonMaxSuppressionAsync"),u=dp(a,s,n,r,o),n=u.maxOutputSize,r=u.iouThreshold,o=u.scoreThreshold,[4,Promise.all([a.data(),s.data()])];case 1:return c=i.sent(),l=c[0],p=c[1],h=Lo(l,p,n,r,o),a!==t&&a.dispose(),s!==e&&s.dispose(),[2,h]}})})},xp=In({cropAndResize_:function(t,e,n,r,o,a){var i=dn(t,"image","cropAndResize","float32"),s=dn(e,"boxes","cropAndResize","float32"),u=dn(n,"boxInd","cropAndResize","int32");o=o||"bilinear",a=a||0;var c=s.shape[0];return b(4===i.rank,function(){return"Error in cropAndResize: image must be rank 4,but got rank "+i.rank+"."}),b(2===s.rank&&4===s.shape[1],function(){return"Error in cropAndResize: boxes must be have size ["+c+",4] but had shape "+s.shape+"."}),b(1===u.rank&&u.shape[0]===c,function(){return"Error in cropAndResize: boxInd must be have size ["+c+"] but had shape "+s.shape+"."}),b(2===r.length,function(){return"Error in cropAndResize: cropSize must be of length 2, but got length "+r.length+"."}),b(r[0]>=1&&r[1]>=1,function(){return"cropSize must be atleast [1,1], but was "+r}),b("bilinear"===o||"nearest"===o,function(){return"method must be bilinear or nearest, but was "+o}),_t.runKernelFunc(function(t,e){return t.cropAndResize(i,s,u,r,o,a)},{images:i,boxes:s,boxInd:u},null,"CropAndResize",{method:o,extrapolationValue:a,cropSize:r})}}),yp=Object.freeze({resizeBilinear:fp,resizeNearestNeighbor:vp,nonMaxSuppression:mp,nonMaxSuppressionAsync:gp,cropAndResize:xp}),bp=function(t,e){return!(t>0||"linear"!==e&&"relu"!==e)},wp=function(t,e,n){if(null==n||"linear"===n)return t;if("relu"===n)return t.mul(e.step());throw new Error("Gradient for activation "+n+" has not been implemented yet.")},Cp=function(t,e){var n=e,r=mo(t.shape,e.shape);return r.length>0&&(n=n.sum(r)),n.reshape(t.shape)},Ep=function(t,e,n){if("linear"===e)return t;if("relu"===e)return Rl(t);if("elu"===e)return wl(t);if("relu6"===e)return Il(t);if("prelu"===e)return El(t,n);throw new Error("Unknown fused activation "+e+".")};exports.image=yp;var Rp=In({matMul_:function(t){var e,n=t.a,r=t.b,o=t.transposeA,a=void 0!==o&&o,i=t.transposeB,s=void 0!==i&&i,u=t.bias,c=t.activation,l=void 0===c?"linear":c,p=t.preluActivationWeights;if(!1===bp(_t.state.gradientDepth,l)){var h=Gc(n,r,a,s);return null!=u&&(h=Hu(h,u)),Ep(h,l,p)}var d=dn(n,"a","fused matMul"),f=dn(r,"b","fused matMul");e=St(d,f),d=e[0],f=e[1];var v=a?d.shape[d.rank-2]:d.shape[d.rank-1],m=s?f.shape[f.rank-1]:f.shape[f.rank-2],g=a?d.shape[d.rank-1]:d.shape[d.rank-2],x=s?f.shape[f.rank-2]:f.shape[f.rank-1],y=d.shape.slice(0,-2),w=f.shape.slice(0,-2),C=R(y),E=R(w);b(d.rank>=2&&f.rank>=2&&d.rank===f.rank,function(){return"Error in fused matMul: inputs must have the same rank of at least 2, got ranks "+d.rank+" and "+f.rank+"."}),b(I(y,w),function(){return"Error in fused matMul: outer dimensions ("+y+") and ("+w+") of Tensors with shapes "+d.shape+" and "+f.shape+" must match."}),b(v===m,function(){return"Error in fused matMul: inner shapes ("+v+") and ("+m+") of Tensors with shapes "+d.shape+" and "+f.shape+" and transposeA="+a+" and transposeB="+s+" must match."});var k,S,A=d.shape.slice(0,-2).concat([g,x]),D=a?d.as3D(C,v,g):d.as3D(C,g,v),N=s?f.as3D(E,x,m):f.as3D(E,m,x);null!=u&&go(A,(k=St(k=dn(u,"bias","fused matMul"),d)[0]).shape),null!=p&&(S=dn(p,"prelu weights","fused matMul"));var T={$a:D,$b:N};return null!=u&&(T.$bias=k),null!=p&&(T.$preluActivationWeights=S),_t.runKernelFunc(function(t,e){var n=t.fusedBatchMatMul({a:D,b:N,transposeA:a,transposeB:s,bias:k,activation:l,preluActivationWeights:S});return e([D,N,n]),n},T,function(t,e){var n=e[0],r=e[1],o=e[2],i=wp(t,o,l),c={};return null!=u&&(c={$bias:function(){return Cp(k,i)}}),a||s?!a&&s?Object.assign({$a:function(){return i.matMul(r,!1,!1)},$b:function(){return i.matMul(n,!0,!1)}},c):a&&!s?Object.assign({$a:function(){return r.matMul(i,!1,!0)},$b:function(){return n.matMul(i,!1,!1)}},c):Object.assign({$a:function(){return r.matMul(i,!0,!0)},$b:function(){return i.matMul(n,!0,!0)}},c):Object.assign({$a:function(){return i.matMul(r,!1,!0)},$b:function(){return n.matMul(i,!0,!1)}},c)}).reshape(A)}}),Ip=In({conv2d_:function(t){var e=t.x,n=t.filter,r=t.strides,o=t.pad,a=t.dataFormat,i=void 0===a?"NHWC":a,s=t.dilations,u=void 0===s?[1,1]:s,c=t.dimRoundingMode,l=t.bias,p=t.activation,h=void 0===p?"linear":p,d=t.preluActivationWeights;if(h=h||"linear",!1===bp(_t.state.gradientDepth,h)){var f=Oc(e,n,r,o,i,u,c);return null!=l&&(f=Hu(f,l)),Ep(f,h,d)}var v=dn(e,"x","conv2d"),m=dn(n,"filter","conv2d"),g=v,x=!1;3===v.rank&&(x=!0,g=v.as4D(1,v.shape[0],v.shape[1],v.shape[2])),b(4===g.rank,function(){return"Error in fused conv2d: input must be rank 4, but got rank "+g.rank+"."}),b(4===m.rank,function(){return"Error in fused conv2d: filter must be rank 4, but got rank "+m.rank+"."}),null!=c&&b(k(o),function(){return"Error in fused conv2d: pad must be an integer when using, dimRoundingMode "+c+" but got pad "+o+"."}),b(g.shape[3]===m.shape[2],function(){return"Error in conv2d: depth of input ("+g.shape[3]+") must match input depth for filter "+m.shape[2]+"."}),b(Ao(r,u),function(){return"Error in conv2D: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+u+"'"}),b("NHWC"===i,function(){return"Error in conv2d: got dataFormat of "+i+" but only NHWC is currently supported."});var y,w,C=bo(g.shape,m.shape,r,u,o,c);null!=l&&(y=St(y=dn(l,"bias","fused conv2d"),v)[0],go(C.outShape,y.shape)),null!=d&&(w=dn(d,"prelu weights","fused conv2d"));var E={x:g,filter:m};null!=l&&(E.bias=y),null!=d&&(E.preluActivationWeights=w);var R=[m,g],I=_t.runKernelFunc(function(t,e){var n=t.fusedConv2d({input:g,filter:m,convInfo:C,bias:y,activation:h,preluActivationWeights:w});return e([m,g,n]),n},E,function(t,e){var n=e,a=n[0],i=n[1],s=n[2],c=wp(t,s,h);b(So(u),function(){return"Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '"+u+"'"});var p={};return null!=l&&(p={$bias:function(){return Cp(y,c)}}),Object.assign({x:function(){return Bc(i.shape,c,a,r,o)},filter:function(){return Mc(i,c,a.shape,r,o)}},p)},"FusedConv2D",{convInfo:C,activation:h},R,[!0]);return x?I.as3D(I.shape[1],I.shape[2],I.shape[3]):I}}),kp=In({depthwiseConv2d_:function(t){var e=t.x,n=t.filter,r=t.strides,o=t.pad,a=t.dataFormat,i=void 0===a?"NHWC":a,s=t.dilations,u=void 0===s?[1,1]:s,c=t.dimRoundingMode,l=t.bias,p=t.activation,h=void 0===p?"linear":p,d=t.preluActivationWeights;if(!1===bp(_t.state.gradientDepth,h)){var f=Pc(e,n,r,o,i,u,c);return null!=l&&(f=Hu(f,l)),Ep(f,h,d)}var v=dn(e,"x","depthwiseConv2d"),m=dn(n,"filter","depthwiseConv2d"),g=v,x=!1;3===v.rank&&(x=!0,g=v.as4D(1,v.shape[0],v.shape[1],v.shape[2])),b(4===g.rank,function(){return"Error in fused depthwiseConv2d: input must be rank 4, but got rank "+g.rank+"."}),b(4===m.rank,function(){return"Error in fused depthwiseConv2d: filter must be rank 4, but got rank "+m.rank+"."}),b(g.shape[3]===m.shape[2],function(){return"Error in fused depthwiseConv2d: number of input channels ("+g.shape[3]+") must match the inChannels dimension in filter "+m.shape[2]+"."}),null==u&&(u=[1,1]),b(Ao(r,u),function(){return"Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides "+r+" and dilations '"+u+"'"}),null!=c&&b(k(o),function(){return"Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode "+c+" but got pad "+o+"."});var y,w,C=bo(g.shape,m.shape,r,u,o,c,!0);null!=l&&(y=St(y=dn(l,"bias","fused conv2d"),v)[0],go(C.outShape,y.shape)),null!=d&&(w=dn(d,"prelu weights","fused depthwiseConv2d"));var E={x:g,$filter:m};null!=l&&(E.$bias=y),null!=d&&(E.$preluActivationWeights=w);var R=_t.runKernelFunc(function(t,e){var n=t.fusedDepthwiseConv2D({input:g,filter:m,convInfo:C,bias:y,activation:h,preluActivationWeights:w});return e([g,m,n]),n},E,function(t,e){b(So(u),function(){return"Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '"+u+"'"});var n=e[0],r=e[1],o=e[2],a=wp(t,o,h),i={};return null!=l&&(i={$bias:function(){return Cp(y,a)}}),Object.assign({x:function(){return Lc(n.shape,a,r,C)},$filter:function(){return Wc(n,a,r.shape,C)}},i)});return x?R.as3D(R.shape[1],R.shape[2],R.shape[3]):R}}),Sp=Object.freeze({matMul:Rp,conv2d:Ip,depthwiseConv2d:kp}),Ap=Object.freeze({image:yp,linalg:hp,losses:up,spectral:zl,fused:Sp,signal:Yl,square:Gs,conv1d:Fc,conv2d:Oc,conv3d:_c,depthwiseConv2d:Pc,separableConv2d:zc,conv2dTranspose:Uc,conv3dTranspose:Vc,op:In,batchNormalization2d:Nu,batchNormalization3d:Tu,batchNormalization4d:Fu,batchNormalization:Ou,batchNorm:_u,batchNorm2d:Mu,batchNorm3d:Bu,batchNorm4d:Pu,booleanMaskAsync:Ac,complex:kn,real:Sn,imag:An,concat:Kn,concat1d:jn,concat2d:Xn,concat3d:$n,concat4d:Yn,split:Qn,matMul:Gc,dot:Hc,outerProduct:qc,reverse:Kc,reverse1d:jc,reverse2d:Xc,reverse3d:$c,reverse4d:Yc,maxPool:Zc,avgPool:tl,pool:el,maxPool3d:nl,avgPool3d:rl,slice:ol,slice1d:al,slice2d:il,slice3d:sl,slice4d:ul,abs:Hs,acos:qs,acosh:Ks,asin:js,asinh:Xs,atan:$s,atanh:Ys,ceil:Qs,clipByValue:Js,cos:Zs,cosh:tu,erf:eu,exp:nu,expm1:ru,floor:ou,log:au,log1p:iu,logSigmoid:su,neg:uu,reciprocal:cu,round:lu,rsqrt:pu,sigmoid:hu,sign:du,isNaN:fu,isInf:vu,isFinite:mu,sin:gu,sinh:xu,softplus:yu,sqrt:bu,step:wu,tan:Cu,tanh:Eu,all:ll,any:pl,argMax:hl,argMin:dl,logSumExp:fl,max:vl,mean:ml,min:gl,moments:xl,sum:yl,prod:bl,equal:hc,equalStrict:dc,greater:fc,greaterEqual:vc,greaterEqualStrict:mc,greaterStrict:gc,less:xc,lessEqual:yc,lessEqualStrict:bc,lessStrict:wc,notEqual:Cc,notEqualStrict:Ec,add:Hu,addN:qu,addStrict:Ku,atan2:ju,div:Xu,divNoNan:$u,divStrict:Yu,floorDiv:Qu,maximum:Ju,maximumStrict:Zu,minimum:tc,minimumStrict:ec,mod:nc,modStrict:rc,mul:oc,mulStrict:ac,pow:ic,powStrict:sc,squaredDifference:uc,squaredDifferenceStrict:cc,sub:lc,subStrict:pc,elu:wl,leakyRelu:Cl,prelu:El,relu:Rl,relu6:Il,selu:kl,logicalAnd:Lu,logicalNot:Wu,logicalOr:zu,logicalXor:Uu,where:Vu,whereAsync:Gu,buffer:lr,print:pr,batchToSpaceND:hr,cast:dr,clone:fr,cumsum:vr,depthToSpace:mr,expandDims:gr,eye:xr,multinomial:yr,oneHot:br,pad:wr,pad1d:Cr,pad2d:Er,pad3d:Rr,pad4d:Ir,rand:kr,randomNormal:Sr,randomGamma:Ar,randomUniform:Dr,reshape:Nr,spaceToBatchND:Tr,squeeze:Fr,stack:Or,tile:_r,truncatedNormal:Mr,unstack:Br,setdiff1dAsync:Pr,fill:Un,linspace:Vn,ones:Wn,range:Gn,scalar:Tn,tensor:Dn,tensor1d:Fn,tensor2d:On,tensor3d:_n,tensor4d:Mn,tensor5d:Bn,tensor6d:Pn,variable:Ln,zeros:zn,onesLike:Hn,zerosLike:qn,transpose:Sl,softmax:co,logSoftmax:lo,localResponseNormalization:Al,norm:Dl,gather:kc,unsortedSegmentSum:Sc,basicLSTMCell:Nl,multiRNNCell:Tl,movingAverage:Fl,stridedSlice:Ol,topk:_l,scatterND:Ml,fft:Bl,ifft:Pl,rfft:Ll,irfft:Wl,sparseToDense:Ul,gatherND:Vl,diag:Gl,dropout:Hl,hannWindow:Kl,hammingWindow:jl,frame:Xl,stft:$l,inTopKAsync:Jl});function Dp(t,e){Array.isArray(t)||(t=[t]),t.forEach(function(t){null!=t&&b("complex64"!==t.dtype,function(){return e+" does not support complex64 tensors."})})}function Np(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.")}exports.fused=Sp;var Tp=function(t){function e(){var e=t.call(this)||this;if(e.blockSize=48,e.firstUse=!0,u().get("IS_BROWSER")){var n="undefined"!=typeof OffscreenCanvas?new OffscreenCanvas(300,150):"undefined"!=typeof document?document.createElement("canvas"):null;null!==n&&(e.fromPixels2DContext=n.getContext("2d"))}return e.data=new po(e,_t),e}return o(e,t),e.prototype.write=function(t,e,n){this.firstUse&&(this.firstUse=!1,u().get("IS_NODE")&&ln("\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"));var r={};return this.data.set(r,{values:t,dtype:n}),r},e.prototype.move=function(t,e,n,r){this.data.set(t,{values:e,dtype:r})},e.prototype.numDataIds=function(){return this.data.numDataIds()},e.prototype.fromPixels=function(t,e){if(null==t)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");var n,r,o=t.data instanceof Uint8Array,a="undefined"!=typeof ImageData&&t instanceof ImageData,i="undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement,s="undefined"!=typeof HTMLImageElement&&t instanceof HTMLImageElement,c=i?[t.videoWidth,t.videoHeight]:[t.width,t.height],l=c[0],p=c[1];if(u().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,l,p).data;else if(a||o)n=t.data;else{if(!s&&!i)throw new Error("pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData or {data: Uint32Array, width: number, height: number}, but was "+t.constructor.name);if(null==this.fromPixels2DContext)throw new Error("Can't read pixels from HTMLImageElement outside the browser.");this.fromPixels2DContext.canvas.width=l,this.fromPixels2DContext.canvas.height=p,this.fromPixels2DContext.drawImage(t,0,0,l,p),n=this.fromPixels2DContext.getImageData(0,0,l,p).data}if(4===e)r=new Int32Array(n);else{var h=l*p;r=new Int32Array(h*e);for(var d=0;d<h;d++)for(var f=0;f<e;++f)r[d*e+f]=n[4*d+f]}return _n(r,[p,l,e],"int32")},e.prototype.read=function(t){return a(this,void 0,void 0,function(){return i(this,function(e){return[2,this.readSync(t)]})})},e.prototype.readSync=function(t){var e=this.data.get(t),n=e.dtype,r=e.complexTensors;return"complex64"===n?_o(this.readSync(r.real.dataId),this.readSync(r.imag.dataId)):this.data.get(t).values},e.prototype.bufferSync=function(t){var e=this.readSync(t.dataId),n=e;if("string"===t.dtype)try{n=e.map(function(t){return nt(t)})}catch(t){throw new Error("Failed to decode encoded string bytes into utf-8")}return lr(t.shape,t.dtype,n)},e.prototype.makeOutput=function(t,e,n){var r=this.write(t,e,n);return _t.makeTensorFromDataId(r,e,n,this)},e.prototype.disposeData=function(t){if(this.data.has(t)){var e=this.data.get(t).complexTensors;null!=e&&(e.real.dispose(),e.imag.dispose()),this.data.delete(t)}},e.prototype.time=function(t){return a(this,void 0,void 0,function(){var e;return i(this,function(n){return e=Z(),t(),[2,{kernelMs:Z()-e}]})})},e.prototype.memory=function(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}},e.prototype.complex=function(t,e){var n=this.makeOutput(null,t.shape,"complex64");return this.data.get(n.dataId).complexTensors={real:_t.keep(t.clone()),imag:_t.keep(e.clone())},n},e.prototype.real=function(t){return this.data.get(t.dataId).complexTensors.real.clone()},e.prototype.imag=function(t){return this.data.get(t.dataId).complexTensors.imag.clone()},e.prototype.slice=function(t,e,n){if(Dp(t,"slice"),Zr(t.shape,e,n)){var r=to(e,t.strides),o=R(n);return Dn(this.readSync(t.dataId).subarray(r,r+o),n,t.dtype)}for(var a=lr(n,t.dtype),i=this.bufferSync(t),s=0;s<a.size;++s){var u=a.indexToLoc(s).map(function(t,n){return t+e[n]});a.values[s]=i.get.apply(i,u)}return a.toTensor()},e.prototype.stridedSlice=function(t,e,n,r){Dp(t,"stridedSlice");var o=Yr(e,n,r);if(o.some(function(t){return 0===t}))return Dn([],o);for(var a=lr(o,t.dtype),i=this.bufferSync(t),s=0;s<a.size;s++){for(var u=a.indexToLoc(s),c=new Array(u.length),l=0;l<c.length;l++)c[l]=u[l]*r[l]+e[l];a.set.apply(a,[i.get.apply(i,c)].concat(u))}return a.toTensor()},e.prototype.diag=function(t){for(var e=this.readSync(t.dataId),n=lr([t.size,t.size],t.dtype),r=n.values,o=0;o<e.length;o++)r[o*t.size+o]=e[o];return n.toTensor()},e.prototype.unstack=function(t,e){for(var n=t.shape[e],r=new Array(t.rank-1),o=0,a=0;a<t.rank;a++)a!==e&&(r[o++]=t.shape[a]);var i=new Array(t.rank).fill(0),s=t.shape.slice();s[e]=1;var u=new Array(n);for(a=0;a<u.length;a++)i[e]=a,u[a]=this.slice(t,i,s).reshape(r);return u},e.prototype.reverse=function(t,e){Dp(t,"reverse");for(var n=lr(t.shape,t.dtype),r=this.bufferSync(t),o=function(o){var a=n.indexToLoc(o),i=a.slice();e.forEach(function(e){return i[e]=t.shape[e]-1-i[e]}),n.set.apply(n,[r.get.apply(r,i)].concat(a))},a=0;a<n.size;a++)o(a);return n.toTensor()},e.prototype.concat=function(t,e){var n=this;if("complex64"===t[0].dtype){var r=t.map(function(t){return Sn(t)}),o=t.map(function(t){return An(t)});return kn(this.concat(r,e),this.concat(o,e))}var a=t.map(function(t){var n=R(t.shape.slice(e));return t.as2D(-1,n)}),i=Rn(a.map(function(t){return t.shape}),1),s=lr(i,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 c=0;a.forEach(function(t){for(var e=n.readSync(t.dataId),r=0,o=0;o<t.shape[0];++o)for(var a=o*i[1]+c,u=0;u<t.shape[1];++u)s[a+u]=e[r++];c+=t.shape[1]})}var l=Rn(t.map(function(t){return t.shape}),e);return Dn(s,l,t[0].dtype)},e.prototype.neg=function(t){return Dp(t,"neg"),this.multiply(Tn(-1),t)},e.prototype.add=function(t,e){return"complex64"===t.dtype||"complex64"===e.dtype?this.broadcastedBinaryComplexOp(t.cast("complex64"),e.cast("complex64"),function(t,e,n,r){return{real:t+n,imag:e+r}}):this.broadcastedBinaryOp(t,e,It(t.dtype,e.dtype),function(t,e){return t+e})},e.prototype.addN=function(t){var e=this;Dp(t,"addN");for(var n=t.map(function(t){return e.readSync(t.dataId)}),r=lr(t[0].shape,t[0].dtype),o=r.values,a=0;a<t.length;a++)for(var i=n[a],s=0;s<o.length;s++)o[s]+=i[s];return r.toTensor()},e.prototype.subtract=function(t,e){return"complex64"===t.dtype||"complex64"===e.dtype?this.broadcastedBinaryComplexOp(t.cast("complex64"),e.cast("complex64"),function(t,e,n,r){return{real:t-n,imag:e-r}}):this.broadcastedBinaryOp(t,e,It(t.dtype,e.dtype),function(t,e){return t-e})},e.prototype.pow=function(t,e){return Dp([t,e],"pow"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){return Math.pow(t,e)})},e.prototype.batchMatMul=function(t,e,n,r){Dp([t,e],"matMul");for(var o=n?t.shape[1]:t.shape[2],a=n?t.shape[2]:t.shape[1],i=r?e.shape[1]:e.shape[2],s=t.shape[0],u=this.readSync(t.dataId),c=this.readSync(e.dataId),l=n?[t.strides[0],1,t.strides[1]]:[t.strides[0],t.strides[1],1],p=l[0],h=l[1],d=l[2],f=r?[1,e.strides[1],e.strides[0]]:[e.strides[1],1,e.strides[0]],v=f[0],m=f[1],g=f[2],x=a*i,y=lr([s,a,i],t.dtype),b=y.values,w=this.blockSize,C=0;C<s;C++)for(var E=0;E<a;E+=w)for(var R=0;R<i;R+=w)for(var I=0;I<o;I+=w)for(var k=Math.min(E+w,a),S=Math.min(R+w,i),A=Math.min(I+w,o),D=E;D<k;D++)for(var N=R;N<S;N++){for(var T=0,F=I;F<A;F++)T+=u[C*p+D*h+F*d]*c[F*v+N*m+C*g];b[C*x+(D*i+N)]+=T}return y.toTensor()},e.prototype.fusedBatchMatMul=function(t){var e=t.a,n=t.b,r=t.transposeA,o=t.transposeB,a=t.bias,i=t.activation,s=t.preluActivationWeights,u=this.batchMatMul(e,n,r,o);return a&&(u=this.add(u,a)),i&&(u=Np(this,u,i,s)),u},e.prototype.multiply=function(t,e){return"complex64"===t.dtype||"complex64"===e.dtype?this.broadcastedBinaryComplexOp(t.cast("complex64"),e.cast("complex64"),function(t,e,n,r){return{real:t*n-e*r,imag:t*r+e*n}}):this.broadcastedBinaryOp(t,e,It(t.dtype,e.dtype),function(t,e){return t*e})},e.prototype.realDivide=function(t,e){return Dp([t,e],"realDivide"),this.broadcastedBinaryOp(t,e,"float32",function(t,e){return t/e})},e.prototype.floorDiv=function(t,e){return Dp([t,e],"floorDiv"),this.broadcastedBinaryOp(t,e,"int32",function(t,e){return Math.floor(t/e)})},e.prototype.sum=function(t,e){Dp(t,"sum"),yn("sum",e,t.rank);for(var n=gn(t.shape,e),r=n[0],o=n[1],a=zn(r,It(t.dtype,"int32")),i=R(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*i,p=0,h=0;h<i;++h)p+=u[l+h];s[c]=p}return a},e.prototype.prod=function(t,e){Dp(t,"sum");for(var n=gn(t.shape,e),r=n[0],o=n[1],a=zn(r,It(t.dtype,"int32")),i=R(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*i,p=1,h=0;h<i;++h)p*=u[l+h];s[c]=p}return a},e.prototype.unsortedSegmentSum=function(t,e,n){Dp(t,"unsortedSegmentSum");for(var r=[],o=t.rank-e.rank,a=0;a<o;++a)e=e.expandDims(a+1);for(a=0;a<n;++a){var i=Tn(a,"int32"),s=hc(i,e).asType("float32").mul(t).sum(0);r.push(s)}return Or(r)},e.prototype.argMin=function(t,e){Dp(t,"argMin");var n=[e];yn("argMin",n,t.rank);for(var r=gn(t.shape,n),o=r[0],a=r[1],i=zn(o,"int32"),s=R(a),u=this.readSync(i.dataId),c=this.readSync(t.dataId),l=0;l<u.length;++l){for(var p=l*s,h=c[p],d=0,f=0;f<s;++f){var v=c[p+f];v<h&&(h=v,d=f)}u[l]=d}return i},e.prototype.argMax=function(t,e){Dp(t,"argMax");var n=[e];yn("argMax",n,t.rank);for(var r=gn(t.shape,n),o=r[0],a=r[1],i=zn(o,"int32"),s=R(a),u=this.readSync(i.dataId),c=this.readSync(t.dataId),l=0;l<u.length;++l){for(var p=l*s,h=c[p],d=0,f=0;f<s;++f){var v=c[p+f];v>h&&(h=v,d=f)}u[l]=d}return i},e.prototype.cumsum=function(t,e,n,r){if(Dp(t,"cumsum"),e!==t.rank-1)throw new Error("backend.cumsum in CPU expects an inner-most axis="+(t.rank-1)+" but got axis="+e);for(var o=It(t.dtype,"int32"),a=zn(t.shape,o),i=this.readSync(a.dataId),s=this.readSync(t.dataId),u=t.shape[t.rank-1],c=r?function(t,e){return t+u-e-1}:function(t,e){return t+e},l=0;l<s.length;l+=u)for(var p=0;p<u;p++){var h=c(l,p);if(0===p)i[h]=n?0:s[h];else{var d=c(l,p-1);i[h]=n?s[d]+i[d]:s[h]+i[d]}}return a},e.prototype.equal=function(t,e){return Dp([t,e],"equal"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t===e?1:0})},e.prototype.notEqual=function(t,e){return Dp([t,e],"notEqual"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t!==e?1:0})},e.prototype.less=function(t,e){return Dp([t,e],"less"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t<e?1:0})},e.prototype.lessEqual=function(t,e){return Dp([t,e],"lessEqual"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t<=e?1:0})},e.prototype.greater=function(t,e){return Dp([t,e],"greater"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t>e?1:0})},e.prototype.greaterEqual=function(t,e){return Dp([t,e],"greaterEqual"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t>=e?1:0})},e.prototype.logicalNot=function(t){Dp(t,"logicalNot");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r<e.length;++r)n[r]=e[r]?0:1;return this.makeOutput(n,t.shape,"bool")},e.prototype.logicalAnd=function(t,e){return Dp([t,e],"logicalAnd"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t&&e})},e.prototype.logicalOr=function(t,e){return Dp([t,e],"logicalOr"),this.broadcastedBinaryOp(t,e,"bool",function(t,e){return t||e})},e.prototype.select=function(t,e,n){Dp([t,e,n],"select");for(var r=this.readSync(t.dataId),o=this.readSync(e.dataId),a=this.readSync(n.dataId),i=zn(e.shape,It(e.dtype,n.dtype)),s=this.readSync(i.dataId),u=0,c=0===t.rank||t.rank>1||1===e.rank?1:R(e.shape.slice(1)),l=0;l<r.length;l++)for(var p=0;p<c;p++)1===r[l]?s[u++]=o[l]:s[u++]=a[l];return i},e.prototype.where=function(t){Dp([t],"where");var e=this.readSync(t.dataId);return Go(t.shape,e)},e.prototype.topk=function(t,e,n){return Dp(t,"topk"),Vo(this.readSync(t.dataId),t.shape,t.dtype,e)},e.prototype.min=function(t,e){Dp(t,"min"),yn("min",e,t.rank);for(var n=gn(t.shape,e),r=n[0],o=n[1],a=zn(r,t.dtype),i=R(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*i,p=u[l],h=0;h<i;++h){var d=u[l+h];d<p&&(p=d)}s[c]=p}return a},e.prototype.minimum=function(t,e){return Dp([t,e],"minimum"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){return Math.min(t,e)})},e.prototype.mod=function(t,e){return Dp([t,e],"mod"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){var n=t%e;return t<0&&e<0||t>=0&&e>=0?n:(n+e)%e})},e.prototype.max=function(t,e){Dp(t,"max"),yn("max",e,t.rank);for(var n=gn(t.shape,e),r=n[0],o=n[1],a=zn(r,t.dtype),i=R(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*i,p=u[l],h=0;h<i;++h){var d=u[l+h];d>p&&(p=d)}s[c]=p}return a},e.prototype.maximum=function(t,e){return Dp([t,e],"maximum"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){return Math.max(t,e)})},e.prototype.all=function(t,e){Dp(t,"all"),yn("all",e,t.rank);for(var n=gn(t.shape,e),r=n[0],o=n[1],a=zn(r,t.dtype),i=R(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*i,p=u[l],h=0;h<i;++h){var d=u[l+h];p=p&&d}s[c]=p}return a},e.prototype.any=function(t,e){Dp(t,"any"),yn("any",e,t.rank);for(var n=gn(t.shape,e),r=n[0],o=n[1],a=zn(r,t.dtype),i=R(o),s=this.readSync(a.dataId),u=this.readSync(t.dataId),c=0;c<s.length;++c){for(var l=c*i,p=u[l],h=0;h<i;++h){var d=u[l+h];p=p||d}s[c]=p}return a},e.prototype.squaredDifference=function(t,e){return Dp([t,e],"squaredDifference"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){var n=t-e;return n*n})},e.prototype.ceil=function(t){Dp(t,"ceil");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.ceil(e[r]);return this.makeOutput(n,t.shape,"float32")},e.prototype.floor=function(t){Dp(t,"floor");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.floor(e[r]);return this.makeOutput(n,t.shape,"float32")},e.prototype.sign=function(t){Dp(t,"x");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)e[r]<0?n[r]=-1:e[r]>0?n[r]=1:n[r]=0;return this.makeOutput(n,t.shape,"float32")},e.prototype.isNaN=function(t){Dp(t,"x");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r<e.length;++r)Number.isNaN(e[r])&&(n[r]=1);return this.makeOutput(n,t.shape,"bool")},e.prototype.isInf=function(t){Dp(t,"x");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r<e.length;++r)Math.abs(e[r])===1/0&&(n[r]=1);return this.makeOutput(n,t.shape,"bool")},e.prototype.isFinite=function(t){Dp(t,"x");for(var e=this.readSync(t.dataId),n=new Uint8Array(e.length),r=0;r<e.length;++r)Number.isFinite(e[r])&&(n[r]=1);return this.makeOutput(n,t.shape,"bool")},e.prototype.round=function(t){Dp(t,"round");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var o=Math.floor(e[r]);e[r]-o<.5?n[r]=Math.floor(e[r]):e[r]-o>.5?n[r]=Math.ceil(e[r]):n[r]=o%2==0?o:o+1}return this.makeOutput(n,t.shape,"float32")},e.prototype.exp=function(t){Dp(t,"exp");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.exp(e[r]);return this.makeOutput(n,t.shape,"float32")},e.prototype.expm1=function(t){Dp(t,"expm1");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=Math.expm1(e[r]);return this.makeOutput(n,t.shape,"float32")},e.prototype.log=function(t){Dp(t,"log");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var o=e[r];n[r]=Math.log(o)}return this.makeOutput(n,t.shape,"float32")},e.prototype.log1p=function(t){Dp(t,"log1p");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var o=e[r];n[r]=Math.log1p(o)}return this.makeOutput(n,t.shape,"float32")},e.prototype.sqrt=function(t){Dp(t,"sqrt");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var o=e[r];n[r]=Math.sqrt(o)}return this.makeOutput(n,t.shape,"float32")},e.prototype.rsqrt=function(t){Dp(t,"rsqrt");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r){var o=e[r];n[r]=1/Math.sqrt(o)}return this.makeOutput(n,t.shape,"float32")},e.prototype.reciprocal=function(t){Dp(t,"reciprocal");for(var e=this.readSync(t.dataId),n=new Float32Array(e.length),r=0;r<e.length;++r)n[r]=1/e[r];return this.makeOutput(n,t.shape,"float32")},e.prototype.linear=function(t){return t},e.prototype.relu=function(t){Dp(t,"relu");for(var e=zn(t.shape,t.dtype),n=this.readSync(e.dataId),r=this.readSync(t.dataId),o=0;o<r.length;++o)n[o]=Math.max(0,r[o]);return e},e.prototype.relu6=function(t){Dp(t,"relu");for(var e=zn(t.shape,t.dtype),n=this.readSync(e.dataId),r=this.readSync(t.dataId),o=0;o<r.length;++o)n[o]=Math.min(Math.max(0,r[o]),6);return e},e.prototype.prelu=function(t,e){return Dp([t,e],"prelu"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){return t<0?e*t:t})},e.prototype.elu=function(t){Dp(t,"elu");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r){var o=n[r];e[r]=o>=0?o:Math.exp(o)-1}return this.makeOutput(e,t.shape,"float32")},e.prototype.eluDer=function(t,e){Dp([t,e],"eluDer");for(var n=new Float32Array(e.size),r=this.readSync(e.dataId),o=this.readSync(t.dataId),a=0;a<r.length;++a){var i=r[a];n[a]=i>=1?o[a]:o[a]*(i+1)}return this.makeOutput(n,e.shape,"float32")},e.prototype.selu=function(t){Dp(t,"selu");for(var e=cs,n=ls,r=new Float32Array(t.size),o=this.readSync(t.dataId),a=0;a<o.length;++a){var i=o[a];r[a]=i>=0?n*i:e*(Math.exp(i)-1)}return this.makeOutput(r,t.shape,"float32")},e.prototype.clip=function(t,e,n){Dp(t,"clip");for(var r=new Float32Array(t.size),o=this.readSync(t.dataId),a=0;a<o.length;++a){var i=o[a];r[a]=i>n?n:i<e?e:i}return this.makeOutput(r,t.shape,"float32")},e.prototype.abs=function(t){for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.abs(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.complexAbs=function(t){for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<t.size;++r){var o=n[2*r],a=n[2*r+1];e[r]=Math.hypot(o,a)}return this.makeOutput(e,t.shape,"float32")},e.prototype.int=function(t){Dp(t,"int");for(var e=new Int32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=n[r];return this.makeOutput(e,t.shape,"int32")},e.prototype.sigmoid=function(t){Dp(t,"sigmoid");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=1/(1+Math.exp(-n[r]));return this.makeOutput(e,t.shape,"float32")},e.prototype.softplus=function(t){Dp(t,"softplus");for(var e=Math.log(1.1920928955078125e-7)+2,n=new Float32Array(t.size),r=this.readSync(t.dataId),o=0;o<r.length;++o){var a,i=r[o]>-e,s=r[o]<e,u=Math.exp(r[o]);a=s?u:i?r[o]:Math.log(1+u),n[o]=a}return this.makeOutput(n,t.shape,"float32")},e.prototype.sin=function(t){Dp(t,"sin");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.sin(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.cos=function(t){Dp(t,"cos");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.cos(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.tan=function(t){Dp(t,"tan");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.tan(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.asin=function(t){Dp(t,"asin");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.asin(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.acos=function(t){Dp(t,"acos");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.acos(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.atan=function(t){Dp(t,"atan");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.atan(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.atan2=function(t,e){return Dp([t,e],"atan2"),this.broadcastedBinaryOp(t,e,t.dtype,function(t,e){return Math.atan2(t,e)})},e.prototype.sinh=function(t){Dp(t,"sinh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.sinh(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.cosh=function(t){Dp(t,"cosh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.cosh(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.tanh=function(t){Dp(t,"tanh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=S(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.asinh=function(t){Dp(t,"asinh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.asinh(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.acosh=function(t){Dp(t,"acosh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.acosh(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.atanh=function(t){Dp(t,"atanh");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r)e[r]=Math.atanh(n[r]);return this.makeOutput(e,t.shape,"float32")},e.prototype.erf=function(t){Dp(t,"erf");for(var e=new Float32Array(t.size),n=this.readSync(t.dataId),r=0;r<n.length;++r){var o=Math.sign(n[r]),a=Math.abs(n[r]),i=1/(1+.3275911*a);e[r]=o*(1-((((1.061405429*i-1.453152027)*i+1.421413741)*i-.284496736)*i+.254829592)*i*Math.exp(-a*a))}return this.makeOutput(e,t.shape,"float32")},e.prototype.step=function(t,e){void 0===e&&(e=0),Dp(t,"step");for(var n=new Float32Array(t.size),r=this.readSync(t.dataId),o=0;o<r.length;++o){var a=r[o];isNaN(a)?n[o]=NaN:n[o]=a>0?1:e}return this.makeOutput(n,t.shape,"float32")},e.prototype.fusedConv2d=function(t){var e=t.input,n=t.filter,r=t.convInfo,o=t.bias,a=t.activation,i=t.preluActivationWeights,s=this.conv2d(e,n,r);return o&&(s=this.add(s,o)),a&&(s=Np(this,s,a,i)),s},e.prototype.conv2d=function(t,e,n){Dp([t,e],"conv2d");for(var r=n.filterHeight,o=n.filterWidth,a=n.dilationHeight,i=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,c="channelsLast"===n.dataFormat,l=lr(n.outShape,t.dtype),p=t.strides[0],h=c?t.strides[1]:t.strides[2],d=c?t.strides[2]:1,f=c?1:t.strides[1],v=l.strides[0],m=c?l.strides[1]:l.strides[2],g=c?l.strides[2]:1,x=c?1:l.strides[1],y=this.readSync(t.dataId),b=this.readSync(e.dataId),w=l.values,C=0;C<n.batchSize;++C)for(var E=C*p,R=C*v,I=0;I<n.outHeight;++I)for(var k=R+I*m,S=I*n.strideHeight-u,A=0;A<r;A++){var D=S+A*a;if(!(D<0||D>=n.inHeight))for(var N=A*e.strides[0],T=E+D*h,F=0;F<n.outWidth;++F)for(var O=k+F*g,_=F*n.strideWidth-s,M=0;M<o;M++){var B=_+M*i;if(!(B<0||B>=n.inWidth))for(var P=T+B*d,L=N+M*e.strides[1],W=0;W<n.inChannels;++W){for(var z=y[P+W*f],U=0;U<n.outChannels;++U)w[O+U*x]+=z*b[L+U];L+=n.outChannels}}}return l.toTensor()},e.prototype.conv3d=function(t,e,n){for(var r=n.filterDepth,o=n.filterHeight,a=n.filterWidth,i=n.dilationDepth,s=n.dilationHeight,u=n.dilationWidth,c=n.padInfo.front,l=n.padInfo.left,p=n.padInfo.top,h=lr(n.outShape,t.dtype),d=this.readSync(t.dataId),f=this.readSync(e.dataId),v=h.values,m=0;m<n.batchSize;++m)for(var g=m*t.strides[0],x=m*h.strides[0],y=0;y<n.outDepth;++y)for(var b=x+y*h.strides[1],w=y*n.strideDepth-c,C=0;C<r;C++){var E=w+C*i;if(!(E<0||E>=n.inDepth))for(var R=C*e.strides[0],I=g+E*t.strides[1],k=0;k<n.outHeight;++k)for(var S=b+k*h.strides[2],A=k*n.strideHeight-p,D=0;D<o;D++){var N=A+D*s;if(!(N<0||N>=n.inHeight))for(var T=R+D*e.strides[1],F=I+N*t.strides[2],O=0;O<n.outWidth;++O)for(var _=S+O*n.outChannels,M=O*n.strideWidth-l,B=0;B<a;B++){var P=M+B*u;if(!(P<0||P>=n.inWidth))for(var L=T+B*e.strides[2],W=F+P*n.inChannels,z=L,U=0;U<n.inChannels;++U){for(var V=d[W+U],G=0;G<n.outChannels;++G)v[_+G]+=V*f[z+G];z+=n.outChannels}}}}return h.toTensor()},e.prototype.conv2dDerInput=function(t,e,n){Dp([t,e],"conv2dDerInput");for(var r=lr(n.inShape,"float32"),o=r.values,a=this.readSync(t.dataId),i=this.readSync(e.dataId),s=e.strides,u=s[0],c=s[1],l=s[2],p=n.batchSize,h=n.filterHeight,d=n.filterWidth,f=n.inChannels,v=n.inHeight,m=n.inWidth,g=n.outChannels,x=n.outHeight,y=n.outWidth,b=n.strideHeight,w=n.strideWidth,C=n.dataFormat,E=h-1-n.padInfo.top,R=d-1-n.padInfo.left,I="channelsLast"===C,k=r.strides[0],S=I?r.strides[1]:r.strides[2],A=I?r.strides[2]:1,D=I?1:r.strides[1],N=t.strides[0],T=I?t.strides[1]:t.strides[2],F=I?t.strides[2]:1,O=I?1:t.strides[1],_=0;_<p;++_)for(var M=0;M<f;++M)for(var B=0;B<v;++B)for(var P=B-E,L=Math.max(0,Math.ceil(P/b)),W=Math.min(x,(h+P)/b),z=0;z<m;++z){for(var U=z-R,V=Math.max(0,Math.ceil(U/w)),G=Math.min(y,(d+U)/w),H=0,q=L;q<W;++q)for(var K=q*b-P,j=V;j<G;++j)for(var X=N*_+T*q+F*j,$=u*(h-1-K)+c*(d-1-(j*w-U))+l*M,Y=0;Y<g;++Y)H+=a[X+O*Y]*i[$+Y];o[k*_+S*B+A*z+D*M]=H}return r.toTensor()},e.prototype.conv3dDerInput=function(t,e,n){for(var r=lr(n.inShape,"float32"),o=r.values,a=r.strides,i=a[0],s=a[1],u=a[2],c=a[3],l=this.readSync(t.dataId),p=t.strides,h=p[0],d=p[1],f=p[2],v=p[3],m=this.readSync(e.dataId),g=e.strides,x=g[0],y=g[1],b=g[2],w=g[3],C=n.batchSize,E=n.filterDepth,R=n.filterHeight,I=n.filterWidth,k=n.inChannels,S=n.inDepth,A=n.inHeight,D=n.inWidth,N=n.outChannels,T=n.outDepth,F=n.outHeight,O=n.outWidth,_=n.strideDepth,M=n.strideHeight,B=n.strideWidth,P=E-1-n.padInfo.front,L=R-1-n.padInfo.top,W=I-1-n.padInfo.left,z=0;z<C;++z)for(var U=0;U<k;++U)for(var V=0;V<S;++V)for(var G=V-P,H=Math.max(0,Math.ceil(G/_)),q=Math.min(T,(E+G)/_),K=0;K<A;++K)for(var j=K-L,X=Math.max(0,Math.ceil(j/M)),$=Math.min(F,(R+j)/M),Y=0;Y<D;++Y){for(var Q=Y-W,J=Math.max(0,Math.ceil(Q/B)),Z=Math.min(O,(I+Q)/B),tt=0,et=H;et<q;++et)for(var nt=et*_-G,rt=X;rt<$;++rt)for(var ot=rt*M-j,at=J;at<Z;++at)for(var it=h*z+d*et+f*rt+v*at,st=x*(E-1-nt)+y*(R-1-ot)+b*(I-1-(at*B-Q))+w*U,ut=0;ut<N;++ut)tt+=l[it+ut]*m[st+ut];o[i*z+s*V+u*K+c*Y+U]=tt}return r.toTensor()},e.prototype.conv2dDerFilter=function(t,e,n){Dp([t,e],"conv2dDerFilter");for(var r=n.strideHeight,o=n.strideWidth,a=n.filterHeight,i=n.filterWidth,s="channelsLast"===n.dataFormat,u=lr(n.filterShape,"float32"),c=n.padInfo.left,l=n.padInfo.top,p=this.bufferSync(t),h=this.bufferSync(e),d=0;d<a;++d)for(var f=Math.max(0,Math.ceil((l-d)/r)),v=Math.min(n.outHeight,(n.inHeight+l-d)/r),m=0;m<i;++m)for(var g=Math.max(0,Math.ceil((c-m)/o)),x=Math.min(n.outWidth,(n.inWidth+c-m)/o),y=0;y<n.inChannels;++y)for(var b=0;b<n.outChannels;++b){for(var w=0,C=0;C<n.batchSize;++C)for(var E=f;E<v;++E)for(var R=d+E*r-l,I=g;I<x;++I){var k=m+I*o-c;w+=s?p.get(C,R,k,y)*h.get(C,E,I,b):p.get(C,y,R,k)*h.get(C,b,E,I)}u.set(w,d,m,y,b)}return u.toTensor()},e.prototype.conv3dDerFilter=function(t,e,n){for(var r=n.strideDepth,o=n.strideHeight,a=n.strideWidth,i=n.filterDepth,s=n.filterHeight,u=n.filterWidth,c=lr(n.filterShape,"float32"),l=c.values,p=c.strides,h=p[0],d=p[1],f=p[2],v=p[3],m=this.readSync(e.dataId),g=e.strides,x=g[0],y=g[1],b=g[2],w=g[3],C=this.readSync(t.dataId),E=t.strides,R=E[0],I=E[1],k=E[2],S=E[3],A=n.padInfo.front,D=n.padInfo.left,N=n.padInfo.top,T=0;T<i;++T)for(var F=Math.max(0,Math.ceil((A-T)/r)),O=Math.min(n.outDepth,(n.inDepth+A-T)/r),_=T*h,M=0;M<s;++M)for(var B=Math.max(0,Math.ceil((N-M)/o)),P=Math.min(n.outHeight,(n.inHeight+N-M)/o),L=M*d+_,W=0;W<u;++W)for(var z=Math.max(0,Math.ceil((D-W)/a)),U=Math.min(n.outWidth,(n.inWidth+D-W)/a),V=W*f+L,G=0;G<n.inChannels;++G)for(var H=G*v+V,q=0;q<n.outChannels;++q){for(var K=0,j=0;j<n.batchSize;++j)for(var X=j*R,$=j*x,Y=F;Y<O;++Y)for(var Q=(T+Y*r-A)*I+X,J=Y*y+$,Z=B;Z<P;++Z)for(var tt=(M+Z*o-N)*k+Q,et=Z*b+J,nt=z;nt<U;++nt){var rt=nt*w+et;K+=C[(W+nt*a-D)*S+tt+G]*m[rt+q]}l[H+q]=K}return c.toTensor()},e.prototype.fusedDepthwiseConv2D=function(t){var e=t.input,n=t.filter,r=t.convInfo,o=t.bias,a=t.activation,i=t.preluActivationWeights,s=this.depthwiseConv2D(e,n,r);return o&&(s=this.add(s,o)),a&&(s=Np(this,s,a,i)),s},e.prototype.depthwiseConv2D=function(t,e,n){Dp([t,e],"depthwiseConv2D");for(var r=n.filterHeight,o=n.filterWidth,a=n.dilationHeight,i=n.dilationWidth,s=n.padInfo.left,u=n.padInfo.top,c=n.outChannels/n.inChannels,l=lr(n.outShape,t.dtype),p=this.readSync(t.dataId),h=this.readSync(e.dataId),d=l.values,f=0;f<n.batchSize;++f)for(var v=f*t.strides[0],m=f*l.strides[0],g=0;g<n.outHeight;++g)for(var x=m+g*l.strides[1],y=g*n.strideHeight-s,b=0;b<r;++b){var w=y+b*a;if(!(w<0||w>=n.inHeight))for(var C=b*e.strides[0],E=v+w*t.strides[1],R=0;R<n.outWidth;++R)for(var I=x+R*l.strides[2],k=R*n.strideWidth-u,S=0;S<o;++S){var A=k+S*i;if(!(A<0||A>=n.inWidth))for(var D=C+S*e.strides[1],N=E+A*n.inChannels,T=I,F=D,O=0;O<n.inChannels;++O){for(var _=p[N+O],M=0;M<c;++M)d[T+M]+=_*h[F+M];T+=c,F+=c}}}return l.toTensor()},e.prototype.depthwiseConv2DDerInput=function(t,e,n){Dp([t,e],"depthwiseConv2DDerInput");for(var r=lr(n.inShape,"float32"),o=r.values,a=r.strides,i=a[0],s=a[1],u=a[2],c=this.readSync(t.dataId),l=t.strides,p=l[0],h=l[1],d=l[2],f=this.readSync(e.dataId),v=e.strides,m=v[0],g=v[1],x=v[2],y=n.batchSize,b=n.filterHeight,w=n.filterWidth,C=n.inChannels,E=n.inHeight,R=n.inWidth,I=n.outChannels,k=n.outHeight,S=n.outWidth,A=n.strideHeight,D=n.strideWidth,N=b-1-n.padInfo.top,T=w-1-n.padInfo.left,F=I/C,O=0;O<y;++O)for(var _=0;_<C;++_)for(var M=0;M<E;++M)for(var B=M-N,P=Math.max(0,Math.ceil(B/A)),L=Math.min(k,(b+B)/A),W=0;W<R;++W){for(var z=W-T,U=Math.max(0,Math.ceil(z/D)),V=Math.min(S,(w+z)/D),G=0,H=P;H<L;++H)for(var q=H*A-B,K=U;K<V;++K)for(var j=p*O+h*H+d*K,X=m*(b-1-q)+g*(w-1-(K*D-z))+x*_,$=0;$<F;++$)G+=c[j+(_*F+$)]*f[X+$];o[i*O+s*M+u*W+_]=G}return r.toTensor()},e.prototype.depthwiseConv2DDerFilter=function(t,e,n){Dp([t,e],"depthwiseConv2DDerFilter");for(var r=n.strideHeight,o=n.strideWidth,a=n.filterHeight,i=n.filterWidth,s=lr(n.filterShape,"float32"),u=n.padInfo.left,c=n.padInfo.top,l=n.outChannels/n.inChannels,p=this.bufferSync(t),h=this.bufferSync(e),d=0;d<a;++d)for(var f=Math.max(0,Math.ceil((c-d)/r)),v=Math.min(n.outHeight,(n.inHeight+c-d)/r),m=0;m<i;++m)for(var g=Math.max(0,Math.ceil((u-m)/o)),x=Math.min(n.outWidth,(n.inWidth+u-m)/o),y=0;y<n.outChannels;++y){for(var b=Math.trunc(y/l),w=y%l,C=0,E=0;E<n.batchSize;++E)for(var R=f;R<v;++R)for(var I=d+R*r-c,k=g;k<x;++k){var S=m+k*o-u;C+=p.get(E,I,S,b)*h.get(E,R,k,y)}s.set(C,d,m,b,w)}return s.toTensor()},e.prototype.tile=function(t,e){return Dp(t,"tile"),Uo(this.bufferSync(t),e)},e.prototype.pad=function(t,e,n){Dp(t,"pad");var r=e.map(function(e,n){return e[0]+t.shape[n]+e[1]}),o=e.map(function(t){return t[0]}),a=this.bufferSync(t),i=lr(r,t.dtype);0!==n&&i.values.fill(n);for(var s=0;s<t.size;s++){var u=a.indexToLoc(s),c=u.map(function(t,e){return t+o[e]});i.set.apply(i,[a.get.apply(a,u)].concat(c))}return i.toTensor()},e.prototype.transpose=function(t,e){Dp(t,"transpose");for(var n=new Array(t.rank),r=0;r<n.length;r++)n[r]=t.shape[e[r]];var o=this.readSync(t.dataId),a=lr(n,t.dtype),i=this.bufferSync(t);for(r=0;r<t.size;++r){for(var s=i.indexToLoc(r),u=new Array(s.length),c=0;c<u.length;c++)u[c]=s[e[c]];var l=a.locToIndex(u);a.values[l]=o[r]}return a.toTensor()},e.prototype.gather=function(t,e,n){Dp([t,e],"gather");var r=t.shape.slice(),o=this.readSync(e.dataId);r[n]=o.length;for(var a=lr(r,t.dtype),i=this.bufferSync(t),s=0;s<a.size;++s){var u=a.indexToLoc(s),c=u.slice();c[n]=o[u[n]];var l=i.locToIndex(c);a.values[s]=i.values[l]}return a.toTensor()},e.prototype.batchToSpaceND=function(t,e,n){Dp([t],"batchToSpaceND");var r=e.reduce(function(t,e){return t*e}),o=Lr(t.shape,e,r),a=Wr(o.length,e.length),i=zr(t.shape,e,r),s=Ur(n,e.length),u=Vr(i,n,e.length);return t.reshape(o).transpose(a).reshape(i).slice(s,u)},e.prototype.spaceToBatchND=function(t,e,n){Dp([t],"spaceToBatchND");var r=e.reduce(function(t,e){return t*e}),o=[[0,0]];o.push.apply(o,n);for(var a=1+e.length;a<t.shape.length;++a)o.push([0,0]);var i=t.pad(o),s=Lr(i.shape,e,r,!1),u=Wr(s.length,e.length,!1),c=zr(i.shape,e,r,!1);return i.reshape(s).transpose(u).reshape(c)},e.prototype.pool=function(t,e,n){Dp(t,"pool");for(var r=e.strideHeight,o=e.strideWidth,a=e.dilationHeight,i=e.dilationWidth,s=e.effectiveFilterHeight,u=e.effectiveFilterWidth,c=e.padInfo.top,l=e.padInfo.left,p="max"===n?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,h=this.readSync(t.dataId),d=lr(e.outShape,t.dtype),f=d.values,v=e.outShape[1]*e.outShape[2]*e.outShape[3],m=e.outShape[2]*e.outShape[3],g=e.outShape[3],x=0;x<e.batchSize;++x)for(var y=x*v,b=x*t.strides[0],w=0;w<e.inChannels;++w)for(var C=0;C<e.outHeight;++C)for(var E=C*r-c,R=Math.max(0,E),I=Math.min(e.inHeight,s+E),k=y+C*m,S=0;S<e.outWidth;++S){for(var A=S*o-l,D=Math.max(0,A),N=Math.min(e.inWidth,u+A),T=p,F=0,O=0,_=R;_<I;_+=a){for(var M=b+_*t.strides[1],B=D;B<N;B+=i){var P=h[M+B*t.strides[2]+w];"max"===n&&P>T?T=P:"avg"===n&&(F+=P,O++)}if(isNaN(T))break}f[k+S*g+w]="avg"===n?F/O:T}return d.toTensor()},e.prototype.maxPool=function(t,e){return this.pool(t,e,"max")},e.prototype.maxPoolPositions=function(t,e){for(var n=lr(e.outShape,"int32"),r=e.strideHeight,o=e.strideWidth,a=e.dilationHeight,i=e.dilationWidth,s=e.effectiveFilterHeight,u=e.effectiveFilterWidth,c=e.padInfo.top,l=e.padInfo.left,p=this.bufferSync(t),h=0;h<e.batchSize;++h)for(var d=0;d<e.inChannels;++d)for(var f=0;f<e.outHeight;++f){for(var v=f*r-c,m=v;m<0;)m+=a;for(var g=Math.min(e.inHeight,s+v),x=0;x<e.outWidth;++x){for(var y=x*o-l,b=y;b<0;)b+=i;for(var w=Math.min(e.inWidth,u+y),C=Number.NEGATIVE_INFINITY,E=-1,R=m;R<g;R+=a)for(var I=R-v,k=b;k<w;k+=i){var S=k-y,A=p.get(h,R,k,d);A>C&&(C=A,E=I*u+S)}n.set(E,h,f,x,d)}}return n.toTensor()},e.prototype.maxPoolBackprop=function(t,e,n,r){Dp([e,n],"maxPoolBackprop");for(var o=this.maxPoolPositions(e,r),a=r.strideHeight,i=r.strideWidth,s=r.dilationHeight,u=r.dilationWidth,c=r.effectiveFilterHeight,l=r.effectiveFilterWidth,p=l-1-r.padInfo.left,h=c-1-r.padInfo.top,d=lr(e.shape,"float32"),f=this.bufferSync(o),v=this.bufferSync(t),m=0;m<r.batchSize;++m)for(var g=0;g<r.inChannels;++g)for(var x=0;x<r.inHeight;++x)for(var y=0;y<r.inWidth;++y){for(var b=x-h,w=y-p,C=0,E=0;E<c;E+=s){var R=(b+E)/a;if(!(R<0||R>=r.outHeight||Math.floor(R)!==R))for(var I=0;I<l;I+=u){var k=(w+I)/i;if(!(k<0||k>=r.outWidth||Math.floor(k)!==k)){var S=c*l-1-f.get(m,R,k,g)===E*l+I?1:0;0!==S&&(C+=v.get(m,R,k,g)*S)}}}d.set(C,m,x,y,g)}return d.toTensor()},e.prototype.avgPoolBackprop=function(t,e,n){Dp([t,e],"avgPoolBackprop");for(var r=n.strideHeight,o=n.strideWidth,a=n.filterHeight,i=n.filterWidth,s=n.dilationHeight,u=n.dilationWidth,c=n.effectiveFilterHeight,l=n.effectiveFilterWidth,p=l-1-n.padInfo.left,h=c-1-n.padInfo.top,d=lr(e.shape,"float32"),f=1/(a*i),v=this.bufferSync(t),m=0;m<n.batchSize;++m)for(var g=0;g<n.inChannels;++g)for(var x=0;x<n.inHeight;++x)for(var y=0;y<n.inWidth;++y){for(var b=x-h,w=y-p,C=0,E=0;E<c;E+=s){var R=(b+E)/r;if(!(R<0||R>=n.outHeight||Math.floor(R)!==R))for(var I=0;I<l;I+=u){var k=(w+I)/o;k<0||k>=n.outWidth||Math.floor(k)!==k||(C+=v.get(m,R,k,g))}}d.set(C*f,m,x,y,g)}return d.toTensor()},e.prototype.pool3d=function(t,e,n){Dp(t,"pool3d");for(var r=e.strideDepth,o=e.strideHeight,a=e.strideWidth,i=e.dilationDepth,s=e.dilationHeight,u=e.dilationWidth,c=e.effectiveFilterDepth,l=e.effectiveFilterHeight,p=e.effectiveFilterWidth,h=e.padInfo.front,d=e.padInfo.top,f=e.padInfo.left,v="max"===n?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=this.readSync(t.dataId),g=lr(e.outShape,t.dtype),x=g.values,y=e.outShape[1]*e.outShape[2]*e.outShape[3]*e.outShape[4],b=e.outShape[2]*e.outShape[3]*e.outShape[4],w=e.outShape[3]*e.outShape[4],C=e.outShape[4],E=0;E<e.batchSize;++E)for(var R=E*y,I=E*t.strides[0],k=0;k<e.inChannels;++k)for(var S=0;S<e.outDepth;++S){for(var A=S*r-h,D=A;D<0;)D+=i;for(var N=Math.min(e.inDepth,c+A),T=R+S*b,F=0;F<e.outHeight;++F){for(var O=F*o-d,_=O;_<0;)_+=s;for(var M=Math.min(e.inHeight,l+O),B=T+F*w,P=0;P<e.outWidth;++P){for(var L=P*a-f,W=L;W<0;)W+=u;for(var z=Math.min(e.inWidth,p+L),U=B+P*C,V=v,G=0,H=0,q=D;q<N;q+=i){for(var K=I+q*t.strides[1],j=_;j<M;j+=s){for(var X=K+j*t.strides[2],$=W;$<z;$+=u){var Y=m[X+$*t.strides[3]+k];if("max"===n&&Y>V?V=Y:"avg"===n&&(G+=Y,H++),isNaN(V))break}if(isNaN(V))break}if(isNaN(V))break}x[U+k]="avg"===n?G/H:V}}}return g.toTensor()},e.prototype.avgPool3d=function(t,e){return Dp(t,"avgPool3d"),this.pool3d(t,e,"avg").toFloat()},e.prototype.avgPool3dBackprop=function(t,e,n){Dp([t,e],"avgPool3dBackprop");for(var r=n.strideDepth,o=n.strideHeight,a=n.strideWidth,i=n.filterDepth,s=n.filterHeight,u=n.filterWidth,c=n.dilationDepth,l=n.dilationHeight,p=n.dilationWidth,h=n.effectiveFilterDepth,d=n.effectiveFilterHeight,f=n.effectiveFilterWidth,v=h-1-n.padInfo.front,m=f-1-n.padInfo.left,g=d-1-n.padInfo.top,x=lr(e.shape,"float32"),y=1/(i*s*u),b=this.bufferSync(t),w=0;w<n.batchSize;++w)for(var C=0;C<n.inChannels;++C)for(var E=0;E<n.inDepth;++E)for(var R=0;R<n.inHeight;++R)for(var I=0;I<n.inWidth;++I){for(var k=E-v,S=R-g,A=I-m,D=0,N=0;N<h;N+=c){var T=(k+N)/r;if(!(T<0||T>=n.outDepth||Math.floor(T)!==T))for(var F=0;F<d;F+=l){var O=(S+F)/o;if(!(O<0||O>=n.outHeight||Math.floor(O)!==O))for(var _=0;_<f;_+=p){var M=(A+_)/a;M<0||M>=n.outWidth||Math.floor(M)!==M||(D+=b.get(w,T,O,M,C))}}}x.set(D*y,w,E,R,I,C)}return x.toTensor()},e.prototype.maxPool3d=function(t,e){return Dp(t,"maxPool3d"),this.pool3d(t,e,"max").toFloat()},e.prototype.maxPool3dPositions=function(t,e){for(var n=lr(e.outShape,"int32"),r=e.strideDepth,o=e.strideHeight,a=e.strideWidth,i=e.dilationDepth,s=e.dilationHeight,u=e.dilationWidth,c=e.effectiveFilterDepth,l=e.effectiveFilterHeight,p=e.effectiveFilterWidth,h=e.padInfo.front,d=e.padInfo.top,f=e.padInfo.left,v=this.bufferSync(t),m=0;m<e.batchSize;++m)for(var g=0;g<e.inChannels;++g)for(var x=0;x<e.outDepth;++x){for(var y=x*r-h,b=y;b<0;)b+=i;for(var w=Math.min(e.inDepth,c+y),C=0;C<e.outHeight;++C){for(var E=C*o-d,R=E;R<0;)R+=s;for(var I=Math.min(e.inHeight,l+E),k=0;k<e.outWidth;++k){for(var S=k*a-f,A=S;A<0;)A+=u;for(var D=Math.min(e.inWidth,p+S),N=Number.NEGATIVE_INFINITY,T=-1,F=b;F<w;F+=i)for(var O=F-y,_=R;_<I;_+=s)for(var M=_-E,B=A;B<D;B+=u){var P=B-S,L=v.get(m,F,_,B,g);L>=N&&(N=L,T=O*l*p+M*l+P)}n.set(T,m,x,C,k,g)}}}return n.toTensor()},e.prototype.maxPool3dBackprop=function(t,e,n,r){Dp([e,n],"maxPool3dBackprop");for(var o=this.maxPool3dPositions(e,r),a=r.strideDepth,i=r.strideHeight,s=r.strideWidth,u=r.dilationDepth,c=r.dilationHeight,l=r.dilationWidth,p=r.effectiveFilterDepth,h=r.effectiveFilterHeight,d=r.effectiveFilterWidth,f=p-1-r.padInfo.front,v=d-1-r.padInfo.left,m=h-1-r.padInfo.top,g=lr(e.shape,"float32"),x=this.bufferSync(o),y=this.bufferSync(t),b=0;b<r.batchSize;++b)for(var w=0;w<r.inChannels;++w)for(var C=0;C<r.inDepth;++C)for(var E=0;E<r.inHeight;++E)for(var R=0;R<r.inWidth;++R){for(var I=C-f,k=E-m,S=R-v,A=0,D=0;D<p;D+=u){var N=(I+D)/a;if(!(N<0||N>=r.outDepth||Math.floor(N)!==N))for(var T=0;T<h;T+=c){var F=(k+T)/i;if(!(F<0||F>=r.outHeight||Math.floor(F)!==F))for(var O=0;O<d;O+=l){var _=(S+O)/s;if(!(_<0||_>=r.outWidth||Math.floor(_)!==_)){var M=p*h*d-1-x.get(b,N,F,_,w)===D*h*d+T*d+O?1:0;0!==M&&(A+=y.get(b,N,F,_,w)*M)}}}}g.set(A,b,C,E,R,w)}return g.toTensor()},e.prototype.cast=function(t,e){return No(t,e,this)},e.prototype.reshape=function(t,e){return To(t,e)},e.prototype.avgPool=function(t,e){return Dp(t,"avgPool"),this.pool(t,e,"avg").toFloat()},e.prototype.resizeBilinear=function(t,e,n,r){Dp(t,"resizeBilinear");for(var o=t.shape,a=o[0],i=o[1],s=o[2],u=o[3],c=this.readSync(t.dataId),l=new Float32Array(R([a,e,n,u])),p=[r&&e>1?i-1:i,r&&n>1?s-1:s],h=[r&&e>1?e-1:e,r&&n>1?n-1:n],d=0,f=p[0]/h[0],v=p[1]/h[1],m=0;m<a;m++)for(var g=0;g<e;g++)for(var x=f*g,y=Math.floor(x),b=x-y,w=Math.min(i-1,Math.ceil(x)),C=m*t.strides[0]+y*t.strides[1],E=m*t.strides[0]+w*t.strides[1],I=0;I<n;I++)for(var k=v*I,S=Math.floor(k),A=k-S,D=Math.min(s-1,Math.ceil(k)),N=C+S*t.strides[2],T=E+S*t.strides[2],F=C+ +D*t.strides[2],O=E+D*t.strides[2],_=0;_<u;_++){var M=c[N+_],B=c[T+_],P=M+(c[F+_]-M)*A,L=P+(B+(c[O+_]-B)*A-P)*b;l[d++]=L}return Dn(l,[a,e,n,u])},e.prototype.resizeBilinearBackprop=function(t,e,n){Dp([t,e],"resizeBilinearBackprop");for(var r=e.shape,o=r[0],a=r[1],i=r[2],s=r[3],u=t.shape,c=u[1],l=u[2],p=new Float32Array(o*a*i*s),h=[n&&c>1?a-1:a,n&&l>1?i-1:i],d=[n&&c>1?c-1:c,n&&l>1?l-1:l],f=h[0]/d[0],v=h[1]/d[1],m=this.readSync(t.dataId),g=0,x=0;x<o;x++)for(var y=x*e.strides[0],b=0;b<c;b++)for(var w=b*f,C=Math.floor(w),E=Math.min(Math.ceil(w),a-1),R=y+C*e.strides[1],I=y+E*e.strides[1],k=w-C,S=1-k,A=0;A<l;A++)for(var D=A*v,N=Math.floor(D),T=Math.min(Math.ceil(D),i-1),F=D-N,O=1-F,_=R+N*e.strides[2],M=R+T*e.strides[2],B=I+N*e.strides[2],P=I+T*e.strides[2],L=S*O,W=S*F,z=k*O,U=k*F,V=0;V<s;V++){var G=m[g++];p[_+V]+=G*L,p[M+V]+=G*W,p[B+V]+=G*z,p[P+V]+=G*U}return Mn(p,[o,i,a,s],e.dtype)},e.prototype.resizeNearestNeighbor=function(t,e,n,r){Dp(t,"resizeNearestNeighbor");for(var o=t.shape,a=o[0],i=o[1],s=o[2],u=o[3],c=this.readSync(t.dataId),l=new Float32Array(a*e*n*u),p=[r&&e>1?i-1:i,r&&n>1?s-1:s],h=[r&&e>1?e-1:e,r&&n>1?n-1:n],d=p[0]/h[0],f=p[1]/h[1],v=0,m=0;m<a;m++)for(var g=m*t.strides[0],x=0;x<e;x++)for(var y=d*x,b=g+Math.min(i-1,r?Math.round(y):Math.floor(y))*t.strides[1],w=0;w<n;w++)for(var C=f*w,E=b+Math.min(s-1,r?Math.round(C):Math.floor(C))*t.strides[2],R=0;R<u;R++){var I=c[E+R];l[v++]=I}return Dn(l,[a,e,n,u],t.dtype)},e.prototype.resizeNearestNeighborBackprop=function(t,e,n){Dp([t,e],"resizeNearestNeighborBackprop");for(var r=e.shape,o=r[0],a=r[1],i=r[2],s=r[3],u=t.shape,c=u[1],l=u[2],p=new Float32Array(o*a*i*s),h=this.readSync(t.dataId),d=[n&&c>1?a-1:a,n&&l>1?i-1:i],f=[n&&c>1?c-1:c,n&&l>1?l-1:l],v=d[0]/f[0],m=d[1]/f[1],g=1/v,x=1/m,y=2*Math.ceil(g)+2,b=2*Math.ceil(x)+2,w=0;w<o;w++)for(var C=w*e.strides[0],E=0;E<a;E++)for(var R=C+E*e.strides[1],I=Math.floor(E*g),k=Math.floor(I-y/2),S=0;S<i;S++)for(var A=R+S*e.strides[2],D=Math.floor(S*x),N=Math.floor(D-b/2),T=0;T<s;T++){for(var F=0,O=0;O<y;O++){var _=O+k;if(!(_<0||_>=c)){var M=C+_*t.strides[1],B=_*v;if(E===Math.min(a-1,n?Math.round(B):Math.floor(B)))for(var P=0;P<b;P++){var L=P+N;if(!(L<0||L>=l)){var W=M+L*t.strides[2],z=L*m;S===Math.min(i-1,n?Math.round(z):Math.floor(z))&&(F+=h[W+T])}}}}p[A+T]=F}return Mn(p,e.shape,e.dtype)},e.prototype.batchNormalization=function(t,e,n,r,o,a){Dp([t,e,n,o,a],"batchNorm");for(var i=this.readSync(t.dataId),s=this.readSync(e.dataId),u=this.readSync(n.dataId),c=o?this.readSync(o.dataId):new Float32Array([1]),l=a?this.readSync(a.dataId):new Float32Array([0]),p=new Float32Array(i.length),h=l.length,d=c.length,f=u.length,v=s.length,m=0,g=0,x=0,y=0,b=0;b<i.length;++b)p[b]=l[m++]+(i[b]-s[g++])*c[x++]/Math.sqrt(u[y++]+r),m>=h&&(m=0),g>=v&&(g=0),x>=d&&(x=0),y>=f&&(y=0);return Mn(p,t.shape)},e.prototype.localResponseNormalization4D=function(t,e,n,r,o){Dp(t,"localResponseNormalization4D");var a=t.shape[3],i=a-1,s=this.readSync(t.dataId),u=t.size,c=new Float32Array(u);function l(t){for(var n=t%a,r=t-n+Math.max(0,n-e),o=t-n+Math.min(n+e,i),u=0;r<=o;r++){var c=s[r];u+=c*c}return u}for(var p=0;p<u;p++){var h=l(p),d=s[p]*Math.pow(n+r*h,-o);c[p]=d}return Mn(c,t.shape)},e.prototype.LRNGrad=function(t,e,n,r,o,a,i){Dp(t,"LRNGrad");for(var s=t.shape[3],u=this.readSync(t.dataId),c=this.readSync(e.dataId),l=this.readSync(n.dataId),p=new Float32Array(t.size),h=t.size,d=0;d<h;d++){for(var f=d%s,v=d-f+Math.max(0,f-r),m=d-f+Math.min(s,f+r+1),g=0,x=v;x<m;x++)g+=Math.pow(c[x],2);for(g=a*g+o,x=v;x<m;x++){var y=-2*a*i*c[x]*l[d]/g;d===x&&(y+=Math.pow(g,-i)),y*=u[d],p[x]+=y}}return Mn(p,t.shape)},e.prototype.multinomial=function(t,e,n,r){Dp(t,"multinomial");for(var o=e?t:co(t),a=o.shape[0],i=o.shape[1],s=zn([a,n],"int32"),u=this.readSync(s.dataId),c=this.readSync(o.dataId),l=0;l<a;++l){var p=l*i,h=new Float32Array(i-1);h[0]=c[p];for(var d=1;d<h.length;++d)h[d]=h[d-1]+c[p+d];for(var f=ir(r.toString()),v=l*n,m=0;m<n;++m){var g=f();u[v+m]=h.length;for(var x=0;x<h.length;x++)if(g<h[x]){u[v+m]=x;break}}}return s},e.prototype.oneHot=function(t,e,n,r){Dp(t,"oneHot");var o=new Float32Array(t.size*e);o.fill(r);for(var a=this.readSync(t.dataId),i=0;i<t.size;++i)a[i]>=0&&a[i]<e&&(o[i*e+a[i]]=n);return On(o,[t.size,e],"int32")},e.prototype.nonMaxSuppression=function(t,e,n,r,o){return Dp(t,"nonMaxSuppression"),Lo(this.readSync(t.dataId),this.readSync(e.dataId),n,r,o)},e.prototype.fft=function(t){return this.fftBatch(t,!1)},e.prototype.ifft=function(t){return this.fftBatch(t,!0)},e.prototype.fftBatch=function(t,e){for(var n=t.shape[0],r=t.shape[1],o=lr(t.shape,"float32"),a=lr(t.shape,"float32"),i=Sn(t).as2D(n,r),s=An(t).as2D(n,r),u=0;u<n;u++)for(var c=i.slice([u,0],[1,r]),l=s.slice([u,0],[1,r]),p=kn(c,l),h=this.readSync(this.fftImpl(p,e).dataId),d=0;d<r;d++){var f=Mo(h,d);o.values[u*r+d]=f.real,a.values[u*r+d]=f.imag}return kn(o.toTensor(),a.toTensor()).as2D(n,r)},e.prototype.fftImpl=function(t,e){var n=t.as1D(),r=n.size;if(this.isExponentOf2(r)){var o=this.fftRadix2(n,r,e).as2D(t.shape[0],t.shape[1]);return e&&(o=kn(Sn(o).div(Tn(r)),An(o).div(Tn(r)))),o}var a=this.readSync(t.dataId),i=function(t){for(var e=new Float32Array(t.length/2),n=new Float32Array(t.length/2),r=0;r<t.length;r+=2)e[r/2]=t[r],n[r/2]=t[r+1];return{real:e,imag:n}}(this.fourierTransformByMatmul(a,r,e));return kn(i.real,i.imag).as2D(t.shape[0],t.shape[1])},e.prototype.isExponentOf2=function(t){return 0==(t&t-1)},e.prototype.fftRadix2=function(t,e,n){if(1===e)return t;var r=this.readSync(t.dataId),o=e/2,a=function(t){for(var e=Math.ceil(t.length/4),n=new Float32Array(e),r=new Float32Array(e),o=0;o<t.length;o+=4)n[Math.floor(o/4)]=t[o],r[Math.floor(o/4)]=t[o+1];return{real:n,imag:r}}(r),i=kn(a.real,a.imag).as1D(),s=function(t){for(var e=Math.floor(t.length/4),n=new Float32Array(e),r=new Float32Array(e),o=2;o<t.length;o+=4)n[Math.floor(o/4)]=t[o],r[Math.floor(o/4)]=t[o+1];return{real:n,imag:r}}(r),u=kn(s.real,s.imag).as1D();i=this.fftRadix2(i,o,n),u=this.fftRadix2(u,o,n);var c=function(t,e){for(var n=new Float32Array(t/2),r=new Float32Array(t/2),o=0;o<Math.ceil(t/2);o++){var a=(e?2:-2)*Math.PI*(o/t);n[o]=Math.cos(a),r[o]=Math.sin(a)}return{real:n,imag:r}}(e,n),l=kn(c.real,c.imag).mul(u),p=i.add(l),h=i.sub(l),d=Sn(p).concat(Sn(h)),f=An(p).concat(An(h));return kn(d,f).as1D()},e.prototype.fourierTransformByMatmul=function(t,e,n){for(var r=new Float32Array(2*e),o=0;o<e;o++){for(var a=0,i=0,s=0;s<e;s++){var u=Po(o*s,e,n),c=Mo(t,s);a+=c.real*u.real-c.imag*u.imag,i+=c.real*u.imag+c.imag*u.real}n&&(a/=e,i/=e),Bo(r,a,i,o)}return r},e.prototype.depthToSpace=function(t,e,n){b("NHWC"===n,function(){return"Only NHWC dataFormat supported on CPU for depthToSpace. Got "+n}),b(e>1,function(){return"blockSize should be > 1 for depthToSpace, but was: "+e});for(var r=t.shape[0],o=t.shape[1],a=t.shape[2],i=t.shape[3],s=o*e,u=a*e,c=i/(e*e),l=this.readSync(t.dataId),p=new Float32Array(r*s*u*c),h=0,d=0;d<r;++d)for(var f=0;f<s;++f)for(var v=Math.floor(f/e),m=f%e,g=0;g<u;++g)for(var x=Math.floor(g/e),y=(m*e+g%e)*c,w=0;w<c;++w){var C=w+y+i*(x+a*(v+o*d));p[h++]=l[C]}return Mn(p,[r,s,u,c])},e.prototype.broadcastedBinaryOp=function(t,e,n,r){var o=go(t.shape,e.shape),a=lr(o,n),i=this.readSync(t.dataId),s=this.readSync(e.dataId),u=vo(t.shape,o),c=vo(e.shape,o),l=a.values;if(u.length+c.length===0)for(var p=0;p<l.length;++p)l[p]=r(i[p%i.length],s[p%s.length]);else{var h=this.bufferSync(t),d=this.bufferSync(e),f=function(n){var o=a.indexToLoc(n),p=o.slice(-t.rank);u.forEach(function(t){return p[t]=0});var f=h.locToIndex(p),v=o.slice(-e.rank);c.forEach(function(t){return v[t]=0});var m=d.locToIndex(v);l[n]=r(i[f],s[m])};for(p=0;p<l.length;++p)f(p)}return a.toTensor()},e.prototype.broadcastedBinaryComplexOp=function(t,e,n){var r=go(t.shape,e.shape),o=lr(r,"float32"),a=lr(r,"float32"),i=this.readSync(t.dataId),s=this.readSync(e.dataId),u=vo(t.shape,r),c=vo(e.shape,r),l=o.values,p=a.values;if(u.length+c.length===0)for(var h=0;h<l.length;h++){var d=h%i.length,f=h%s.length,v=n(i[2*d],i[2*d+1],s[2*f],s[2*f+1]);l[h]=v.real,p[h]=v.imag}else{var m=this.bufferSync(this.data.get(t.dataId).complexTensors.real),g=this.bufferSync(this.data.get(e.dataId).complexTensors.real),x=function(r){var a=o.indexToLoc(r),h=a.slice(-t.rank);u.forEach(function(t){return h[t]=0});var d=m.locToIndex(h),f=a.slice(-e.rank);c.forEach(function(t){return f[t]=0});var v=g.locToIndex(f),x=n(i[2*d],i[2*d+1],s[2*v],s[2*v+1]);l[r]=x.real,p[r]=x.imag};for(h=0;h<l.length;h++)x(h)}return this.complex(o.toTensor(),a.toTensor())},e.prototype.split=function(t,e,n){return zo(t,e,n)},e.prototype.dispose=function(){},e.prototype.floatPrecision=function(){return 32},e.prototype.epsilon=function(){return 1e-7},e.prototype.cropAndResize=function(t,e,n,r,o,a){for(var i=t.shape,s=i[0],u=i[1],c=i[2],l=i[3],p=e.shape[0],h=r[0],d=r[1],f=lr([p,h,d,l],t.dtype),v=this.readSync(e.dataId),m=this.readSync(n.dataId),g=this.readSync(t.dataId),x=t.strides,y=f.strides,b=0;b<p;b++){var w=4*b,C=v[w],E=v[w+1],R=v[w+2],I=v[w+3],k=m[b];if(!(k>=s))for(var S=h>1?(R-C)*(u-1)/(h-1):0,A=d>1?(I-E)*(c-1)/(d-1):0,D=0;D<h;D++){var N=h>1?C*(u-1)+D*S:.5*(C+R)*(u-1);if(N<0||N>u-1)for(var T=0;T<d;T++)for(var F=0;F<l;F++){var O=F+T*y[2]+D*y[1]+b*y[0];f.values[O]=a}else if("bilinear"===o){var _=Math.floor(N),M=Math.ceil(N),B=N-_;for(T=0;T<d;T++)if((q=d>1?E*(c-1)+T*A:.5*(E+I)*(c-1))<0||q>c-1)for(F=0;F<l;F++)O=F+T*y[2]+D*y[1]+b*y[0],f.values[O]=a;else{var P=Math.floor(q),L=Math.ceil(q),W=q-P;for(F=0;F<l;F++){var z=g[O=F+P*x[2]+_*x[1]+k*x[0]],U=g[O=F+L*x[2]+_*x[1]+k*x[0]],V=g[O=F+P*x[2]+M*x[1]+k*x[0]],G=z+(U-z)*W,H=V+(g[O=F+L*x[2]+M*x[1]+k*x[0]]-V)*W;O=F+T*y[2]+D*y[1]+b*y[0],f.values[O]=G+(H-G)*B}}}else for(T=0;T<d;++T){var q;if((q=d>1?E*(c-1)+T*A:.5*(E+I)*(c-1))<0||q>c-1)for(F=0;F<l;F++)O=F+T*y[2]+D*y[1]+b*y[0],f.values[O]=a;else{var K=Math.round(q),j=Math.round(N);for(F=0;F<l;F++){var X=F+K*x[2]+j*x[1]+k*x[0],$=F+T*y[2]+D*y[1]+b*y[0];f.values[$]=g[X]}}}}}return f.toTensor()},e.prototype.sparseToDense=function(t,e,n,r){var o=jr(0,t,n),a=o.sliceRank,i=o.numUpdates,s=o.sliceSize,u=o.strides,c=o.outputSize;return this.scatter(t,e,n,c,s,i,a,u,r,!1)},e.prototype.gatherND=function(t,e){var n=e.shape,r=n[n.length-1],o=Gr(t,e),a=o[0],i=o[1],s=o[2],u=o[3];if(0===i)return Dn([],a,t.dtype);for(var c=new dt([i,s],t.dtype),l=this.readSync(e.dataId),p=this.readSync(t.dataId),h=0;h<i;h++){for(var d=[],f=0,v=0;v<r;v++){var m=l[h*r+v];f+=m*u[v],d.push(m)}if(f<0||f>=t.size/s)throw new Error("Invalid indices: "+d+" does not index into "+t.shape);for(var g=0;g<s;g++)c.values[h*s+g]=p[f*s+g]}return c.toTensor().reshape(a)},e.prototype.scatterND=function(t,e,n){var r=jr(0,t,n),o=r.sliceRank,a=r.numUpdates,i=r.sliceSize,s=r.strides,u=r.outputSize,c=Tn(0);return this.scatter(t,e,n,u,i,a,o,s,c,!0)},e.prototype.fill=function(t,e,n){var r=M(n=n||q(e),R(t));return r.fill(e),_t.makeTensor(r,t,n,this)},e.prototype.onesLike=function(t){if("string"===t.dtype)throw new Error("onesLike is not supported for string tensors");return this.fill(t.shape,1,t.dtype)},e.prototype.zerosLike=function(t){var e=M(t.dtype,R(t.shape));return this.makeOutput(e,t.shape,t.dtype)},e.prototype.linspace=function(t,e,n){return Fo(t,e,n)},e.prototype.scatter=function(t,e,n,r,o,a,i,s,u,c){var l=[r/o,o],p=this.readSync(t.dataId),h=this.readSync(e.dataId);if(0===r)return Dn([],n,e.dtype);var d=new dt(l,e.dtype);d.values.fill(this.readSync(u.dataId)[0]);for(var f=0;f<a;f++){for(var v=[],m=0,g=0;g<i;g++){var x=p[f*i+g];v.push(x),m+=x*s[g]}if(m<0||m>=r/o)throw new Error("Invalid indices: "+v+" does not index into "+n);for(var y=0;y<o;y++)c?d.values[m*o+y]+=h[f*o+y]:d.values[m*o+y]=0===e.rank?h[0]:h[f*o+y]}return d.toTensor().reshape(n)},e}(ho);_t.registerBackend("cpu",function(){return new Tp},1),d({kernelName:"Square",backendName:"cpu",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=e.x,o=n;Dp(r,"square");for(var a=o.data.get(r.dataId).values,i=new Float32Array(a.length),s=0;s<a.length;++s){var u=a[s];i[s]=u*u}return{dataId:o.write(i,r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}}),d({kernelName:"Square",backendName:"webgl",kernelFunc:function(t){var e=t.inputs,n=t.backend,r=e.x,o=n,a=new ps(r.shape,"return x * x;");return o.runWebGLProgram(a,[r],r.dtype)}});var Fp=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}();u().get("IS_BROWSER")&&u().setPlatform("browser",new Fp);var Op,_p=function(){return require("node-fetch")},Mp=function(){function t(){this.util=require("util"),this.textEncoder=new this.util.TextEncoder}return t.prototype.fetch=function(t,e){return null!=u().global.fetch?u().global.fetch(t,e):(null==Op&&(Op=_p()),Op(t,e))},t.prototype.now=function(){var t=e.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}();u().get("IS_NODE")&&u().setPlatform("node",new Mp);var Bp={float32:4,int32:4,uint16:2,uint8:1,bool:1},Pp=4;function Lp(t,e){for(var n={},r=0,o=function(e){var o=e.name,a=e.dtype,i=e.shape,s=R(i),u=void 0;if("quantization"in e){var c=e.quantization;if("uint8"!==c.dtype&&"uint16"!==c.dtype)throw new Error("Weight "+e.name+" has unknown quantization dtype "+c.dtype+". Supported quantization dtypes are: 'uint8' and 'uint16'.");var l=Bp[c.dtype],p=t.slice(r,r+s*l),h="uint8"===c.dtype?new Uint8Array(p):new Uint16Array(p);if("float32"===a)u=Float32Array.from(h,function(t){return t*c.scale+c.min});else{if("int32"!==a)throw new Error("Unsupported dtype in weight '"+o+"': "+a);u=Int32Array.from(h,function(t){return Math.round(t*c.scale+c.min)})}r+=s*l}else if("string"===a){var d=R(e.shape);u=[];for(var f=0;f<d;f++){var v=new Uint32Array(t.slice(r,r+Pp))[0];r+=Pp;var m=new Uint8Array(t.slice(r,r+v));u.push(m),r+=v}}else{var g=Bp[a];if(p=t.slice(r,r+s*g),"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 '"+o+"': "+a);u=new Uint8Array(p)}r+=s*g}n[o]=Dn(u,i,a)},a=0,i=e;a<i.length;a++)o(i[a]);return n}function Wp(t){if(null===t)throw new Error("Invalid input value: "+JSON.stringify(t));var e=0,n=[];t.forEach(function(t){if(e+=t.byteLength,n.push(t.byteLength===t.buffer.byteLength?t:new t.constructor(t)),!(t instanceof Float32Array||t instanceof Int32Array||t instanceof Uint8Array))throw new Error("Unsupported TypedArray subtype: "+t.constructor.name)});var r=new Uint8Array(e),o=0;return n.forEach(function(t){r.set(new Uint8Array(t.buffer),o),o+=t.byteLength}),r.buffer}var zp=void 0!==n&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function Up(t){return zp?n.byteLength(t):new Blob([t]).size}function Vp(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 Gp(t){for(t=t.trim();t.endsWith("/");)t=t.slice(0,t.length-1);var e=t.split("/");return e[e.length-1]}function Hp(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:Up(JSON.stringify(t.modelTopology)),weightSpecsBytes:null==t.weightSpecs?0:Up(JSON.stringify(t.weightSpecs)),weightDataBytes:null==t.weightData?0:t.weightData.byteLength}}var qp=function(){function t(){this.saveRouters=[],this.loadRouters=[]}return t.getInstance=function(){return null==t.instance&&(t.instance=new t),t.instance},t.registerSaveRouter=function(e){t.getInstance().saveRouters.push(e)},t.registerLoadRouter=function(e){t.getInstance().loadRouters.push(e)},t.getSaveHandlers=function(e){return t.getHandlers(e,"save")},t.getLoadHandlers=function(e,n){return t.getHandlers(e,"load",n)},t.getHandlers=function(e,n,r){var o=[];return("load"===n?t.getInstance().loadRouters:t.getInstance().saveRouters).forEach(function(t){var n=t(e,r);null!==n&&o.push(n)}),o},t}(),Kp="://",jp=function(){function t(){this.managers={}}return t.getInstance=function(){return null==t.instance&&(t.instance=new t),t.instance},t.registerManager=function(e,n){b(null!=e,function(){return"scheme must not be undefined or null."}),e.endsWith(Kp)&&(e=e.slice(0,e.indexOf(Kp))),b(e.length>0,function(){return"scheme must not be an empty string."});var r=t.getInstance();b(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 Xp(t){if(-1===t.indexOf(Kp))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+jp.getSchemes().join(","));return{scheme:t.split(Kp)[0],path:t.split(Kp)[1]}}function $p(t,e,n){return void 0===n&&(n=!1),a(this,void 0,void 0,function(){var r,o,a,s,u,c,l,p,h;return i(this,function(i){switch(i.label){case 0:return b(t!==e,function(){return"Old path and new path are the same: '"+t+"'"}),b((r=qp.getLoadHandlers(t)).length>0,function(){return"Copying failed because no load handler is found for source URL "+t+"."}),b(r.length<2,function(){return"Copying failed because more than one ("+r.length+") load handlers for source URL "+t+"."}),o=r[0],b((a=qp.getSaveHandlers(e)).length>0,function(){return"Copying failed because no save handler is found for destination URL "+e+"."}),b(a.length<2,function(){return"Copying failed because more than one ("+r.length+") save handlers for destination URL "+e+"."}),s=a[0],u=Xp(t).scheme,c=Xp(t).path,l=u===Xp(t).scheme,[4,o.load()];case 1:return p=i.sent(),n&&l?[4,jp.getManager(u).removeModel(c)]:[3,3];case 2:i.sent(),i.label=3;case 3:return[4,s.save(p)];case 4:return h=i.sent(),!n||l?[3,6]:[4,jp.getManager(u).removeModel(c)];case 5:i.sent(),i.label=6;case 6:return[2,h.modelArtifactsInfo]}})})}var Yp="models_store",Qp="model_info_store";function Jp(){if(!u().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 Zp(t){var e=t.result;e.createObjectStore(Yp,{keyPath:"modelPath"}),e.createObjectStore(Qp,{keyPath:"modelPath"})}var th=function(){function t(t){if(this.indexedDB=Jp(),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 a(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 a(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 o=n.indexedDB.open("tensorflowjs",1);o.onupgradeneeded=function(){return Zp(o)},o.onsuccess=function(){var a=o.result;if(null==e){var i=a.transaction(Yp,"readonly"),s=i.objectStore(Yp).get(n.modelPath);s.onsuccess=function(){if(null==s.result)return a.close(),r(new Error("Cannot find model with path '"+n.modelPath+"' in IndexedDB."));t(s.result.modelArtifacts)},s.onerror=function(t){return a.close(),r(s.error)},i.oncomplete=function(){return a.close()}}else{var u,c=Hp(e),l=a.transaction(Qp,"readwrite"),p=l.objectStore(Qp),h=p.put({modelPath:n.modelPath,modelArtifactsInfo:c});h.onsuccess=function(){var o=(u=a.transaction(Yp,"readwrite")).objectStore(Yp).put({modelPath:n.modelPath,modelArtifacts:e,modelArtifactsInfo:c});o.onsuccess=function(){return t({modelArtifactsInfo:c})},o.onerror=function(t){var e=(p=l.objectStore(Qp)).delete(n.modelPath);e.onsuccess=function(){return a.close(),r(o.error)},e.onerror=function(t){return a.close(),r(o.error)}}},h.onerror=function(t){return a.close(),r(h.error)},l.oncomplete=function(){null==u?a.close():u.oncomplete=function(){return a.close()}}}},o.onerror=function(t){return r(o.error)}})},t.URL_SCHEME="indexeddb://",t}(),eh=function(t){return u().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(th.URL_SCHEME)?(e=t.slice(th.URL_SCHEME.length),new th(e)):null;var e};qp.registerSaveRouter(eh),qp.registerLoadRouter(eh);var nh=function(){function t(){this.indexedDB=Jp()}return t.prototype.listModels=function(){return a(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 Zp(r)},r.onsuccess=function(){var t=r.result,o=t.transaction(Qp,"readonly"),a=o.objectStore(Qp).getAll();a.onsuccess=function(){for(var t={},n=0,r=a.result;n<r.length;n++){var o=r[n];t[o.modelPath]=o.modelArtifactsInfo}e(t)},a.onerror=function(e){return t.close(),n(a.error)},o.oncomplete=function(){return t.close()}},r.onerror=function(t){return n(r.error)}})]})})},t.prototype.removeModel=function(t){return a(this,void 0,void 0,function(){var e=this;return i(this,function(n){var r;return t=(r=t).startsWith(th.URL_SCHEME)?r.slice(th.URL_SCHEME.length):r,[2,new Promise(function(n,r){var o=e.indexedDB.open("tensorflowjs",1);o.onupgradeneeded=function(){return Zp(o)},o.onsuccess=function(){var e,a=o.result,i=a.transaction(Qp,"readwrite"),s=i.objectStore(Qp),u=s.get(t);u.onsuccess=function(){if(null==u.result)return a.close(),r(new Error("Cannot find model with path '"+t+"' in IndexedDB."));var o=s.delete(t),i=function(){var o=(e=a.transaction(Yp,"readwrite")).objectStore(Yp).delete(t);o.onsuccess=function(){return n(u.result.modelArtifactsInfo)},o.onerror=function(t){return r(u.error)}};o.onsuccess=i,o.onerror=function(t){return i(),a.close(),r(u.error)}},u.onerror=function(t){return a.close(),r(u.error)},i.oncomplete=function(){null==e?a.close():e.oncomplete=function(){return a.close()}}},o.onerror=function(t){return r(o.error)}})]})})},t}();if(u().getBool("IS_BROWSER"))try{jp.registerManager(th.URL_SCHEME,new nh)}catch(r){}var rh="/",oh="tensorflowjs_models",ah="info",ih="model_topology",sh="weight_specs",uh="weight_data",ch="model_metadata";function lh(t){return{info:[oh,t,ah].join(rh),topology:[oh,t,ih].join(rh),weightSpecs:[oh,t,sh].join(rh),weightData:[oh,t,uh].join(rh),modelMetadata:[oh,t,ch].join(rh)}}function ph(t){var e=t.split(rh);if(e.length<3)throw new Error("Invalid key format: "+t);return e.slice(1,e.length-1).join(rh)}var hh=function(){function t(t){if(!u().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=lh(this.modelPath)}return t.prototype.save=function(t){return a(this,void 0,void 0,function(){var e,r,o;return i(this,function(a){if(t.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");e=JSON.stringify(t.modelTopology),r=JSON.stringify(t.weightSpecs),o=Hp(t);try{return this.LS.setItem(this.keys.info,JSON.stringify(o)),this.LS.setItem(this.keys.topology,e),this.LS.setItem(this.keys.weightSpecs,r),this.LS.setItem(this.keys.weightData,(i=t.weightData,zp?n.from(i).toString("base64"):btoa(String.fromCharCode.apply(null,new Uint8Array(i))))),this.LS.setItem(this.keys.modelMetadata,JSON.stringify({format:t.format,generatedBy:t.generatedBy,convertedBy:t.convertedBy})),[2,{modelArtifactsInfo:o}]}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="+o.modelTopologyBytes+", weightSpecsBytes="+o.weightSpecsBytes+", weightDataBytes="+o.weightDataBytes+".")}var i;return[2]})})},t.prototype.load=function(){return a(this,void 0,void 0,function(){var t,e,r,o,a,s,u;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==(r=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=r,null==(o=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=o,null!=(a=this.LS.getItem(this.keys.modelMetadata))&&(s=JSON.parse(a),e.format=s.format,e.generatedBy=s.generatedBy,e.convertedBy=s.convertedBy),null==(u=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(zp){var e=n.from(t,"base64");return e.buffer.slice(e.byteOffset,e.byteOffset+e.byteLength)}for(var r=atob(t),o=new Uint8Array(r.length),a=0;a<r.length;++a)o.set([r.charCodeAt(a)],a);return o.buffer}(u),[2,e]})})},t.URL_SCHEME="localstorage://",t}(),dh=function(t){return u().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(hh.URL_SCHEME)?(e=t.slice(hh.URL_SCHEME.length),new hh(e)):null;var e};qp.registerSaveRouter(dh),qp.registerLoadRouter(dh);var fh=function(){function t(){b(u().getBool("IS_BROWSER"),function(){return"Current environment is not a web browser"}),b(void 0!==window.localStorage,function(){return"Current browser does not appear to support localStorage"}),this.LS=window.localStorage}return t.prototype.listModels=function(){return a(this,void 0,void 0,function(){var t,e,n,r,o,a;return i(this,function(i){for(t={},e=oh+rh,n=rh+ah,r=0;r<this.LS.length;++r)(o=this.LS.key(r)).startsWith(e)&&o.endsWith(n)&&(a=ph(o),t[a]=JSON.parse(this.LS.getItem(o)));return[2,t]})})},t.prototype.removeModel=function(t){return a(this,void 0,void 0,function(){var e,n;return i(this,function(r){var o;if(t=(o=t).startsWith(hh.URL_SCHEME)?o.slice(hh.URL_SCHEME.length):o,e=lh(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(u().getBool("IS_BROWSER"))try{jp.registerManager(hh.URL_SCHEME,new fh)}catch(r){}var vh="model",mh=".json",gh=".weights.bin";function xh(t){return new Promise(function(t){return setTimeout(t)}).then(t)}var yh=function(){function t(e){if(!u().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=vh),this.modelTopologyFileName=e+mh,this.weightDataFileName=e+gh}return t.prototype.save=function(t){return a(this,void 0,void 0,function(){var e,n,r,o,a,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},o=window.URL.createObjectURL(new Blob([JSON.stringify(r)],{type:"application/json"})),(a=null==this.jsonAnchor?document.createElement("a"):this.jsonAnchor).download=this.modelTopologyFileName,a.href=o,[4,xh(function(){return a.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,xh(function(){return s.dispatchEvent(new MouseEvent("click"))})]);case 3:i.sent(),i.label=4;case 4:return[2,{modelArtifactsInfo:Hp(t)}]}})})},t.URL_SCHEME="downloads://",t}(),bh=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 a(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,o){var a=new FileReader;a.onload=function(a){var i=JSON.parse(a.target.result),s=i.modelTopology;if(null!=s){0===e.length&&r({modelTopology:s});var u=i.weightsManifest;if(null!=u){var c;try{c=n.checkManifestAndWeightFiles(u,e)}catch(t){return void o(t)}var l=[],p=[],h=[];u.forEach(function(t){t.paths.forEach(function(t){p.push(t),h.push(null)}),l.push.apply(l,t.weights)}),u.forEach(function(t){t.paths.forEach(function(t){var e=new FileReader;e.onload=function(e){var n=e.target.result,o=p.indexOf(t);h[o]=n,-1===h.indexOf(null)&&r({modelTopology:s,weightSpecs:l,weightData:Vp(h)})},e.onerror=function(e){return o("Failed to weights data from file of path '"+t+"'.")},e.readAsArrayBuffer(c[t])})})}else o(new Error("weightManifest field is missing from file "+t.name))}else o(new Error("modelTopology field is missing from file "+t.name))},a.onerror=function(e){return o("Failed to read model topology and weights manifest JSON from file '"+t.name+"'. BrowserFiles supports loading Keras-style tf.Model artifacts only.")},a.readAsText(t)})]})})},t.prototype.checkManifestAndWeightFiles=function(t,e){for(var n=[],r=e.map(function(t){return Gp(t.name)}),o={},a=0,i=t;a<i.length;a++)i[a].paths.forEach(function(t){var a=Gp(t);if(-1!==n.indexOf(a))throw new Error("Duplicate file basename found in weights manifest: '"+a+"'");if(n.push(a),-1===r.indexOf(a))throw new Error("Weight file with basename '"+a+"' is not provided.");o[t]=e[r.indexOf(a)]});if(n.length!==e.length)throw new Error("Mismatch in the number of files in weights manifest ("+n.length+") and the number of weight files provided ("+e.length+").");return o},t}();function wh(t,e,n,r){!function(t){b(null!=t&&Array.isArray(t)&&t.length>0,function(){return"promises must be a none empty array"})}(t),function(t,e){b(t>=0&&t<=1,function(){return"Progress fraction must be in range [0, 1], but got startFraction "+t}),b(e>=0&&e<=1,function(){return"Progress fraction must be in range [0, 1], but got endFraction "+e}),b(e>=t,function(){return"startFraction must be no more than endFraction, but got startFraction "+t+" and endFraction "+e})}(n=null==n?0:n,r=null==r?1:r);var o=0;return Promise.all(t.map(function(a){return a.then(function(a){var i=n+ ++o/t.length*(r-n);return e(i),a}),a}))}function Ch(t,e){return a(this,void 0,void 0,function(){var n,r,o,a,s,c,l,p,h;return i(this,function(i){switch(i.label){case 0:return null==e&&(e={}),n=null==e.fetchFunc?u().platform.fetch:e.fetchFunc,r=t.map(function(t){return n(t,e.requestInit,{isBinary:!0})}),o=0,a=.5,null!=e.onProgress?[3,2]:[4,Promise.all(r)];case 1:return s=i.sent(),[3,4];case 2:return[4,wh(r,e.onProgress,o,a)];case 3:s=i.sent(),i.label=4;case 4:return c=s.map(function(t){return t.arrayBuffer()}),l=.5,p=1,null!=e.onProgress?[3,6]:[4,Promise.all(c)];case 5:return h=i.sent(),[3,8];case 6:return[4,wh(c,e.onProgress,l,p)];case 7:h=i.sent(),i.label=8;case 8:return[2,h]}})})}function Eh(t){var e=this;return function(n,r,o){return void 0===r&&(r=""),a(e,void 0,void 0,function(){var e,a,s,u,c,l,p,h,d,f;return i(this,function(i){switch(i.label){case 0:if(e=n.map(function(){return!1}),a={},s=null!=o?o.map(function(){return!1}):[],u=[],n.forEach(function(t,n){var r=0;t.weights.forEach(function(t){var i="quantization"in t?t.quantization.dtype:t.dtype,c=Bp[i]*R(t.shape),l=function(){e[n]=!0,null==a[n]&&(a[n]=[]),a[n].push({manifestEntry:t,groupOffset:r,sizeBytes:c})};null!=o?o.forEach(function(e,n){e===t.name&&(l(),s[n]=!0)}):l(),u.push(t.name),r+=c})}),!s.every(function(t){return t}))throw c=o.filter(function(t,e){return!s[e]}),new Error("Could not find weights in manifest with names: "+c.join(", ")+". \nManifest JSON has weights with names: "+u.join(", ")+".");return l=e.reduce(function(t,e,n){return e&&t.push(n),t},[]),p=[],l.forEach(function(t){n[t].paths.forEach(function(t){var e=r+(r.endsWith("/")?"":"/")+t;p.push(e)})}),[4,t(p)];case 1:return h=i.sent(),d={},f=0,l.forEach(function(t){for(var e=n[t].paths.length,r=0,o=0;o<e;o++)r+=h[f+o].byteLength;for(var i=new ArrayBuffer(r),s=new Uint8Array(i),u=0,c=0;c<e;c++){var l=new Uint8Array(h[f+c]);s.set(l,u),u+=l.byteLength}a[t].forEach(function(t){var e=Lp(i.slice(t.groupOffset,t.groupOffset+t.sizeBytes),[t.manifestEntry]);for(var n in e)d[n]=e[n]}),f+=e}),[2,d]}})})}}qp.registerSaveRouter(function(t){return u().getBool("IS_BROWSER")&&!Array.isArray(t)&&t.startsWith(yh.URL_SCHEME)?(void 0===(e=t.slice(yh.URL_SCHEME.length))&&(e="model"),new yh(e)):null;var e});var Rh=function(){function t(t,e){if(this.DEFAULT_METHOD="POST",null==e&&(e={}),this.weightPathPrefix=e.weightPathPrefix,this.onProgress=e.onProgress,null!=e.fetchFunc?(b("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=u().platform.fetch,b(null!=t&&t.length>0,function(){return"URL path for http must not be null, undefined or empty."}),Array.isArray(t)&&b(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 a(this,void 0,void 0,function(){var e,n,r,o;return i(this,function(a){switch(a.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((o=a.sent()).ok)return[2,{modelArtifactsInfo:Hp(t),responses:[o]}];throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+o.status+".")}})})},t.prototype.load=function(){return a(this,void 0,void 0,function(){var t,e,n,r,o,a,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,o=e.weightsManifest,null==r&&null==o)throw new Error("The JSON from HTTP path "+this.path+" contains neither model topology or manifest for weights.");return null==o?[3,7]:[4,this.loadWeights(o)];case 6:u=i.sent(),a=u[0],s=u[1],i.label=7;case 7:return[2,{modelTopology:r,weightSpecs:a,weightData:s}]}})})},t.prototype.loadWeights=function(t){return a(this,void 0,void 0,function(){var e,n,r,o,a,s,u,c,l,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],o=n[1],a=this.weightPathPrefix||r,s=[],u=0,c=t;u<c.length;u++)l=c[u],s.push.apply(s,l.weights);return p=[],t.forEach(function(t){t.paths.forEach(function(t){p.push(a+t+o)})}),[4,Ch(p,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress})];case 1:return h=i.sent(),[2,[s,Vp(h)]]}})})},t.URL_SCHEME_REGEX=/^https?:\/\//,t}();function Ih(t){return null!=t.match(Rh.URL_SCHEME_REGEX)}var kh=function(t,e){return"undefined"==typeof fetch?null:(Array.isArray(t)?t.every(function(t){return Ih(t)}):Ih(t))?Sh(t,{onProgress:e}):null};function Sh(t,e){return new Rh(t,e)}qp.registerSaveRouter(kh),qp.registerLoadRouter(kh);var Ah=function(){function t(t){this.modelArtifacts=t}return t.prototype.load=function(){return a(this,void 0,void 0,function(){return i(this,function(t){return[2,this.modelArtifacts]})})},t}(),Dh=function(){function t(t){this.saveHandler=t}return t.prototype.save=function(t){return a(this,void 0,void 0,function(){return i(this,function(e){return[2,this.saveHandler(t)]})})},t}(),Nh=Object.freeze({browserFiles:function(t){return new bh(t)},browserHTTPRequest:function(t,e){return Sh(t,e)},concatenateArrayBuffers:Vp,decodeWeights:Lp,encodeWeights:function(t,e){return a(this,void 0,void 0,function(){var n,r,o,s,u,c=this;return i(this,function(l){switch(l.label){case 0:for(n=[],r=[],o=Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t),s=function(s){var u=o[s],l=Array.isArray(t)?t[s].tensor:t[u];if("float32"!==l.dtype&&"int32"!==l.dtype&&"bool"!==l.dtype&&"string"!==l.dtype)throw new Error("Unsupported dtype in weight '"+u+"': "+l.dtype);var p={name:u,shape:l.shape,dtype:l.dtype};if("string"===l.dtype){var h=new Promise(function(t){return a(c,void 0,void 0,function(){var e,n,r,o,a,s,u;return i(this,function(i){switch(i.label){case 0:return[4,l.bytes()];case 1:for(e=i.sent(),n=e.reduce(function(t,e){return t+e.length},0)+Pp*e.length,r=new Uint8Array(n),o=0,a=0;a<e.length;a++)s=e[a],u=new Uint8Array(new Uint32Array([s.length]).buffer),r.set(u,o),o+=Pp,r.set(s,o),o+=s.length;return t(r),[2]}})})});r.push(h)}else r.push(l.data());null!=e&&(p.group=e),n.push(p)},u=0;u<o.length;++u)s(u);return[4,Promise.all(r)];case 1:return[2,{data:Wp(l.sent()),specs:n}]}})})},fromMemory:function(t,e,n,r){return 1===arguments.length?null!=t.modelTopology||null!=t.weightSpecs?new Ah(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 Ah({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 Ah({modelTopology:t,weightSpecs:e,weightData:n,trainingConfig:r}))},getLoadHandlers:function(t,e){return qp.getLoadHandlers(t,e)},getModelArtifactsInfoForJSON:Hp,getSaveHandlers:function(t){return qp.getSaveHandlers(t)},http:Sh,isHTTPScheme:Ih,loadWeights:function(t,e,n,r){return void 0===e&&(e=""),a(this,void 0,void 0,function(){return i(this,function(o){return[2,Eh(function(t){return Ch(t,{requestInit:r})})(t,e,n)]})})},registerLoadRouter:function(t){return qp.registerLoadRouter(t)},registerSaveRouter:function(t){return qp.registerSaveRouter(t)},weightsLoaderFactory:Eh,withSaveHandler:function(t){return new Dh(t)},copyModel:function(t,e){return a(this,void 0,void 0,function(){return i(this,function(n){return[2,$p(t,e,!1)]})})},listModels:function(){return a(this,void 0,void 0,function(){var t,e,n,r,o,a,s;return i(this,function(i){switch(i.label){case 0:t=jp.getSchemes(),e={},n=0,r=t,i.label=1;case 1:return n<r.length?(o=r[n],[4,jp.getManager(o).listModels()]):[3,4];case 2:for(s in a=i.sent())e[o+Kp+s]=a[s];i.label=3;case 3:return n++,[3,1];case 4:return[2,e]}})})},moveModel:function(t,e){return a(this,void 0,void 0,function(){return i(this,function(n){return[2,$p(t,e,!0)]})})},removeModel:function(t){return a(this,void 0,void 0,function(){var e;return i(this,function(n){return e=Xp(t),[2,jp.getManager(e.scheme).removeModel(e.path)]})})}});exports.io=Nh;var Th=In({confusionMatrix_:function(t,e,n){var r=dn(t,"labels","confusionMatrix"),o=dn(e,"predictions","confusionMatrix");b(null==n||n>0&&Number.isInteger(n),function(){return"If provided, numClasses must be a positive integer, but got "+n}),b(1===r.rank,function(){return"Expected the rank of labels to be 1, but got "+r.rank}),b(1===o.rank,function(){return"Expected the rank of predictions to be 1, but got "+o.rank}),b(r.shape[0]===o.shape[0],function(){return"Mismatch in the number of examples: "+r.shape[0]+" vs. "+o.shape[0]+". Labels and predictions should have the same number of elements."}),b(n>0&&Number.isInteger(n),function(){return"numClasses is required to be a positive integer, but got "+n});var a=br(r.asType("int32"),n),i=br(o.asType("int32"),n);return a.transpose().matMul(i).asType("int32")}}),Fh=Object.freeze({confusionMatrix:Th});exports.math=Fh;var Oh=In({fromPixels_:function(t,e){if(void 0===e&&(e=3),e>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");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 _t.fromPixels(t,e)}}),_h=Object.freeze({toPixels:function(t,e){return a(this,void 0,void 0,function(){var n,r,o,a,s,u,c,l,p,h,d,f,v,m,g,x,y,b,w,C,E,R,I;return i(this,function(i){switch(i.label){case 0:if(n=dn(t,"img","toPixels"),t instanceof gt||(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),o=r[0],a=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(),c=n.min(),l=n.max(),[4,Promise.all([c.data(),l.data()])];case 2:if(p=i.sent(),h=p[0],d=p[1],f=h[0],v=d[0],c.dispose(),l.dispose(),"float32"===n.dtype){if(f<0||v>1)throw new Error("Tensor values for a float32 Tensor must be in the range [0 - 1] but got range ["+f+" - "+v+"].")}else{if("int32"!==n.dtype)throw new Error("Unsupported type for toPixels: "+n.dtype+". Please use float32 or int32 tensors.");if(f<0||v>255)throw new Error("Tensor values for a int32 Tensor must be in the range [0 - 255] but got range ["+f+" - "+v+"].")}for(m="float32"===n.dtype?255:1,g=new Uint8ClampedArray(a*o*4),x=0;x<o*a;++x)y=void 0,b=void 0,w=void 0,C=void 0,1===s?(y=u[x]*m,b=u[x]*m,w=u[x]*m,C=255):3===s?(y=u[3*x]*m,b=u[3*x+1]*m,w=u[3*x+2]*m,C=255):4===s&&(y=u[4*x]*m,b=u[4*x+1]*m,w=u[4*x+2]*m,C=u[4*x+3]*m),g[0+(E=4*x)]=Math.round(y),g[E+1]=Math.round(b),g[E+2]=Math.round(w),g[E+3]=Math.round(C);return null!=e&&(e.width=a,e.height=o,R=e.getContext("2d"),I=new ImageData(g,a,o),R.putImageData(I,0,0)),n!==t&&n.dispose(),[2,g]}})})},fromPixels:Oh}),Mh=function(){function t(){}return t.prototype.getClassName=function(){return this.constructor.className},t.fromConfig=function(t,e){return new t(e)},t}(),Bh=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 Ph(t){b(null!=t.className,function(){return"Class being registered does not have the static className property defined."}),b("string"==typeof t.className,function(){return"className is required to be a string, but got type "+typeof t.className}),b(t.className.length>0,function(){return"Class being registered has an empty-string as its className, which is disallowed."}),Bh.register(t)}exports.browser=_h;var Lh=Object.freeze({Serializable:Mh,SerializationMap:Bh,registerClass:Ph}),Wh=.001,zh=.1;function Uh(){return 32===_t.backend.floatPrecision()?Wh:zh}function Vh(t,e,n){var r=!0;if((W(t)||W(e))&&(r=!1),W(t)&&W(e)&&(r=!0),r){var o=t.constructor.name,a=e.constructor.name;if(o!==a)throw new Error("Arrays are of different type. Actual: "+o+". Expected: "+a)}if(Array.isArray(t)&&Array.isArray(e)){var i=pn(t),s=pn(e);if(!I(i,s))throw new Error("Arrays have different shapes. Actual: ["+i+"]. Expected: ["+s+"]")}var u=W(t)?t:E(t),c=W(e)?e:E(e);if(u.length!==c.length)throw new Error("Arrays have different lengths actual: "+u.length+" vs expected: "+c.length+".\nActual:   "+u+".\nExpected: "+c+".");for(var l=0;l<c.length;++l){var p=u[l],h=c[l];if(!n(p,h))throw new Error("Arrays differ: actual["+l+"] = "+p+", expected["+l+"] = "+h+".\nActual:   "+u+".\nExpected: "+c+".")}}function Gh(t,e,n){return!isFinite(t)&&!isFinite(e)||!(isNaN(t)||isNaN(e)||Math.abs(t-e)>n)}exports.serialization=Lh;var Hh=Object.freeze({TEST_EPSILON_FLOAT16:zh,expectArraysClose:function(t,e,n){return null==n&&(n=Uh()),Vh(t,e,function(t,e){return Gh(t,e,n)})},testEpsilon:Uh,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 V(t)||V(t[0])||V(e)||V(e[0])?Vh(t,n,function(t,e){return t==e}):Vh(t,e,function(t,e){return Gh(t,e,0)})},expectNumbersClose:function(t,e,n){if(null==n&&(n=Uh()),!Gh(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))}}),qh="1.3.2";exports.version_core=qh,exports.test_util=Hh;var Kh=Object.freeze({gpgpu_util:Ri,webgl_util:ze,forceHalfFloat:function(){u().set("WEBGL_FORCE_F16_TEXTURES",!0)},MathBackendWebGL:Vs,setWebGLContext:Vt,GPGPUContext:Ii}),jh=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return o(e,t),e.prototype.minimize=function(t,e,n){void 0===e&&(e=!1);var r=this.computeGradients(t,n),o=r.value,a=r.grads;if(null!=n){var i=n.map(function(t){return{name:t.name,tensor:a[t.name]}});this.applyGradients(i)}else this.applyGradients(a);return Qe(a),e?o:(o.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 io(t,e)},e.prototype.dispose=function(){null!=this.iterations_&&Qe(this.iterations_)},e.prototype.saveIterations=function(){return a(this,void 0,void 0,function(){return i(this,function(t){return null==this.iterations_&&(this.iterations_=0),[2,{name:"iter",tensor:Tn(this.iterations_,"int32")}]})})},e.prototype.getWeights=function(){return a(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 a(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 a(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}(Mh);exports.Optimizer=jh,exports.webgl=Kh,Object.defineProperty(jh,Symbol.hasInstance,{value:function(t){return null!=t.minimize&&null!=t.computeGradients&&null!=t.applyGradients}});var Xh=function(t){function e(e,n,r){void 0===r&&(r=null);var o=t.call(this)||this;return o.learningRate=e,o.rho=n,o.epsilon=r,o.accumulatedGrads=[],o.accumulatedUpdates=[],null==r&&(o.epsilon=_t.backend.epsilon()),o}return o(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 o=_t.registeredVariables[n];null==e.accumulatedGrads[r]&&(e.accumulatedGrads[r]={originalName:n+"/accum_grad",variable:Ye(function(){return qn(o).variable(!1)})}),null==e.accumulatedUpdates[r]&&(e.accumulatedUpdates[r]={originalName:n+"/accum_var",variable:Ye(function(){return qn(o).variable(!1)})});var a=Array.isArray(t)?t[r].tensor:t[n];if(null!=a){var i=e.accumulatedGrads[r].variable,s=e.accumulatedUpdates[r].variable;Ye(function(){var t=i.mul(e.rho).add(a.square().mul(1-e.rho)),n=s.add(e.epsilon).sqrt().div(i.add(e.epsilon).sqrt()).mul(a),r=s.mul(e.rho).add(n.square().mul(1-e.rho));i.assign(t),s.assign(r);var u=n.mul(-e.learningRate).add(o);o.assign(u)})}}),this.incrementIterations()},e.prototype.dispose=function(){null!=this.accumulatedUpdates&&(Qe(this.accumulatedGrads.map(function(t){return t.variable})),Qe(this.accumulatedUpdates.map(function(t){return t.variable})))},e.prototype.getWeights=function(){return a(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 a(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}(jh);exports.AdadeltaOptimizer=Xh,Ph(Xh);var $h=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 o(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 o=_t.registeredVariables[n];null==e.accumulatedGrads[r]&&(e.accumulatedGrads[r]={originalName:n+"/accumulator",variable:Ye(function(){return Un(o.shape,e.initialAccumulatorValue).variable(!1)})});var a=Array.isArray(t)?t[r].tensor:t[n];if(null!=a){var i=e.accumulatedGrads[r].variable;Ye(function(){var t=i.add(a.square());i.assign(t);var n=a.div(t.add(_t.backend.epsilon()).sqrt()).mul(-e.learningRate).add(o);o.assign(n)})}}),this.incrementIterations()},e.prototype.dispose=function(){null!=this.accumulatedGrads&&Qe(this.accumulatedGrads.map(function(t){return t.variable}))},e.prototype.getWeights=function(){return a(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 a(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}(jh);exports.AdagradOptimizer=$h,Ph($h);var Yh=function(t){function e(e,n,r,o){void 0===o&&(o=null);var a=t.call(this)||this;return a.learningRate=e,a.beta1=n,a.beta2=r,a.epsilon=o,a.accumulatedFirstMoment=[],a.accumulatedSecondMoment=[],Ye(function(){a.accBeta1=Tn(n).variable(),a.accBeta2=Tn(r).variable()}),null==o&&(a.epsilon=_t.backend.epsilon()),a}return o(e,t),e.prototype.applyGradients=function(t){var e=this,n=Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t);Ye(function(){var r=lc(1,e.accBeta1),o=lc(1,e.accBeta2);n.forEach(function(n,a){var i=_t.registeredVariables[n];null==e.accumulatedFirstMoment[a]&&(e.accumulatedFirstMoment[a]={originalName:n+"/m",variable:Ye(function(){return qn(i).variable(!1)})}),null==e.accumulatedSecondMoment[a]&&(e.accumulatedSecondMoment[a]={originalName:n+"/v",variable:Ye(function(){return qn(i).variable(!1)})});var s=Array.isArray(t)?t[a].tensor:t[n];if(null!=s){var u=e.accumulatedFirstMoment[a].variable,c=e.accumulatedSecondMoment[a].variable,l=u.mul(e.beta1).add(s.mul(1-e.beta1)),p=c.mul(e.beta2).add(s.square().mul(1-e.beta2)),h=l.div(r),d=p.div(o);u.assign(l),c.assign(p);var f=h.div(d.sqrt().add(e.epsilon)).mul(-e.learningRate).add(i);i.assign(f)}}),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&&Qe(this.accumulatedFirstMoment.map(function(t){return t.variable})),null!=this.accumulatedSecondMoment&&Qe(this.accumulatedSecondMoment.map(function(t){return t.variable}))},e.prototype.getWeights=function(){return a(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 a(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(),Ye(function(){n.accBeta1.assign(ic(n.beta1,n.iterations_+1)),n.accBeta2.assign(ic(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}(jh);exports.AdamOptimizer=Yh,Ph(Yh);var Qh=function(t){function e(e,n,r,o,a){void 0===o&&(o=null),void 0===a&&(a=0);var i=t.call(this)||this;return i.learningRate=e,i.beta1=n,i.beta2=r,i.epsilon=o,i.decay=a,i.accumulatedFirstMoment=[],i.accumulatedWeightedInfNorm=[],Ye(function(){i.iteration=Tn(0).variable(),i.accBeta1=Tn(n).variable()}),null==o&&(i.epsilon=_t.backend.epsilon()),i}return o(e,t),e.prototype.applyGradients=function(t){var e=this,n=Array.isArray(t)?t.map(function(t){return t.name}):Object.keys(t);Ye(function(){var r=lc(1,e.accBeta1),o=Xu(-e.learningRate,e.iteration.mul(e.decay).add(1));n.forEach(function(n,a){var i=_t.registeredVariables[n];null==e.accumulatedFirstMoment[a]&&(e.accumulatedFirstMoment[a]={originalName:n+"/m",variable:qn(i).variable(!1)}),null==e.accumulatedWeightedInfNorm[a]&&(e.accumulatedWeightedInfNorm[a]={originalName:n+"/v",variable:qn(i).variable(!1)});var s=Array.isArray(t)?t[a].tensor:t[n];if(null!=s){var u=e.accumulatedFirstMoment[a].variable,c=e.accumulatedWeightedInfNorm[a].variable,l=u.mul(e.beta1).add(s.mul(1-e.beta1)),p=c.mul(e.beta2),h=s.abs(),d=p.maximum(h);u.assign(l),c.assign(d);var f=o.div(r).mul(l.div(d.add(e.epsilon))).add(i);i.assign(f)}}),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&&Qe(this.accumulatedFirstMoment.map(function(t){return t.variable})),null!=this.accumulatedWeightedInfNorm&&Qe(this.accumulatedWeightedInfNorm.map(function(t){return t.variable}))},e.prototype.getWeights=function(){return a(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 a(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}(jh);exports.AdamaxOptimizer=Qh,Ph(Qh);var Jh=function(t){function e(e){var n=t.call(this)||this;return n.learningRate=e,n.setLearningRate(e),n}return o(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 o=Array.isArray(t)?t[r].tensor:t[n];if(null!=o){var a=_t.registeredVariables[n];Ye(function(){var t=e.c.mul(o).add(a);a.assign(t)})}}),this.incrementIterations()},e.prototype.setLearningRate=function(t){this.learningRate=t,null!=this.c&&this.c.dispose(),this.c=Je(Tn(-t))},e.prototype.dispose=function(){this.c.dispose()},e.prototype.getWeights=function(){return a(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 a(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}(jh);exports.SGDOptimizer=Jh,Ph(Jh);var Zh=function(t){function e(e,n,r){void 0===r&&(r=!1);var o=t.call(this,e)||this;return o.learningRate=e,o.momentum=n,o.useNesterov=r,o.accumulations=[],o.m=Tn(o.momentum),o}return o(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 o=_t.registeredVariables[n];null==e.accumulations[r]&&(e.accumulations[r]={originalName:n+"/momentum",variable:Ye(function(){return qn(o).variable(!1)})});var a=e.accumulations[r].variable,i=Array.isArray(t)?t[r].tensor:t[n];null!=i&&Ye(function(){var t,n=e.m.mul(a).add(i);t=e.useNesterov?e.c.mul(i.add(n.mul(e.m))).add(o):e.c.mul(n).add(o),a.assign(n),o.assign(t)})}),this.incrementIterations()},e.prototype.dispose=function(){this.m.dispose(),null!=this.accumulations&&Qe(this.accumulations.map(function(t){return t.variable}))},e.prototype.setMomentum=function(t){this.momentum=t},e.prototype.getWeights=function(){return a(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 a(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}(Jh);exports.MomentumOptimizer=Zh,Ph(Zh);var td=function(t){function e(e,n,r,o,a){void 0===n&&(n=.9),void 0===r&&(r=0),void 0===o&&(o=null),void 0===a&&(a=!1);var i=t.call(this)||this;return i.learningRate=e,i.decay=n,i.momentum=r,i.epsilon=o,i.accumulatedMeanSquares=[],i.accumulatedMoments=[],i.accumulatedMeanGrads=[],i.centered=a,null==o&&(i.epsilon=_t.backend.epsilon()),i}return o(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 o=_t.registeredVariables[n];null==e.accumulatedMeanSquares[r]&&(e.accumulatedMeanSquares[r]={originalName:n+"/rms",variable:Ye(function(){return qn(o).variable(!1)})}),null==e.accumulatedMoments[r]&&(e.accumulatedMoments[r]={originalName:n+"/momentum",variable:Ye(function(){return qn(o).variable(!1)})}),null==e.accumulatedMeanGrads[r]&&e.centered&&(e.accumulatedMeanGrads[r]={originalName:n+"/mg",variable:Ye(function(){return qn(o).variable(!1)})});var a=Array.isArray(t)?t[r].tensor:t[n];if(null!=a){var i=e.accumulatedMeanSquares[r].variable,s=e.accumulatedMoments[r].variable;Ye(function(){var t=i.mul(e.decay).add(a.square().mul(1-e.decay));if(e.centered){var n=e.accumulatedMeanGrads[r].variable,u=n.mul(e.decay).add(a.mul(1-e.decay)),c=s.mul(e.momentum).add(a.mul(e.learningRate).div(t.sub(u.square().add(e.epsilon)).sqrt()));i.assign(t),n.assign(u),s.assign(c);var l=o.sub(c);o.assign(l)}else{var p=i.mul(e.decay).add(a.square().mul(1-e.decay));c=s.mul(e.momentum).add(a.mul(e.learningRate).div(p.add(e.epsilon).sqrt())),i.assign(p),s.assign(c),l=o.sub(c),o.assign(l)}})}}),this.incrementIterations()},e.prototype.dispose=function(){null!=this.accumulatedMeanSquares&&Qe(this.accumulatedMeanSquares.map(function(t){return t.variable})),null!=this.accumulatedMeanGrads&&this.centered&&Qe(this.accumulatedMeanGrads.map(function(t){return t.variable})),null!=this.accumulatedMoments&&Qe(this.accumulatedMoments.map(function(t){return t.variable}))},e.prototype.getWeights=function(){return a(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 a(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}(jh);exports.RMSPropOptimizer=td,Ph(td);var ed=function(){function t(){}return t.sgd=function(t){return new Jh(t)},t.momentum=function(t,e,n){return void 0===n&&(n=!1),new Zh(t,e,n)},t.rmsprop=function(t,e,n,r,o){return void 0===e&&(e=.9),void 0===n&&(n=0),void 0===r&&(r=null),void 0===o&&(o=!1),new td(t,e,n,r,o)},t.adam=function(t,e,n,r){return void 0===t&&(t=.001),void 0===e&&(e=.9),void 0===n&&(n=.999),void 0===r&&(r=null),new Yh(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 Xh(t,e,n)},t.adamax=function(t,e,n,r,o){return void 0===t&&(t=.002),void 0===e&&(e=.9),void 0===n&&(n=.999),void 0===r&&(r=null),void 0===o&&(o=0),new Qh(t,e,n,r,o)},t.adagrad=function(t,e){return void 0===e&&(e=.1),new $h(t,e)},t}(),nd={sgd:ed.sgd,momentum:ed.momentum,adadelta:ed.adadelta,adagrad:ed.adagrad,rmsprop:ed.rmsprop,adamax:ed.adamax,adam:ed.adam},rd="undefined"!=typeof requestAnimationFrame?requestAnimationFrame:"undefined"!=typeof setImmediate?setImmediate:function(t){return t()};function od(){return new Promise(function(t){return rd(function(){return t()})})}exports.train=nd,vt=Ap;
  },{"crypto":"sC8V","node-fetch":"sC8V","util":"sC8V","process":"g5IB","buffer":"aMB2"}],"rGPK":[function(require,module,exports) {
  var Buffer = require("buffer").Buffer;
  var e=require("buffer").Buffer;Object.defineProperty(exports,"__esModule",{value:!0}),exports.loadGraphModel=Be,exports.deregisterOp=m,exports.registerOp=i,exports.version_converter=exports.GraphModel=void 0;var t,a,r=require("@tensorflow/tfjs-core"),n=function(){return(n=Object.assign||function(e){for(var t,a=1,r=arguments.length;a<r;a++)for(var n in t=arguments[a])Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n]);return e}).apply(this,arguments)};function s(e,t,a,r){return new(a||(a=Promise))(function(n,s){function o(e){try{i(r.next(e))}catch(e){s(e)}}function p(e){try{i(r.throw(e))}catch(e){s(e)}}function i(e){e.done?n(e.value):new a(function(t){t(e.value)}).then(o,p)}i((r=r.apply(e,t||[])).next())})}function o(e,t){var a,r,n,s,o={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]};return s={next:p(0),throw:p(1),return:p(2)},"function"==typeof Symbol&&(s[Symbol.iterator]=function(){return this}),s;function p(s){return function(p){return function(s){if(a)throw new TypeError("Generator is already executing.");for(;o;)try{if(a=1,r&&(n=2&s[0]?r.return:s[0]?r.throw||((n=r.return)&&n.call(r),0):r.next)&&!(n=n.call(r,s[1])).done)return n;switch(r=0,n&&(s=[2&s[0],n.value]),s[0]){case 0:case 1:n=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!(n=(n=o.trys).length>0&&n[n.length-1])&&(6===s[0]||2===s[0])){o=0;continue}if(3===s[0]&&(!n||s[1]>n[0]&&s[1]<n[3])){o.label=s[1];break}if(6===s[0]&&o.label<n[1]){o.label=n[1],n=s;break}if(n&&o.label<n[2]){o.label=n[2],o.ops.push(s);break}n[2]&&o.ops.pop(),o.trys.pop();continue}s=t.call(e,o)}catch(e){s=[6,e],r=0}finally{a=n=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,p])}}}!function(e){e[e.DT_INVALID=0]="DT_INVALID",e[e.DT_FLOAT=1]="DT_FLOAT",e[e.DT_DOUBLE=2]="DT_DOUBLE",e[e.DT_INT32=3]="DT_INT32",e[e.DT_UINT8=4]="DT_UINT8",e[e.DT_INT16=5]="DT_INT16",e[e.DT_INT8=6]="DT_INT8",e[e.DT_STRING=7]="DT_STRING",e[e.DT_COMPLEX64=8]="DT_COMPLEX64",e[e.DT_INT64=9]="DT_INT64",e[e.DT_BOOL=10]="DT_BOOL",e[e.DT_QINT8=11]="DT_QINT8",e[e.DT_QUINT8=12]="DT_QUINT8",e[e.DT_QINT32=13]="DT_QINT32",e[e.DT_BFLOAT16=14]="DT_BFLOAT16",e[e.DT_FLOAT_REF=101]="DT_FLOAT_REF",e[e.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",e[e.DT_INT32_REF=103]="DT_INT32_REF",e[e.DT_UINT8_REF=104]="DT_UINT8_REF",e[e.DT_INT16_REF=105]="DT_INT16_REF",e[e.DT_INT8_REF=106]="DT_INT8_REF",e[e.DT_STRING_REF=107]="DT_STRING_REF",e[e.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",e[e.DT_INT64_REF=109]="DT_INT64_REF",e[e.DT_BOOL_REF=110]="DT_BOOL_REF",e[e.DT_QINT8_REF=111]="DT_QINT8_REF",e[e.DT_QUINT8_REF=112]="DT_QUINT8_REF",e[e.DT_QINT32_REF=113]="DT_QINT32_REF",e[e.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF"}(t||(t={})),function(e){!function(e){e[e.LEGACY=0]="LEGACY",e[e.V1=1]="V1",e[e.V2=2]="V2"}(e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))}(a||(a={}));var p={};function i(e,t){var a={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};p[e]=a}function u(e){return p[e]}function m(e){delete p[e]}function c(e,t,a,r){var n=t.inputParams[e];if(n&&void 0!==n.inputIndexStart){var s=n.inputIndexStart,o=0===n.inputIndexEnd?void 0:void 0===n.inputIndexEnd?s+1:n.inputIndexEnd;if("tensor"===n.type)return d(t.inputNames[n.inputIndexStart],a,r);if("tensors"===n.type)return t.inputNames.slice(s,o).map(function(e){return d(e,a,r)});var p=Array.prototype.slice.call(d(t.inputNames.slice(s)[0],a,r).dataSync());return"number"===n.type?p[0]:p}var i=t.attrParams[e];return i&&i.value}function d(e,t,a){var r=h(e),n=r[0],s=r[1],o=a.currentContextIds.find(function(e){return!!t[f(n,e)]});return void 0!==o?t[f(n,o)][s]:void 0}function y(e,t,a){return t[f(e,a.currentContextId)]}function l(e,t){var a=h(e),r=a[0],n=a[1];return[f(r,t&&t.currentContextId),n]}function f(e,t){return t?e+"-"+t:e}function h(e){var t=e.lastIndexOf(":");return-1===t?[e,0]:[e.substring(0,t),Number(e.substring(t+1))]}function N(e,t){for(var a=[],r=0;r<e.length;r+=t)a.push(e.slice(r,r+t));return a}var g=[{tfOpName:"Add",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddV2",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddN",category:"arithmetic",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"BiasAdd",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sub",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"RealDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Div",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"DivNoNan",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mul",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Maximum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}]},{tfOpName:"Minimum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}]},{tfOpName:"Pow",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorMod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],b=Object.freeze({json:g}),x=[{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}]}],T=Object.freeze({json:x}),v=[{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"}]}],O=Object.freeze({json:v}),S=[{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[]"}]}],w=Object.freeze({json:S}),_=[{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"}]}],A=Object.freeze({json:_}),D=[{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}]}],E=Object.freeze({json:D}),I=[{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]}],V=Object.freeze({json:I}),k=[{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"}]}],C=Object.freeze({json:k}),M=[{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"}]}],z=Object.freeze({json:M}),F=[{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}]}],j=Object.freeze({json:F}),P=[{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}]}],R=Object.freeze({json:P}),L=[{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}]}],B=Object.freeze({json:L}),q=[{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"}]}],U=Object.freeze({json:q}),G=[{tfOpName:"ConcatV2",category:"slice_join",inputs:[{start:0,end:-1,name:"tensors",type:"tensors"},{start:-1,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"Concat",category:"slice_join",inputs:[{start:1,end:0,name:"tensors",type:"tensors"},{start:0,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"GatherV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Gather",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"validate_indices",name:"validateIndices",type:"bool",notSupported:!0}]},{tfOpName:"Reverse",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"dims",type:"bool",notSupported:!0}]},{tfOpName:"ReverseV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}]},{tfOpName:"Slice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"size",type:"number[]"}]},{tfOpName:"StridedSlice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"end",type:"number[]"},{start:3,name:"strides",type:"number[]"}],attrs:[{tfName:"begin_mask",name:"beginMask",type:"number",defaultValue:0},{tfName:"end_mask",name:"endMask",type:"number",defaultValue:0},{tfName:"new_axis_mask",name:"newAxisMask",type:"number",defaultValue:0},{tfName:"ellipsis_mask",name:"ellipsisMask",type:"number",defaultValue:0},{tfName:"shrink_axis_mask",name:"shrinkAxisMask",type:"number",defaultValue:0}]},{tfOpName:"Pack",category:"slice_join",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Unpack",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"num",name:"num",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Tile",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"reps",type:"number[]"}]},{tfOpName:"Split",category:"slice_join",inputs:[{start:0,name:"axis",type:"number",defaultValue:0},{start:1,name:"x",type:"tensor"}],attrs:[{tfName:"num_split",name:"numOrSizeSplits",type:"number",defaultValue:1}]},{tfOpName:"SplitV",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"numOrSizeSplits",type:"number[]"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"ScatterNd",category:"slice_join",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"shape",type:"number[]"}]},{tfOpName:"GatherNd",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}]},{tfOpName:"SparseToDense",category:"slice_join",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!1,notSupported:!0}]}],W=Object.freeze({json:G}),H=[{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}]}],Q=Object.freeze({json:H}),K=[{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"}]}],X=Object.freeze({json:K}),Z=function(){function e(){var e=[b,T,O,w,A,E,V,j,z,C,R,B,U,W,Q,X],t=[].concat.apply([],e.map(function(e){return e.json}));this.opMappers=t.reduce(function(e,t){return e[t.tfOpName]=t,e},{})}return Object.defineProperty(e,"Instance",{get:function(){return this._instance||(this._instance=new this)},enumerable:!0,configurable:!0}),e.prototype.transformGraph=function(e){var t=this,a=[],r=[],n=e.node.reduce(function(e,n){return e[n.name]=t.mapNode(n),"Placeholder"===n.op&&a.push(e[n.name]),"Const"===n.op&&r.push(e[n.name]),e},{}),s=[],o=[],p=Object.keys(n);return p.forEach(function(e){var t=n[e];t.inputNames.forEach(function(e){var a=l(e)[0];t.inputs.push(n[a]),n[a].children.push(t)}),0===t.inputs.length&&s.push(t)}),p.forEach(function(e){var t=n[e];0===t.children.length&&o.push(t)}),{nodes:n,inputs:s,outputs:o,weights:r,placeholders:a}},e.prototype.mapNode=function(e){var t=u(e.op)||this.opMappers[e.op]||{};null==e.attr&&(e.attr={});var a={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map(function(e){return e.startsWith("^")?e.substr(1):e}),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr};return null!=t.inputs&&(a.inputParams=t.inputs.reduce(function(e,t){return e[t.name]={type:t.type,inputIndexStart:t.start,inputIndexEnd:t.end},e},{})),null!=t.attrs&&(a.attrParams=t.attrs.reduce(function(t,a){var r=a.type,n=void 0;switch(a.type){case"string":void 0===(n=$(e.attr,a.tfName,a.defaultValue))&&a.tfDeprecatedName&&(n=$(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"string[]":void 0===(n=ie(e.attr,a.tfName,a.defaultValue))&&a.tfDeprecatedName&&(n=ie(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"number":void 0===(n=te(e.attr,a.tfName,a.defaultValue||0))&&a.tfDeprecatedName&&(n=te(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"number[]":void 0===(n=pe(e.attr,a.tfName,a.defaultValue))&&a.tfDeprecatedName&&(n=pe(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"bool":void 0===(n=ee(e.attr,a.tfName,a.defaultValue))&&a.tfDeprecatedName&&(n=ee(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"bool[]":void 0===(n=me(e.attr,a.tfName,a.defaultValue))&&a.tfDeprecatedName&&(n=me(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"shape":void 0===(n=oe(e.attr,a.tfName,a.defaultValue))&&a.tfDeprecatedName&&(n=oe(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"shape[]":void 0===(n=ue(e.attr,a.tfName,a.defaultValue))&&a.tfDeprecatedName&&(n=ue(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"dtype":void 0===(n=re(e.attr,a.tfName,a.defaultValue))&&a.tfDeprecatedName&&(n=re(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"dtype[]":void 0===(n=ne(e.attr,a.tfName,a.defaultValue))&&a.tfDeprecatedName&&(n=ne(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error("Unsupported param type: "+a.type+" for op: "+e.op)}return t[a.name]={value:n,type:r},t},{})),a},e}();function Y(t){var a=(0,r.env)().global;if(void 0!==a.atob)return a.atob(t);if(void 0!==e)return new e(t,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}function J(e,t){var a=Array.isArray(e)?String.fromCharCode.apply(null,e):Y(e);return t?a:a.toLowerCase()}function $(e,t,a,r){void 0===r&&(r=!1);var n=e[t];return null!=n?J(n.s,r):a}function ee(e,t,a){var r=e[t];return r?r.b:a}function te(e,t,a){var r=e[t]||{},n=null!=r.i?r.i:null!=r.f?r.f:a;return"number"==typeof n?n:parseInt(n,10)}function ae(e){switch("string"==typeof e&&(e=t[e]),e){case t.DT_FLOAT:return"float32";case t.DT_INT32:case t.DT_INT64:return"int32";case t.DT_BOOL:return"bool";case t.DT_DOUBLE:return"float32";case t.DT_STRING:return"string";default:return null}}function re(e,t,a){var r=e[t];return r&&r.type?ae(r.type):a}function ne(e,t,a){var r=e[t];return r&&r.list&&r.list.type?r.list.type.map(function(e){return ae(e)}):a}function se(e){if(!e.unknownRank)return null!=e.dim?e.dim.map(function(e){return"number"==typeof e.size?e.size:parseInt(e.size,10)}):[]}function oe(e,t,a){var r=e[t];return r&&r.shape?se(r.shape):a}function pe(e,t,a){var r=e[t];return r?((r.list.f&&r.list.f.length?r.list.f:r.list.i)||[]).map(function(e){return"number"==typeof e?e:parseInt(e,10)}):a}function ie(e,t,a,r){void 0===r&&(r=!1);var n=e[t];return n&&n.list&&n.list.s?n.list.s.map(function(e){return J(e,r)}):a}function ue(e,t,a){var r=e[t];return r&&r.list&&r.list.shape?r.list.shape.map(function(e){return se(e)}):a}function me(e,t,a){var r=e[t];return r&&r.list&&r.list.b?r.list.b:a}var ce=function(){function e(e,t,a){var r=this;this.node=e,this.tensorMap=t,this.context=a,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map(function(e){return r.getInput(e)}),null!=e.rawAttrs&&(this.attrs=Object.keys(e.rawAttrs).reduce(function(e,t){return e[t]=r.getAttr(t),e},{}))}return e.prototype.getInput=function(e){return d(e,this.tensorMap,this.context)},e.prototype.getAttr=function(e,t){var a=this.node.rawAttrs[e];if(null!=a.tensor)return d(e,this.tensorMap,this.context);if(null!=a.i||null!=a.f)return te(this.node.rawAttrs,e,t);if(null!=a.s)return $(this.node.rawAttrs,e,t);if(null!=a.b)return ee(this.node.rawAttrs,e,t);if(null!=a.shape)return oe(this.node.rawAttrs,e,t);if(null!=a.type)return re(this.node.rawAttrs,e,t);if(null!=a.list){if(null!=a.list.i||null!=a.list.f)return pe(this.node.rawAttrs,e,t);if(null!=a.list.s)return ie(this.node.rawAttrs,e,t);if(null!=a.list.shape)return ue(this.node.rawAttrs,e,t);if(null!=a.list.b)return me(this.node.rawAttrs,e,t);if(null!=a.list.type)return ne(this.node.rawAttrs,e,t)}return t},e}(),de=function(e,t,a){switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[(0,r.add)(c("a",e,t,a),c("b",e,t,a))];case"AddN":return[(0,r.addN)(c("tensors",e,t,a))];case"FloorMod":case"Mod":return[(0,r.mod)(c("a",e,t,a),c("b",e,t,a))];case"Mul":return[(0,r.mul)(c("a",e,t,a),c("b",e,t,a))];case"RealDiv":case"Div":return[(0,r.div)(c("a",e,t,a),c("b",e,t,a))];case"DivNoNan":return[(0,r.divNoNan)(c("a",e,t,a),c("b",e,t,a))];case"FloorDiv":return[(0,r.floorDiv)(c("a",e,t,a),c("b",e,t,a))];case"Sub":return[(0,r.sub)(c("a",e,t,a),c("b",e,t,a))];case"Minimum":return[(0,r.minimum)(c("a",e,t,a),c("b",e,t,a))];case"Maximum":return[(0,r.maximum)(c("a",e,t,a),c("b",e,t,a))];case"Pow":return[(0,r.pow)(c("a",e,t,a),c("b",e,t,a))];case"SquaredDifference":return[(0,r.squaredDifference)(c("a",e,t,a),c("b",e,t,a))];default:throw TypeError("Node type "+e.op+" is not implemented")}},ye=function(e,t,a){switch(e.op){case"Abs":case"ComplexAbs":return[(0,r.abs)(c("x",e,t,a))];case"Acos":return[(0,r.acos)(c("x",e,t,a))];case"Acosh":return[(0,r.acosh)(c("x",e,t,a))];case"Asin":return[(0,r.asin)(c("x",e,t,a))];case"Asinh":return[(0,r.asinh)(c("x",e,t,a))];case"Atan":return[(0,r.atan)(c("x",e,t,a))];case"Atan2":return[(0,r.atan2)(c("x",e,t,a),c("y",e,t,a))];case"Atanh":return[(0,r.atanh)(c("x",e,t,a))];case"Ceil":return[(0,r.ceil)(c("x",e,t,a))];case"Complex":return[(0,r.complex)(c("real",e,t,a),c("imag",e,t,a))];case"Cos":return[(0,r.cos)(c("x",e,t,a))];case"Cosh":return[(0,r.cosh)(c("x",e,t,a))];case"Elu":return[(0,r.elu)(c("x",e,t,a))];case"Erf":return[(0,r.erf)(c("x",e,t,a))];case"Exp":return[(0,r.exp)(c("x",e,t,a))];case"Expm1":return[(0,r.expm1)(c("x",e,t,a))];case"Floor":return[(0,r.floor)(c("x",e,t,a))];case"Log":return[(0,r.log)(c("x",e,t,a))];case"Log1p":return[(0,r.log1p)(c("x",e,t,a))];case"Imag":return[(0,r.imag)(c("x",e,t,a))];case"Neg":return[(0,r.neg)(c("x",e,t,a))];case"Reciprocal":return[(0,r.reciprocal)(c("x",e,t,a))];case"Real":return[(0,r.real)(c("x",e,t,a))];case"Relu":return[(0,r.relu)(c("x",e,t,a))];case"Round":return[(0,r.round)(c("x",e,t,a))];case"Selu":return[(0,r.selu)(c("x",e,t,a))];case"Sigmoid":return[(0,r.sigmoid)(c("x",e,t,a))];case"Sin":return[(0,r.sin)(c("x",e,t,a))];case"Sign":return[(0,r.sign)(c("x",e,t,a))];case"Sinh":return[(0,r.sinh)(c("x",e,t,a))];case"Softplus":return[(0,r.softplus)(c("x",e,t,a))];case"Sqrt":return[(0,r.sqrt)(c("x",e,t,a))];case"Square":return[(0,r.square)(c("x",e,t,a))];case"Tanh":return[(0,r.tanh)(c("x",e,t,a))];case"Tan":return[(0,r.tan)(c("x",e,t,a))];case"Relu6":case"ClipByValue":return[(0,r.clipByValue)(c("x",e,t,a),c("clipValueMin",e,t,a),c("clipValueMax",e,t,a))];case"Rsqrt":return[(0,r.rsqrt)(d(e.inputNames[0],t,a))];case"Prod":return[(0,r.prod)(c("x",e,t,a),c("axes",e,t,a))];case"LeakyRelu":return[(0,r.leakyRelu)(c("x",e,t,a),c("alpha",e,t,a))];case"Prelu":return[(0,r.prelu)(c("x",e,t,a),c("alpha",e,t,a))];default:throw TypeError("Node type "+e.op+" is not implemented")}},le=function(){function e(t,a,r,n,s,o,p){this.name=t,this.dtype=a,this.maxSize=r,this.elementShape=n,this.identicalElementShapes=s,this.dynamicSize=o,this.clearAfterRead=p,this.tensors=[],this.closed_=!1,this.id=e.nextId++}return Object.defineProperty(e.prototype,"closed",{get:function(){return this.closed_},enumerable:!0,configurable:!0}),e.prototype.clearAndClose=function(){this.tensors.forEach(function(e){return e.tensor.dispose()}),this.tensors=[],this.closed_=!0},e.prototype.size=function(){return this.tensors.length},e.prototype.read=function(e){if(this.closed_)throw new Error("TensorArray "+this.name+" has already been closed.");if(e<0||e>=this.tensors.length)throw new Error("Tried to read from index "+e+", but array size is: "+this.tensors.length);var t=this.tensors[e];if(t.cleared)throw new Error("TensorArray "+this.name+": Could not read index "+e+" twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).");return this.clearAfterRead&&(t.cleared=!0),t.read=!0,t.tensor},e.prototype.readMany=function(e){var t=this;return e.map(function(e){return t.read(e)})},e.prototype.write=function(e,t){if(this.closed_)throw new Error("TensorArray "+this.name+" has already been closed.");if(e<0||!this.dynamicSize&&e>=this.maxSize)throw new Error("Tried to write to index "+e+", but array is not resizeable and size is: "+this.maxSize);var a=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+e+",\n          because the value dtype is "+t.dtype+", but TensorArray dtype is "+this.dtype+".");if(0!==this.size()||null!=this.elementShape&&0!==this.elementShape.length||(this.elementShape=t.shape),this.assertShapesMatchAllowUndefinedSize(this.elementShape,t.shape,"TensorArray "+this.name+": Could not write to TensorArray index "+e+"."),a&&a.read)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+e+", because it has already been read.");if(a&&a.written)throw new Error("TensorArray "+this.name+": Could not write to TensorArray index "+e+", because it has already been written.");a.tensor=t,a.written=!0,this.tensors[e]=a},e.prototype.writeMany=function(e,t){var a=this;if(e.length!==t.length)throw new Error("TensorArray "+this.name+": could not write multiple tensors,because the index size: "+e.length+" is not the same as tensors size: "+t.length+".");e.forEach(function(e,r){return a.write(e,t[r])})},e.prototype.gather=function(e,t){if(t&&t!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but gather requested dtype "+t);if(!e){e=[];for(var a=0;a<this.size();a++)e.push(a)}if(0===e.length)return(0,r.tensor)([],[0].concat(this.elementShape));var n=this.readMany(e);return this.assertShapesMatchAllowUndefinedSize(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),(0,r.stack)(n,0)},e.prototype.concat=function(e){if(e&&e!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but concat requested dtype "+e);if(0===this.size())return(0,r.tensor)([],[0].concat(this.elementShape));for(var t=[],a=0;a<this.size();a++)t.push(a);var n=this.readMany(t);return this.assertShapesMatchAllowUndefinedSize(this.elementShape,n[0].shape,"TensorArray shape mismatch: tensor array shape ("+this.elementShape+") vs first tensor shape ("+n[0].shape+")"),(0,r.concat)(n,0)},e.prototype.scatter=function(e,t){if(t.dtype!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but tensor has dtype "+t.dtype);if(e.length!==t.shape[0])throw new Error("Expected len(indices) == tensor.shape[0], but saw: "+e.length+" vs. "+t.shape[0]);var a=Math.max.apply(Math,e);if(!this.dynamicSize&&a>=this.maxSize)throw new Error("Max index must be < array size ("+a+"  vs. "+this.maxSize+")");this.writeMany(e,(0,r.unstack)(t,0))},e.prototype.split=function(e,t){var a=this;if(t.dtype!==this.dtype)throw new Error("TensorArray dtype is "+this.dtype+" but tensor has dtype "+t.dtype);var n=0,s=e.map(function(e){return n+=e});if(n!==t.shape[0])throw new Error("Expected sum of lengths to be equal to\n          tensor.shape[0], but sum of lengths is\n        "+n+", and tensor's shape is: "+t.shape);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error("TensorArray's size is not equal to the size of lengths ("+this.maxSize+" vs. "+e.length+"), and the TensorArray is not marked as dynamically resizeable");var o=0===n?0:t.size/n,p=[];(0,r.tidy)(function(){t=t.reshape([1,n,o]);for(var i=0;i<e.length;++i){var u=[0,0===i?0:s[i-1],0],m=[1,e[i],o];p[i]=(0,r.slice)(t,u,m).reshape(a.elementShape)}return p});for(var i=[],u=0;u<e.length;u++)i[u]=u;this.writeMany(i,p)},e.prototype.assertShapesMatchAllowUndefinedSize=function(e,t,a){void 0===a&&(a=""),r.util.assert(this.shapesEqualAllowUndefinedSize(e,t),function(){return a+" Shapes "+e+" and "+t+" must match"})},e.prototype.shapesEqualAllowUndefinedSize=function(e,t){if(e.length!==t.length)return!1;for(var a=0;a<e.length;a++)if(-1!==e[a]&&-1!==t[a]&&e[a]!==t[a])return!1;return!0},e.nextId=0,e}();function fe(e,t,a){return s(this,void 0,void 0,function(){var n,s,p,i,u,m,y,l,f,h,N,g,b,x,T,v,O,S,w,_,A,D,E,I,V,k,C,M,z,F,j,P,R,L,B;return o(this,function(o){switch(o.label){case 0:switch(e.op){case"LoopCond":return[3,1];case"Switch":return[3,2];case"Merge":return[3,4];case"Enter":return[3,5];case"Exit":return[3,6];case"NextIteration":return[3,7];case"TensorArrayV3":return[3,8];case"TensorArrayWriteV3":return[3,9];case"TensorArrayReadV3":return[3,10];case"TensorArrayGatherV3":return[3,11];case"TensorArrayScatterV3":return[3,12];case"TensorArrayConcatV3":return[3,13];case"TensorArraySplitV3":return[3,14];case"TensorArraySizeV3":return[3,15];case"TensorArrayCloseV3":return[3,16]}return[3,17];case 1:return[2,[c("pred",e,t,a).clone()]];case 2:return n=c("pred",e,t,a),s=c("data",e,t,a),[4,n.data()];case 3:return[2,o.sent()[0]?[void 0,s.clone()]:[s.clone(),void 0]];case 4:return[2,(p=e.inputNames.find(function(e){return void 0!==d(e,t,a)}))?[d(p,t,a).clone()]:void 0];case 5:return i=c("frameName",e,t,a),u=c("tensor",e,t,a),a.enterFrame(i),[2,[u.clone()]];case 6:return m=c("tensor",e,t,a),a.exitFrame(),[2,[m.clone()]];case 7:return y=c("tensor",e,t,a),a.nextIteration(),[2,[y.clone()]];case 8:return l=c("size",e,t,a),f=c("dtype",e,t,a),h=c("elementShape",e,t,a),N=c("dynamicSize",e,t,a),g=c("clearAfterRead",e,t,a),b=c("identicalElementShapes",e,t,a),x=c("name",e,t,a),T=new le(x,f,l,h,b,N,g),a.addTensorArray(T),[2,[(0,r.scalar)(T.id),(0,r.scalar)(1)]];case 9:return v=c("tensorArrayId",e,t,a),O=c("index",e,t,a),S=c("tensor",e,t,a),a.getTensorArray(v).write(O,S),[2,[(0,r.scalar)(1)]];case 10:return w=c("tensorArrayId",e,t,a),_=c("index",e,t,a),[2,[a.getTensorArray(w).read(_)]];case 11:return A=c("tensorArrayId",e,t,a),D=c("indices",e,t,a),E=c("dtype",e,t,a),[2,[a.getTensorArray(A).gather(D,E)]];case 12:return I=c("tensorArrayId",e,t,a),V=c("indices",e,t,a),k=c("tensor",e,t,a),a.getTensorArray(I).scatter(V,k),[2,[(0,r.scalar)(1)]];case 13:return C=c("tensorArrayId",e,t,a),M=a.getTensorArray(C),z=c("dtype",e,t,a),[2,[M.concat(z)]];case 14:return F=c("tensorArrayId",e,t,a),j=c("tensor",e,t,a),P=c("lengths",e,t,a),a.getTensorArray(F).split(P,j),[2,[(0,r.scalar)(1)]];case 15:return R=c("tensorArrayId",e,t,a),L=a.getTensorArray(R),[2,[(0,r.scalar)(L.size(),"int32")]];case 16:return B=c("tensorArrayId",e,t,a),a.getTensorArray(B).clearAndClose(),[2,[(0,r.scalar)(0)]];case 17:throw TypeError("Node type "+e.op+" is not implemented")}})})}var he=function(e,t,a){var n,s;switch(e.op){case"Conv1D":var o=c("stride",e,t,a),p=c("pad",e,t,a),i=c("dataFormat",e,t,a).toUpperCase(),u=c("dilation",e,t,a);return[(0,r.conv1d)(c("x",e,t,a),c("filter",e,t,a),o,p,i,u)];case"Conv2D":o=c("strides",e,t,a),p=c("pad",e,t,a),i=c("dataFormat",e,t,a).toUpperCase();var m=c("dilations",e,t,a);return[(0,r.conv2d)(c("x",e,t,a),c("filter",e,t,a),[o[1],o[2]],p,i,[m[1],m[2]])];case"_FusedConv2D":var d=(n=c("fusedOps",e,t,a))[0],y=n[1],l="biasadd"===d,f="prelu"===y,h="fusedbatchnorm"===d,N=c("numArgs",e,t,a);if(l){if(f&&2!==N)throw new Error("Fused Conv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!f&&1!==N)throw new Error("Fused Conv2d with BiasAdd must have one extra argument: bias.")}if(h)throw new Error("Fused Conv2d with FusedBatchNorm is not supported.");o=c("strides",e,t,a),p=c("pad",e,t,a),i=c("dataFormat",e,t,a).toUpperCase(),m=c("dilations",e,t,a);var g=(s=c("args",e,t,a))[0],b=s[1];return[r.fused.conv2d({x:c("x",e,t,a),filter:c("filter",e,t,a),strides:[o[1],o[2]],pad:p,dataFormat:i,dilations:[m[1],m[2]],bias:g,activation:y,preluActivationWeights:b})];case"Conv2DBackpropInput":case"Conv2dTranspose":var x=c("outputShape",e,t,a);return o=c("strides",e,t,a),p=c("pad",e,t,a),[(0,r.conv2dTranspose)(c("x",e,t,a),c("filter",e,t,a),x,[o[1],o[2]],p)];case"DepthwiseConv2dNative":case"DepthwiseConv2d":return o=c("strides",e,t,a),p=c("pad",e,t,a),m=c("dilations",e,t,a),i=c("dataFormat",e,t,a).toUpperCase(),[(0,r.depthwiseConv2d)(c("input",e,t,a),c("filter",e,t,a),[o[1],o[2]],p,i,[m[1],m[2]])];case"Conv3D":return o=c("strides",e,t,a),p=c("pad",e,t,a),i=c("dataFormat",e,t,a).toUpperCase(),m=c("dilations",e,t,a),[(0,r.conv3d)(c("x",e,t,a),c("filter",e,t,a),[o[1],o[2],o[3]],p,i,[m[1],m[2],m[3]])];case"AvgPool":o=c("strides",e,t,a),p=c("pad",e,t,a);var T=c("kernelSize",e,t,a);return[(0,r.avgPool)(c("x",e,t,a),[T[1],T[2]],[o[1],o[2]],p)];case"MaxPool":return o=c("strides",e,t,a),p=c("pad",e,t,a),T=c("kernelSize",e,t,a),[(0,r.maxPool)(c("x",e,t,a),[T[1],T[2]],[o[1],o[2]],p)];case"AvgPool3D":return o=c("strides",e,t,a),p=c("pad",e,t,a),T=c("kernelSize",e,t,a),[(0,r.avgPool3d)(c("x",e,t,a),[T[1],T[2],T[3]],[o[1],o[2],o[3]],p)];case"MaxPool3D":return o=c("strides",e,t,a),p=c("pad",e,t,a),T=c("kernelSize",e,t,a),[(0,r.maxPool3d)(c("x",e,t,a),[T[1],T[2],T[3]],[o[1],o[2],o[3]],p)];default:throw TypeError("Node type "+e.op+" is not implemented")}},Ne=function(e,t,a){switch(e.op){case"Fill":var n=c("shape",e,t,a),s=c("dtype",e,t,a),o=c("value",e,t,a);return[(0,r.fill)(n,o,s)];case"LinSpace":var p=c("start",e,t,a),i=c("stop",e,t,a),u=c("num",e,t,a);return[(0,r.linspace)(p,i,u)];case"Multinomial":var m=c("logits",e,t,a),d=c("numSamples",e,t,a),y=c("seed",e,t,a);return[(0,r.multinomial)(m,d,y)];case"OneHot":var l=c("indices",e,t,a),f=c("depth",e,t,a),h=c("onValue",e,t,a),N=c("offValue",e,t,a);return[(0,r.oneHot)(l,f,h,N)];case"Ones":return[(0,r.ones)(c("shape",e,t,a),c("dtype",e,t,a))];case"OnesLike":return[(0,r.onesLike)(c("x",e,t,a))];case"RandomUniform":return[(0,r.randomUniform)(c("shape",e,t,a),c("minval",e,t,a),c("maxval",e,t,a),c("dtype",e,t,a))];case"Range":p=c("start",e,t,a);var g=c("stop",e,t,a),b=c("step",e,t,a);return[(0,r.range)(p,g,b,c("dtype",e,t,a))];case"TruncatedNormal":n=c("shape",e,t,a);var x=c("mean",e,t,a),T=c("stdDev",e,t,a);return y=c("seed",e,t,a),[(0,r.truncatedNormal)(n,x,T,c("dtype",e,t,a),y)];case"Zeros":return[(0,r.zeros)(c("shape",e,t,a),c("dtype",e,t,a))];case"ZerosLike":return[(0,r.zerosLike)(c("x",e,t,a))];default:throw TypeError("Node type "+e.op+" is not implemented")}};function ge(e,t,a){return s(this,void 0,void 0,function(){var n,s,p,i,u;return o(this,function(o){switch(o.label){case 0:switch(e.op){case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":return[3,1];case"Where":return[3,3];case"ListDiff":return[3,5]}return[3,6];case 1:return n=c("boxes",e,t,a),s=c("scores",e,t,a),p=c("maxOutputSize",e,t,a),i=c("iouThreshold",e,t,a),u=c("scoreThreshold",e,t,a),[4,r.image.nonMaxSuppressionAsync(n,s,p,i,u)];case 2:return[2,[o.sent()]];case 3:return[4,(0,r.whereAsync)(c("condition",e,t,a).asType("bool"))];case 4:return[2,[o.sent()]];case 5:return[2,(0,r.setdiff1dAsync)(c("x",e,t,a),c("y",e,t,a))];case 6:throw TypeError("Node type "+e.op+" is not implemented")}})})}var be=function(e,t,a){switch(e.op){case"TopKV2":var n=c("x",e,t,a),s=c("k",e,t,a),o=c("sorted",e,t,a),p=(0,r.topk)(n,s,o);return[p.values,p.indices];default:throw TypeError("Node type "+e.op+" is not implemented")}},xe=function(e,t,a){switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":var n=c("default",e,t,a);return[d(e.name,t,a)||n];case"Placeholder":return[d(e.name,t,a)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":return[c("x",e,t,a).clone()];case"IdentityN":return c("x",e,t,a).map(function(e){return e.clone()});case"Snapshot":return[c("x",e,t,a).clone()];case"Shape":return[(0,r.tensor1d)(c("x",e,t,a).shape,"int32")];case"ShapeN":return c("x",e,t,a).map(function(e){return(0,r.tensor1d)(e.shape)});case"Size":return[(0,r.scalar)(c("x",e,t,a).size,"int32")];case"Rank":return[(0,r.scalar)(c("x",e,t,a).rank,"int32")];case"NoOp":return[(0,r.scalar)(1)];case"Print":var s=c("x",e,t,a),o=c("data",e,t,a),p=c("message",e,t,a),i=c("summarize",e,t,a);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(p);for(var u=0;u<o.length;u++)console.log(Array.prototype.slice.call(o[u].dataSync()).slice(0,i));return[s];default:throw TypeError("Node type "+e.op+" is not implemented")}},Te=function(e,t,a){switch(e.op){case"ResizeBilinear":var n=c("images",e,t,a),s=c("size",e,t,a),o=c("alignCorners",e,t,a);return[r.image.resizeBilinear(n,[s[0],s[1]],o)];case"ResizeNearestNeighbor":return n=c("images",e,t,a),s=c("size",e,t,a),o=c("alignCorners",e,t,a),[r.image.resizeNearestNeighbor(n,[s[0],s[1]],o)];case"CropAndResize":var p=c("image",e,t,a),i=c("boxes",e,t,a),u=c("boxInd",e,t,a),m=c("cropSize",e,t,a),d=c("method",e,t,a),y=c("extrapolationValue",e,t,a);return[r.image.cropAndResize(p,i,u,m,d,y)];default:throw TypeError("Node type "+e.op+" is not implemented")}},ve=function(e,t,a){switch(e.op){case"Equal":return[(0,r.equal)(c("a",e,t,a),c("b",e,t,a))];case"NotEqual":return[(0,r.notEqual)(c("a",e,t,a),c("b",e,t,a))];case"Greater":return[(0,r.greater)(c("a",e,t,a),c("b",e,t,a))];case"GreaterEqual":return[(0,r.greaterEqual)(c("a",e,t,a),c("b",e,t,a))];case"Less":return[(0,r.less)(c("a",e,t,a),c("b",e,t,a))];case"LessEqual":return[(0,r.lessEqual)(c("a",e,t,a),c("b",e,t,a))];case"LogicalAnd":return[(0,r.logicalAnd)(c("a",e,t,a),c("b",e,t,a))];case"LogicalNot":return[(0,r.logicalNot)(c("a",e,t,a))];case"LogicalOr":return[(0,r.logicalOr)(c("a",e,t,a),c("b",e,t,a))];case"Select":return[(0,r.where)(c("condition",e,t,a),c("a",e,t,a),c("b",e,t,a))];default:throw TypeError("Node type "+e.op+" is not implemented")}},Oe=function(e,t,a){switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[(0,r.matMul)(c("a",e,t,a),c("b",e,t,a),c("transposeA",e,t,a),c("transposeB",e,t,a))];case"Transpose":return[(0,r.transpose)(c("x",e,t,a),c("perm",e,t,a))];default:throw TypeError("Node type "+e.op+" is not implemented")}},Se=function(e,t,a){switch(e.op){case"FusedBatchNorm":case"FusedBatchNormV2":case"FusedBatchNormV3":return[(0,r.batchNorm)(c("x",e,t,a),c("mean",e,t,a),c("variance",e,t,a),c("offset",e,t,a),c("scale",e,t,a),c("epsilon",e,t,a))];case"LRN":return[(0,r.localResponseNormalization)(c("x",e,t,a),c("radius",e,t,a),c("bias",e,t,a),c("alpha",e,t,a),c("beta",e,t,a))];case"Softmax":return[(0,r.softmax)(c("x",e,t,a))];case"LogSoftmax":return[(0,r.logSoftmax)(c("x",e,t,a))];case"SparseToDense":return[(0,r.sparseToDense)(c("sparseIndices",e,t,a),c("outputShape",e,t,a),c("sparseValues",e,t,a),c("defaultValue",e,t,a))];default:throw TypeError("Node type "+e.op+" is not implemented")}},we=function(e,t,a){switch(e.op){case"Max":var n=c("axis",e,t,a),s=c("keepDims",e,t,a);return[(0,r.max)(c("x",e,t,a),n,s)];case"Mean":return n=c("axis",e,t,a),s=c("keepDims",e,t,a),[(0,r.mean)(c("x",e,t,a),n,s)];case"Min":return n=c("axis",e,t,a),s=c("keepDims",e,t,a),[(0,r.min)(c("x",e,t,a),n,s)];case"Sum":return n=c("axis",e,t,a),s=c("keepDims",e,t,a),[(0,r.sum)(c("x",e,t,a),n,s)];case"All":return n=c("axis",e,t,a),s=c("keepDims",e,t,a),[(0,r.all)(c("x",e,t,a),n,s)];case"Any":return n=c("axis",e,t,a),s=c("keepDims",e,t,a),[(0,r.any)(c("x",e,t,a),n,s)];case"ArgMax":return n=c("axis",e,t,a),[(0,r.argMax)(c("x",e,t,a),n)];case"ArgMin":return n=c("axis",e,t,a),[(0,r.argMin)(c("x",e,t,a),n)];case"Prod":return n=c("axis",e,t,a),s=c("keepDims",e,t,a),[(0,r.prod)(c("x",e,t,a),n,s)];default:throw TypeError("Node type "+e.op+" is not implemented")}},_e=function(e,t,a){switch(e.op){case"ConcatV2":case"Concat":var n=c("n",e,t,a),s=c("axis",e,t,a),o=c("tensors",e,t,a);return o=o.slice(0,n),[(0,r.concat)(o,s)];case"GatherV2":case"Gather":s=c("axis",e,t,a);var p=c("x",e,t,a),i=c("indices",e,t,a);return[(0,r.gather)(p,i.asType("int32"),s)];case"ReverseV2":case"Reverse":return s=c("axis",e,t,a),p=c("x",e,t,a),[(0,r.reverse)(p,s)];case"Slice":var u=c("begin",e,t,a),m=c("size",e,t,a);return[(0,r.slice)(c("x",e,t,a),u,m)];case"StridedSlice":u=c("begin",e,t,a);var d=c("end",e,t,a),y=c("strides",e,t,a),l=c("beginMask",e,t,a),f=c("endMask",e,t,a),h=c("ellipsisMask",e,t,a),N=c("newAxisMask",e,t,a),g=c("shrinkAxisMask",e,t,a),b=c("x",e,t,a);if(1===u.length&&b.shape.length>1)for(var x=1;x<b.shape.length;x++)u.push(0),d.push(b.shape[x]),y.push(y[0]);return[(0,r.stridedSlice)(b,u,d,y,l,f,h,N,g)];case"Pack":return(0,r.tidy)(function(){var n=c("axis",e,t,a),s=c("tensors",e,t,a),o=s[0].shape,p=s[0].squeeze().shape,i=s.map(function(e){var t=r.util.arraysEqual(e.shape,o);if(!t&&!r.util.arraysEqual(e.squeeze().shape,p))throw new Error("the input tensors shape does not match");return t?e:e.reshape(o)});return[(0,r.stack)(i,n)]});case"Unpack":return(0,r.tidy)(function(){var n=c("axis",e,t,a),s=c("tensor",e,t,a);return(0,r.unstack)(s,n)});case"Tile":var T=c("reps",e,t,a);return[(0,r.tile)(c("x",e,t,a),T)];case"Split":case"SplitV":s=c("axis",e,t,a);var v=c("numOrSizeSplits",e,t,a);return(0,r.split)(c("x",e,t,a),v,s);case"ScatterNd":i=c("indices",e,t,a);var O=c("values",e,t,a),S=c("shape",e,t,a);return[(0,r.scatterND)(i,O,S)];case"GatherNd":var w=c("x",e,t,a);return i=c("indices",e,t,a),[(0,r.gatherND)(w,i)];case"SparseToDense":i=c("sparseIndices",e,t,a),S=c("outputShape",e,t,a);var _=c("sparseValues",e,t,a),A=c("defaultValue",e,t,a);return[(0,r.sparseToDense)(i,_,S,_.dtype===A.dtype?A:A.asType(_.dtype))];default:throw TypeError("Node type "+e.op+" is not implemented")}},Ae=function(e,t,a){switch(e.op){case"FFT":return[(0,r.fft)(c("x",e,t,a))];case"IFFT":return[(0,r.ifft)(c("x",e,t,a))];case"RFFT":return[(0,r.rfft)(c("x",e,t,a))];case"IRFFT":return[(0,r.irfft)(c("x",e,t,a))];default:throw TypeError("Node type "+e.op+" is not implemented")}},De=function(e,t,a){switch(e.op){case"Cast":return[(0,r.cast)(c("x",e,t,a),c("dtype",e,t,a))];case"ExpandDims":var n=c("axis",e,t,a);return[(0,r.expandDims)(c("x",e,t,a),n)];case"Squeeze":return n=c("axis",e,t,a),[(0,r.squeeze)(c("x",e,t,a),n)];case"Reshape":return[(0,r.reshape)(c("x",e,t,a),c("shape",e,t,a))];case"PadV2":case"Pad":return[(0,r.pad)(c("x",e,t,a),N(c("padding",e,t,a),2),c("constantValue",e,t,a))];case"SpaceToBatchND":var s=c("blockShape",e,t,a),o=N(c("paddings",e,t,a),2);return[(0,r.spaceToBatchND)(c("x",e,t,a),s,o)];case"BatchToSpaceND":s=c("blockShape",e,t,a);var p=N(c("crops",e,t,a),2);return[(0,r.batchToSpaceND)(c("x",e,t,a),s,p)];case"DepthToSpace":var i=c("blockSize",e,t,a),u=c("dataFormat",e,t,a).toUpperCase();return[(0,r.depthToSpace)(c("x",e,t,a),i,u)];default:throw TypeError("Node type "+e.op+" is not implemented")}};function Ee(e,t,a){var r=function(e,t,a){switch(e.category){case"arithmetic":return de(e,t,a);case"basic_math":return ye(e,t,a);case"control":return fe(e,t,a);case"convolution":return he(e,t,a);case"creation":return Ne(e,t,a);case"dynamic":return ge(e,t,a);case"evaluation":return be(e,t,a);case"image":return Te(e,t,a);case"graph":return xe(e,t,a);case"logical":return ve(e,t,a);case"matrices":return Oe(e,t,a);case"normalization":return Se(e,t,a);case"reduction":return we(e,t,a);case"slice_join":return _e(e,t,a);case"spectral":return Ae(e,t,a);case"transformation":return De(e,t,a);case"custom":var r=u(e.op);if(r&&r.customExecutor)return r.customExecutor(new ce(e,t,a));throw TypeError("Custom op "+e.op+" is not registered.");default:throw TypeError("Unknown op '"+e.op+"'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()")}}(e,t,a);return r instanceof Promise?r.then(function(e){return[].concat(e)}):[].concat(r)}var Ie=function(){function e(e,t){this.weightMap=e,this.tensorArrayMap=t,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}return e.prototype.newFrame=function(e,t){return{id:e,frameName:t,iterationId:0}},Object.defineProperty(e.prototype,"currentContext",{get:function(){return this.contexts},set:function(e){this.contexts!==e&&(this.contexts=e,this.generateCurrentContextIds())},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"currentContextId",{get:function(){return this._currentContextIds[0]},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"currentContextIds",{get:function(){return this._currentContextIds},enumerable:!0,configurable:!0}),e.prototype.generateCurrentContextIds=function(){for(var e=[],t=0;t<this.contexts.length-1;t++){var a=this.contexts.slice(0,this.contexts.length-t);e.push(this.contextIdforContexts(a))}e.push(""),this._currentContextIds=e},e.prototype.contextIdforContexts=function(e){return e?e.map(function(e){return 0===e.id&&0===e.iterationId?"":e.frameName+"-"+e.iterationId}).join("/"):""},e.prototype.enterFrame=function(e){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,e)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))},e.prototype.exitFrame=function(){if(!(this.contexts&&this.contexts.length>1))throw new Error("Cannot exit frame, the context is empty");this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift()},e.prototype.nextIteration=function(){if(!(this.contexts&&this.contexts.length>0))throw new Error("Cannot increase frame iteration, the context is empty");this.contexts=this.contexts.slice(),this.lastId++;var e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1,e.id=this.lastId,this.contexts.splice(-1,1,e),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))},e.prototype.getWeight=function(e){return this.weightMap[e]},e.prototype.addTensorArray=function(e){this.tensorArrayMap[e.id]=e},e.prototype.getTensorArray=function(e){return this.tensorArrayMap[e]},e}();function Ve(e,t,a){for(var r=new Set,n=[],s=null,o=null,p=new Set,i=t.slice();i.length>0;){var u=i.pop();(ze(u)||Fe(u))&&null==s&&(o=(s=u).children.map(function(e){return e.name}).filter(function(e){return r.has(e)})),r.add(u.name),null==a[u.name]&&null==e[u.name]&&(0!==u.inputs.length?u.inputs.forEach(function(e){p.has(e.name)||(p.add(e.name),i.push(e))}):n.push(u.name))}return{inputs:e,outputs:t,usedNodes:r,missingInputs:n,dynamicNode:s,syncInputs:o}}function ke(e,t,a){var r=a.usedNodes,n=a.inputs,s=[];Object.keys(n).map(function(t){return e.nodes[t]}).forEach(function(e){r.has(e.name)&&s.push(e)}),e.weights.forEach(function(e){r.has(e.name)&&s.push(e)});for(var o=new Set,p=[];s.length>0;){var i=s.pop();o.add(i.name),t[i.name]||p.push(i),i.children.forEach(function(e){!o.has(e.name)&&r.has(e.name)&&e.inputs.every(function(e){return o.has(e.name)})&&s.push(e)})}return p}var Ce=["Switch","Merge","Enter","Exit","NextIteration"],Me=["NonMaxSuppressionV2","NonMaxSuppressionV3","Where"];function ze(e){return Ce.indexOf(e.op)>=0}function Fe(e){return Me.indexOf(e.op)>=0}var je=function(){function e(e){this.graph=e,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this.placeholders=e.placeholders,this._outputs=e.outputs}return Object.defineProperty(e.prototype,"weightMap",{get:function(){return this._weightMap},set:function(e){var t=Object.keys(e).map(function(t){return e[t].map(function(e){return e.id})});this.weightIds=[].concat.apply([],t),this._weightMap=e},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"inputs",{get:function(){return this.placeholders.map(function(e){return{name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}})},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"outputs",{get:function(){return this._outputs.map(function(e){return{name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}})},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"inputNodes",{get:function(){return this.placeholders.map(function(e){return e.name})},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"outputNodes",{get:function(){return this.outputs.map(function(e){return e.name})},enumerable:!0,configurable:!0}),e.prototype.getCompilationKey=function(e,t){var a=e.map(function(e){return e.name}).sort(),r=t.map(function(e){return e.name}).sort();return a.join(this.SEPERATOR)+"--"+r.join(this.SEPERATOR)},e.prototype.compile=function(e,t){var a=Ve(e,t,this.weightMap),r=a.missingInputs,n=a.dynamicNode,s=a.syncInputs;if(null!=n)throw new Error("This execution contains the node '"+n.name+"', which has the dynamic op '"+n.op+"'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs ["+s+"]");if(r.length>0){var o=t.map(function(e){return e.name}),p=Object.keys(e);throw new Error("Cannot compute the outputs ["+o+"] from the provided inputs ["+p+"]. Missing the following inputs: ["+r+"]")}return ke(this.graph,this.weightMap,a)},e.prototype.execute=function(e,t){var a=this,s=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),this.checkOutputs(t);var o=s.map(function(e){return a.graph.nodes[e]}),p=t.map(function(e){return a.graph.nodes[h(e)[0]]}),i=this.getCompilationKey(o,p),u=this.compiledMap.get(i);null==u&&(u=this.compile(e,p),this.compiledMap.set(i,u));var m={};return(0,r.tidy)(function(){var r=new Ie(a._weightMap,m),s=n({},a.weightMap);Object.keys(e).forEach(function(t){s[t]=[e[t]]});for(var o=a.getFrozenTensorIds(s),p={},i=0;i<u.length;i++){var c=u[i];if(!s[c.name]){var y=Ee(c,s,r);if(y instanceof Promise)throw new Error("The execution of the op '"+c.op+"' returned a promise. Please use model.executeAsync() instead.");s[c.name]=y,a.checkTensorForDisposal(c.name,c,s,r,o,t,p)}}return t.map(function(e){return d(e,s,r)})})},e.prototype.getFrozenTensorIds=function(e){var t=[].concat.apply([],Object.keys(e).map(function(t){return e[t]}).map(function(e){return e.map(function(e){return e.id})}));return new Set(t)},e.prototype.checkTensorForDisposal=function(e,t,a,r,n,s,o){"control"!==t.category&&-1===s.indexOf(e)&&(a[e].forEach(function(e){null!=e&&(o[e.id]=(o[e.id]||0)+t.children.length)}),t.inputs.forEach(function(e){if("control"!==e.category){var t=y(e.name,a,r);null!=t&&t.forEach(function(e){if(e&&!n.has(e.id)){var t=o[e.id];1===t?(e.dispose(),delete o[e.id]):null!=t&&o[e.id]--}})}}))},e.prototype.executeAsync=function(e,t){return s(this,void 0,void 0,function(){var a,r,n,s,p,i,u=this;return o(this,function(o){switch(o.label){case 0:return this.checkInputs(e),this.checkInputShapeAndType(e),this.checkOutputs(t),a={},r=new Ie(this._weightMap,a),[4,this.executeWithControlFlow(e,r,t)];case 1:return n=o.sent(),s=t.map(function(e){return d(e,n,r)}),p=new Set(s.map(function(e){return e.id})),i=new Set(Object.keys(e).map(function(t){return e[t].id})),Object.keys(n).forEach(function(e){n[e].forEach(function(e){!e||e.isDisposed||p.has(e.id)||i.has(e.id)||-1!==u.weightIds.indexOf(e.id)||e.dispose()})}),[2,s]}})})},e.prototype.executeWithControlFlow=function(e,t,a){return s(this,void 0,void 0,function(){var r,s,p,i,u,m,c,y,l,f,N,g,b,x,T,v,O=this;return o(this,function(o){switch(o.label){case 0:r=Object.keys(e),s=r.map(function(e){return O.graph.nodes[e]}),p=a.map(function(e){return O.graph.nodes[h(e)[0]]}),i=Ve(e,p,this.weightMap),u=i.usedNodes,m=i.missingInputs,c=i.dynamicNode,y=i.syncInputs,l=s.concat(this.graph.weights).map(function(e){return{node:e,contexts:t.currentContext}}),f=n({},this.weightMap),Object.keys(e).forEach(function(t){f[t]=[e[t]]}),N={},g=this.getFrozenTensorIds(f),b={},o.label=1;case 1:return l.length>0?(x=this.processStack(s,l,t,f,b,g,a,N,u),[4,Promise.all(x)]):[3,3];case 2:return o.sent(),[3,1];case 3:if(null==c&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead."),(T=p.filter(function(e){return!ze(e)&&!d(e.name,f,t)}).map(function(e){return e.name})).length>0)throw v="",null!=c&&(v="Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs ["+y+"]"),new Error("Cannot compute the outputs ["+T+"] from the provided inputs ["+r+"]. Consider providing the following inputs: ["+m+"]. "+v);return[2,f]}})})},e.prototype.processStack=function(e,t,a,r,n,s,o,p,i){for(var u=this,m=[],d=function(){var d=t.pop();a.currentContext=d.contexts;var f="";if("Enter"===d.node.op&&c("isConstant",d.node,r,a)&&(f=l(d.node.name,a)[0]),-1===e.indexOf(d.node)){var h=Ee(d.node,r,a);f||(f=l(d.node.name,a)[0]);var N=a.currentContext;h instanceof Promise?m.push(h.then(function(e){return r[f]=e,a.currentContext=N,u.checkTensorForDisposal(f,d.node,r,a,s,o,p),u.processChildNodes(d.node,t,a,r,n,i),e})):(r[f]=h,y.checkTensorForDisposal(f,d.node,r,a,s,o,p),y.processChildNodes(d.node,t,a,r,n,i))}else y.processChildNodes(d.node,t,a,r,n,i)},y=this;t.length>0;)d();return m},e.prototype.processChildNodes=function(e,t,a,r,n,s){e.children.forEach(function(e){var o=l(e.name,a)[0];!n[o]&&s.has(e.name)&&("Merge"===e.op?e.inputNames.some(function(e){return!!d(e,r,a)})&&(n[o]=!0,t.push({contexts:a.currentContext,node:e})):e.inputNames.every(function(e){return!!d(e,r,a)})&&(n[o]=!0,t.push({contexts:a.currentContext,node:e})))})},e.prototype.dispose=function(){var e=this;Object.keys(this.weightMap).forEach(function(t){return e.weightMap[t].forEach(function(e){return e.dispose()})})},e.prototype.checkInputShapeAndType=function(e){var t=this;Object.keys(e).forEach(function(a){var n=e[a],s=t.graph.nodes[a];if(s.attrParams.shape&&s.attrParams.shape.value){var o=s.attrParams.shape.value,p=o.length===n.shape.length&&n.shape.every(function(e,t){return-1===o[t]||o[t]===e});r.util.assert(p,function(){return"The shape of dict['"+s.name+"'] provided in model.execute(dict) must be ["+o+"], but was ["+n.shape+"]"})}s.attrParams.dtype&&s.attrParams.dtype.value&&r.util.assert(n.dtype===s.attrParams.dtype.value,function(){return"The dtype of dict['"+s.name+"'] provided in model.execute(dict) must be "+s.attrParams.dtype.value+", but was "+n.dtype})})},e.prototype.checkInputs=function(e){var t=this,a=Object.keys(e).filter(function(e){return!t.graph.nodes[e]});if(a.length>0)throw new Error("The dict provided in model.execute(dict) has keys: ["+a+"] that are not part of graph")},e.prototype.checkOutputs=function(e){var t=this;e.forEach(function(e){var a=h(e)[0];if(!t.graph.nodes[a])throw new Error("The output '"+e+"' is not found in the graph")})},e}(),Pe="?tfjs-format=file",Re="model.json",Le=function(){function e(e,t){void 0===t&&(t={}),this.modelUrl=e,this.loadOptions=t,this.version="n/a",null==t&&(this.loadOptions={})}return Object.defineProperty(e.prototype,"modelVersion",{get:function(){return this.version},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"inputNodes",{get:function(){return this.executor.inputNodes},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"outputNodes",{get:function(){return this.executor.outputNodes},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"inputs",{get:function(){return this.executor.inputs},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"outputs",{get:function(){return this.executor.outputs},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"weights",{get:function(){return this.executor.weightMap},enumerable:!0,configurable:!0}),e.prototype.findIOHandler=function(){var e=this.modelUrl;if(null!=e.load)this.handler=e;else if(null!=this.loadOptions.requestInit)this.handler=r.io.browserHTTPRequest(e,this.loadOptions);else{var t=r.io.getLoadHandlers(e,this.loadOptions.onProgress);if(0===t.length)t.push(r.io.browserHTTPRequest(e,this.loadOptions));else if(t.length>1)throw new Error("Found more than one ("+t.length+") load handlers for URL '"+[e]+"'");this.handler=t[0]}},e.prototype.load=function(){return s(this,void 0,void 0,function(){var e,t,a;return o(this,function(n){switch(n.label){case 0:if(this.findIOHandler(),null==this.handler.load)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");return[4,this.handler.load()];case 1:return e=n.sent(),t=e.modelTopology,this.version=t.versions.producer+"."+t.versions.minConsumer,a=r.io.decodeWeights(e.weightData,e.weightSpecs),this.executor=new je(Z.Instance.transformGraph(t)),this.executor.weightMap=this.convertTensorMapToTensorsMap(a),[2,!0]}})})},e.prototype.predict=function(e,t){return this.execute(e,this.outputNodes)},e.prototype.normalizeInputs=function(e){if(!(e instanceof r.Tensor||Array.isArray(e)))return e;if((e=Array.isArray(e)?e:[e]).length!==this.inputNodes.length)throw new Error("Input tensor count mismatch,the graph model has "+this.inputNodes.length+" placeholders, while there are "+e.length+" input tensors.");return this.inputNodes.reduce(function(t,a,r){return t[a]=e[r],t},{})},e.prototype.normalizeOutputs=function(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]},e.prototype.execute=function(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);var a=this.executor.execute(e,t);return a.length>1?a:a[0]},e.prototype.executeAsync=function(e,t){return s(this,void 0,void 0,function(){var a;return o(this,function(r){switch(r.label){case 0:return e=this.normalizeInputs(e),t=this.normalizeOutputs(t),[4,this.executor.executeAsync(e,t)];case 1:return[2,(a=r.sent()).length>1?a:a[0]]}})})},e.prototype.convertTensorMapToTensorsMap=function(e){return Object.keys(e).reduce(function(t,a){return t[a]=[e[a]],t},{})},e.prototype.dispose=function(){this.executor.dispose()},e}();function Be(e,t){return void 0===t&&(t={}),s(this,void 0,void 0,function(){var a;return o(this,function(r){switch(r.label){case 0:if(null==e)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");return null==t&&(t={}),t.fromTFHub&&null==e.load&&(e.endsWith("/")||(e+="/"),e=""+e+Re+Pe),[4,(a=new Le(e,t)).load()];case 1:return r.sent(),[2,a]}})})}exports.GraphModel=Le;var qe="1.3.2";exports.version_converter=qe;
  },{"@tensorflow/tfjs-core":"PqBP","buffer":"aMB2"}],"yqJr":[function(require,module,exports) {
  "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.decodeMultiplePoses=F,exports.decodeSinglePose=z,exports.load=Nt,exports.getAdjacentKeyPoints=Z,exports.getBoundingBox=et,exports.getBoundingBoxPoints=rt,exports.scaleAndFlipPoses=gt,exports.scalePose=ot,exports.version=exports.PoseNet=exports.poseChain=exports.partNames=exports.partIds=exports.partChannels=exports.MobileNet=void 0;var t=n(require("@tensorflow/tfjs-core")),e=require("@tensorflow/tfjs-converter");function r(){if("function"!=typeof WeakMap)return null;var t=new WeakMap;return r=function(){return t},t}function n(t){if(t&&t.__esModule)return t;if(null===t||"object"!=typeof t&&"function"!=typeof t)return{default:t};var e=r();if(e&&e.has(t))return e.get(t);var n={},o=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var i in t)if(Object.prototype.hasOwnProperty.call(t,i)){var u=o?Object.getOwnPropertyDescriptor(t,i):null;u&&(u.get||u.set)?Object.defineProperty(n,i,u):n[i]=t[i]}return n.default=t,e&&e.set(t,n),n}var o=function(t,e){return(o=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r])})(t,e)};function i(t,e){function r(){this.constructor=t}o(t,e),t.prototype=null===e?Object.create(e):(r.prototype=e.prototype,new r)}var u=function(){return(u=Object.assign||function(t){for(var e,r=1,n=arguments.length;r<n;r++)for(var o in e=arguments[r])Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o]);return t}).apply(this,arguments)};function s(t,e,r,n){return new(r||(r=Promise))(function(o,i){function u(t){try{a(n.next(t))}catch(t){i(t)}}function s(t){try{a(n.throw(t))}catch(t){i(t)}}function a(t){t.done?o(t.value):new r(function(e){e(t.value)}).then(u,s)}a((n=n.apply(t,e||[])).next())})}function a(t,e){var r,n,o,i,u={label:0,sent:function(){if(1&o[0])throw o[1];return o[1]},trys:[],ops:[]};return i={next:s(0),throw:s(1),return:s(2)},"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(i){return function(s){return function(i){if(r)throw new TypeError("Generator is already executing.");for(;u;)try{if(r=1,n&&(o=2&i[0]?n.return:i[0]?n.throw||((o=n.return)&&o.call(n),0):n.next)&&!(o=o.call(n,i[1])).done)return o;switch(n=0,o&&(i=[2&i[0],o.value]),i[0]){case 0:case 1:o=i;break;case 4:return u.label++,{value:i[1],done:!1};case 5:u.label++,n=i[1],i=[0];continue;case 7:i=u.ops.pop(),u.trys.pop();continue;default:if(!(o=(o=u.trys).length>0&&o[o.length-1])&&(6===i[0]||2===i[0])){u=0;continue}if(3===i[0]&&(!o||i[1]>o[0]&&i[1]<o[3])){u.label=i[1];break}if(6===i[0]&&u.label<o[1]){u.label=o[1],o=i;break}if(o&&u.label<o[2]){u.label=o[2],u.ops.push(i);break}o[2]&&u.ops.pop(),u.trys.pop();continue}i=e.call(t,u)}catch(t){i=[6,t],n=0}finally{r=o=0}if(5&i[0])throw i[1];return{value:i[0]?i[1]:void 0,done:!0}}([i,s])}}}var l=function(){function e(e,r){this.model=e,this.outputStride=r;var n=this.model.inputs[0].shape;t.util.assert(-1===n[1]&&-1===n[2],function(){return"Input shape ["+n[1]+", "+n[2]+"] must both be equal to or -1"})}return e.prototype.predict=function(e){var r=this;return(0,t.tidy)(function(){var t=r.preprocessInput(e.toFloat()).expandDims(0),n=r.model.predict(t).map(function(t){return t.squeeze([0])}),o=r.nameOutputResults(n);return{heatmapScores:o.heatmap.sigmoid(),offsets:o.offsets,displacementFwd:o.displacementFwd,displacementBwd:o.displacementBwd}})},e.prototype.dispose=function(){this.model.dispose()},e}(),f=function(e){function r(){return null!==e&&e.apply(this,arguments)||this}return i(r,e),r.prototype.preprocessInput=function(e){return(0,t.tidy)(function(){return(0,t.div)(e,127.5).sub(1)})},r.prototype.nameOutputResults=function(t){return{offsets:t[0],heatmap:t[1],displacementFwd:t[2],displacementBwd:t[3]}},r}(l);function p(t){return Math.floor(t/2)}exports.MobileNet=f;var c=function(){function t(t,e){this.priorityQueue=new Array(t),this.numberOfElements=-1,this.getElementValue=e}return t.prototype.enqueue=function(t){this.priorityQueue[++this.numberOfElements]=t,this.swim(this.numberOfElements)},t.prototype.dequeue=function(){var t=this.priorityQueue[0];return this.exchange(0,this.numberOfElements--),this.sink(0),this.priorityQueue[this.numberOfElements+1]=null,t},t.prototype.empty=function(){return-1===this.numberOfElements},t.prototype.size=function(){return this.numberOfElements+1},t.prototype.all=function(){return this.priorityQueue.slice(0,this.numberOfElements+1)},t.prototype.max=function(){return this.priorityQueue[0]},t.prototype.swim=function(t){for(;t>0&&this.less(p(t),t);)this.exchange(t,p(t)),t=p(t)},t.prototype.sink=function(t){for(;2*t<=this.numberOfElements;){var e=2*t;if(e<this.numberOfElements&&this.less(e,e+1)&&e++,!this.less(t,e))break;this.exchange(t,e),t=e}},t.prototype.getValueAt=function(t){return this.getElementValue(this.priorityQueue[t])},t.prototype.less=function(t,e){return this.getValueAt(t)<this.getValueAt(e)},t.prototype.exchange=function(t,e){var r=this.priorityQueue[t];this.priorityQueue[t]=this.priorityQueue[e],this.priorityQueue[e]=r},t}();function h(t,e,r,n,o,i){for(var u=i.shape,s=u[0],a=u[1],l=!0,f=Math.max(r-o,0),p=Math.min(r+o+1,s),c=f;c<p;++c){for(var h=Math.max(n-o,0),d=Math.min(n+o+1,a),m=h;m<d;++m)if(i.get(c,m,t)>e){l=!1;break}if(!l)break}return l}function d(t,e,r){for(var n=r.shape,o=n[0],i=n[1],u=n[2],s=new c(o*i*u,function(t){return t.score}),a=0;a<o;++a)for(var l=0;l<i;++l)for(var f=0;f<u;++f){var p=r.get(a,l,f);p<t||h(f,p,a,l,e,r)&&s.enqueue({score:p,part:{heatmapY:a,heatmapX:l,id:f}})}return s}var m=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"],y=m.length,v=m.reduce(function(t,e,r){return t[e]=r,t},{}),g=[["leftHip","leftShoulder"],["leftElbow","leftShoulder"],["leftElbow","leftWrist"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["rightHip","rightShoulder"],["rightElbow","rightShoulder"],["rightElbow","rightWrist"],["rightHip","rightKnee"],["rightKnee","rightAnkle"],["leftShoulder","rightShoulder"],["leftHip","rightHip"]],b=[["nose","leftEye"],["leftEye","leftEar"],["nose","rightEye"],["rightEye","rightEar"],["nose","leftShoulder"],["leftShoulder","leftElbow"],["leftElbow","leftWrist"],["leftShoulder","leftHip"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["nose","rightShoulder"],["rightShoulder","rightElbow"],["rightElbow","rightWrist"],["rightShoulder","rightHip"],["rightHip","rightKnee"],["rightKnee","rightAnkle"]],w=g.map(function(t){var e=t[0],r=t[1];return[v[e],v[r]]}),x=["left_face","right_face","right_upper_leg_front","right_lower_leg_back","right_upper_leg_back","left_lower_leg_front","left_upper_leg_front","left_upper_leg_back","left_lower_leg_back","right_feet","right_lower_leg_front","left_feet","torso_front","torso_back","right_upper_arm_front","right_upper_arm_back","right_lower_arm_back","left_lower_arm_front","left_upper_arm_front","left_upper_arm_back","left_lower_arm_back","right_hand","right_lower_arm_front","left_hand"];function _(t,e,r,n){return{y:n.get(t,e,r),x:n.get(t,e,r+y)}}function S(t,e,r){var n=_(t.heatmapY,t.heatmapX,t.id,r),o=n.y,i=n.x;return{x:t.heatmapX*e+i,y:t.heatmapY*e+o}}function E(t,e,r){return t<e?e:t>r?r:t}function M(t,e,r,n){var o=r-t,i=n-e;return o*o+i*i}function O(t,e){return{x:t.x+e.x,y:t.y+e.y}}exports.partChannels=x,exports.poseChain=b,exports.partIds=v,exports.partNames=m;var k=b.map(function(t){var e=t[0],r=t[1];return[v[e],v[r]]}),P=k.map(function(t){return t[1]}),j=k.map(function(t){return t[0]});function I(t,e,r){var n=r.shape[2]/2;return{y:r.get(e.y,e.x,t),x:r.get(e.y,e.x,n+t)}}function N(t,e,r,n){return{y:E(Math.round(t.y/e),0,r-1),x:E(Math.round(t.x/e),0,n-1)}}function R(t,e,r,n,o,i,u,s){void 0===s&&(s=2);for(var a=n.shape,l=a[0],f=a[1],p=I(t,N(e.position,i,l,f),u),c=O(e.position,p),h=0;h<s;h++){var d=N(c,i,l,f),y=_(d.y,d.x,r,o);c=O({x:d.x*i,y:d.y*i},{x:y.x,y:y.y})}var v=N(c,i,l,f),g=n.get(v.y,v.x,r);return{position:c,part:m[r],score:g}}function B(t,e,r,n,o,i){var u=e.shape[2],s=P.length,a=new Array(u),l=t.part,f=t.score,p=S(l,n,r);a[l.id]={score:f,part:m[l.id],position:p};for(var c=s-1;c>=0;--c){var h=P[c],d=j[c];a[h]&&!a[d]&&(a[d]=R(c,a[h],d,e,r,n,i))}for(c=0;c<s;++c)h=j[c],d=P[c],a[h]&&!a[d]&&(a[d]=R(c,a[h],d,e,r,n,o));return a}function q(t,e,r,n){var o=r.x,i=r.y;return t.some(function(t){var r=t.keypoints[n].position;return M(i,o,r.y,r.x)<=e})}function A(t,e,r){return r.reduce(function(r,n,o){var i=n.position,u=n.score;return q(t,e,i,o)||(r+=u),r},0)/r.length}var H=1;function F(t,e,r,n,o,i,u,s){void 0===u&&(u=.5),void 0===s&&(s=20);for(var a=[],l=d(u,H,t),f=s*s;a.length<i&&!l.empty();){var p=l.dequeue();if(!q(a,f,S(p.part,o,e),p.part.id)){var c=B(p,t,e,o,r,n),h=A(a,f,c);a.push({keypoints:c,score:h})}}return a}function T(e,r){return(0,t.tidy)(function(){var n=e.div((0,t.scalar)(r,"int32"));return e.sub(n.mul((0,t.scalar)(r,"int32")))})}function V(e){var r=e.shape,n=r[0],o=r[1],i=r[2];return(0,t.tidy)(function(){var r=e.reshape([n*o,i]).argMax(0),u=r.div((0,t.scalar)(o,"int32")).expandDims(1),s=T(r,o).expandDims(1);return(0,t.concat)([u,s],1)})}function Y(t,e){for(var r=e.shape[0],n=new Float32Array(r),o=0;o<r;o++){var i=e.get(o,0),u=e.get(o,1);n[o]=t.get(i,u,o)}return n}function K(t,e,r,n){return{y:n.get(t,e,r),x:n.get(t,e,r+y)}}function Q(e,r){for(var n=[],o=0;o<y;o++){var i=K(e.get(o,0).valueOf(),e.get(o,1).valueOf(),o,r),u=i.x,s=i.y;n.push(s),n.push(u)}return(0,t.tensor2d)(n,[y,2])}function X(e,r,n){return(0,t.tidy)(function(){var o=Q(e,n);return e.toTensor().mul((0,t.scalar)(r,"int32")).toFloat().add(o)})}function z(t,e,r){return s(this,void 0,void 0,function(){var n,o,i,u,s,l,f,p,c,h;return a(this,function(a){switch(a.label){case 0:return n=0,o=V(t),[4,Promise.all([t.buffer(),e.buffer(),o.buffer()])];case 1:return i=a.sent(),u=i[0],s=i[1],l=i[2],[4,(f=X(l,r,s)).buffer()];case 2:return p=a.sent(),c=Array.from(Y(u,l)),h=c.map(function(t,e){return n+=t,{position:{y:p.get(e,0),x:p.get(e,1)},part:m[e],score:t}}),o.dispose(),f.dispose(),[2,{keypoints:h,score:n/h.length}]}})})}var D="https://storage.googleapis.com/tfjs-models/savedmodel/posenet/mobilenet/",W="https://storage.googleapis.com/tfjs-models/savedmodel/posenet/resnet50/";function C(t,e){var r="model-stride"+t+".json";return 4===e?W+"float/"+r:W+"quant"+e+"/"+r}function G(t,e,r){var n={1:"100",.75:"075",.5:"050"},o="model-stride"+t+".json";return 4===r?D+"float/"+n[e]+"/"+o:D+"quant"+r+"/"+n[e]+"/"+o}var U=[-123.15,-115.9,-103.06],J=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return i(e,t),e.prototype.preprocessInput=function(t){return t.add(U)},e.prototype.nameOutputResults=function(t){var e=t[0],r=t[1];return{offsets:t[2],heatmap:t[3],displacementFwd:e,displacementBwd:r}},e}(l);function L(t,e,r){return t<r||e<r}function Z(t,e){return w.reduce(function(r,n){var o=n[0],i=n[1];return L(t[o].score,t[i].score,e)?r:(r.push([t[o],t[i]]),r)},[])}var $=Number.NEGATIVE_INFINITY,tt=Number.POSITIVE_INFINITY;function et(t){return t.reduce(function(t,e){var r=t.maxX,n=t.maxY,o=t.minX,i=t.minY,u=e.position,s=u.x,a=u.y;return{maxX:Math.max(r,s),maxY:Math.max(n,a),minX:Math.min(o,s),minY:Math.min(i,a)}},{maxX:$,maxY:$,minX:tt,minY:tt})}function rt(t){var e=et(t),r=e.minX,n=e.minY,o=e.maxX,i=e.maxY;return[{x:r,y:n},{x:o,y:n},{x:o,y:i},{x:r,y:i}]}function nt(t){return s(this,void 0,void 0,function(){return a(this,function(e){return[2,Promise.all(t.map(function(t){return t.buffer()}))]})})}function ot(t,e,r,n,o){return void 0===n&&(n=0),void 0===o&&(o=0),{score:t.score,keypoints:t.keypoints.map(function(t){var i=t.score,u=t.part,s=t.position;return{score:i,part:u,position:{x:s.x*r+o,y:s.y*e+n}}})}}function it(t,e,r,n,o){return void 0===n&&(n=0),void 0===o&&(o=0),1===r&&1===e&&0===n&&0===o?t:t.map(function(t){return ot(t,e,r,n,o)})}function ut(t,e){return{score:t.score,keypoints:t.keypoints.map(function(t){var r=t.score,n=t.part,o=t.position;return{score:r,part:n,position:{x:e-1-o.x,y:o.y}}})}}function st(t,e){return e<=0?t:t.map(function(t){return ut(t,e)})}function at(t,e){return ht(t,e)?t:Math.floor(t/e)*e+1}function lt(e){t.util.assert("number"==typeof e||"object"==typeof e,function(){return"Invalid inputResolution "+e+". Should be a number or an object with width and height"}),"object"==typeof e&&(t.util.assert("number"==typeof e.width,function(){return"inputResolution.width has a value of "+e.width+" which is invalid; it must be a number"}),t.util.assert("number"==typeof e.height,function(){return"inputResolution.height has a value of "+e.height+" which is invalid; it must be a number"}))}function ft(t,e){return lt(t),"object"==typeof t?[at(t.height,e),at(t.width,e)]:[at(t,e),at(t,e)]}var pt=[8,16,32];function ct(e){t.util.assert("number"==typeof e,function(){return"outputStride is not a number"}),t.util.assert(pt.indexOf(e)>=0,function(){return"outputStride of "+e+" is invalid. It must be either 8, 16, or 32"})}function ht(t,e){return(t-1)%e==0}function dt(e,r){t.util.assert("number"==typeof e[0]&&"number"==typeof e[1],function(){return"both resolution values must be a number but had values "+e}),t.util.assert(ht(e[0],r),function(){return"height of "+e[0]+" is invalid for output stride "+r+"."}),t.util.assert(ht(e[1],r),function(){return"width of "+e[1]+" is invalid for output stride "+r+"."})}function mt(e){return e instanceof t.Tensor?[e.shape[0],e.shape[1]]:[e.height,e.width]}function yt(e){return e instanceof t.Tensor?e:t.browser.fromPixels(e)}function vt(e,r){var n=r[0],o=r[1],i=mt(e),u=i[0],s=i[1],a=o/n,l=[0,0,0,0],f=l[0],p=l[1],c=l[2],h=l[3];return s/u<a?(f=0,p=0,c=Math.round(.5*(a*u-s)),h=Math.round(.5*(a*u-s))):(f=Math.round(.5*(1/a*s-u)),p=Math.round(.5*(1/a*s-u)),c=0,h=0),{resized:(0,t.tidy)(function(){var r=yt(e);return(r=(0,t.pad3d)(r,[[f,p],[c,h],[0,0]])).resizeBilinear([n,o])}),padding:{top:f,left:c,right:h,bottom:p}}}function gt(t,e,r,n,o){var i=e[0],u=e[1],s=r[0],a=r[1],l=it(t,(i+n.top+n.bottom)/s,(u+n.left+n.right)/a,-n.top,-n.left);return o?st(l,u):l}var bt={architecture:"MobileNetV1",outputStride:16,multiplier:.75,inputResolution:257},wt=["MobileNetV1","ResNet50"],xt={MobileNetV1:[8,16,32],ResNet50:[32,16]},_t={MobileNetV1:[.5,.75,1],ResNet50:[1]},St=[1,2,4];function Et(t){if(null==(t=t||bt).architecture&&(t.architecture="MobileNetV1"),wt.indexOf(t.architecture)<0)throw new Error("Invalid architecture "+t.architecture+". Should be one of "+wt);if(null==t.inputResolution&&(t.inputResolution=257),lt(t.inputResolution),null==t.outputStride&&(t.outputStride=16),xt[t.architecture].indexOf(t.outputStride)<0)throw new Error("Invalid outputStride "+t.outputStride+". Should be one of "+xt[t.architecture]+" for architecutre "+t.architecture+".");if(null==t.multiplier&&(t.multiplier=1),_t[t.architecture].indexOf(t.multiplier)<0)throw new Error("Invalid multiplier "+t.multiplier+". Should be one of "+_t[t.architecture]+" for architecutre "+t.architecture+".");if(null==t.quantBytes&&(t.quantBytes=4),St.indexOf(t.quantBytes)<0)throw new Error("Invalid quantBytes "+t.quantBytes+". Should be one of "+St+" for architecutre "+t.architecture+".");return t}var Mt={flipHorizontal:!1},Ot={flipHorizontal:!1,maxDetections:5,scoreThreshold:.5,nmsRadius:20};function kt(t){var e=t.maxDetections,r=t.scoreThreshold,n=t.nmsRadius;if(e<=0)throw new Error("Invalid maxDetections "+e+". Should be > 0");if(r<0||r>1)throw new Error("Invalid scoreThreshold "+r+". Should be in range [0.0, 1.0]");if(n<=0)throw new Error("Invalid nmsRadius "+n+".")}var Pt=function(){function t(t,e){ct(t.outputStride),dt(e,t.outputStride),this.baseModel=t,this.inputResolution=e}return t.prototype.estimateMultiplePoses=function(t,e){return void 0===e&&(e=Ot),s(this,void 0,void 0,function(){var r,n,o,i,s,l,f,p,c,h,d,m,y,v,g,b,w,x,_,S,E;return a(this,function(a){switch(a.label){case 0:return r=u({},Ot,e),kt(e),n=this.baseModel.outputStride,o=this.inputResolution,i=mt(t),s=i[0],l=i[1],f=vt(t,o),p=f.resized,c=f.padding,h=this.baseModel.predict(p),d=h.heatmapScores,m=h.offsets,y=h.displacementFwd,v=h.displacementBwd,[4,nt([d,m,y,v])];case 1:return g=a.sent(),b=g[0],w=g[1],x=g[2],_=g[3],[4,F(b,w,x,_,n,r.maxDetections,r.scoreThreshold,r.nmsRadius)];case 2:return S=a.sent(),E=gt(S,[s,l],o,c,r.flipHorizontal),d.dispose(),m.dispose(),y.dispose(),v.dispose(),p.dispose(),[2,E]}})})},t.prototype.estimateSinglePose=function(t,e){return void 0===e&&(e=Mt),s(this,void 0,void 0,function(){var r,n,o,i,s,l,f,p,c,h,d,m,y,v,g,b;return a(this,function(a){switch(a.label){case 0:return r=u({},Mt,e),n=this.baseModel.outputStride,o=this.inputResolution,i=mt(t),s=i[0],l=i[1],f=vt(t,o),p=f.resized,c=f.padding,h=this.baseModel.predict(p),d=h.heatmapScores,m=h.offsets,y=h.displacementFwd,v=h.displacementBwd,[4,z(d,m,n)];case 1:return g=a.sent(),b=gt([g],[s,l],o,c,r.flipHorizontal),d.dispose(),m.dispose(),y.dispose(),v.dispose(),p.dispose(),[2,b[0]]}})})},t.prototype.estimatePoses=function(t,e){return s(this,void 0,void 0,function(){return a(this,function(r){switch(r.label){case 0:return"single-person"!==e.decodingMethod?[3,2]:[4,this.estimateSinglePose(t,e)];case 1:return[2,[r.sent()]];case 2:return[2,this.estimateMultiplePoses(t,e)]}})})},t.prototype.dispose=function(){this.baseModel.dispose()},t}();function jt(r){return s(this,void 0,void 0,function(){var n,o,i,u,s,l,p;return a(this,function(a){switch(a.label){case 0:if(n=r.outputStride,o=r.quantBytes,i=r.multiplier,null==t)throw new Error("Cannot find TensorFlow.js. If you are using a <script> tag, please also include @tensorflow/tfjs on the page before using this\n        model.");return u=G(n,i,o),[4,(0,e.loadGraphModel)(r.modelUrl||u)];case 1:return s=a.sent(),l=new f(s,n),p=ft(r.inputResolution,l.outputStride),[2,new Pt(l,p)]}})})}function It(r){return s(this,void 0,void 0,function(){var n,o,i,u,s,l;return a(this,function(a){switch(a.label){case 0:if(n=r.outputStride,o=r.quantBytes,null==t)throw new Error("Cannot find TensorFlow.js. If you are using a <script> tag, please also include @tensorflow/tfjs on the page before using this\n        model.");return i=C(n,o),[4,(0,e.loadGraphModel)(r.modelUrl||i)];case 1:return u=a.sent(),s=new J(u,n),l=ft(r.inputResolution,s.outputStride),[2,new Pt(s,l)]}})})}function Nt(t){return void 0===t&&(t=bt),s(this,void 0,void 0,function(){return a(this,function(e){return"ResNet50"===(t=Et(t)).architecture?[2,It(t)]:"MobileNetV1"===t.architecture?[2,jt(t)]:[2,null]})})}exports.PoseNet=Pt;var Rt="2.2.1";exports.version=Rt;
  },{"@tensorflow/tfjs-core":"PqBP","@tensorflow/tfjs-converter":"rGPK"}],"ArXC":[function(require,module,exports) {
  "use strict";function e(e){if(e&&"undefined"!=typeof window){var t=document.createElement("style");return t.setAttribute("type","text/css"),t.innerHTML=e,document.head.appendChild(t),e}}function t(e,t){var n=e.__state.conversionName.toString(),o=Math.round(e.r),i=Math.round(e.g),r=Math.round(e.b),s=e.a,a=Math.round(e.h),l=e.s.toFixed(1),d=e.v.toFixed(1);if(t||"THREE_CHAR_HEX"===n||"SIX_CHAR_HEX"===n){for(var c=e.hex.toString(16);c.length<6;)c="0"+c;return"#"+c}return"CSS_RGB"===n?"rgb("+o+","+i+","+r+")":"CSS_RGBA"===n?"rgba("+o+","+i+","+r+","+s+")":"HEX"===n?"0x"+e.hex.toString(16):"RGB_ARRAY"===n?"["+o+","+i+","+r+"]":"RGBA_ARRAY"===n?"["+o+","+i+","+r+","+s+"]":"RGB_OBJ"===n?"{r:"+o+",g:"+i+",b:"+r+"}":"RGBA_OBJ"===n?"{r:"+o+",g:"+i+",b:"+r+",a:"+s+"}":"HSV_OBJ"===n?"{h:"+a+",s:"+l+",v:"+d+"}":"HSVA_OBJ"===n?"{h:"+a+",s:"+l+",v:"+d+",a:"+s+"}":"unknown format"}Object.defineProperty(exports,"__esModule",{value:!0}),exports.default=exports.GUI=exports.gui=exports.dom=exports.controllers=exports.color=void 0;var n=Array.prototype.forEach,o=Array.prototype.slice,i={BREAK:{},extend:function(e){return this.each(o.call(arguments,1),function(t){(this.isObject(t)?Object.keys(t):[]).forEach(function(n){this.isUndefined(t[n])||(e[n]=t[n])}.bind(this))},this),e},defaults:function(e){return this.each(o.call(arguments,1),function(t){(this.isObject(t)?Object.keys(t):[]).forEach(function(n){this.isUndefined(e[n])&&(e[n]=t[n])}.bind(this))},this),e},compose:function(){var e=o.call(arguments);return function(){for(var t=o.call(arguments),n=e.length-1;n>=0;n--)t=[e[n].apply(this,t)];return t[0]}},each:function(e,t,o){if(e)if(n&&e.forEach&&e.forEach===n)e.forEach(t,o);else if(e.length===e.length+0){var i,r=void 0;for(r=0,i=e.length;r<i;r++)if(r in e&&t.call(o,e[r],r)===this.BREAK)return}else for(var s in e)if(t.call(o,e[s],s)===this.BREAK)return},defer:function(e){setTimeout(e,0)},debounce:function(e,t,n){var o=void 0;return function(){var i=this,r=arguments;var s=n||!o;clearTimeout(o),o=setTimeout(function(){o=null,n||e.apply(i,r)},t),s&&e.apply(i,r)}},toArray:function(e){return e.toArray?e.toArray():o.call(e)},isUndefined:function(e){return void 0===e},isNull:function(e){return null===e},isNaN:function(e){function t(t){return e.apply(this,arguments)}return t.toString=function(){return e.toString()},t}(function(e){return isNaN(e)}),isArray:Array.isArray||function(e){return e.constructor===Array},isObject:function(e){return e===Object(e)},isNumber:function(e){return e===e+0},isString:function(e){return e===e+""},isBoolean:function(e){return!1===e||!0===e},isFunction:function(e){return e instanceof Function}},r=[{litmus:i.isString,conversions:{THREE_CHAR_HEX:{read:function(e){var t=e.match(/^#([A-F0-9])([A-F0-9])([A-F0-9])$/i);return null!==t&&{space:"HEX",hex:parseInt("0x"+t[1].toString()+t[1].toString()+t[2].toString()+t[2].toString()+t[3].toString()+t[3].toString(),0)}},write:t},SIX_CHAR_HEX:{read:function(e){var t=e.match(/^#([A-F0-9]{6})$/i);return null!==t&&{space:"HEX",hex:parseInt("0x"+t[1].toString(),0)}},write:t},CSS_RGB:{read:function(e){var t=e.match(/^rgb\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);return null!==t&&{space:"RGB",r:parseFloat(t[1]),g:parseFloat(t[2]),b:parseFloat(t[3])}},write:t},CSS_RGBA:{read:function(e){var t=e.match(/^rgba\(\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*,\s*(.+)\s*\)/);return null!==t&&{space:"RGB",r:parseFloat(t[1]),g:parseFloat(t[2]),b:parseFloat(t[3]),a:parseFloat(t[4])}},write:t}}},{litmus:i.isNumber,conversions:{HEX:{read:function(e){return{space:"HEX",hex:e,conversionName:"HEX"}},write:function(e){return e.hex}}}},{litmus:i.isArray,conversions:{RGB_ARRAY:{read:function(e){return 3===e.length&&{space:"RGB",r:e[0],g:e[1],b:e[2]}},write:function(e){return[e.r,e.g,e.b]}},RGBA_ARRAY:{read:function(e){return 4===e.length&&{space:"RGB",r:e[0],g:e[1],b:e[2],a:e[3]}},write:function(e){return[e.r,e.g,e.b,e.a]}}}},{litmus:i.isObject,conversions:{RGBA_OBJ:{read:function(e){return!!(i.isNumber(e.r)&&i.isNumber(e.g)&&i.isNumber(e.b)&&i.isNumber(e.a))&&{space:"RGB",r:e.r,g:e.g,b:e.b,a:e.a}},write:function(e){return{r:e.r,g:e.g,b:e.b,a:e.a}}},RGB_OBJ:{read:function(e){return!!(i.isNumber(e.r)&&i.isNumber(e.g)&&i.isNumber(e.b))&&{space:"RGB",r:e.r,g:e.g,b:e.b}},write:function(e){return{r:e.r,g:e.g,b:e.b}}},HSVA_OBJ:{read:function(e){return!!(i.isNumber(e.h)&&i.isNumber(e.s)&&i.isNumber(e.v)&&i.isNumber(e.a))&&{space:"HSV",h:e.h,s:e.s,v:e.v,a:e.a}},write:function(e){return{h:e.h,s:e.s,v:e.v,a:e.a}}},HSV_OBJ:{read:function(e){return!!(i.isNumber(e.h)&&i.isNumber(e.s)&&i.isNumber(e.v))&&{space:"HSV",h:e.h,s:e.s,v:e.v}},write:function(e){return{h:e.h,s:e.s,v:e.v}}}}}],s=void 0,a=void 0,l=function(){a=!1;var e=arguments.length>1?i.toArray(arguments):arguments[0];return i.each(r,function(t){if(t.litmus(e))return i.each(t.conversions,function(t,n){if(s=t.read(e),!1===a&&!1!==s)return a=s,s.conversionName=n,s.conversion=t,i.BREAK}),i.BREAK}),a},d=void 0,c={hsv_to_rgb:function(e,t,n){var o=Math.floor(e/60)%6,i=e/60-Math.floor(e/60),r=n*(1-t),s=n*(1-i*t),a=n*(1-(1-i)*t),l=[[n,a,r],[s,n,r],[r,n,a],[r,s,n],[a,r,n],[n,r,s]][o];return{r:255*l[0],g:255*l[1],b:255*l[2]}},rgb_to_hsv:function(e,t,n){var o=Math.min(e,t,n),i=Math.max(e,t,n),r=i-o,s=void 0;return 0===i?{h:NaN,s:0,v:0}:(s=e===i?(t-n)/r:t===i?2+(n-e)/r:4+(e-t)/r,(s/=6)<0&&(s+=1),{h:360*s,s:r/i,v:i/255})},rgb_to_hex:function(e,t,n){var o=this.hex_with_component(0,2,e);return o=this.hex_with_component(o,1,t),o=this.hex_with_component(o,0,n)},component_from_hex:function(e,t){return e>>8*t&255},hex_with_component:function(e,t,n){return n<<(d=8*t)|e&~(255<<d)}},u="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},_=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},h=function(){function e(e,t){for(var n=0;n<t.length;n++){var o=t[n];o.enumerable=o.enumerable||!1,o.configurable=!0,"value"in o&&(o.writable=!0),Object.defineProperty(e,o.key,o)}}return function(t,n,o){return n&&e(t.prototype,n),o&&e(t,o),t}}(),p=function e(t,n,o){null===t&&(t=Function.prototype);var i=Object.getOwnPropertyDescriptor(t,n);if(void 0===i){var r=Object.getPrototypeOf(t);return null===r?void 0:e(r,n,o)}if("value"in i)return i.value;var s=i.get;return void 0!==s?s.call(o):void 0},f=function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)},m=function(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t},g=function(){function e(){if(_(this,e),this.__state=l.apply(this,arguments),!1===this.__state)throw new Error("Failed to interpret color arguments");this.__state.a=this.__state.a||1}return h(e,[{key:"toString",value:function(){return t(this)}},{key:"toHexString",value:function(){return t(this,!0)}},{key:"toOriginal",value:function(){return this.__state.conversion.write(this)}}]),e}();function b(e,t,n){Object.defineProperty(e,t,{get:function(){return"RGB"===this.__state.space?this.__state[t]:(g.recalculateRGB(this,t,n),this.__state[t])},set:function(e){"RGB"!==this.__state.space&&(g.recalculateRGB(this,t,n),this.__state.space="RGB"),this.__state[t]=e}})}function v(e,t){Object.defineProperty(e,t,{get:function(){return"HSV"===this.__state.space?this.__state[t]:(g.recalculateHSV(this),this.__state[t])},set:function(e){"HSV"!==this.__state.space&&(g.recalculateHSV(this),this.__state.space="HSV"),this.__state[t]=e}})}g.recalculateRGB=function(e,t,n){if("HEX"===e.__state.space)e.__state[t]=c.component_from_hex(e.__state.hex,n);else{if("HSV"!==e.__state.space)throw new Error("Corrupted color state");i.extend(e.__state,c.hsv_to_rgb(e.__state.h,e.__state.s,e.__state.v))}},g.recalculateHSV=function(e){var t=c.rgb_to_hsv(e.r,e.g,e.b);i.extend(e.__state,{s:t.s,v:t.v}),i.isNaN(t.h)?i.isUndefined(e.__state.h)&&(e.__state.h=0):e.__state.h=t.h},g.COMPONENTS=["r","g","b","h","s","v","hex","a"],b(g.prototype,"r",2),b(g.prototype,"g",1),b(g.prototype,"b",0),v(g.prototype,"h"),v(g.prototype,"s"),v(g.prototype,"v"),Object.defineProperty(g.prototype,"a",{get:function(){return this.__state.a},set:function(e){this.__state.a=e}}),Object.defineProperty(g.prototype,"hex",{get:function(){return"HEX"!==this.__state.space&&(this.__state.hex=c.rgb_to_hex(this.r,this.g,this.b),this.__state.space="HEX"),this.__state.hex},set:function(e){this.__state.space="HEX",this.__state.hex=e}});var y=function(){function e(t,n){_(this,e),this.initialValue=t[n],this.domElement=document.createElement("div"),this.object=t,this.property=n,this.__onChange=void 0,this.__onFinishChange=void 0}return h(e,[{key:"onChange",value:function(e){return this.__onChange=e,this}},{key:"onFinishChange",value:function(e){return this.__onFinishChange=e,this}},{key:"setValue",value:function(e){return this.object[this.property]=e,this.__onChange&&this.__onChange.call(this,e),this.updateDisplay(),this}},{key:"getValue",value:function(){return this.object[this.property]}},{key:"updateDisplay",value:function(){return this}},{key:"isModified",value:function(){return this.initialValue!==this.getValue()}}]),e}(),w={HTMLEvents:["change"],MouseEvents:["click","mousemove","mousedown","mouseup","mouseover"],KeyboardEvents:["keydown"]},x={};i.each(w,function(e,t){i.each(e,function(e){x[e]=t})});var E=/(\d+(\.\d+)?)px/;function C(e){if("0"===e||i.isUndefined(e))return 0;var t=e.match(E);return i.isNull(t)?0:parseFloat(t[1])}var A={makeSelectable:function(e,t){void 0!==e&&void 0!==e.style&&(e.onselectstart=t?function(){return!1}:function(){},e.style.MozUserSelect=t?"auto":"none",e.style.KhtmlUserSelect=t?"auto":"none",e.unselectable=t?"on":"off")},makeFullscreen:function(e,t,n){var o=n,r=t;i.isUndefined(r)&&(r=!0),i.isUndefined(o)&&(o=!0),e.style.position="absolute",r&&(e.style.left=0,e.style.right=0),o&&(e.style.top=0,e.style.bottom=0)},fakeEvent:function(e,t,n,o){var r=n||{},s=x[t];if(!s)throw new Error("Event type "+t+" not supported.");var a=document.createEvent(s);switch(s){case"MouseEvents":var l=r.x||r.clientX||0,d=r.y||r.clientY||0;a.initMouseEvent(t,r.bubbles||!1,r.cancelable||!0,window,r.clickCount||1,0,0,l,d,!1,!1,!1,!1,0,null);break;case"KeyboardEvents":var c=a.initKeyboardEvent||a.initKeyEvent;i.defaults(r,{cancelable:!0,ctrlKey:!1,altKey:!1,shiftKey:!1,metaKey:!1,keyCode:void 0,charCode:void 0}),c(t,r.bubbles||!1,r.cancelable,window,r.ctrlKey,r.altKey,r.shiftKey,r.metaKey,r.keyCode,r.charCode);break;default:a.initEvent(t,r.bubbles||!1,r.cancelable||!0)}i.defaults(a,o),e.dispatchEvent(a)},bind:function(e,t,n,o){var i=o||!1;return e.addEventListener?e.addEventListener(t,n,i):e.attachEvent&&e.attachEvent("on"+t,n),A},unbind:function(e,t,n,o){var i=o||!1;return e.removeEventListener?e.removeEventListener(t,n,i):e.detachEvent&&e.detachEvent("on"+t,n),A},addClass:function(e,t){if(void 0===e.className)e.className=t;else if(e.className!==t){var n=e.className.split(/ +/);-1===n.indexOf(t)&&(n.push(t),e.className=n.join(" ").replace(/^\s+/,"").replace(/\s+$/,""))}return A},removeClass:function(e,t){if(t)if(e.className===t)e.removeAttribute("class");else{var n=e.className.split(/ +/),o=n.indexOf(t);-1!==o&&(n.splice(o,1),e.className=n.join(" "))}else e.className=void 0;return A},hasClass:function(e,t){return new RegExp("(?:^|\\s+)"+t+"(?:\\s+|$)").test(e.className)||!1},getWidth:function(e){var t=getComputedStyle(e);return C(t["border-left-width"])+C(t["border-right-width"])+C(t["padding-left"])+C(t["padding-right"])+C(t.width)},getHeight:function(e){var t=getComputedStyle(e);return C(t["border-top-width"])+C(t["border-bottom-width"])+C(t["padding-top"])+C(t["padding-bottom"])+C(t.height)},getOffset:function(e){var t=e,n={left:0,top:0};if(t.offsetParent)do{n.left+=t.offsetLeft,n.top+=t.offsetTop,t=t.offsetParent}while(t);return n},isActive:function(e){return e===document.activeElement&&(e.type||e.href)}},k=function(e){function t(e,n){_(this,t);var o=m(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n)),i=o;return o.__prev=o.getValue(),o.__checkbox=document.createElement("input"),o.__checkbox.setAttribute("type","checkbox"),A.bind(o.__checkbox,"change",function(){i.setValue(!i.__prev)},!1),o.domElement.appendChild(o.__checkbox),o.updateDisplay(),o}return f(t,y),h(t,[{key:"setValue",value:function(e){var n=p(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"setValue",this).call(this,e);return this.__onFinishChange&&this.__onFinishChange.call(this,this.getValue()),this.__prev=this.getValue(),n}},{key:"updateDisplay",value:function(){return!0===this.getValue()?(this.__checkbox.setAttribute("checked","checked"),this.__checkbox.checked=!0,this.__prev=!0):(this.__checkbox.checked=!1,this.__prev=!1),p(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"updateDisplay",this).call(this)}}]),t}(),S=function(e){function t(e,n,o){_(this,t);var r=m(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n)),s=o,a=r;if(r.__select=document.createElement("select"),i.isArray(s)){var l={};i.each(s,function(e){l[e]=e}),s=l}return i.each(s,function(e,t){var n=document.createElement("option");n.innerHTML=t,n.setAttribute("value",e),a.__select.appendChild(n)}),r.updateDisplay(),A.bind(r.__select,"change",function(){var e=this.options[this.selectedIndex].value;a.setValue(e)}),r.domElement.appendChild(r.__select),r}return f(t,y),h(t,[{key:"setValue",value:function(e){var n=p(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"setValue",this).call(this,e);return this.__onFinishChange&&this.__onFinishChange.call(this,this.getValue()),n}},{key:"updateDisplay",value:function(){return A.isActive(this.__select)?this:(this.__select.value=this.getValue(),p(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"updateDisplay",this).call(this))}}]),t}(),O=function(e){function t(e,n){_(this,t);var o=m(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n)),i=o;function r(){i.setValue(i.__input.value)}return o.__input=document.createElement("input"),o.__input.setAttribute("type","text"),A.bind(o.__input,"keyup",r),A.bind(o.__input,"change",r),A.bind(o.__input,"blur",function(){i.__onFinishChange&&i.__onFinishChange.call(i,i.getValue())}),A.bind(o.__input,"keydown",function(e){13===e.keyCode&&this.blur()}),o.updateDisplay(),o.domElement.appendChild(o.__input),o}return f(t,y),h(t,[{key:"updateDisplay",value:function(){return A.isActive(this.__input)||(this.__input.value=this.getValue()),p(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"updateDisplay",this).call(this)}}]),t}();function T(e){var t=e.toString();return t.indexOf(".")>-1?t.length-t.indexOf(".")-1:0}var L=function(e){function t(e,n,o){_(this,t);var r=m(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n)),s=o||{};return r.__min=s.min,r.__max=s.max,r.__step=s.step,i.isUndefined(r.__step)?0===r.initialValue?r.__impliedStep=1:r.__impliedStep=Math.pow(10,Math.floor(Math.log(Math.abs(r.initialValue))/Math.LN10))/10:r.__impliedStep=r.__step,r.__precision=T(r.__impliedStep),r}return f(t,y),h(t,[{key:"setValue",value:function(e){var n=e;return void 0!==this.__min&&n<this.__min?n=this.__min:void 0!==this.__max&&n>this.__max&&(n=this.__max),void 0!==this.__step&&n%this.__step!=0&&(n=Math.round(n/this.__step)*this.__step),p(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"setValue",this).call(this,n)}},{key:"min",value:function(e){return this.__min=e,this}},{key:"max",value:function(e){return this.__max=e,this}},{key:"step",value:function(e){return this.__step=e,this.__impliedStep=e,this.__precision=T(e),this}}]),t}();function R(e,t){var n=Math.pow(10,t);return Math.round(e*n)/n}var B=function(e){function t(e,n,o){_(this,t);var r=m(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n,o));r.__truncationSuspended=!1;var s=r,a=void 0;function l(){s.__onFinishChange&&s.__onFinishChange.call(s,s.getValue())}function d(e){var t=a-e.clientY;s.setValue(s.getValue()+t*s.__impliedStep),a=e.clientY}function c(){A.unbind(window,"mousemove",d),A.unbind(window,"mouseup",c),l()}return r.__input=document.createElement("input"),r.__input.setAttribute("type","text"),A.bind(r.__input,"change",function(){var e=parseFloat(s.__input.value);i.isNaN(e)||s.setValue(e)}),A.bind(r.__input,"blur",function(){l()}),A.bind(r.__input,"mousedown",function(e){A.bind(window,"mousemove",d),A.bind(window,"mouseup",c),a=e.clientY}),A.bind(r.__input,"keydown",function(e){13===e.keyCode&&(s.__truncationSuspended=!0,this.blur(),s.__truncationSuspended=!1,l())}),r.updateDisplay(),r.domElement.appendChild(r.__input),r}return f(t,L),h(t,[{key:"updateDisplay",value:function(){return this.__input.value=this.__truncationSuspended?this.getValue():R(this.getValue(),this.__precision),p(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"updateDisplay",this).call(this)}}]),t}();function N(e,t,n,o,i){return o+(e-t)/(n-t)*(i-o)}var H=function(e){function t(e,n,o,i,r){_(this,t);var s=m(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n,{min:o,max:i,step:r})),a=s;function l(e){e.preventDefault();var t=a.__background.getBoundingClientRect();return a.setValue(N(e.clientX,t.left,t.right,a.__min,a.__max)),!1}function d(){A.unbind(window,"mousemove",l),A.unbind(window,"mouseup",d),a.__onFinishChange&&a.__onFinishChange.call(a,a.getValue())}function c(e){var t=e.touches[0].clientX,n=a.__background.getBoundingClientRect();a.setValue(N(t,n.left,n.right,a.__min,a.__max))}function u(){A.unbind(window,"touchmove",c),A.unbind(window,"touchend",u),a.__onFinishChange&&a.__onFinishChange.call(a,a.getValue())}return s.__background=document.createElement("div"),s.__foreground=document.createElement("div"),A.bind(s.__background,"mousedown",function(e){document.activeElement.blur(),A.bind(window,"mousemove",l),A.bind(window,"mouseup",d),l(e)}),A.bind(s.__background,"touchstart",function(e){if(1!==e.touches.length)return;A.bind(window,"touchmove",c),A.bind(window,"touchend",u),c(e)}),A.addClass(s.__background,"slider"),A.addClass(s.__foreground,"slider-fg"),s.updateDisplay(),s.__background.appendChild(s.__foreground),s.domElement.appendChild(s.__background),s}return f(t,L),h(t,[{key:"updateDisplay",value:function(){var e=(this.getValue()-this.__min)/(this.__max-this.__min);return this.__foreground.style.width=100*e+"%",p(t.prototype.__proto__||Object.getPrototypeOf(t.prototype),"updateDisplay",this).call(this)}}]),t}(),F=function(e){function t(e,n,o){_(this,t);var i=m(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n)),r=i;return i.__button=document.createElement("div"),i.__button.innerHTML=void 0===o?"Fire":o,A.bind(i.__button,"click",function(e){return e.preventDefault(),r.fire(),!1}),A.addClass(i.__button,"button"),i.domElement.appendChild(i.__button),i}return f(t,y),h(t,[{key:"fire",value:function(){this.__onChange&&this.__onChange.call(this),this.getValue().call(this.object),this.__onFinishChange&&this.__onFinishChange.call(this,this.getValue())}}]),t}(),P=function(e){function t(e,n){_(this,t);var o=m(this,(t.__proto__||Object.getPrototypeOf(t)).call(this,e,n));o.__color=new g(o.getValue()),o.__temp=new g(0);var r=o;o.domElement=document.createElement("div"),A.makeSelectable(o.domElement,!1),o.__selector=document.createElement("div"),o.__selector.className="selector",o.__saturation_field=document.createElement("div"),o.__saturation_field.className="saturation-field",o.__field_knob=document.createElement("div"),o.__field_knob.className="field-knob",o.__field_knob_border="2px solid ",o.__hue_knob=document.createElement("div"),o.__hue_knob.className="hue-knob",o.__hue_field=document.createElement("div"),o.__hue_field.className="hue-field",o.__input=document.createElement("input"),o.__input.type="text",o.__input_textShadow="0 1px 1px ",A.bind(o.__input,"keydown",function(e){13===e.keyCode&&h.call(this)}),A.bind(o.__input,"blur",h),A.bind(o.__selector,"mousedown",function(){A.addClass(this,"drag").bind(window,"mouseup",function(){A.removeClass(r.__selector,"drag")})}),A.bind(o.__selector,"touchstart",function(){A.addClass(this,"drag").bind(window,"touchend",function(){A.removeClass(r.__selector,"drag")})});var s=document.createElement("div");function a(e){f(e),A.bind(window,"mousemove",f),A.bind(window,"touchmove",f),A.bind(window,"mouseup",c),A.bind(window,"touchend",c)}function d(e){b(e),A.bind(window,"mousemove",b),A.bind(window,"touchmove",b),A.bind(window,"mouseup",u),A.bind(window,"touchend",u)}function c(){A.unbind(window,"mousemove",f),A.unbind(window,"touchmove",f),A.unbind(window,"mouseup",c),A.unbind(window,"touchend",c),p()}function u(){A.unbind(window,"mousemove",b),A.unbind(window,"touchmove",b),A.unbind(window,"mouseup",u),A.unbind(window,"touchend",u),p()}function h(){var e=l(this.value);!1!==e?(r.__color.__state=e,r.setValue(r.__color.toOriginal())):this.value=r.__color.toString()}function p(){r.__onFinishChange&&r.__onFinishChange.call(r,r.__color.toOriginal())}function f(e){-1===e.type.indexOf("touch")&&e.preventDefault();var t=r.__saturation_field.getBoundingClientRect(),n=e.touches&&e.touches[0]||e,o=n.clientX,i=n.clientY,s=(o-t.left)/(t.right-t.left),a=1-(i-t.top)/(t.bottom-t.top);return a>1?a=1:a<0&&(a=0),s>1?s=1:s<0&&(s=0),r.__color.v=a,r.__color.s=s,r.setValue(r.__color.toOriginal()),!1}function b(e){-1===e.type.indexOf("touch")&&e.preventDefault();var t=r.__hue_field.getBoundingClientRect(),n=1-((e.touches&&e.touches[0]||e).clientY-t.top)/(t.bottom-t.top);return n>1?n=1:n<0&&(n=0),r.__color.h=360*n,r.setValue(r.__color.toOriginal()),!1}return i.extend(o.__selector.style,{width:"122px",height:"102px",padding:"3px",backgroundColor:"#222",boxShadow:"0px 1px 3px rgba(0,0,0,0.3)"}),i.extend(o.__field_knob.style,{position:"absolute",width:"12px",height:"12px",border:o.__field_knob_border+(o.__color.v<.5?"#fff":"#000"),boxShadow:"0px 1px 3px rgba(0,0,0,0.5)",borderRadius:"12px",zIndex:1}),i.extend(o.__hue_knob.style,{position:"absolute",width:"15px",height:"2px",borderRight:"4px solid #fff",zIndex:1}),i.extend(o.__saturation_field.style,{width:"100px",height:"100px",border:"1px solid #555",marginRight:"3px",display:"inline-block",cursor:"pointer"}),i.extend(s.style,{width:"100%",height:"100%",background:"none"}),j(s,"top","rgba(0,0,0,0)","#000"),i.extend(o.__hue_field.style,{width:"15px",height:"100px",border:"1px solid #555",cursor:"ns-resize",position:"absolute",top:"3px",right:"3px"}),V(o.__hue_field),i.extend(o.__input.style,{outline:"none",textAlign:"center",color:"#fff",border:0,fontWeight:"bold",textShadow:o.__input_textShadow+"rgba(0,0,0,0.7)"}),A.bind(o.__saturation_field,"mousedown",a),A.bind(o.__saturation_field,"touchstart",a),A.bind(o.__field_knob,"mousedown",a),A.bind(o.__field_knob,"touchstart",a),A.bind(o.__hue_field,"mousedown",d),A.bind(o.__hue_field,"touchstart",d),o.__saturation_field.appendChild(s),o.__selector.appendChild(o.__field_knob),o.__selector.appendChild(o.__saturation_field),o.__selector.appendChild(o.__hue_field),o.__hue_field.appendChild(o.__hue_knob),o.domElement.appendChild(o.__input),o.domElement.appendChild(o.__selector),o.updateDisplay(),o}return f(t,y),h(t,[{key:"updateDisplay",value:function(){var e=l(this.getValue());if(!1!==e){var t=!1;i.each(g.COMPONENTS,function(n){if(!i.isUndefined(e[n])&&!i.isUndefined(this.__color.__state[n])&&e[n]!==this.__color.__state[n])return t=!0,{}},this),t&&i.extend(this.__color.__state,e)}i.extend(this.__temp.__state,this.__color.__state),this.__temp.a=1;var n=this.__color.v<.5||this.__color.s>.5?255:0,o=255-n;i.extend(this.__field_knob.style,{marginLeft:100*this.__color.s-7+"px",marginTop:100*(1-this.__color.v)-7+"px",backgroundColor:this.__temp.toHexString(),border:this.__field_knob_border+"rgb("+n+","+n+","+n+")"}),this.__hue_knob.style.marginTop=100*(1-this.__color.h/360)+"px",this.__temp.s=1,this.__temp.v=1,j(this.__saturation_field,"left","#fff",this.__temp.toHexString()),this.__input.value=this.__color.toString(),i.extend(this.__input.style,{backgroundColor:this.__color.toHexString(),color:"rgb("+n+","+n+","+n+")",textShadow:this.__input_textShadow+"rgba("+o+","+o+","+o+",.7)"})}}]),t}(),D=["-moz-","-o-","-webkit-","-ms-",""];function j(e,t,n,o){e.style.background="",i.each(D,function(i){e.style.cssText+="background: "+i+"linear-gradient("+t+", "+n+" 0%, "+o+" 100%); "})}function V(e){e.style.background="",e.style.cssText+="background: -moz-linear-gradient(top,  #ff0000 0%, #ff00ff 17%, #0000ff 34%, #00ffff 50%, #00ff00 67%, #ffff00 84%, #ff0000 100%);",e.style.cssText+="background: -webkit-linear-gradient(top,  #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);",e.style.cssText+="background: -o-linear-gradient(top,  #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);",e.style.cssText+="background: -ms-linear-gradient(top,  #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);",e.style.cssText+="background: linear-gradient(top,  #ff0000 0%,#ff00ff 17%,#0000ff 34%,#00ffff 50%,#00ff00 67%,#ffff00 84%,#ff0000 100%);"}var I={load:function(e,t){var n=t||document,o=n.createElement("link");o.type="text/css",o.rel="stylesheet",o.href=e,n.getElementsByTagName("head")[0].appendChild(o)},inject:function(e,t){var n=t||document,o=document.createElement("style");o.type="text/css",o.innerHTML=e;var i=n.getElementsByTagName("head")[0];try{i.appendChild(o)}catch(r){}}},z='<div id="dg-save" class="dg dialogue">\n\n  Here\'s the new load parameter for your <code>GUI</code>\'s constructor:\n\n  <textarea id="dg-new-constructor"></textarea>\n\n  <div id="dg-save-locally">\n\n    <input id="dg-local-storage" type="checkbox"/> Automatically save\n    values to <code>localStorage</code> on exit.\n\n    <div id="dg-local-explain">The values saved to <code>localStorage</code> will\n      override those passed to <code>dat.GUI</code>\'s constructor. This makes it\n      easier to work incrementally, but <code>localStorage</code> is fragile,\n      and your friends may not see the same values you do.\n\n    </div>\n\n  </div>\n\n</div>',M=function(e,t){var n=e[t];return i.isArray(arguments[2])||i.isObject(arguments[2])?new S(e,t,arguments[2]):i.isNumber(n)?i.isNumber(arguments[2])&&i.isNumber(arguments[3])?i.isNumber(arguments[4])?new H(e,t,arguments[2],arguments[3],arguments[4]):new H(e,t,arguments[2],arguments[3]):i.isNumber(arguments[4])?new B(e,t,{min:arguments[2],max:arguments[3],step:arguments[4]}):new B(e,t,{min:arguments[2],max:arguments[3]}):i.isString(n)?new O(e,t):i.isFunction(n)?new F(e,t,""):i.isBoolean(n)?new k(e,t):null};function G(e){setTimeout(e,1e3/60)}var U=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||G,X=function(){function e(){_(this,e),this.backgroundElement=document.createElement("div"),i.extend(this.backgroundElement.style,{backgroundColor:"rgba(0,0,0,0.8)",top:0,left:0,display:"none",zIndex:"1000",opacity:0,WebkitTransition:"opacity 0.2s linear",transition:"opacity 0.2s linear"}),A.makeFullscreen(this.backgroundElement),this.backgroundElement.style.position="fixed",this.domElement=document.createElement("div"),i.extend(this.domElement.style,{position:"fixed",display:"none",zIndex:"1001",opacity:0,WebkitTransition:"-webkit-transform 0.2s ease-out, opacity 0.2s linear",transition:"transform 0.2s ease-out, opacity 0.2s linear"}),document.body.appendChild(this.backgroundElement),document.body.appendChild(this.domElement);var t=this;A.bind(this.backgroundElement,"click",function(){t.hide()})}return h(e,[{key:"show",value:function(){var e=this;this.backgroundElement.style.display="block",this.domElement.style.display="block",this.domElement.style.opacity=0,this.domElement.style.webkitTransform="scale(1.1)",this.layout(),i.defer(function(){e.backgroundElement.style.opacity=1,e.domElement.style.opacity=1,e.domElement.style.webkitTransform="scale(1)"})}},{key:"hide",value:function(){var e=this,t=function t(){e.domElement.style.display="none",e.backgroundElement.style.display="none",A.unbind(e.domElement,"webkitTransitionEnd",t),A.unbind(e.domElement,"transitionend",t),A.unbind(e.domElement,"oTransitionEnd",t)};A.bind(this.domElement,"webkitTransitionEnd",t),A.bind(this.domElement,"transitionend",t),A.bind(this.domElement,"oTransitionEnd",t),this.backgroundElement.style.opacity=0,this.domElement.style.opacity=0,this.domElement.style.webkitTransform="scale(1.1)"}},{key:"layout",value:function(){this.domElement.style.left=window.innerWidth/2-A.getWidth(this.domElement)/2+"px",this.domElement.style.top=window.innerHeight/2-A.getHeight(this.domElement)/2+"px"}}]),e}(),K=e(".dg ul{list-style:none;margin:0;padding:0;width:100%;clear:both}.dg.ac{position:fixed;top:0;left:0;right:0;height:0;z-index:0}.dg:not(.ac) .main{overflow:hidden}.dg.main{-webkit-transition:opacity .1s linear;-o-transition:opacity .1s linear;-moz-transition:opacity .1s linear;transition:opacity .1s linear}.dg.main.taller-than-window{overflow-y:auto}.dg.main.taller-than-window .close-button{opacity:1;margin-top:-1px;border-top:1px solid #2c2c2c}.dg.main ul.closed .close-button{opacity:1 !important}.dg.main:hover .close-button,.dg.main .close-button.drag{opacity:1}.dg.main .close-button{-webkit-transition:opacity .1s linear;-o-transition:opacity .1s linear;-moz-transition:opacity .1s linear;transition:opacity .1s linear;border:0;line-height:19px;height:20px;cursor:pointer;text-align:center;background-color:#000}.dg.main .close-button.close-top{position:relative}.dg.main .close-button.close-bottom{position:absolute}.dg.main .close-button:hover{background-color:#111}.dg.a{float:right;margin-right:15px;overflow-y:visible}.dg.a.has-save>ul.close-top{margin-top:0}.dg.a.has-save>ul.close-bottom{margin-top:27px}.dg.a.has-save>ul.closed{margin-top:0}.dg.a .save-row{top:0;z-index:1002}.dg.a .save-row.close-top{position:relative}.dg.a .save-row.close-bottom{position:fixed}.dg li{-webkit-transition:height .1s ease-out;-o-transition:height .1s ease-out;-moz-transition:height .1s ease-out;transition:height .1s ease-out;-webkit-transition:overflow .1s linear;-o-transition:overflow .1s linear;-moz-transition:overflow .1s linear;transition:overflow .1s linear}.dg li:not(.folder){cursor:auto;height:27px;line-height:27px;padding:0 4px 0 5px}.dg li.folder{padding:0;border-left:4px solid rgba(0,0,0,0)}.dg li.title{cursor:pointer;margin-left:-4px}.dg .closed li:not(.title),.dg .closed ul li,.dg .closed ul li>*{height:0;overflow:hidden;border:0}.dg .cr{clear:both;padding-left:3px;height:27px;overflow:hidden}.dg .property-name{cursor:default;float:left;clear:left;width:40%;overflow:hidden;text-overflow:ellipsis}.dg .c{float:left;width:60%;position:relative}.dg .c input[type=text]{border:0;margin-top:4px;padding:3px;width:100%;float:right}.dg .has-slider input[type=text]{width:30%;margin-left:0}.dg .slider{float:left;width:66%;margin-left:-5px;margin-right:0;height:19px;margin-top:4px}.dg .slider-fg{height:100%}.dg .c input[type=checkbox]{margin-top:7px}.dg .c select{margin-top:5px}.dg .cr.function,.dg .cr.function .property-name,.dg .cr.function *,.dg .cr.boolean,.dg .cr.boolean *{cursor:pointer}.dg .cr.color{overflow:visible}.dg .selector{display:none;position:absolute;margin-left:-9px;margin-top:23px;z-index:10}.dg .c:hover .selector,.dg .selector.drag{display:block}.dg li.save-row{padding:0}.dg li.save-row .button{display:inline-block;padding:0px 6px}.dg.dialogue{background-color:#222;width:460px;padding:15px;font-size:13px;line-height:15px}#dg-new-constructor{padding:10px;color:#222;font-family:Monaco, monospace;font-size:10px;border:0;resize:none;box-shadow:inset 1px 1px 1px #888;word-wrap:break-word;margin:12px 0;display:block;width:440px;overflow-y:scroll;height:100px;position:relative}#dg-local-explain{display:none;font-size:11px;line-height:17px;border-radius:3px;background-color:#333;padding:8px;margin-top:10px}#dg-local-explain code{font-size:10px}#dat-gui-save-locally{display:none}.dg{color:#eee;font:11px 'Lucida Grande', sans-serif;text-shadow:0 -1px 0 #111}.dg.main::-webkit-scrollbar{width:5px;background:#1a1a1a}.dg.main::-webkit-scrollbar-corner{height:0;display:none}.dg.main::-webkit-scrollbar-thumb{border-radius:5px;background:#676767}.dg li:not(.folder){background:#1a1a1a;border-bottom:1px solid #2c2c2c}.dg li.save-row{line-height:25px;background:#dad5cb;border:0}.dg li.save-row select{margin-left:5px;width:108px}.dg li.save-row .button{margin-left:5px;margin-top:1px;border-radius:2px;font-size:9px;line-height:7px;padding:4px 4px 5px 4px;background:#c5bdad;color:#fff;text-shadow:0 1px 0 #b0a58f;box-shadow:0 -1px 0 #b0a58f;cursor:pointer}.dg li.save-row .button.gears{background:#c5bdad url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAsAAAANCAYAAAB/9ZQ7AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAQJJREFUeNpiYKAU/P//PwGIC/ApCABiBSAW+I8AClAcgKxQ4T9hoMAEUrxx2QSGN6+egDX+/vWT4e7N82AMYoPAx/evwWoYoSYbACX2s7KxCxzcsezDh3evFoDEBYTEEqycggWAzA9AuUSQQgeYPa9fPv6/YWm/Acx5IPb7ty/fw+QZblw67vDs8R0YHyQhgObx+yAJkBqmG5dPPDh1aPOGR/eugW0G4vlIoTIfyFcA+QekhhHJhPdQxbiAIguMBTQZrPD7108M6roWYDFQiIAAv6Aow/1bFwXgis+f2LUAynwoIaNcz8XNx3Dl7MEJUDGQpx9gtQ8YCueB+D26OECAAQDadt7e46D42QAAAABJRU5ErkJggg==) 2px 1px no-repeat;height:7px;width:8px}.dg li.save-row .button:hover{background-color:#bab19e;box-shadow:0 -1px 0 #b0a58f}.dg li.folder{border-bottom:0}.dg li.title{padding-left:16px;background:#000 url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlI+hKgFxoCgAOw==) 6px 10px no-repeat;cursor:pointer;border-bottom:1px solid rgba(255,255,255,0.2)}.dg .closed li.title{background-image:url(data:image/gif;base64,R0lGODlhBQAFAJEAAP////Pz8////////yH5BAEAAAIALAAAAAAFAAUAAAIIlGIWqMCbWAEAOw==)}.dg .cr.boolean{border-left:3px solid #806787}.dg .cr.color{border-left:3px solid}.dg .cr.function{border-left:3px solid #e61d5f}.dg .cr.number{border-left:3px solid #2FA1D6}.dg .cr.number input[type=text]{color:#2FA1D6}.dg .cr.string{border-left:3px solid #1ed36f}.dg .cr.string input[type=text]{color:#1ed36f}.dg .cr.function:hover,.dg .cr.boolean:hover{background:#111}.dg .c input[type=text]{background:#303030;outline:none}.dg .c input[type=text]:hover{background:#3c3c3c}.dg .c input[type=text]:focus{background:#494949;color:#fff}.dg .c .slider{background:#303030;cursor:ew-resize}.dg .c .slider-fg{background:#2FA1D6;max-width:100%}.dg .c .slider:hover{background:#3c3c3c}.dg .c .slider:hover .slider-fg{background:#44abda}\n");I.inject(K);var Y="dg",J=72,W=20,Q="Default",q=function(){try{return!!window.localStorage}catch(e){return!1}}(),Z=void 0,$=!0,ee=void 0,te=!1,ne=[],oe=function e(t){var n=this,o=t||{};this.domElement=document.createElement("div"),this.__ul=document.createElement("ul"),this.domElement.appendChild(this.__ul),A.addClass(this.domElement,Y),this.__folders={},this.__controllers=[],this.__rememberedObjects=[],this.__rememberedObjectIndecesToControllers=[],this.__listening=[],o=i.defaults(o,{closeOnTop:!1,autoPlace:!0,width:e.DEFAULT_WIDTH}),o=i.defaults(o,{resizable:o.autoPlace,hideable:o.autoPlace}),i.isUndefined(o.load)?o.load={preset:Q}:o.preset&&(o.load.preset=o.preset),i.isUndefined(o.parent)&&o.hideable&&ne.push(this),o.resizable=i.isUndefined(o.parent)&&o.resizable,o.autoPlace&&i.isUndefined(o.scrollable)&&(o.scrollable=!0);var r,s=q&&"true"===localStorage.getItem(ce(this,"isLocal")),a=void 0,l=void 0;if(Object.defineProperties(this,{parent:{get:function(){return o.parent}},scrollable:{get:function(){return o.scrollable}},autoPlace:{get:function(){return o.autoPlace}},closeOnTop:{get:function(){return o.closeOnTop}},preset:{get:function(){return n.parent?n.getRoot().preset:o.load.preset},set:function(e){n.parent?n.getRoot().preset=e:o.load.preset=e,ge(this),n.revert()}},width:{get:function(){return o.width},set:function(e){o.width=e,fe(n,e)}},name:{get:function(){return o.name},set:function(e){o.name=e,l&&(l.innerHTML=o.name)}},closed:{get:function(){return o.closed},set:function(t){o.closed=t,o.closed?A.addClass(n.__ul,e.CLASS_CLOSED):A.removeClass(n.__ul,e.CLASS_CLOSED),this.onResize(),n.__closeButton&&(n.__closeButton.innerHTML=t?e.TEXT_OPEN:e.TEXT_CLOSED)}},load:{get:function(){return o.load}},useLocalStorage:{get:function(){return s},set:function(e){q&&(s=e,e?A.bind(window,"unload",a):A.unbind(window,"unload",a),localStorage.setItem(ce(n,"isLocal"),e))}}}),i.isUndefined(o.parent)){if(this.closed=o.closed||!1,A.addClass(this.domElement,e.CLASS_MAIN),A.makeSelectable(this.domElement,!1),q&&s){n.useLocalStorage=!0;var d=localStorage.getItem(ce(this,"gui"));d&&(o.load=JSON.parse(d))}this.__closeButton=document.createElement("div"),this.__closeButton.innerHTML=e.TEXT_CLOSED,A.addClass(this.__closeButton,e.CLASS_CLOSE_BUTTON),o.closeOnTop?(A.addClass(this.__closeButton,e.CLASS_CLOSE_TOP),this.domElement.insertBefore(this.__closeButton,this.domElement.childNodes[0])):(A.addClass(this.__closeButton,e.CLASS_CLOSE_BOTTOM),this.domElement.appendChild(this.__closeButton)),A.bind(this.__closeButton,"click",function(){n.closed=!n.closed})}else{void 0===o.closed&&(o.closed=!0);var c=document.createTextNode(o.name);A.addClass(c,"controller-name"),l=ie(n,c);A.addClass(this.__ul,e.CLASS_CLOSED),A.addClass(l,"title"),A.bind(l,"click",function(e){return e.preventDefault(),n.closed=!n.closed,!1}),o.closed||(this.closed=!1)}o.autoPlace&&(i.isUndefined(o.parent)&&($&&(ee=document.createElement("div"),A.addClass(ee,Y),A.addClass(ee,e.CLASS_AUTO_PLACE_CONTAINER),document.body.appendChild(ee),$=!1),ee.appendChild(this.domElement),A.addClass(this.domElement,e.CLASS_AUTO_PLACE)),this.parent||fe(n,o.width)),this.__resizeHandler=function(){n.onResizeDebounced()},A.bind(window,"resize",this.__resizeHandler),A.bind(this.__ul,"webkitTransitionEnd",this.__resizeHandler),A.bind(this.__ul,"transitionend",this.__resizeHandler),A.bind(this.__ul,"oTransitionEnd",this.__resizeHandler),this.onResize(),o.resizable&&pe(this),a=function(){q&&"true"===localStorage.getItem(ce(n,"isLocal"))&&localStorage.setItem(ce(n,"gui"),JSON.stringify(n.getSaveObject()))},this.saveToLocalStorageIfPossible=a,o.parent||((r=n.getRoot()).width+=1,i.defer(function(){r.width-=1}))};function ie(e,t,n){var o=document.createElement("li");return t&&o.appendChild(t),n?e.__ul.insertBefore(o,n):e.__ul.appendChild(o),e.onResize(),o}function re(e){A.unbind(window,"resize",e.__resizeHandler),e.saveToLocalStorageIfPossible&&A.unbind(window,"unload",e.saveToLocalStorageIfPossible)}function se(e,t){var n=e.__preset_select[e.__preset_select.selectedIndex];n.innerHTML=t?n.value+"*":n.value}function ae(e,t,n){if(n.__li=t,n.__gui=e,i.extend(n,{options:function(t){if(arguments.length>1){var o=n.__li.nextElementSibling;return n.remove(),de(e,n.object,n.property,{before:o,factoryArgs:[i.toArray(arguments)]})}if(i.isArray(t)||i.isObject(t)){var r=n.__li.nextElementSibling;return n.remove(),de(e,n.object,n.property,{before:r,factoryArgs:[t]})}},name:function(e){return n.__li.firstElementChild.firstElementChild.innerHTML=e,n},listen:function(){return n.__gui.listen(n),n},remove:function(){return n.__gui.remove(n),n}}),n instanceof H){var o=new B(n.object,n.property,{min:n.__min,max:n.__max,step:n.__step});i.each(["updateDisplay","onChange","onFinishChange","step","min","max"],function(e){var t=n[e],i=o[e];n[e]=o[e]=function(){var e=Array.prototype.slice.call(arguments);return i.apply(o,e),t.apply(n,e)}}),A.addClass(t,"has-slider"),n.domElement.insertBefore(o.domElement,n.domElement.firstElementChild)}else if(n instanceof B){var r=function(t){if(i.isNumber(n.__min)&&i.isNumber(n.__max)){var o=n.__li.firstElementChild.firstElementChild.innerHTML,r=n.__gui.__listening.indexOf(n)>-1;n.remove();var s=de(e,n.object,n.property,{before:n.__li.nextElementSibling,factoryArgs:[n.__min,n.__max,n.__step]});return s.name(o),r&&s.listen(),s}return t};n.min=i.compose(r,n.min),n.max=i.compose(r,n.max)}else n instanceof k?(A.bind(t,"click",function(){A.fakeEvent(n.__checkbox,"click")}),A.bind(n.__checkbox,"click",function(e){e.stopPropagation()})):n instanceof F?(A.bind(t,"click",function(){A.fakeEvent(n.__button,"click")}),A.bind(t,"mouseover",function(){A.addClass(n.__button,"hover")}),A.bind(t,"mouseout",function(){A.removeClass(n.__button,"hover")})):n instanceof P&&(A.addClass(t,"color"),n.updateDisplay=i.compose(function(e){return t.style.borderLeftColor=n.__color.toString(),e},n.updateDisplay),n.updateDisplay());n.setValue=i.compose(function(t){return e.getRoot().__preset_select&&n.isModified()&&se(e.getRoot(),!0),t},n.setValue)}function le(e,t){var n=e.getRoot(),o=n.__rememberedObjects.indexOf(t.object);if(-1!==o){var i=n.__rememberedObjectIndecesToControllers[o];if(void 0===i&&(i={},n.__rememberedObjectIndecesToControllers[o]=i),i[t.property]=t,n.load&&n.load.remembered){var r=n.load.remembered,s=void 0;if(r[e.preset])s=r[e.preset];else{if(!r[Q])return;s=r[Q]}if(s[o]&&void 0!==s[o][t.property]){var a=s[o][t.property];t.initialValue=a,t.setValue(a)}}}}function de(e,t,n,o){if(void 0===t[n])throw new Error('Object "'+t+'" has no property "'+n+'"');var i=void 0;if(o.color)i=new P(t,n);else{var r=[t,n].concat(o.factoryArgs);i=M.apply(e,r)}o.before instanceof y&&(o.before=o.before.__li),le(e,i),A.addClass(i.domElement,"c");var s=document.createElement("span");A.addClass(s,"property-name"),s.innerHTML=i.property;var a=document.createElement("div");a.appendChild(s),a.appendChild(i.domElement);var l=ie(e,a,o.before);return A.addClass(l,oe.CLASS_CONTROLLER_ROW),i instanceof P?A.addClass(l,"color"):A.addClass(l,u(i.getValue())),ae(e,l,i),e.__controllers.push(i),i}function ce(e,t){return document.location.href+"."+t}function ue(e,t,n){var o=document.createElement("option");o.innerHTML=t,o.value=t,e.__preset_select.appendChild(o),n&&(e.__preset_select.selectedIndex=e.__preset_select.length-1)}function _e(e,t){t.style.display=e.useLocalStorage?"block":"none"}function he(e){var t=e.__save_row=document.createElement("li");A.addClass(e.domElement,"has-save"),e.__ul.insertBefore(t,e.__ul.firstChild),A.addClass(t,"save-row");var n=document.createElement("span");n.innerHTML="&nbsp;",A.addClass(n,"button gears");var o=document.createElement("span");o.innerHTML="Save",A.addClass(o,"button"),A.addClass(o,"save");var r=document.createElement("span");r.innerHTML="New",A.addClass(r,"button"),A.addClass(r,"save-as");var s=document.createElement("span");s.innerHTML="Revert",A.addClass(s,"button"),A.addClass(s,"revert");var a=e.__preset_select=document.createElement("select");if(e.load&&e.load.remembered?i.each(e.load.remembered,function(t,n){ue(e,n,n===e.preset)}):ue(e,Q,!1),A.bind(a,"change",function(){for(var t=0;t<e.__preset_select.length;t++)e.__preset_select[t].innerHTML=e.__preset_select[t].value;e.preset=this.value}),t.appendChild(a),t.appendChild(n),t.appendChild(o),t.appendChild(r),t.appendChild(s),q){var l=document.getElementById("dg-local-explain"),d=document.getElementById("dg-local-storage");document.getElementById("dg-save-locally").style.display="block","true"===localStorage.getItem(ce(e,"isLocal"))&&d.setAttribute("checked","checked"),_e(e,l),A.bind(d,"change",function(){e.useLocalStorage=!e.useLocalStorage,_e(e,l)})}var c=document.getElementById("dg-new-constructor");A.bind(c,"keydown",function(e){!e.metaKey||67!==e.which&&67!==e.keyCode||Z.hide()}),A.bind(n,"click",function(){c.innerHTML=JSON.stringify(e.getSaveObject(),void 0,2),Z.show(),c.focus(),c.select()}),A.bind(o,"click",function(){e.save()}),A.bind(r,"click",function(){var t=prompt("Enter a new preset name.");t&&e.saveAs(t)}),A.bind(s,"click",function(){e.revert()})}function pe(e){var t=void 0;function n(n){return n.preventDefault(),e.width+=t-n.clientX,e.onResize(),t=n.clientX,!1}function o(){A.removeClass(e.__closeButton,oe.CLASS_DRAG),A.unbind(window,"mousemove",n),A.unbind(window,"mouseup",o)}function r(i){return i.preventDefault(),t=i.clientX,A.addClass(e.__closeButton,oe.CLASS_DRAG),A.bind(window,"mousemove",n),A.bind(window,"mouseup",o),!1}e.__resize_handle=document.createElement("div"),i.extend(e.__resize_handle.style,{width:"6px",marginLeft:"-3px",height:"200px",cursor:"ew-resize",position:"absolute"}),A.bind(e.__resize_handle,"mousedown",r),A.bind(e.__closeButton,"mousedown",r),e.domElement.insertBefore(e.__resize_handle,e.domElement.firstElementChild)}function fe(e,t){e.domElement.style.width=t+"px",e.__save_row&&e.autoPlace&&(e.__save_row.style.width=t+"px"),e.__closeButton&&(e.__closeButton.style.width=t+"px")}function me(e,t){var n={};return i.each(e.__rememberedObjects,function(o,r){var s={},a=e.__rememberedObjectIndecesToControllers[r];i.each(a,function(e,n){s[n]=t?e.initialValue:e.getValue()}),n[r]=s}),n}function ge(e){for(var t=0;t<e.__preset_select.length;t++)e.__preset_select[t].value===e.preset&&(e.__preset_select.selectedIndex=t)}function be(e){0!==e.length&&U.call(window,function(){be(e)}),i.each(e,function(e){e.updateDisplay()})}oe.toggleHide=function(){te=!te,i.each(ne,function(e){e.domElement.style.display=te?"none":""})},oe.CLASS_AUTO_PLACE="a",oe.CLASS_AUTO_PLACE_CONTAINER="ac",oe.CLASS_MAIN="main",oe.CLASS_CONTROLLER_ROW="cr",oe.CLASS_TOO_TALL="taller-than-window",oe.CLASS_CLOSED="closed",oe.CLASS_CLOSE_BUTTON="close-button",oe.CLASS_CLOSE_TOP="close-top",oe.CLASS_CLOSE_BOTTOM="close-bottom",oe.CLASS_DRAG="drag",oe.DEFAULT_WIDTH=245,oe.TEXT_CLOSED="Close Controls",oe.TEXT_OPEN="Open Controls",oe._keydownHandler=function(e){"text"===document.activeElement.type||e.which!==J&&e.keyCode!==J||oe.toggleHide()},A.bind(window,"keydown",oe._keydownHandler,!1),i.extend(oe.prototype,{add:function(e,t){return de(this,e,t,{factoryArgs:Array.prototype.slice.call(arguments,2)})},addColor:function(e,t){return de(this,e,t,{color:!0})},remove:function(e){this.__ul.removeChild(e.__li),this.__controllers.splice(this.__controllers.indexOf(e),1);var t=this;i.defer(function(){t.onResize()})},destroy:function(){if(this.parent)throw new Error("Only the root GUI should be removed with .destroy(). For subfolders, use gui.removeFolder(folder) instead.");this.autoPlace&&ee.removeChild(this.domElement);var e=this;i.each(this.__folders,function(t){e.removeFolder(t)}),A.unbind(window,"keydown",oe._keydownHandler,!1),re(this)},addFolder:function(e){if(void 0!==this.__folders[e])throw new Error('You already have a folder in this GUI by the name "'+e+'"');var t={name:e,parent:this};t.autoPlace=this.autoPlace,this.load&&this.load.folders&&this.load.folders[e]&&(t.closed=this.load.folders[e].closed,t.load=this.load.folders[e]);var n=new oe(t);this.__folders[e]=n;var o=ie(this,n.domElement);return A.addClass(o,"folder"),n},removeFolder:function(e){this.__ul.removeChild(e.domElement.parentElement),delete this.__folders[e.name],this.load&&this.load.folders&&this.load.folders[e.name]&&delete this.load.folders[e.name],re(e);var t=this;i.each(e.__folders,function(t){e.removeFolder(t)}),i.defer(function(){t.onResize()})},open:function(){this.closed=!1},close:function(){this.closed=!0},hide:function(){this.domElement.style.display="none"},show:function(){this.domElement.style.display=""},onResize:function(){var e=this.getRoot();if(e.scrollable){var t=A.getOffset(e.__ul).top,n=0;i.each(e.__ul.childNodes,function(t){e.autoPlace&&t===e.__save_row||(n+=A.getHeight(t))}),window.innerHeight-t-W<n?(A.addClass(e.domElement,oe.CLASS_TOO_TALL),e.__ul.style.height=window.innerHeight-t-W+"px"):(A.removeClass(e.domElement,oe.CLASS_TOO_TALL),e.__ul.style.height="auto")}e.__resize_handle&&i.defer(function(){e.__resize_handle.style.height=e.__ul.offsetHeight+"px"}),e.__closeButton&&(e.__closeButton.style.width=e.width+"px")},onResizeDebounced:i.debounce(function(){this.onResize()},50),remember:function(){if(i.isUndefined(Z)&&((Z=new X).domElement.innerHTML=z),this.parent)throw new Error("You can only call remember on a top level GUI.");var e=this;i.each(Array.prototype.slice.call(arguments),function(t){0===e.__rememberedObjects.length&&he(e),-1===e.__rememberedObjects.indexOf(t)&&e.__rememberedObjects.push(t)}),this.autoPlace&&fe(this,this.width)},getRoot:function(){for(var e=this;e.parent;)e=e.parent;return e},getSaveObject:function(){var e=this.load;return e.closed=this.closed,this.__rememberedObjects.length>0&&(e.preset=this.preset,e.remembered||(e.remembered={}),e.remembered[this.preset]=me(this)),e.folders={},i.each(this.__folders,function(t,n){e.folders[n]=t.getSaveObject()}),e},save:function(){this.load.remembered||(this.load.remembered={}),this.load.remembered[this.preset]=me(this),se(this,!1),this.saveToLocalStorageIfPossible()},saveAs:function(e){this.load.remembered||(this.load.remembered={},this.load.remembered[Q]=me(this,!0)),this.load.remembered[e]=me(this),this.preset=e,ue(this,e,!0),this.saveToLocalStorageIfPossible()},revert:function(e){i.each(this.__controllers,function(t){this.getRoot().load.remembered?le(e||this.getRoot(),t):t.setValue(t.initialValue),t.__onFinishChange&&t.__onFinishChange.call(t,t.getValue())},this),i.each(this.__folders,function(e){e.revert(e)}),e||se(this.getRoot(),!1)},listen:function(e){var t=0===this.__listening.length;this.__listening.push(e),t&&be(this.__listening)},updateDisplay:function(){i.each(this.__controllers,function(e){e.updateDisplay()}),i.each(this.__folders,function(e){e.updateDisplay()})}});var ve={Color:g,math:c,interpret:l};exports.color=ve;var ye={Controller:y,BooleanController:k,OptionController:S,StringController:O,NumberController:L,NumberControllerBox:B,NumberControllerSlider:H,FunctionController:F,ColorController:P};exports.controllers=ye;var we={dom:A};exports.dom=we;var xe={GUI:oe};exports.gui=xe;var Ee=oe;exports.GUI=Ee;var Ce={color:ve,controllers:ye,dom:we,gui:xe,GUI:Ee},Ae=Ce;exports.default=Ae;
  },{}],"ZsAW":[function(require,module,exports) {
  var define;
  var e;!function(t,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof e&&e.amd?e(n):t.Stats=n()}(this,function(){var e=function(){function t(e){return i.appendChild(e.dom),e}function n(e){for(var t=0;t<i.children.length;t++)i.children[t].style.display=t===e?"block":"none";l=e}var l=0,i=document.createElement("div");i.style.cssText="position:fixed;top:0;left:0;cursor:pointer;opacity:0.9;z-index:10000",i.addEventListener("click",function(e){e.preventDefault(),n(++l%i.children.length)},!1);var a=(performance||Date).now(),o=a,r=0,f=t(new e.Panel("FPS","#0ff","#002")),c=t(new e.Panel("MS","#0f0","#020"));if(self.performance&&self.performance.memory)var d=t(new e.Panel("MB","#f08","#201"));return n(0),{REVISION:16,dom:i,addPanel:t,showPanel:n,begin:function(){a=(performance||Date).now()},end:function(){r++;var e=(performance||Date).now();if(c.update(e-a,200),e>o+1e3&&(f.update(1e3*r/(e-o),100),o=e,r=0,d)){var t=performance.memory;d.update(t.usedJSHeapSize/1048576,t.jsHeapSizeLimit/1048576)}return e},update:function(){a=this.end()},domElement:i,setMode:n}};return e.Panel=function(e,t,n){var l=1/0,i=0,a=Math.round,o=a(window.devicePixelRatio||1),r=80*o,f=48*o,c=3*o,d=2*o,p=3*o,u=15*o,s=74*o,m=30*o,h=document.createElement("canvas");h.width=r,h.height=f,h.style.cssText="width:80px;height:48px";var v=h.getContext("2d");return v.font="bold "+9*o+"px Helvetica,Arial,sans-serif",v.textBaseline="top",v.fillStyle=n,v.fillRect(0,0,r,f),v.fillStyle=t,v.fillText(e,c,d),v.fillRect(p,u,s,m),v.fillStyle=n,v.globalAlpha=.9,v.fillRect(p,u,s,m),{dom:h,update:function(f,y){l=Math.min(l,f),i=Math.max(i,f),v.fillStyle=n,v.globalAlpha=1,v.fillRect(0,0,r,u),v.fillStyle=t,v.fillText(a(f)+" "+e+" ("+a(l)+"-"+a(i)+")",c,d),v.drawImage(h,p+o,u,s-o,m,p,u,s-o,m),v.fillRect(p+s-o,u,o,m),v.fillStyle=n,v.globalAlpha=.9,v.fillRect(p+s-o,u,o,a((1-f/y)*m))}}},e});
  },{}],"KLDv":[function(require,module,exports) {
  "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.input=oi,exports.loadLayersModel=si,exports.model=ii,exports.registerCallbackConstructor=ui,exports.sequential=ai,exports.version_layers=exports.LayerVariable=exports.Sequential=exports.RNN=exports.LayersModel=exports.SymbolicTensor=exports.InputSpec=exports.EarlyStopping=exports.callbacks=exports.Callback=exports.History=exports.CustomCallback=exports.CallbackList=exports.regularizers=exports.models=exports.metrics=exports.layers=exports.initializers=exports.constraints=void 0;var t=require("@tensorflow/tfjs-core"),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)}var r,i=function(){return(i=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 a(t,e,n,r){return new(n||(n=Promise))(function(i,a){function s(t){try{u(r.next(t))}catch(t){a(t)}}function o(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(s,o)}u((r=r.apply(t,e||[])).next())})}function s(t,e){var n,r,i,a,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return a={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function o(a){return function(o){return function(a){if(n)throw new TypeError("Generator is already executing.");for(;s;)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 s.label++,{value:a[1],done:!1};case 5:s.label++,r=a[1],a=[0];continue;case 7:a=s.ops.pop(),s.trys.pop();continue;default:if(!(i=(i=s.trys).length>0&&i[i.length-1])&&(6===a[0]||2===a[0])){s=0;continue}if(3===a[0]&&(!i||a[1]>i[0]&&a[1]<i[3])){s.label=a[1];break}if(6===a[0]&&s.label<i[1]){s.label=i[1],i=a;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(a);break}i[2]&&s.ops.pop(),s.trys.pop();continue}a=e.call(t,s)}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,o])}}}function o(){return null==r&&(r=(0,t.backend)().epsilon()),r}function u(){return"channelsLast"}var l=function(t){function e(n){var r=t.call(this,n)||this;return Object.setPrototypeOf(r,e.prototype),r}return n(e,t),e}(Error),c=function(t){function e(n){var r=t.call(this,n)||this;return Object.setPrototypeOf(r,e.prototype),r}return n(e,t),e}(Error),h=function(t){function e(n){var r=t.call(this,n)||this;return Object.setPrototypeOf(r,e.prototype),r}return n(e,t),e}(Error),p=function(t){function e(n){var r=t.call(this,n)||this;return Object.setPrototypeOf(r,e.prototype),r}return n(e,t),e}(Error),f=function(t){function e(n){var r=t.call(this,n)||this;return Object.setPrototypeOf(r,e.prototype),r}return n(e,t),e}(Error),d=function(t){function e(n){var r=t.call(this,n)||this;return Object.setPrototypeOf(r,e.prototype),r}return n(e,t),e}(Error);function g(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 m(t,e){if(!t)throw new f(e)}function y(t,e){for(var n=0,r=0,i=t;r<i.length;r++)i[r]===e&&n++;return n}function v(t){return 1===t.length?t[0]:t}function b(t){return Array.isArray(t)?t:[t]}function w(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 z(t){return t.length<=1?t:-1===t.indexOf("_")?t:t.replace(/[_]+(\w|$)/g,function(t,e){return e.toUpperCase()})}var k={};function S(t){if(null==t)return null;var e={};return e.className=t.getClassName(),e.config=t.getConfig(),e}function N(t){if(null!=t&&"object"==typeof t)if(Array.isArray(t))t.forEach(function(t){return N(t)});else for(var e=0,n=Object.keys(t);e<n.length;e++){var r=n[e],i=t[r];null!=i&&"object"==typeof i&&(Array.isArray(i)||"ndarray"!==i.type||"number"!=typeof i.value?N(i):t[r]=i.value)}}function C(t,e,n,r,a){var s,o,u;if(void 0===e&&(e={}),void 0===n&&(n={}),void 0===r&&(r="object"),void 0===a&&(a=!1),"string"==typeof t){var l=t,c=void 0;if(l in n)c=n[l];else if(l in k)c=k[l];else if(null==(c=e[l]))throw new h("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 c}var p=t;if(null==p.className||null==p.config)throw new h(r+": Improper config format: "+JSON.stringify(p)+".\n'className' and 'config' must set.");var f=p.className,d=void 0,g=void 0;if(f in n?(d=(s=n[f])[0],g=s[1]):f in k?(d=(o=k.className)[0],g=o[1]):f in e&&(d=(u=e[f])[0],g=u[1]),null==d)throw new h("Unknown "+r+": "+f+". 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!=g){for(var m={},y=0,v=Object.keys(k);y<v.length;y++)m[A=v[y]]=k[A];for(var b=0,w=Object.keys(n);b<w.length;b++)m[A=w[b]]=n[A];p.config.customObjects=m;for(var z=i({},k),S=0,C=Object.keys(n);S<C.length;S++){var A=C[S];k[A]=n[A]}N(p.config);var I=g(d,p.config,n,a);return k=i({},z),I}z=i({},k);for(var x=0,T=Object.keys(n);x<T.length;x++)A=T[x],k[A]=n[A];return I=new d(p.config),k=i({},z),I}function A(t,e){return t<e?-1:t>e?1:0}function I(t,e){return-1*A(t,e)}function x(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 T(t){if(null==t)throw new h("Invalid value in obj: "+JSON.stringify(t));for(var e in t)if(t.hasOwnProperty(e))return!1;return!0}function L(t,e,n){if(null!=n&&t.indexOf(n)<0)throw new h(n+" is not a valid "+e+".  Valid values are "+t+" or null/undefined.")}function E(t,e,n,r){return void 0===n&&(n=0),void 0===r&&(r=1/0),m(n>=0),m(r>=n),Array.isArray(t)&&t.length>=n&&t.length<=r&&t.every(function(t){return typeof t===e})}function O(e,n){Array.isArray(e)?(t.util.assert(e.length>0,function(){return n+" is unexpectedly an empty array."}),e.forEach(function(t,e){return O(t,"element "+(e+1)+" of "+n)})):t.util.assert(Number.isInteger(e)&&e>0,function(){return"Expected "+n+" to be a positive integer, but got "+D(e)+"."})}function D(t){return null===t?"null":Array.isArray(t)?"["+t.map(function(t){return D(t)}).join(",")+"]":"string"==typeof t?'"'+t+'"':""+t}function R(e,n){var r,i=t.util.now();return function(){for(var a=[],s=0;s<arguments.length;s++)a[s]=arguments[s];var o=t.util.now();return o-i<n?r:(i=o,r=e.apply(void 0,a))}}function F(t){return"relu"===t?"relu":"linear"===t?"linear":"elu"===t?"elu":null}function _(e,n){return(0,t.tidy)(function(){return(0,t.sqrt)((0,t.sum)((0,t.mulStrict)(e,e),n,!0))})}var M=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.getConfig=function(){return{}},e}(t.serialization.Serializable),B=function(e){function r(t){var n=e.call(this)||this;return n.defaultMaxValue=2,n.defaultAxis=0,n.maxValue=null!=t.maxValue?t.maxValue:n.defaultMaxValue,n.axis=null!=t.axis?t.axis:n.defaultAxis,n}return n(r,e),r.prototype.apply=function(e){var n=this;return(0,t.tidy)(function(){var r=_(e,n.axis),i=(0,t.clipByValue)(r,0,n.maxValue);return(0,t.mul)(e,(0,t.div)(i,(0,t.add)(o(),r)))})},r.prototype.getConfig=function(){return{maxValue:this.maxValue,axis:this.axis}},r.className="MaxNorm",r}(M);t.serialization.registerClass(B);var P=function(e){function r(t){var n=e.call(this)||this;return n.defaultAxis=0,n.axis=null!=t.axis?t.axis:n.defaultAxis,n}return n(r,e),r.prototype.apply=function(e){var n=this;return(0,t.tidy)(function(){return(0,t.div)(e,(0,t.add)(o(),_(e,n.axis)))})},r.prototype.getConfig=function(){return{axis:this.axis}},r.className="UnitNorm",r}(M);t.serialization.registerClass(P);var j=function(e){function r(){return null!==e&&e.apply(this,arguments)||this}return n(r,e),r.prototype.apply=function(e){return(0,t.relu)(e)},r.className="NonNeg",r}(M);t.serialization.registerClass(j);var W=function(e){function r(t){var n=e.call(this)||this;return n.defaultMinValue=0,n.defaultMaxValue=1,n.defaultRate=1,n.defaultAxis=0,n.minValue=null!=t.minValue?t.minValue:n.defaultMinValue,n.maxValue=null!=t.maxValue?t.maxValue:n.defaultMaxValue,n.rate=null!=t.rate?t.rate:n.defaultRate,n.axis=null!=t.axis?t.axis:n.defaultAxis,n}return n(r,e),r.prototype.apply=function(e){var n=this;return(0,t.tidy)(function(){var r=_(e,n.axis),i=(0,t.add)((0,t.mul)(n.rate,(0,t.clipByValue)(r,n.minValue,n.maxValue)),(0,t.mul)(1-n.rate,r));return(0,t.mul)(e,(0,t.div)(i,(0,t.add)(o(),r)))})},r.prototype.getConfig=function(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}},r.className="MinMaxNorm",r}(M);t.serialization.registerClass(W);var U={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function V(t){return S(t)}function q(e,n){return void 0===n&&(n={}),C(e,t.serialization.SerializationMap.getMap().classNameMap,n,"constraint")}function J(t){return null==t?null:"string"==typeof t?q({className:t in U?U[t]:t,config:{}}):t instanceof M?t:q(t)}function H(t){return new B(t)}function Z(t){return new P(t)}function K(){return new j}function G(t){return new W(t)}var Y=Object.freeze({maxNorm:H,unitNorm:Z,nonNeg:K,minMaxNorm:G}),X=["channelsFirst","channelsLast"],$=["valid","same","causal"],Q=["max","avg"],tt=["sum","mul","concat","ave"],et=new Map;function nt(t){L(X,"DataFormat",t)}function rt(t){L($,"PaddingMode",t)}function it(t){L(Q,"PoolMode",t)}exports.constraints=Y;var at=[],st="/";function ot(t,e){at.push(t);try{var n=e();return at.pop(),n}catch(t){throw at.pop(),t}}function ut(){return 0===at.length?"":at.join(st)+st}function lt(t){if(!pt(t))throw new Error("Not a valid tensor name: '"+t+"'");return ut()+t}function ct(t){if(!pt(t))throw new Error("Not a valid tensor name: '"+t+"'");et.has(t)||et.set(t,0);var e=et.get(t);if(et.set(t,et.get(t)+1),e>0){var n=t+"_"+e;return et.set(n,1),n}return t}var ht=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function pt(t){return!!t.match(ht)}function ft(t){return t===parseInt(t.toString(),10)}function dt(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 gt(e){return e=Array.isArray(e)?new Float32Array(e):e,(0,t.tensor1d)(e)}function mt(e){return(0,t.min)(gt(e)).dataSync()[0]}function yt(e){return(0,t.max)(gt(e)).dataSync()[0]}function vt(t,e){if(e<t)throw new h("end ("+e+") < begin ("+t+") is forbidden.");for(var n=[],r=t;r<e;++r)n.push(r);return n}function bt(t,e){return t.asType(e)}function wt(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 zt(e,n){return(0,t.tidy)(function(){if(2!==e.shape.length)throw new h("repeat() expects a rank-2 tensor, but received a rank-"+e.shape.length+" tensor.");return Tt(wt(e,1),[1,n,1])})}function kt(t){var e=[dt(t.shape)];return t.reshape(e)}function St(t){if(t.rank<=1)throw new h("batchFlatten requires a minimum rank of 2. Got rank: "+t.rank+".");var e=[t.shape[0],dt(t.shape,1)];return t.reshape(e)}function Nt(e,n,r){return(0,t.tidy)(function(){switch(e.rank){case 1:return(0,t.slice1d)(e,n,r);case 2:return(0,t.slice2d)(e,[n,0],[r,e.shape[1]]);case 3:return(0,t.slice3d)(e,[n,0,0],[r,e.shape[1],e.shape[2]]);case 4:return(0,t.slice4d)(e,[n,0,0,0],[r,e.shape[1],e.shape[2],e.shape[3]]);case 5:return(0,t.slice)(e,[n,0,0,0,0],[r,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return(0,t.slice)(e,[n,0,0,0,0,0],[r,e.shape[1],e.shape[2],e.shape[3],e.shape[4],e.shape[5]]);default:throw new h("sliceAlongFirstAxis() received an unsupported tensor rank: "+e.rank)}})}function Ct(e,n,r){return(0,t.tidy)(function(){switch(e.rank){case 1:return(0,t.slice1d)(e,n,r);case 2:return(0,t.slice2d)(e,[0,n],[e.shape[0],r]);case 3:return(0,t.slice3d)(e,[0,0,n],[e.shape[0],e.shape[1],r]);case 4:return(0,t.slice4d)(e,[0,0,0,n],[e.shape[0],e.shape[1],e.shape[2],r]);default:throw new h("sliceAlongLastAxis() received an unsupported tensor rank: "+e.rank)}})}function At(e,n,r,i){return(0,t.tidy)(function(){switch(e.rank){case 1:return(0,t.slice1d)(e,n,r);case 2:switch(i){case 1:return Nt(e,n,r);case 2:return Ct(e,n,r);default:throw new h("The axis is not within the rank of the tensor "+i)}case 3:switch(i){case 1:return Nt(e,n,r);case 2:return(0,t.slice3d)(e,[0,n,0],[e.shape[0],r,e.shape[2]]);case 3:return Ct(e,n,r);default:throw new h("The axis is not within the rank of the tensor "+i)}case 4:switch(i){case 1:return Nt(e,n,r);case 2:return(0,t.slice4d)(e,[0,n,0,0],[e.shape[0],r,e.shape[2],e.shape[3]]);case 3:return(0,t.slice4d)(e,[0,0,n,0],[e.shape[0],e.shape[1],r,e.shape[3]]);case 4:return Ct(e,n,r);default:throw new h("The axis is not within the rank of the tensor "+i)}default:throw new h("sliceAlongLastAxis() received an unsupported tensor rank: "+e.rank)}})}function It(e,n){var r;return void 0===n&&(n=-1),n<0&&(n=0!==(r=e[0].rank)?r:0),n===e[0].rank&&(n=-1),(0,t.concat)(e,n)}function xt(e,n){switch(e.rank){case 1:return(0,t.concat1d)([e,n]);case 2:return(0,t.concat2d)([e,n],0);case 3:return(0,t.concat3d)([e,n],0);case 4:return(0,t.concat4d)([e,n],0);default:throw new h("concatAlongFirstAxis() received an unsupported tensor rank: "+e.rank)}}function Tt(e,n){if(Array.isArray(n)||(n=[n]),e.rank!==n.length)throw new h("The length of input n ("+n.length+") does not match the number of dimensions in input x ("+e.rank+")");return(0,t.tile)(e,n)}function Lt(e,n,r,i,a){return void 0===n&&(n=0),void 0===r&&(r=1),(0,t.randomNormal)(e,n,r,i,a)}function Et(e,n,r,i){if(e.rank<2||n.rank<2)throw new p("dot requires both inputs to be rank >= 2 but got x shape = "+e.shape+" and y shape = "+n.shape);if(n.rank>=3&&e.shape.slice(-1)[0]!==(f=n.shape.slice(-2)[0]))throw new p("If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = "+e.shape+" and  y shape = "+n.shape);if(2===e.rank&&2===n.rank){var a=!1,s=!1;return t.fused.matMul({a:e,b:n,transposeA:a,transposeB:s,bias:i?Rt(e.rank,i,u()):null,activation:r})}var o=e.shape.slice(),l=o.pop();e=e.reshape([-1,l]);var c=n.shape.slice(),h=c.pop(),f=c.pop(),d=c.concat([h]),g=Array.from({length:n.rank},function(t,e){return 0===e?n.rank-2:e<=n.rank-2?e-1:e});n=n.transpose(g).reshape([f,-1]);var m=o.concat(d);return a=!1,s=!1,t.fused.matMul({a:e,b:n,transposeA:a,transposeB:s,bias:i?Rt(e.rank,i,u()):null,activation:r}).reshape(m)}function Ot(e,n,r){return(0,t.tidy)(function(){return n=Array.isArray(n)?(0,t.tensor1d)(n,"int32"):n.toInt(),(0,t.gather)(e,n,r)})}function Dt(e){return(0,t.mulStrict)(e,e)}function Rt(t,e,n){var r=e.shape;if(1!==e.rank&&e.rank!==t)throw new h("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 h("Unsupported input rank by biasAdd: "+e.rank)}function Ft(e,n,r){return(0,t.tidy)(function(){return null==r&&(r=u()),nt(r),e.add(Rt(e.rank,n,r))})}function _t(e,n){if(void 0===n&&(n=1),1!==n)throw new p("Support for alpha values other than 1 ("+n+") is not implemented yet.");return(0,t.elu)(e)}function Mt(e){return(0,t.tidy)(function(){return(0,t.div)(e,(0,t.abs)(e).add(1))})}function Bt(e,n,r,i){return(0,t.tidy)(function(){return(0,t.dropout)(e,n,r,i)})}function Pt(e){return(0,t.tidy)(function(){var n=(0,t.add)(.5,(0,t.mul)(.2,e));return(0,t.clipByValue)(n,0,1)})}function jt(t,e,n){return void 0===n&&(n=!1),n?t():e()}var Wt=["fanIn","fanOut","fanAvg"],Ut=["normal","uniform","truncatedNormal"];function Vt(t){L(Wt,"FanMode",t)}function qt(t){L(Ut,"Distribution",t)}var Jt=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.fromConfigUsesCustomObjects=function(){return!1},e.prototype.getConfig=function(){return{}},e}(t.serialization.Serializable),Ht=function(e){function r(){return null!==e&&e.apply(this,arguments)||this}return n(r,e),r.prototype.apply=function(e,n){return(0,t.zeros)(e,n)},r.className="Zeros",r}(Jt);t.serialization.registerClass(Ht);var Zt=function(e){function r(){return null!==e&&e.apply(this,arguments)||this}return n(r,e),r.prototype.apply=function(e,n){return(0,t.ones)(e,n)},r.className="Ones",r}(Jt);t.serialization.registerClass(Zt);var Kt=function(e){function r(t){var n=e.call(this)||this;if("object"!=typeof t)throw new h("Expected argument of type ConstantConfig but got "+t);if(void 0===t.value)throw new h("config must have value set but got "+t);return n.value=t.value,n}return n(r,e),r.prototype.apply=function(e,n){var r=this;return(0,t.tidy)(function(){return(0,t.mul)((0,t.scalar)(r.value),(0,t.ones)(e,n))})},r.prototype.getConfig=function(){return{value:this.value}},r.className="Constant",r}(Jt);t.serialization.registerClass(Kt);var Gt=function(e){function r(t){var n=e.call(this)||this;return n.DEFAULT_MINVAL=-.05,n.DEFAULT_MAXVAL=.05,n.minval=t.minval||n.DEFAULT_MINVAL,n.maxval=t.maxval||n.DEFAULT_MAXVAL,n.seed=t.seed,n}return n(r,e),r.prototype.apply=function(e,n){return(0,t.randomUniform)(e,this.minval,this.maxval,n)},r.prototype.getConfig=function(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}},r.className="RandomUniform",r}(Jt);t.serialization.registerClass(Gt);var Yt=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 n(e,t),e.prototype.apply=function(t,e){if("float32"!==(e=e||"float32")&&"int32"!==e)throw new p("randomNormal does not support dType "+e+".");return Lt(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}(Jt);t.serialization.registerClass(Yt);var Xt=function(e){function r(t){var n=e.call(this)||this;return n.DEFAULT_MEAN=0,n.DEFAULT_STDDEV=.05,n.mean=t.mean||n.DEFAULT_MEAN,n.stddev=t.stddev||n.DEFAULT_STDDEV,n.seed=t.seed,n}return n(r,e),r.prototype.apply=function(e,n){if("float32"!==(n=n||"float32")&&"int32"!==n)throw new p("truncatedNormal does not support dType "+n+".");return(0,t.truncatedNormal)(e,this.mean,this.stddev,n,this.seed)},r.prototype.getConfig=function(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}},r.className="TruncatedNormal",r}(Jt);t.serialization.registerClass(Xt);var $t=function(e){function r(t){var n=e.call(this)||this;return n.gain=null!=t.gain?t.gain:1,n}return n(r,e),r.prototype.apply=function(e,n){var r=this;return(0,t.tidy)(function(){if(2!==e.length||e[0]!==e[1])throw new h("Identity matrix initializer can only be used for 2D square matrices.");return(0,t.mul)(r.gain,(0,t.eye)(e[0]))})},r.prototype.getConfig=function(){return{gain:this.gain}},r.className="Identity",r}(Jt);function Qt(t,e){var n,r;if(void 0===e&&(e="channelsLast"),nt(e),2===t.length)n=t[0],r=t[1];else if(-1!==[3,4,5].indexOf(t.length))if("channelsFirst"===e){var i=dt(t,2);n=t[1]*i,r=t[0]*i}else"channelsLast"===e&&(i=dt(t,0,t.length-2),n=t[t.length-2]*i,r=t[t.length-1]*i);else{var a=dt(t);n=Math.sqrt(a),r=Math.sqrt(a)}return[n,r]}t.serialization.registerClass($t);var te=function(e){function r(t){var n=e.call(this)||this;if(t.scale<0)throw new h("scale must be a positive float. Got: "+t.scale);return n.scale=null==t.scale?1:t.scale,n.mode=null==t.mode?"fanIn":t.mode,Vt(n.mode),n.distribution=null==t.distribution?"normal":t.distribution,qt(n.distribution),n.seed=t.seed,n}return n(r,e),r.prototype.apply=function(e,n){var r=Qt(e),i=r[0],a=r[1],s=this.scale;if("fanIn"===this.mode?s/=Math.max(1,i):"fanOut"===this.mode?s/=Math.max(1,a):s/=Math.max(1,(i+a)/2),"normal"===this.distribution){var o=Math.sqrt(s);if("float32"!==(n=n||"float32")&&"int32"!==n)throw new p(this.getClassName()+" does not support dType "+n+".");return(0,t.truncatedNormal)(e,0,o,n,this.seed)}var u=Math.sqrt(3*s);return(0,t.randomUniform)(e,-u,u,n)},r.prototype.getConfig=function(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}},r.className="VarianceScaling",r}(Jt);t.serialization.registerClass(te);var ee=function(t){function e(e){return t.call(this,{scale:1,mode:"fanAvg",distribution:"uniform",seed:null==e?null:e.seed})||this}return n(e,t),e.prototype.getClassName=function(){return te.className},e.className="GlorotUniform",e}(te);t.serialization.registerClass(ee);var ne=function(t){function e(e){return t.call(this,{scale:1,mode:"fanAvg",distribution:"normal",seed:null==e?null:e.seed})||this}return n(e,t),e.prototype.getClassName=function(){return te.className},e.className="GlorotNormal",e}(te);t.serialization.registerClass(ne);var re=function(t){function e(e){return t.call(this,{scale:2,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})||this}return n(e,t),e.prototype.getClassName=function(){return te.className},e.className="HeNormal",e}(te);t.serialization.registerClass(re);var ie=function(t){function e(e){return t.call(this,{scale:2,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})||this}return n(e,t),e.prototype.getClassName=function(){return te.className},e.className="HeUniform",e}(te);t.serialization.registerClass(ie);var ae=function(t){function e(e){return t.call(this,{scale:1,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})||this}return n(e,t),e.prototype.getClassName=function(){return te.className},e.className="LeCunNormal",e}(te);t.serialization.registerClass(ae);var se=function(t){function e(e){return t.call(this,{scale:1,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})||this}return n(e,t),e.prototype.getClassName=function(){return te.className},e.className="LeCunNormal",e}(te);t.serialization.registerClass(se);var oe=function(e){function r(t){var n=e.call(this)||this;if(n.DEFAULT_GAIN=1,n.gain=null==t.gain?n.DEFAULT_GAIN:t.gain,n.seed=t.seed,null!=n.seed)throw new p("Random seed is not implemented for Orthogonal Initializer yet.");return n}return n(r,e),r.prototype.apply=function(e,n){var r=this;return(0,t.tidy)(function(){if(2!==e.length)throw new p("The Orthogonal Initializer does not support non-2D shapes yet.");e[0]*e[1]>2e3&&console.warn("Orthogonal initializer is being called on a matrix with more than 2000 ("+e[0]*e[1]+") elements: Slowness may result.");var n=Lt(e[0]>e[1]?[e[1],e[0]]:e,0,1,"float32"),i=t.linalg.gramSchmidt(n);return e[0]>e[1]&&(i=i.transpose()),(0,t.mul)(r.gain,i)})},r.prototype.getConfig=function(){return{gain:this.gain,seed:this.seed}},r.className="Orthogonal",r}(Jt);t.serialization.registerClass(oe);var ue={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 le(e,n){return void 0===n&&(n={}),C(e,t.serialization.SerializationMap.getMap().classNameMap,n,"initializer")}function ce(t){return S(t)}function he(t){if("string"==typeof t){var e=t in ue?ue[t]:t;if("GlorotNormal"===e)return new ne;if("GlorotUniform"===e)return new ee;if("HeNormal"===e)return new re;if("HeUniform"===e)return new ie;if("LeCunNormal"===e)return new ae;if("LeCunUniform"===e)return new se;var n={};return n.className=e,n.config={},le(n)}return t instanceof Jt?t:le(t)}function pe(){return new Ht}function fe(){return new Zt}function de(t){return new Kt(t)}function ge(t){return new Gt(t)}function me(t){return new Yt(t)}function ye(t){return new Xt(t)}function ve(t){return new $t(t)}function be(t){return new te(t)}function we(t){return new ee(t)}function ze(t){return new ne(t)}function ke(t){return new re(t)}function Se(t){return new ie(t)}function Ne(t){return new ae(t)}function Ce(t){return new se(t)}function Ae(t){return new oe(t)}var Ie=Object.freeze({zeros:pe,ones:fe,constant:de,randomUniform:ge,randomNormal:me,truncatedNormal:ye,identity:ve,varianceScaling:be,glorotUniform:we,glorotNormal:ze,heNormal:ke,heUniform:Se,leCunNormal:Ne,leCunUniform:Ce,orthogonal:Ae}),xe=0;function Te(){return xe++}exports.initializers=Ie;var Le={};function Ee(t){return void 0===t&&(t=""),t in Le||(Le[t]=0),Le[t]+=1,t+Le[t].toString()}function Oe(t){return Array.isArray(t)&&Array.isArray(t[0])}function De(t){return 0===t.length?[]:Array.isArray(t[0])?t:[t]}function Re(t){var e;if(Array.isArray(t)){if(1!==t.length)throw new h("Expected Tensor length to be 1; got "+t.length);e=t[0]}else e=t;return e}function Fe(t){if(Array.isArray(t)&&Array.isArray(t[0])){if(1===t.length)return(t=t)[0];throw new h("Expected exactly 1 Shape; got "+t.length)}return t}function _e(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 Me="Variable",Be=function(){function e(e,n,r,i,a){void 0===n&&(n="float32"),void 0===r&&(r=Me),void 0===i&&(i=!0),void 0===a&&(a=null),this.dtype=null==n?"float32":n,this.shape=e.shape,this.id=Te(),r=null==r?Me:r,this.originalName=lt(r),this.name=ct(this.originalName),this.trainable_=i,this.constraint=a,this.val=(0,t.variable)(e,this.trainable_,this.name,this.dtype)}return e.prototype.read=function(){return this.assertNotDisposed(),this.val},e.prototype.write=function(t){return this.assertNotDisposed(),Pe(this.val,t),this.val.id!==t.id&&(this.val.assign(t),null!=this.constraint&&this.val.assign(this.constraint.apply(this.val))),this},e.prototype.dispose=function(){this.assertNotDisposed(),this.val.dispose()},e.prototype.assertNotDisposed=function(){if(this.val.isDisposed)throw new Error("LayersVariable "+this.name+" is already disposed.")},Object.defineProperty(e.prototype,"trainable",{get:function(){return this.trainable_},set:function(t){this.trainable_=t,this.val.trainable=t},enumerable:!0,configurable:!0}),e}();function Pe(t,e){if(t.shape.toString()!==e.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(t.shape)+" vs. "+JSON.stringify(e.shape))}function je(t){return t.map(function(t){return t.read()})}function We(t){t.forEach(function(t){t[0].write(t[1])})}exports.LayerVariable=Be;var Ue=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||{}},Ve=function(t,e,n,r,i,a,s){this.dtype=t,this.shape=e,this.sourceLayer=n,this.inputs=r,this.callArgs=i,this.outputTensorIndex=s,this.id=Te(),null!=a&&(this.originalName=lt(a),this.name=ct(this.originalName)),this.rank=e.length},qe=0,Je=function(){function t(t,e){this.callArgs=e,this.id=qe++,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}(),He=0,Ze=function(e){function r(t){var n=e.call(this)||this;n._callHook=null,n._addedWeightNames=[],n._stateful=!1,n.id=He++,n.activityRegularizer=null,n.inputSpec=null,n.supportsMasking=!1,n._trainableWeights=[],n._nonTrainableWeights=[],n._losses=[],n._updates=[],n._built=!1,n.inboundNodes=[],n.outboundNodes=[];var r=t.name;if(!r){var i=n.getClassName();r=w(i)+"_"+Ee(i)}if(n.name=r,n.trainable_=null==t.trainable||t.trainable,null!=t.inputShape||null!=t.batchInputShape){var a=void 0;if(null!=t.batchInputShape)a=t.batchInputShape;else if(null!=t.inputShape){var s=null;null!=t.batchSize&&(s=t.batchSize),a=[s].concat(t.inputShape)}n.batchInputShape=a;var o=t.dtype;null==o&&(o=t.inputDType),null==o&&(o="float32"),n.dtype=o}return null!=t.weights?n.initialWeights=t.weights:n.initialWeights=null,n._refCount=null,n.fastWeightInitDuringBuild=!1,n}return n(r,e),r.nodeKey=function(t,e){return t.name+"_ib-"+e.toString()},r.prototype.getNodeAtIndex=function(t,e){if(0===this.inboundNodes.length)throw new c("The layer has never been called and thus has no defined "+e+".");if(this.inboundNodes.length<=t)throw new h("Asked to get "+e+" at node "+t+", but the layer has only "+this.inboundNodes.length+" inbound nodes.");return this.inboundNodes[t]},r.prototype.getInputAt=function(t){return v(this.getNodeAtIndex(t,"input").inputTensors)},r.prototype.getOutputAt=function(t){return v(this.getNodeAtIndex(t,"output").outputTensors)},Object.defineProperty(r.prototype,"input",{get:function(){if(this.inboundNodes.length>1)throw new l("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 l("Layer "+this.name+" is not connected, no input to return.");return v(this.getNodeAtIndex(0,"input").inputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"output",{get:function(){if(0===this.inboundNodes.length)throw new l("Layer "+this.name+" has no inbound nodes.");if(this.inboundNodes.length>1)throw new l("Layer "+this.name+' has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use `getOutputAt(nodeIndex)` instead.');return v(this.getNodeAtIndex(0,"output").outputTensors)},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"losses",{get:function(){return this._losses},enumerable:!0,configurable:!0}),r.prototype.calculateLosses=function(){return this.losses.map(function(t){return t()})},Object.defineProperty(r.prototype,"updates",{get:function(){return this._updates},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"built",{get:function(){return this._built},set:function(t){this._built=t},enumerable:!0,configurable:!0}),Object.defineProperty(r.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(r.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(r.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(r.prototype,"weights",{get:function(){return this.trainableWeights.concat(this.nonTrainableWeights)},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"stateful",{get:function(){return this._stateful},enumerable:!0,configurable:!0}),r.prototype.resetStates=function(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")},r.prototype.assertInputCompatibility=function(t){if(t=b(t),null!=this.inputSpec&&0!==this.inputSpec.length){var e=b(this.inputSpec);if(t.length!==e.length)throw new h("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 h("Input "+n+" is incompatible with layer "+this.name+": expected ndim="+i.ndim+", found ndim="+a);if(null!=i.maxNDim&&a>i.maxNDim)throw new h("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 h("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 h("Input "+n+" is incompatible with layer "+this.name+" : expected dtype="+i.dtype+", found dtype="+r.dtype+".");if(i.axes){var s=r.shape;for(var o in i.axes){var u=Number(o),l=i.axes[o],c=u>=0?s[u]:s[s.length+u];if(null!=l&&-1===[l,null].indexOf(c))throw new h("Input "+n+" is incompatible with layer "+this.name+": expected axis "+u+" of input shape to have value "+l+" but got shape "+s+".")}}if(null!=i.shape)for(var p=0;p<i.shape.length;++p){var f=i.shape[p],d=r.shape[p];if(null!=f&&null!=d&&f!==d)throw new h("Input "+n+" is incompatible with layer "+this.name+": expected shape="+i.shape+", found shape="+r.shape+".")}}}}},r.prototype.call=function(t,e){return t},r.prototype.invokeCallHook=function(t,e){null!=this._callHook&&this._callHook(t,e)},r.prototype.setCallHook=function(t){this._callHook=t},r.prototype.clearCallHook=function(){this._callHook=null},r.prototype.apply=function(t,e){var n=this;e=e||{},this.assertNotDisposed();for(var r=b(t),i=!0,a=0,s=r;a<s.length;a++)if(!(s[a]instanceof Ve)){i=!1;break}for(var o=!0,u=0,l=r;u<l.length;u++)if(l[u]instanceof Ve){o=!1;break}if(i===o)throw new h("Arguments to apply() must be all SymbolicTensors or all Tensors");return ot(this.name,function(){if(!n.built){n.assertInputCompatibility(t);for(var i=[],a=0,s=b(t);a<s.length;a++){var u=s[a];i.push(u.shape)}n.build(v(i)),n.built=!0,n.initialWeights&&n.setWeights(n.initialWeights),null===n._refCount&&o&&(n._refCount=1)}if(n.assertInputCompatibility(t),o){for(var l=[],c=0,h=b(m=n.call(t,e));c<h.length;c++){var f=h[c];-1!==r.indexOf(f)&&(f=f.clone()),l.push(f)}if(m=v(l),null!=n.activityRegularizer)throw new p("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return m}var d=Ke(t),g=n.computeOutputShape(d),m=void 0,y=Ge(t);if(n.warnOnIncompatibleInputShape(Array.isArray(t)?d[0]:d),m=null!=g&&g.length>0&&Array.isArray(g[0])?g.map(function(r,i){return new Ve(y,r,n,b(t),e,n.name,i)}):new Ve(y,g,n,b(t),e,n.name),n.addInboundNode(t,m,null,null,d,g,e),n._refCount++,null!=n.activityRegularizer)throw new p("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return m})},r.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(r.prototype,"outputShape",{get:function(){if(null==this.inboundNodes||0===this.inboundNodes.length)throw new l("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 l("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}),r.prototype.countParams=function(){if(!this.built)throw new c("You tried to call countParams() on "+this.name+", but the layer is not built yet. Build it first by calling build(batchInputShape).");return _e(this.weights)},r.prototype.build=function(t){this.built=!0},r.prototype.getWeights=function(t){return void 0===t&&(t=!1),je(t?this.trainableWeights:this.weights)},r.prototype.setWeights=function(e){var n=this;(0,t.tidy)(function(){var r=n.weights;if(r.length!==e.length)throw new h('You called setWeights(weights) on layer "'+n.name+'" with a weight list of length '+e.length+", but the layer was expecting "+r.length+" weights. Provided weights: "+e+"...");if(0!==r.length){for(var i=[],a=je(r),s=0;s<a.length;++s){var o=a[s],u=r[s],l=e[s];if(!t.util.arraysEqual(o.shape,l.shape))throw new h("Layer weight shape "+o.shape+" not compatible with provided weight shape "+l.shape);i.push([u,l])}We(i)}})},r.prototype.addWeight=function(t,e,n,r,i,a,s){if(-1!==this._addedWeightNames.indexOf(t))throw new h("Duplicate weight name "+t+" for layer "+this.name);this._addedWeightNames.push(t),null==n&&(n="float32"),this.fastWeightInitDuringBuild&&(r=he("zeros"));var o=r.apply(e,n),u=new Be(o,n,t,a,s);return o.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},r.prototype.setFastWeightInitDuringBuild=function(t){this.fastWeightInitDuringBuild=t},r.prototype.addLoss=function(t){var e;null==t||Array.isArray(t)&&0===t.length||(t=b(t),void 0!==this._losses&&null!==this._losses&&(e=this.losses).push.apply(e,t))},r.prototype.computeOutputShape=function(t){return t},r.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},r.prototype.addInboundNode=function(t,e,n,r,i,a,s){void 0===s&&(s=null);var o=b(t);e=b(e),n=b(n),r=b(r),i=De(i),a=De(a);for(var u=[],l=[],c=[],h=0,p=o;h<p.length;h++){var f=p[h];u.push(f.sourceLayer),l.push(f.nodeIndex),c.push(f.tensorIndex)}new Je({outboundLayer:this,inboundLayers:u,nodeIndices:l,tensorIndices:c,inputTensors:o,outputTensors:e,inputMasks:n,outputMasks:r,inputShapes:i,outputShapes:a},s);for(var d=0;d<e.length;d++)e[d].sourceLayer=this,e[d].nodeIndex=this.inboundNodes.length-1,e[d].tensorIndex=d},r.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},r.prototype.disposeWeights=function(){return this.weights.forEach(function(t){return t.dispose()}),this.weights.length},r.prototype.assertNotDisposed=function(){if(0===this._refCount)throw new Error("Layer '"+this.name+"' is already disposed.")},r.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}},r}(t.serialization.Serializable);function Ke(t){for(var e=[],n=0,r=t=b(t);n<r.length;n++){var i=r[n];e.push(i.shape)}return v(e)}function Ge(t){return"float32"}function Ye(t,e,n){if((null==e||null!=n&&n>0)&&(e=t.sourceLayer,n=t.nodeIndex),0===e.inboundNodes.length)return[t];var r=e.inboundNodes[n];if(0===r.inboundLayers.length)return r.inputTensors;for(var i=[],a=0;a<r.inboundLayers.length;a++)for(var s=0,o=Ye(r.inputTensors[a],r.inboundLayers[a],r.nodeIndices[a]);s<o.length;s++){var u=o[s];-1===i.indexOf(u)&&i.push(u)}return i}exports.SymbolicTensor=Ve,exports.InputSpec=Ue;var Xe,$e=function(t){function e(e){var n=t.call(this,{dtype:e.dtype,name:null!=e.name?e.name:Ee("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 h("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 h("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");r=[e.batchSize].concat(e.inputShape)}else if(null!=e.batchSize)throw new h("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 Ve(n.dtype,n.batchInputShape,n,[],{},n.name);return a.nodeIndex=0,a.tensorIndex=0,new Je({outboundLayer:n,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[a],outputTensors:[a],inputMasks:[null],outputMasks:[null],inputShapes:[r],outputShapes:[r]}),n}return n(e,t),e.prototype.apply=function(t,e){throw new h("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}(Ze);function Qe(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 h("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 $e({batchInputShape:e,name:t.name,dtype:n,sparse:t.sparse}).inboundNodes[0].outputTensors[0]}function tn(e){return a(this,void 0,void 0,function(){var n,r,i,a,o,u,l,c;return s(this,function(s){switch(s.label){case 0:if(null==e)return[2];for(a in n=[],r=[],i=[],e)"number"!=typeof(o=e[a])&&(u=o,n.push(u.data()),r.push(a),i.push(u));return n.length>0?[4,Promise.all(n)]:[3,2];case 1:for(l=s.sent(),c=0;c<l.length;++c)e[r[c]]=l[c][0];(0,t.dispose)(i),s.label=2;case 2:return[2]}})})}function en(t){if(null!=t)for(var e in t){var n=t[e];"number"!=typeof n&&n.dispose()}}t.serialization.registerClass($e),function(t){t[t.SILENT=0]="SILENT",t[t.VERBOSE=1]="VERBOSE"}(Xe||(Xe={}));var nn=125,rn=function(){function t(){this.validationData=null}return t.prototype.setParams=function(t){this.params=t},t.prototype.onEpochBegin=function(t,e){return a(this,void 0,void 0,function(){return s(this,function(t){return[2]})})},t.prototype.onEpochEnd=function(t,e){return a(this,void 0,void 0,function(){return s(this,function(t){return[2]})})},t.prototype.onBatchBegin=function(t,e){return a(this,void 0,void 0,function(){return s(this,function(t){return[2]})})},t.prototype.onBatchEnd=function(t,e){return a(this,void 0,void 0,function(){return s(this,function(t){return[2]})})},t.prototype.onTrainBegin=function(t){return a(this,void 0,void 0,function(){return s(this,function(t){return[2]})})},t.prototype.onTrainEnd=function(t){return a(this,void 0,void 0,function(){return s(this,function(t){return[2]})})},t.prototype.setModel=function(t){},t}(),an=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 a(this,void 0,void 0,function(){var n,r;return s(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 a(this,void 0,void 0,function(){var n,r;return s(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 a(this,void 0,void 0,function(){var n,r;return s(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 a(this,void 0,void 0,function(){var n,r;return s(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 a(this,void 0,void 0,function(){var e,n;return s(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 a(this,void 0,void 0,function(){var e,n;return s(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}(),sn=function(e){function r(){return e.call(this)||this}return n(r,e),r.prototype.onEpochBegin=function(t){return a(this,void 0,void 0,function(){return s(this,function(t){return this.seen=0,this.totals={},[2]})})},r.prototype.onBatchEnd=function(e,n){return a(this,void 0,void 0,function(){var e,r,i,a,o=this;return s(this,function(s){for(a in null==n&&(n={}),e=null==n.size?0:n.size,this.seen+=e,r=function(r){var a=n[r];if("number"==typeof a)i.totals.hasOwnProperty(r)||(i.totals[r]=0),i.totals[r]=i.totals[r]+a*e;else{var s=void 0;r in i.totals?s=i.totals[r]:i.totals[r]=0;var u=(0,t.tidy)(function(){return(0,t.add)(o.totals[r],(0,t.mul)(a,e))});i.totals[r]=u,null!=s&&s.dispose()}},i=this,n)r(a);return[2]})})},r.prototype.onEpochEnd=function(e,n){return a(this,void 0,void 0,function(){var e,r,i,a,o,u=this;return s(this,function(s){if(null!=n)for(e=function(e){if(null==r.totals[e])return"continue";"number"==typeof r.totals[e]?n[e]=r.totals[e]/r.seen:(0,t.tidy)(function(){var r=(0,t.mul)((0,t.div)(1,u.seen),u.totals[e]);n[e]=r,u.totals[e].dispose(),(0,t.keep)(n[e])})},r=this,i=0,a=this.params.metrics;i<a.length;i++)o=a[i],e(o);return[2]})})},r}(rn),on=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.onTrainBegin=function(t){return a(this,void 0,void 0,function(){return s(this,function(t){return this.epoch=[],this.history={},[2]})})},e.prototype.onEpochEnd=function(t,e){return a(this,void 0,void 0,function(){var n;return s(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 a(this,void 0,void 0,function(){var t,e,n,r,i,a,o,u,l;return s(this,function(s){switch(s.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(u=s.sent(),l=0;l<u.length;++l)this.history[e[l]][n[l]].dispose(),this.history[e[l]][n[l]]=u[l][0];return[2]}})})},e}(rn),un=function(e){function r(n,r){var i=e.call(this)||this;if(i.currentEpoch=0,i.yieldEvery=r||"auto","auto"===i.yieldEvery&&(i.yieldEvery=nn),"never"===i.yieldEvery&&null!=n.onYield)throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");return t.util.isNumber(i.yieldEvery)&&(i.maybeWait=R(i.maybeWait.bind(i),i.yieldEvery)),i.trainBegin=n.onTrainBegin,i.trainEnd=n.onTrainEnd,i.epochBegin=n.onEpochBegin,i.epochEnd=n.onEpochEnd,i.batchBegin=n.onBatchBegin,i.batchEnd=n.onBatchEnd,i.yield=n.onYield,i}return n(r,e),r.prototype.maybeWait=function(e,n,r){return a(this,void 0,void 0,function(){var i;return s(this,function(a){switch(a.label){case 0:return i=[],null==this.yield?[3,2]:[4,tn(r)];case 1:a.sent(),i.push(this.yield(e,n,r)),a.label=2;case 2:return i.push((0,t.nextFrame)()),[4,Promise.all(i)];case 3:return a.sent(),[2]}})})},r.prototype.onEpochBegin=function(t,e){return a(this,void 0,void 0,function(){return s(this,function(n){switch(n.label){case 0:return this.currentEpoch=t,null==this.epochBegin?[3,3]:[4,tn(e)];case 1:return n.sent(),[4,this.epochBegin(t,e)];case 2:n.sent(),n.label=3;case 3:return[2]}})})},r.prototype.onEpochEnd=function(e,n){return a(this,void 0,void 0,function(){var r;return s(this,function(i){switch(i.label){case 0:return r=[],null==this.epochEnd?[3,2]:[4,tn(n)];case 1:i.sent(),r.push(this.epochEnd(e,n)),i.label=2;case 2:return"epoch"===this.yieldEvery&&r.push((0,t.nextFrame)()),[4,Promise.all(r)];case 3:return i.sent(),[2]}})})},r.prototype.onBatchBegin=function(t,e){return a(this,void 0,void 0,function(){return s(this,function(n){switch(n.label){case 0:return null==this.batchBegin?[3,3]:[4,tn(e)];case 1:return n.sent(),[4,this.batchBegin(t,e)];case 2:n.sent(),n.label=3;case 3:return[2]}})})},r.prototype.onBatchEnd=function(e,n){return a(this,void 0,void 0,function(){var r;return s(this,function(i){switch(i.label){case 0:return r=[],null==this.batchEnd?[3,2]:[4,tn(n)];case 1:i.sent(),r.push(this.batchEnd(e,n)),i.label=2;case 2:return"batch"===this.yieldEvery?r.push((0,t.nextFrame)()):t.util.isNumber(this.yieldEvery)&&r.push(this.maybeWait(this.currentEpoch,e,n)),[4,Promise.all(r)];case 3:return i.sent(),[2]}})})},r.prototype.onTrainBegin=function(t){return a(this,void 0,void 0,function(){return s(this,function(e){switch(e.label){case 0:return null==this.trainBegin?[3,3]:[4,tn(t)];case 1:return e.sent(),[4,this.trainBegin(t)];case 2:e.sent(),e.label=3;case 3:return[2]}})})},r.prototype.onTrainEnd=function(t){return a(this,void 0,void 0,function(){return s(this,function(e){switch(e.label){case 0:return null==this.trainEnd?[3,3]:[4,tn(t)];case 1:return e.sent(),[4,this.trainEnd(t)];case 2:e.sent(),e.label=3;case 3:return[2]}})})},r}(rn);function ln(t,e){return null==t&&(t={}),t instanceof rn?[t]:Array.isArray(t)&&t[0]instanceof rn?t:b(t).map(function(t){return new un(t,e)})}exports.CustomCallback=un,exports.History=on,exports.CallbackList=an;var cn=function(){function e(){}return e.registerCallbackConstructor=function(n,r){t.util.assert(n>=0&&Number.isInteger(n),function(){return"Verbosity level is expected to be an integer >= 0, but got "+n}),e.checkForDuplicate(r),null==e.constructors[n]&&(e.constructors[n]=[]),e.constructors[n].push(r)},e.checkForDuplicate=function(t){for(var n in e.constructors)e.constructors[+n].forEach(function(e){if(e===t)throw new h("Duplicate callback constructor.")})},e.clear=function(){e.constructors={}},e.createCallbacks=function(t){var n=[];for(var r in e.constructors){var i=+r;t>=i&&n.push.apply(n,e.constructors[i])}return n.map(function(t){return new t})},e.constructors={},e}();function hn(t,e,n,r,i,a,s,o,u){var l=new on,c=[new sn].concat(cn.createCallbacks(e));null!=t&&c.push.apply(c,t),c.push(l);var h=new an(c);return h.setParams({epochs:n,initialEpoch:r,samples:i,steps:a,batchSize:s,verbose:e,doValidation:o,metrics:u}),{callbackList:h,history:l}}function pn(e,n,r){return void 0===n&&(n={}),void 0===r&&(r=!1),C(e,t.serialization.SerializationMap.getMap().classNameMap,n,"layer",r)}function fn(e,n){return(0,t.tidy)(function(){"float32"!==e.dtype&&(e=e.asType("float32"));var r=(0,t.sum)(Dt(e),n,!0),i=(0,t.fill)(r.shape,o()),a=(0,t.sqrt)((0,t.maximum)(r,i));return(0,t.div)(e,a)})}function dn(e,n){return(0,t.tidy)(function(){return(0,t.mean)(Dt((0,t.sub)(n,e)),-1)})}function gn(e,n){return(0,t.tidy)(function(){return(0,t.mean)((0,t.abs)((0,t.sub)(n,e)),-1)})}function mn(e,n){return(0,t.tidy)(function(){var r=(0,t.sub)(e,n),i=(0,t.clipByValue)((0,t.abs)(e),o(),Number.MAX_VALUE),a=(0,t.abs)((0,t.div)(r,i));return(0,t.mul)(100,(0,t.mean)(a,-1))})}function yn(e,n){return(0,t.tidy)(function(){var r=(0,t.clipByValue)(n,o(),Number.MAX_VALUE),i=(0,t.log)((0,t.add)(1,r)),a=(0,t.clipByValue)(e,o(),Number.MAX_VALUE),s=(0,t.log)((0,t.add)(1,a));return(0,t.mean)(Dt((0,t.sub)(i,s)),-1)})}function vn(e,n){return(0,t.tidy)(function(){var r=(0,t.maximum)(0,(0,t.sub)(1,(0,t.mul)(e,n)));return(0,t.mean)(Dt(r),-1)})}function bn(e,n){return(0,t.tidy)(function(){var r=(0,t.maximum)(0,(0,t.sub)(1,(0,t.mul)(e,n)));return(0,t.mean)(r,-1)})}function wn(e,n){return(0,t.tidy)(function(){var r=(0,t.sum)((0,t.mul)(e,n),-1),i=(0,t.max)((0,t.mul)((0,t.sub)(1,e),n),-1);return(0,t.maximum)(0,(0,t.add)(1,(0,t.sub)(i,r)))})}function zn(e,n){return(0,t.tidy)(function(){var r=Math.log(2),i=(0,t.sub)(n,e),a=(0,t.sub)((0,t.add)(i,(0,t.softplus)((0,t.mul)(-2,i))),r);return(0,t.mean)(a,-1)})}function kn(e,n,r){return void 0===r&&(r=!1),(0,t.tidy)(function(){if(r)n=(0,t.softmax)(n);else{var i=(0,t.sum)(n,n.shape.length-1,!0);n=(0,t.div)(n,i)}return n=(0,t.clipByValue)(n,o(),1-o()),(0,t.neg)((0,t.sum)((0,t.mul)(e.toFloat(),(0,t.log)(n)),n.shape.length-1))})}function Sn(e,n){return(0,t.tidy)(function(){var r=(0,t.floor)(kt(e)).toInt(),i=(n=(0,t.clipByValue)(n,o(),1-o())).shape;return kn((0,t.oneHot)(r,i[i.length-1]).reshape(i),n,!1)})}function Nn(e,n){if(!t.util.arraysEqual(e.shape,n.shape))throw new h("logits and labels must have the same shape, but got shapes "+JSON.stringify(e.shape)+" and "+JSON.stringify(n.shape));return(0,t.tidy)(function(){var t=n.relu(),r=n.abs().neg();return t.sub(n.mul(e)).add(r.exp().log1p())})}function Cn(e,n){return(0,t.tidy)(function(){var r;return r=(0,t.clipByValue)(n,o(),1-o()),r=(0,t.log)((0,t.div)(r,(0,t.sub)(1,r))),(0,t.mean)(Nn(e,r),-1)})}function An(e,n){return(0,t.tidy)(function(){var r=(0,t.clipByValue)(e,o(),1),i=(0,t.clipByValue)(n,o(),1);return(0,t.sum)((0,t.mul)(e,(0,t.log)((0,t.div)(r,i))),-1)})}function In(e,n){return(0,t.tidy)(function(){var r=(0,t.log)((0,t.add)(o(),n));return(0,t.mean)((0,t.sub)(n,(0,t.mul)(e,r)),-1)})}function xn(e,n){return(0,t.tidy)(function(){var r=fn(e,-1),i=fn(n,-1),a=(0,t.mul)(r,i);return(0,t.neg)((0,t.sum)(a,-1))})}var Tn={meanSquaredError:dn,meanAbsoluteError:gn,meanAbsolutePercentageError:mn,meanSquaredLogarithmicError:yn,squaredHinge:vn,hinge:bn,categoricalHinge:wn,logcosh:zn,categoricalCrossentropy:kn,sparseCategoricalCrossentropy:Sn,binaryCrossentropy:Cn,kullbackLeiblerDivergence:An,poisson:In,cosineProximity:xn};function Ln(t){if("string"==typeof t){if(t in Tn)return Tn[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 h(e)}return t}function En(e,n){return(0,t.tidy)(function(){var r=(0,t.mul)(.5,(0,t.onesLike)(n)),i=bt((0,t.greater)(n,r),e.dtype);return(0,t.mean)((0,t.equal)(e,i),-1)})}function On(e,n){return(0,t.tidy)(function(){return bt((0,t.equal)((0,t.argMax)(e,-1),(0,t.argMax)(n,-1)),"float32")})}function Dn(e,n){return(0,t.tidy)(function(){return(0,t.logicalAnd)(e.equal(1),n.equal(1)).sum().cast("float32")})}function Rn(e,n){return(0,t.tidy)(function(){return(0,t.logicalAnd)(e.equal(1),n.equal(0)).sum().cast("float32")})}function Fn(e,n){return(0,t.tidy)(function(){return(0,t.logicalAnd)(e.equal(0),n.equal(1)).sum().cast("float32")})}function _n(e,n){return(0,t.tidy)(function(){var r=Dn(e,n),i=Fn(e,n),a=r.add(i);return(0,t.where)((0,t.greater)(a,0),r.div(a),0).cast("float32")})}function Mn(e,n){return(0,t.tidy)(function(){var r=Dn(e,n),i=Rn(e,n),a=r.add(i);return(0,t.where)((0,t.greater)(a,0),r.div(a),0).cast("float32")})}function Bn(t,e){return Cn(t,e)}function Pn(e,n){return e.rank===n.rank&&(e=e.squeeze([e.rank-1])),(n=n.argMax(-1)).dtype!==e.dtype&&(n=n.asType(e.dtype)),(0,t.equal)(e,n).asType("float32")}var jn=dn,Wn=dn,Un=gn,Vn=gn,qn=mn,Jn=mn,Hn=kn,Zn=xn,Kn=Sn,Gn={binaryAccuracy:En,categoricalAccuracy:On,precision:_n,categoricalCrossentropy:Hn,sparseCategoricalCrossentropy:Kn,mse:jn,MSE:Wn,mae:Un,MAE:Vn,mape:qn,MAPE:Jn,cosine:Zn};function Yn(t){if("string"==typeof t&&t in Gn)return Gn[t];if("string"!=typeof t&&null!=t)return t;throw new h("Unknown metric "+t)}function Xn(t){if(m(null!==t,"Unknown LossOrMetricFn "+t),"string"==typeof t)return t;for(var e=void 0,n=0,r=Object.keys(Tn);n<r.length;n++){var i=r[n];if(Tn[i]===t){e=i;break}}if(void 0!==e)return e;for(var a=0,s=Object.keys(Gn);a<s.length;a++)if(i=s[a],Gn[i]===t){e=i;break}return void 0!==e?e:t.name}function $n(e){var n={Adagrad:function(){return t.train.adagrad(.01)},Adadelta:function(){return t.train.adadelta(1,.95,o())},Adam:function(){return t.train.adam(.001,.9,.999,o())},Adamax:function(){return t.train.adamax(.002,.9,.999,o(),0)},RMSProp:function(){return t.train.rmsprop(.001,.9,0,o())},SGD:function(){return t.train.sgd(.01)}};if(n.adagrad=n.Adagrad,n.adadelta=n.Adadelta,n.adam=n.Adam,n.adamax=n.Adamax,n.rmsprop=n.RMSProp,n.sgd=n.SGD,e in n)return n[e]();throw new h("Unknown Optimizer "+e)}var Qn=1048576;function tr(t,e,n){if(void 0===n&&(n=!1),null==t||"object"!=typeof t||Object.getPrototypeOf(t)!==Object.prototype||!er(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>Qn&&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 <= "+Qn+".")}}function er(t){if(null===t)return!0;if("object"==typeof t){if(Object.getPrototypeOf(t)===Object.prototype){for(var e=0,n=Object.keys(t);e<n.length;e++){var r=n[e];if("string"!=typeof r)return!1;if(!er(t[r]))return!1}return!0}if(Array.isArray(t)){for(var i=0,a=t;i<a.length;i++)if(!er(a[i]))return!1;return!0}return!1}var s=typeof t;return"string"===s||"number"===s||"boolean"===s}function nr(t,e,n,r){void 0===r&&(r=console.log);var i,a=ir(t),s=["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 o in s.push("Receives inputs"),i=[],t.nodesByDepth)i.push.apply(i,t.nodesByDepth[o]);r("_".repeat(e)),ar(s,n,r),r("=".repeat(e));for(var u=t.layers,l=0;l<u.length;++l)a?sr(u[l],n,r):or(u[l],n,i,r),r((l===u.length-1?"=":"_").repeat(e));t.checkTrainableWeightsConsistency();var c=rr(t),h=_e(t.nonTrainableWeights);r("Total params: "+(c+h)),r("Trainable params: "+c),r("Non-trainable params: "+h),r("_".repeat(e))}function rr(t){return null!=t.collectedTrainableWeights?_e(t.collectedTrainableWeights):_e(t.trainableWeights)}function ir(t){var e=!0,n=[],r=[];for(var i in t.nodesByDepth)n.push(t.nodesByDepth[i]);for(var a=0,s=n;a<s.length;a++){var o=s[a];if(o.length>1||1===o.length&&o[0].inboundLayers.length>1){e=!1;break}r.push.apply(r,o)}if(e)for(var u=0,l=t.layers;u<l.length;u++){for(var c=!1,h=0,p=l[u].inboundNodes;h<p.length;h++){var f=p[h];if(-1!==r.indexOf(f)){if(c){e=!1;break}c=!0}}if(!e)break}return e}function ar(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 sr(t,e,n){var r;try{r=JSON.stringify(t.outputShape)}catch(t){r="multiple"}ar([t.name+" ("+t.getClassName()+")",r,t.countParams().toString()],e,n)}function or(t,e,n,r){var i;try{i=JSON.stringify(t.outputShape)}catch(t){i="multiple"}for(var a=[],s=0,o=t.inboundNodes;s<o.length;s++){var u=o[s];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,h=u.nodeIndices[l],p=u.tensorIndices[l];a.push(c+"["+h+"]["+p+"]")}}var f=t.name,d=t.getClassName(),g=0===a.length?"":a[0];for(ar([f+" ("+d+")",i,t.countParams().toString(),g],e,r),l=1;l<a.length;++l)ar(["","","",a[l]],e,r)}function ur(t,e,n){return("inboundNodes"===t||"outputLayers"===t||"inputLayers"===t)&&0===e&&"string"==typeof n}function lr(t,e){if(null===t)return null;if("string"==typeof t)return z(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];ur(e,i,a)?n.push(a):n.push(lr(a,e))}return n}for(var s={},o=0,u=Object.keys(t);o<u.length;o++){var l=u[o],c=t[l];if("name"===l&&"string"==typeof c)s[l]=c;else{var h=z(l);s[h]=lr(c,h)}}return s}function cr(t,e){if(null==t)return null;if("string"==typeof t)return w(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];ur(e,i,a)?n.push(a):n.push(cr(a,e))}return n}for(var s={},o=0,u=Object.keys(t);o<u.length;o++){var l=u[o],c=t[l];s[w(l)]="name"!==l&&"className"!==l||"string"!=typeof c?cr(c,l):c}return s}var hr="1.3.2";function pr(e,n){if(null==e.dtype||e.dtype===n.dtype)return n;try{return(0,t.cast)(n,e.dtype)}catch(r){throw new h("The dtype of the feed ("+n.dtype+") can not be cast to the dtype of the key '"+e.name+"' ("+e.dtype+").")}}exports.version_layers=hr;var fr=function(){function e(t){if(this.id2Value={},this.id2Mask={},this.name2Id={},t instanceof e)for(var n in t.id2Value)this.id2Value[n]=t.id2Value[n],n in t.id2Mask&&(this.id2Mask[n]=t.id2Mask[n]);else{if(null==t)return;for(var r=0,i=t;r<i.length;r++){var a=i[r];this.add(a.key,a.value)}}}return e.prototype.add=function(t,e,n){if(null!=this.id2Value[t.id])throw new h("Duplicate key: name="+t.name+", id="+t.id);return this.id2Value[t.id]=pr(t,e),this.name2Id[t.name]=t.id,null!=n&&(this.id2Mask[t.id]=n),this},e.prototype.addFeed=function(t){this.add(t.key,t.value)},e.prototype.hasKey=function(t){return null!=this.id2Value[t.id]},e.prototype.names=function(){return Object.keys(this.name2Id)},e.prototype.getValue=function(t){if(t instanceof Ve){if(null==this.id2Value[t.id])throw new h("Nonexistent key: "+t.name);return this.id2Value[t.id]}var e=this.name2Id[t];if(null==e)throw new h("Feed dict has no SymbolicTensor name: "+t);return this.id2Value[e]},e.prototype.getMask=function(t){if(t instanceof Ve){if(null==this.id2Value[t.id])throw new h("Nonexistent key: "+t.name);return this.id2Mask[t.id]}var e=this.name2Id[t];if(null==e)throw new h("Feed dict has no SymbolicTensor name: "+t);return this.id2Mask[e]},e.prototype.disposeMasks=function(){null!=this.id2Mask&&(0,t.dispose)(this.id2Mask)},e}(),dr={},gr={};function mr(e,n,r,i){for(var a=null!=r&&r.training,s=Array.isArray(e),o=s?e:[e],u=o.map(function(t){return t.name}),l=[],c=n.names(),h=0,p=u;h<p.length;h++){var f=p[h];-1!==c.indexOf(f)?l.push(n.getValue(f)):l.push(null)}null!=i&&(i.maxNumTensors=-1/0,i.minNumTensors=1/0);var d,g,m=u.join(",")+"|"+n.names().join(",");if(null==dr[m]){var y=yr(o,n);d=y.sorted,g=y.recipientCounts,dr[m]=d,gr[m]=g}d=dr[m],g={},a||Object.assign(g,gr[m]);for(var v=new fr(n),w=0;w<d.length;++w){if(null!=i){var z=(0,t.memory)().numTensors;z>i.maxNumTensors&&(i.maxNumTensors=z),z<i.minNumTensors&&(i.minNumTensors=z)}var k=d[w],S=k.sourceLayer;if(!(S instanceof $e)){for(var N=[],C=[],A=[],I=!1,x=0,T=k.inputs;x<T.length;x++){var L=T[x],E=v.getValue(L),O=v.getMask(L);N.push(E),C.push(O),null!=O&&(I=!0),a||(g[L.name]--,0!==g[L.name]||n.hasKey(L)||-1!==u.indexOf(L.name)||E.isDisposed||!0===L.sourceLayer.stateful||A.push(E))}I&&((r=r||{}).mask=C[0]);var D=b(S.apply(N,r)),R=null;S.supportsMasking&&(R=S.computeMask(N,C));for(var F=wr(k),_=Array.isArray(F)?F:[F],M=0;M<_.length;++M){v.hasKey(_[M])||v.add(_[M],D[M],Array.isArray(R)?R[0]:R);var B=u.indexOf(_[M].name);-1!==B&&(l[B]=D[M])}a||(0,t.dispose)(A)}}return v.disposeMasks(),s?l:l[0]}function yr(e,n){t.util.assert(null!=e&&e.length>0,function(){return"Expected at least one fetch, got none"});var r=[],i={};if(1===e.length){var a=br(e[0],n);r=a.sorted,i=a.recipientMap}else for(var s=new Set,o=0,u=e;o<u.length;o++){for(var l=br(u[o],n),c=l.sorted,h=l.recipientMap,p=0,f=c;p<f.length;p++){var d=f[p];s.has(d.name)||(r.push(d),s.add(d.name))}var g=function(t){null==i[t]&&(i[t]=new Set),h[t].forEach(function(e){return i[t].add(e)})};for(var m in h)g(m)}return{sorted:r,recipientCounts:vr(i)}}function vr(t){var e={};for(var n in t)e[n]=t[n].size;return e}function br(t,e){for(var n=new Set,r=[],i={},a=0,s=e.names();a<s.length;a++){var o=s[a];n.add(o)}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 h=l[l.length-1]===u.length-1;if(0===c.inputs.length||h)u.pop(),r.push(c),n.add(c.name),h&&l.pop();else{l.push(u.length-1);for(var p=0,f=c.inputs;p<f.length;p++){var d=f[p];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 wr(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}var zr=function(e){function r(t){var n=e.call(this,{})||this;if(n.containerNodes=new Set,n.name=t.name,null==n.name){var i=n.getClassName().toLowerCase();n.name=Ee(i)}if(n.supportsMasking=!1,n.trainable_=!0,Array.isArray(t.inputs)?n.inputs=t.inputs.slice():n.inputs=[t.inputs],Array.isArray(t.outputs)?n.outputs=t.outputs.slice():n.outputs=[t.outputs],x(n.inputs).length!==n.inputs.length)throw new h("The list of inputs passed to the model is redundant. All inputs should only appear once. Found: "+n.inputs.map(function(t){return t.name}));x(n.outputs).length!==n.outputs.length&&console.warn("The list of outputs passed to the model is redundant. All outputs should only appear once. Found: "+n.outputs.map(function(t){return t.name})),n.inputLayers=[],n.inputLayersNodeIndices=[],n.inputLayersTensorIndices=[],n.outputLayers=[],n.outputLayersNodeIndices=[],n.outputLayersTensorIndices=[],n.layers=[],n.internalContainerRefs=[];for(var a=0,s=n.outputs;a<s.length;a++){var o=(E=s[a]).sourceLayer,u=E.nodeIndex,l=E.tensorIndex;n.outputLayers.push(o),n.outputLayersNodeIndices.push(u),n.outputLayersTensorIndices.push(l)}for(var p=0,f=n.inputs;p<f.length;p++)o=(E=f[p]).sourceLayer,u=E.nodeIndex,l=E.tensorIndex,m(0===u,"input layer has >1 nodes"),m(0===l,"input layer has >1 tensors"),n.inputLayers.push(o),n.inputLayersNodeIndices.push(u),n.inputLayersTensorIndices.push(l);n.inputNames=[],n.outputNames=[],n.feedInputShapes=[],n.feedInputNames=[],n.feedOutputNames=[];for(var d=0;d<n.inputLayers.length;d++){if(!((o=n.inputLayers[d])instanceof $e))throw new TypeError("Input layers to a LayersModel must be InputLayer objects. Received inputs: "+t.inputs+". Input "+d+" (0-based) originates from layer type "+o.getClassName()+".");n.inputNames.push(o.name),n.feedInputShapes.push(o.batchInputShape),n.feedInputNames.push(o.name)}for(var g=0,y=n.outputLayers;g<y.length;g++)o=y[g],n.outputNames.push(o.name);n.internalInputShapes=n.inputs.map(function(t){return t.shape}),n.internalOutputShapes=n.outputs.map(function(t){return t.shape});for(var v={},b={},w={},z={},k={},S=[],N=function(t,e,i,a,s,o){null!=a&&null!=s&&null!=o||(a=t.sourceLayer,s=t.nodeIndex,o=t.tensorIndex);var u=a.inboundNodes[s];if(-1!==i.indexOf(u))throw new c("The tensor "+t.name+' at layer "'+a.name+'" is part of a cycle.');if(-1===e.indexOf(u)){n.containerNodes.add(r.nodeKey(a,s)),a.id in k||(k[a.id]=Object.keys(k).length),-1===i.indexOf(u)&&i.push(u);for(var l=u.inboundLayers.length,h=0;h<l;h++){var p=u.inputTensors[h],f=u.inboundLayers[h],d=u.nodeIndices[h],g=u.tensorIndices[h];N(p,e,i,f,d,g)}for(e.push(u);i.indexOf(u)>=0;)i.splice(i.indexOf(u),1);S.push(u)}},C=[],A=[],T=0,L=n.outputs;T<L.length;T++){var E=L[T];N(E,C,A)}for(var O=0,D=S.slice().reverse();O<D.length;O++){b[(et=D[O]).id]=et,et.id in v||(v[et.id]=0);var R=v[et.id],F=null==w[et.outboundLayer.id]?0:w[et.outboundLayer.id];for(R=Math.max(R,F),w[et.outboundLayer.id]=R,z[et.outboundLayer.id]=et.outboundLayer,v[et.id]=R,d=0;d<et.inboundLayers.length;d++){var _=et.inboundLayers[d],M=(u=et.nodeIndices[d],_.inboundNodes[u]),B=null==v[M.id]?0:v[M.id];v[M.id]=Math.max(R+1,B),b[M.id]=M}}var P={};for(var j in v)(R=v[j])in P||(P[R]=[]),P[R].push(b[j]);var W={};for(var U in w)(R=w[U])in W||(W[R]=[]),W[R].push(z[U]);var V=Object.keys(W).map(function(t){return parseInt(t,10)}).sort(I);n.layers=[];for(var q=0,J=V;q<J.length;q++){var H=W[R=J[q]];H.sort(function(t,e){var n=k[t.id],r=k[e.id];return n<r?-1:n>r?1:0});for(var Z=0,K=H;Z<K.length;Z++)(o=K[Z])instanceof r&&n.internalContainerRefs.push(o),n.layers.push(o)}n.layersByDepth=W,V=Object.keys(P).map(function(t){return parseInt(t,10)}).sort(I);for(var G=n.inputs.slice(),Y=[],X=0,$=V;X<$.length;X++)for(var Q=0,tt=P[R=$[X]];Q<tt.length;Q++){var et;if(null!=(o=(et=tt[Q]).outboundLayer)){for(var nt=0,rt=et.inputTensors;nt<rt.length;nt++)if(E=rt[nt],-1===G.indexOf(E))throw new c("Graph disconnected: cannot obtain value for tensor "+E+' at layer "'+o.name+'". The following previous layers were accessed without issue: '+Y);for(var it=0,at=et.outputTensors;it<at.length;it++)E=at[it],G.push(E);Y.push(o.name)}}n.nodesByDepth=P;for(var st=n.layers.map(function(t){return t.name}),ot=function(t){var e=st.filter(function(e){return e===t}).length;if(1!==e)throw new c('The name "'+t+'" is used '+e+" times in the model. All layer names should be unique. Layer names: "+JSON.stringify(st))},ut=0,lt=st;ut<lt.length;ut++)ot(lt[ut]);return n.outboundNodes=[],n.inboundNodes=[],new Je({outboundLayer:n,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:n.inputs,outputTensors:n.outputs,inputMasks:n.inputs.map(function(t){return null}),outputMasks:n.outputs.map(function(t){return null}),inputShapes:n.inputs.map(function(t){return t.shape}),outputShapes:n.outputs.map(function(t){return t.shape})}),n.built=!0,n._refCount=1,n}return n(r,e),r.prototype.assertNotDisposed=function(){if(0===this._refCount)throw new Error("Container '"+this.name+"' is already disposed.")},r.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 s=a[i];t.numDisposedVariables+=s.dispose().numDisposedVariables}}return t.refCountAfterDispose=this._refCount,t},Object.defineProperty(r.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(r.prototype,"trainableWeights",{get:function(){if(this._trainableWeights.length>0)throw new h("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(r.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,s=this.layers;a<s.length;a++)r=s[a],i.push.apply(i,r.trainableWeights);return i.concat(t)}return t},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"weights",{get:function(){return this.trainableWeights.concat(this.nonTrainableWeights)},enumerable:!0,configurable:!0}),r.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 s=0,o=a[i].weights;s<o.length;s++){var u=o[s];if(null!=n[u.originalName])throw new h("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 h("Provided weight data has no target variable: "+c);delete n[c]}if(e){var p=[];for(var f in n)p.push(f);if(p.length>0)throw new h(p.length+" of "+r+" weights are not set: "+p)}We(l)},r.prototype.updatedConfig=function(){var t=this.getConfig(),e={};return e.className=this.getClassName(),e.config=t,e.kerasVersion="tfjs-layers "+hr,e.backend="TensorFlow.js",e},r.prototype.toJSON=function(t,e){void 0===e&&(e=!0);var n=cr(this.updatedConfig());return e?JSON.stringify(n):n},r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){e=b(e);for(var t=new fr,i=0;i<r.inputs.length;++i)t.add(r.inputs[i],e[i]);return mr(r.outputs,t,n)})},r.prototype.computeMask=function(e,n){var r=this;return(0,t.tidy)(function(){var t;return e=b(e),t=null==n?g(null,e.length):b(n),r.runInternalGraph(e,t)[1]})},r.prototype.computeOutputShape=function(t){var e=De(t);if(e.length!==this.inputLayers.length)throw new h("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[A=i.name+"_0_0"]=a}var s=Object.keys(this.nodesByDepth).map(function(t){return parseInt(t,10)}).sort(I);if(s.length>1)for(var o=0,u=s;o<u.length;o++)for(var l=u[o],c=0,p=this.nodesByDepth[l];c<p.length;c++){var f=p[c];if(i=f.outboundLayer,-1===this.inputLayers.map(function(t){return t.id}).indexOf(i.id)){for(var d=[],g=0;g<f.inboundLayers.length;g++){var y=f.inboundLayers[g],b=f.nodeIndices[g],w=f.tensorIndices[g],z=n[A=y.name+"_"+b+"_"+w];d.push(z)}var k=De(i.computeOutputShape(v(d))),S=i.inboundNodes.indexOf(f);for(g=0;g<k.length;g++)n[A=i.name+"_"+S+"_"+g]=k[g]}}var N=[],C=[];for(r=0;r<this.outputLayers.length;r++){i=this.outputLayers[r],S=this.outputLayersNodeIndices[r],w=this.outputLayersTensorIndices[r];var A=i.name+"_"+S+"_"+w;C.push(A)}for(r=0;r<C.length;r++){var x=C[r];m(x in n),N.push(n[x])}return v(N)},r.prototype.runInternalGraph=function(t,e){null==e&&(e=g(null,t.length));for(var n={},r=0;r<this.inputs.length;++r){var i=this.inputs[r],a=t[r],s=e[r];n[i.id]=[a,s]}for(var o=0,u=Object.keys(this.nodesByDepth).map(function(t){return parseInt(t,10)}).sort(I);o<u.length;o++)for(var l=u[o],c=0,h=this.nodesByDepth[l];c<h.length;c++){for(var f=h[c],d=f.outboundLayer,y=f.inputTensors,v=f.outputTensors,w=new Array,z=0,k=y;z<k.length;z++)(i=k[z]).id in n&&w.push(n[i.id]);if(w.length===y.length){var S={},N=void 0,C=void 0,A=void 0,x=void 0;if(null!=f.callArgs&&(S=f.callArgs),1===w.length){var T=w[0],L=T[0],E=T[1];null==S.mask&&(S.mask=E),A=b(d.call(L,S)),x=b(d.computeMask(L,E)),N=[L],C=[E]}else N=w.map(function(t){return t[0]}),C=w.map(function(t){return t[1]}),null==S.mask&&(S.mask=C),A=b(d.call(N,S)),x=b(d.computeMask(N,C));if(d.activityRegularizer)throw new p("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(r=0;r<v.length;++r)i=v[r],a=A[r],s=x[r],n[i.id]=[a,s]}}for(var O=[],D=[],R=[],F=0,_=this.outputs;F<_.length;F++){m((i=_[F]).id in n,"Could not compute output "+i.name+" : "+i.id);var M=n[i.id],B=M[0];s=M[1],R.push(B.shape),O.push(B),D.push(s)}return[O,D,R]},r.prototype.buildNodeConversionMap=function(t){for(var e,n={},i=0,a=this.layers;i<a.length;i++){var s=a[i];e=s instanceof r?1:0;for(var o=0;o<s.inboundNodes.length;o++){var u=r.nodeKey(s,o);this.containerNodes.has(u)&&(n[u]=e,e+=1)}}return n},r.prototype.getLayer=function(t,e){if(null!=e){if(this.layers.length<=e)throw new h("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 h("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 h("No such layer: "+t)},r.prototype.calculateLosses=function(){var e=this;return(0,t.tidy)(function(){for(var t=[],n=0,i=e.layers;n<i.length;n++)for(var a=i[n],s=0;s<a.inboundNodes.length;++s){var o=r.nodeKey(a,s);e.containerNodes.has(o)&&t.push.apply(t,a.calculateLosses())}return t})},r.prototype.getConfig=function(){for(var t={name:this.name},e=this.buildNodeConversionMap(this.layers),n=[],i=0,a=this.layers;i<a.length;i++){for(var s=(w=a[i]).getClassName(),o=w.getConfig(),u=[],l=0;l<w.inboundNodes.length;l++){var c=w.inboundNodes[l],h=r.nodeKey(w,l),p={};if(this.containerNodes.has(h)){if(c.callArgs)try{JSON.stringify(c.callArgs),p=c.callArgs}catch(t){console.warn("Layer "+w.name+" was passed non-serializable keyword arguments: "+c.callArgs+". They will not be included in the serialized model (and thus will be missing at deserialization time)."),p={}}if(c.inboundLayers.length>0){for(var f=[],d=0;d<c.inboundLayers.length;d++){var g=c.inboundLayers[d],m=c.nodeIndices[d],y=c.tensorIndices[d];null==(k=e[r.nodeKey(g,m)])&&(k=0),f.push([g.name,k,y,p])}u.push(f)}}}var v={};v.name=w.name,v.className=s,v.config=o,v.inboundNodes=u,n.push(v)}t.layers=n;var b=[];for(d=0;d<this.inputLayers.length;d++){var w=this.inputLayers[d];m=this.inputLayersNodeIndices[d],h=r.nodeKey(w,m),this.containerNodes.has(h)&&(null!==(k=e[h])&&void 0!==k||(k=0),y=this.inputLayersTensorIndices[d],b.push([w.name,k,y]))}t.inputLayers=b;var z=[];for(d=0;d<this.outputLayers.length;d++){var k;if(w=this.outputLayers[d],m=this.outputLayersNodeIndices[d],h=r.nodeKey(w,m),this.containerNodes.has(h))null!==(k=e[h])&&void 0!==k||(k=0),y=this.outputLayersTensorIndices[d],z.push([w.name,k,y])}return t.outputLayers=z,t},r.fromConfig=function(t,e,n,r){void 0===n&&(n={}),void 0===r&&(r=!1);var i={},a={};function s(t,e){t.name in a?a[t.name].push(e):a[t.name]=[e]}function o(t,e){for(var n,r=[],a=0,o=e;a<o.length;a++){var u=o[a],l=u[0],c=u[1],h=u[2];if(n=null==u[3]?{}:u[3],!(l in i))return void s(t,e);var p=i[l];if(p.inboundNodes.length<=c)return void s(t,e);var f=p.inboundNodes[c];r.push(f.outputTensors[h])}r.length>0&&t.apply(v(r),n)}function u(t){var n=t.name,a=pn(t,null!=e.customObjects?e.customObjects:{});a.setFastWeightInitDuringBuild(r),i[n]=a,t.inboundNodes.forEach(function(t){if(!(t instanceof Array))throw new h("Corrupted configuration, expected array for nodeData: "+t);s(a,t)})}for(var l=e.name,c=e.layers,p=0,f=c;p<f.length;p++)u(y=f[p]);for(;!T(a);)for(var d=0,g=c;d<g.length;d++){var y=g[d];if((D=i[y.name]).name in a){var b=a[D.name];delete a[D.name];for(var w=0,z=b;w<z.length;w++)o(D,z[w])}}for(var k=[],S=[],N=0,C=e.inputLayers;N<C.length;N++){var A=(y=C[N])[0],I=y[1],x=y[2];m(A in i);var L=(D=i[A]).inboundNodes[I].outputTensors;k.push(L[x])}for(var E=0,O=e.outputLayers;E<O.length;E++){var D;A=(y=O[E])[0],I=y[1],x=y[2],m(A in i),L=(D=i[A]).inboundNodes[I].outputTensors,S.push(L[x])}return new t({inputs:k,outputs:S,name:l})},Object.defineProperty(r.prototype,"stateful",{get:function(){if(this._stateful)throw new h("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}),r.prototype.resetStates=function(){var e=this;(0,t.tidy)(function(){e.layers.forEach(function(t){t.stateful&&t.resetStates()})})},r}(Ze);function kr(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))}function Sr(t,e){return kr(t,e,"classWeight")}function Nr(e,n,r,i){return a(this,void 0,void 0,function(){var a,o,u,l,c;return s(this,function(s){switch(s.label){case 0:if(null!=n||null!=i)throw new Error("Support sampleWeight is not implemented yet");return null==r?[3,2]:(a=(0,t.tidy)(function(){if(1===e.shape.length)return e.clone();if(2===e.shape.length){if(e.shape[1]>1)return e.argMax(1);if(1===e.shape[1])return e.reshape([e.shape[0]]);throw new Error("Encountered unexpected last-dimension size ("+e.shape[1]+") during handling of class weights. The size is expected to be >= 1.")}throw new Error("Unexpected rank of target (y) tensor ("+e.rank+") during handling of class weights. The rank is expected to be 1 or 2.")}),l=(u=Array).from,[4,a.data()]);case 1:return o=l.apply(u,[s.sent()]),(0,t.dispose)(a),c=[],o.forEach(function(t){if(null==r[t])throw new Error("classWeight must contain all classes in the training data. The class "+t+" exists in the data but not in classWeight");c.push(r[t])}),[2,(0,t.tensor1d)(c,"float32")];case 2:return[2,null]}})})}function Cr(e,n){return(0,t.mul)(e,n)}var Ar=32;function Ir(e,n){var r,i,a=n;r=a.xs,i=a.ys,t.util.assert(null!=r&&null!=i,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 "+n});var s=xr("input",e.inputNames,r),o=xr("output",e.outputNames,i),u=s[0].shape[0];t.util.assert(s.length===e.inputs.length,function(){return"LayersModel has "+e.inputs.length+" inputs, but the dataset provides "+s.length+" inputs.  (Expected input keys: "+JSON.stringify(e.inputNames)+")"}),t.util.assert(o.length===e.outputs.length,function(){return"LayersModel has "+e.outputs.length+" outputs, but the dataset provides "+o.length+" outputs.  (Expected output keys: "+JSON.stringify(e.outputNames)+")"});var l=function(n){t.util.assert(s[n].shape[0]===u,function(){return"Batch size mismatch: input "+e.inputNames[n]+" has "+s[n].shape[0]+"; expected  "+u+" based on input "+e.inputNames[0]+"."})};for(var c in s)l(c);var h=function(n){t.util.assert(o[n].shape[0]===u,function(){return"Batch size mismatch: output "+e.outputNames[n]+" has "+o[n].shape[0]+"; expected  "+u+" based on input "+e.inputNames[0]+"."})};for(var p in o)h(p);return{xs:s,ys:o}}function xr(e,n,r){if(r instanceof t.Tensor)return[r];if(Array.isArray(r))return t.util.assert(r.length===n.length,function(){return"Received an array of "+r.length+" Tensors, but expected "+n.length+" to match the "+e+" keys "+n+"."}),r;for(var i=[],a=0,s=n;a<s.length;a++){var o=s[a];if(null==r[o])throw new h("The feature data generated by the dataset lacks the required "+e+" key '"+o+"'.");i.push(r[o])}return i}function Tr(t){if(3===t.length)throw new p("Validation with sample weights is not implemented yet.");return{xs:t[0],ys:t[1]}}function Lr(e,n,r){return a(this,void 0,void 0,function(){var i,a,o,u,l,c,h,p,f,d,g,m,y,v,w,z,k,S,N,C,A,I,x,T,L,E,O,D,R,F,_,M,B,P;return s(this,function(s){switch(s.label){case 0:if(i=null!=r.batchesPerEpoch,t.util.assert(null!=e.optimizer,function(){return"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."}),t.util.assert(null!=r,function(){return"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."}),t.util.assert(null!=r.epochs&&r.epochs>0&&Number.isInteger(r.epochs),function(){return"For fitDataset(), config.epochs is expected to be a positive integer, but got "+r.epochs}),t.util.assert(!i||r.batchesPerEpoch>0&&Number.isInteger(r.batchesPerEpoch),function(){return"For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got "+r.batchesPerEpoch}),t.util.assert(null==r.validationSplit,function(){return"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."}),e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0,s.label=1;case 1:return s.trys.push([1,,26,27]),a=null!=r.validationData,o=void 0,u=void 0,a&&(Or(r.validationData)?t.util.assert(null==r.validationBatches||r.validationBatches>0&&Number.isInteger(r.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 "+r.validationBatches}):(l=Tr(r.validationData),o=l.xs,u=l.ys)),c=e.makeTrainFunction(),h=e.getDedupedMetricsNames(),void 0,p=a?h.slice().concat(h.map(function(t){return"val_"+t})):h.slice(),f=ln(r.callbacks,r.yieldEvery),d=null==r.verbose?1:r.verbose,g=hn(f,d,r.epochs,null,null,Er(n,r),null,a,p),m=g.callbackList,y=g.history,m.setModel(e),e.history=y,[4,m.onTrainBegin()];case 2:return s.sent(),e.stopTraining_=!1,v=null==r.initialEpoch?0:r.initialEpoch,[4,n.iterator()];case 3:w=s.sent(),s.label=4;case 4:return v<r.epochs?(z={},[4,m.onEpochBegin(v)]):[3,23];case 5:return s.sent(),k=0,S=0,i?[3,7]:[4,n.iterator()];case 6:w=s.sent(),s.label=7;case 7:return!i||k<r.batchesPerEpoch?[4,w.next()]:[3,21];case 8:return N=s.sent(),i&&N.done?(console.warn("You provided `batchesPerEpoch` as "+r.batchesPerEpoch+", but your dataset iterator ran out of data after "+k+" batches; interrupting training. Make sure that your dataset can generate at least `batchesPerEpoch * epochs` batches (in this case, "+r.batchesPerEpoch*r.epochs+" batches). You may need to use the repeat() function when building your dataset."),[3,21]):null==N.value?[3,15]:(C=Ir(e,N.value),A=C.xs,I=C.ys,(x={}).batch=S,x.size=A[0].shape[0],[4,m.onBatchBegin(S,x)]);case 9:if(s.sent(),T=[],null==r.classWeight)return[3,13];L=Sr(r.classWeight,e.outputNames),P=0,s.label=10;case 10:return P<L.length?(O=(E=T).push,[4,Nr(I[P],null,L[P])]):[3,13];case 11:O.apply(E,[s.sent()]),s.label=12;case 12:return++P,[3,10];case 13:for(D=A.concat(I).concat(T),R=c(D),(0,t.dispose)(D),P=0;P<h.length;++P)F=h[P],_=R[P],x[F]=_,(0,t.keep)(_);return[4,m.onBatchEnd(S,x)];case 14:s.sent(),en(x),S++,k++,s.label=15;case 15:return(i?k>=r.batchesPerEpoch:N.done)?a?(M=void 0,Or(r.validationData)?(B=b,[4,e.evaluateDataset(r.validationData,{batches:r.validationBatches})]):[3,17]):[3,19]:[3,20];case 16:return M=B.apply(void 0,[s.sent()]),[3,18];case 17:M=b(e.evaluate(o,u,{batchSize:null==r.validationBatchSize?Ar:r.validationBatchSize,verbose:0})),s.label=18;case 18:for(P=0;P<e.metricsNames.length;++P)z["val_"+e.metricsNames[P]]=M[P];s.label=19;case 19:return[3,21];case 20:return e.stopTraining_?[3,21]:[3,7];case 21:return[4,m.onEpochEnd(v,z)];case 22:return s.sent(),v++,e.stopTraining_?[3,23]:[3,4];case 23:return[4,m.onTrainEnd()];case 24:return s.sent(),[4,e.history.syncData()];case 25:return s.sent(),[2,e.history];case 26:return e.isTraining=!1,[7];case 27:return[2]}})})}function Er(t,e){var n=null;return null!=e.batchesPerEpoch?n=e.batchesPerEpoch:Number.isFinite(t.size)&&(n=t.size),n}function Or(t){return"function"==typeof t.iterator}function Dr(t){return"function"==typeof t.next}function Rr(e,n,r){return a(this,void 0,void 0,function(){var i,a,o,u,l,c,h,f,d,g;return s(this,function(m){switch(m.label){case 0:if(i=null!=(r=r||{}).batches,a=e.testFunction,o=[],r.verbose>0)throw new p("Verbose mode is not implemented yet.");return t.util.assert(!i||r.batches>0&&Number.isInteger(r.batches),function(){return"Test loop expects `batches` to be a positive integer, but received "+JSON.stringify(r.batches)}),Dr(n)?(l=n,[3,3]):[3,1];case 1:return[4,n.iterator()];case 2:l=m.sent(),m.label=3;case 3:u=l,c=0,h=0,f=function(){var n;return s(this,function(s){switch(s.label){case 0:return[4,u.next()];case 1:return n=s.sent(),o=(0,t.tidy)(function(){if(n.value){var r=Ir(e,n.value),i=r.xs,s=r.ys,u=i.concat(s),l=(0,t.tidy)(function(){return a(u)});if((0,t.dispose)(u),0===h)for(var p=0;p<l.length;++p)o.push((0,t.scalar)(0));var f=u[0].shape[0],d=function(e){var n=l[e],r=o[e];o[e]=(0,t.tidy)(function(){return(0,t.add)(o[e],(0,t.mul)(f,n))}),h>0&&(0,t.dispose)(r)};for(p=0;p<l.length;++p)d(p);(0,t.dispose)(l),c+=f,++h}return o}),n.done?(i&&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, "+r.batches+" batches). You may need to use the repeat() function when building your dataset."),[2,"break"]):[2]}})},m.label=4;case 4:return!i||h<r.batches?[5,f()]:[3,6];case 5:return"break"===m.sent()?[3,6]:[3,4];case 6:for(d=0;d<o.length;++d)g=o[d],o[d]=(0,t.div)(o[d],c),(0,t.dispose)(g);return[2,v(o)]}})})}function Fr(e){t.util.assert(e>0&&Number.isInteger(e),function(){return"batchSize is required to be a positive integer, but got "+e})}function _r(t,e,n){return null==t?[null]:Array.isArray(t)?t.map(function(t){return Nt(t,e,n-e)}):Nt(t,e,n-e)}function Mr(e,n){return(0,t.tidy)(function(){return null==e?null:Array.isArray(e)?e.map(function(t){return Mr(t,n)}):Ot(e,"int32"===n.dtype?n:n.toInt())})}function Br(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 Pr(e,n,r,i,o,u,l,c,f,d,g,m,y,v,b){return a(this,void 0,void 0,function(){var a,w,z,k,S,N,C,A;return s(this,function(I){switch(I.label){case 0:if(null==o&&(o=32),null==u&&(u=1),null==g&&(g=!0),null==y&&(y=0),a=!1,null!=f&&null!=d&&(a=!0),null!=b&&(a=!0,null==v))throw new h("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");return null!=(w=e.checkNumSamples(r,o,v,"steps_per_epoch"))&&(z=vt(0,w)),null==l&&(l=1),k=hn(c,l,u,y,w,v,o,a,m),S=k.callbackList,N=k.history,S.setModel(e),e.history=N,[4,S.onTrainBegin()];case 1:I.sent(),e.stopTraining_=!1,C=function(u){var l,c,h,m,y;return s(this,function(b){switch(b.label){case 0:return[4,S.onEpochBegin(u)];case 1:if(b.sent(),l={},null==v)return[3,2];throw new p("stepsPerEpoch mode is not implemented yet.");case 2:if("batch"===g)throw new p("batch shuffling is not implemneted yet");g&&t.util.shuffle(z),c=(0,t.tensor1d)(z),h=Br(w,o),m=function(u){var p;return s(this,function(s){switch(s.label){case 0:return p={},[4,S.onBatchBegin(u,p)];case 1:return s.sent(),(0,t.tidy)(function(){var s=h[u][0],g=h[u][1],m=Nt(c,s,g-s);p.batch=u,p.size=g-s;for(var y=Mr(r,m),v=n(y),b=0;b<i.length;++b){var w=i[b],z=v[b];p[w]=z,(0,t.keep)(z)}if(u===h.length-1&&a){var k=e.testLoop(f,d,o);for(b=0;b<i.length;++b)w=i[b],z=k[b],(0,t.keep)(z),l["val_"+w]=z}}),[4,S.onBatchEnd(u,p)];case 2:return s.sent(),en(p),e.stopTraining_?[2,"break"]:[2]}})},y=0,b.label=3;case 3:return y<h.length?[5,m(y)]:[3,6];case 4:if("break"===b.sent())return[3,6];b.label=5;case 5:return++y,[3,3];case 6:c.dispose(),b.label=7;case 7:return[4,S.onEpochEnd(u,l)];case 8:return b.sent(),e.stopTraining_?[2,"break"]:[2]}})},A=y,I.label=2;case 2:return A<u?[5,C(A)]:[3,5];case 3:if("break"===I.sent())return[3,5];I.label=4;case 4:return++A,[3,2];case 5:return[4,S.onTrainEnd()];case 6:return I.sent(),[4,e.history.syncData()];case 7:return I.sent(),[2,e.history]}})})}function jr(e,n,r,i){return void 0===i&&(i={}),a(this,void 0,void 0,function(){var a,o,u,l,c,f,d,g,m,y,v,b,w,z,k,S,N,C,A,I;return s(this,function(s){switch(s.label){case 0:if(e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0,s.label=1;case 1:return s.trys.push([1,,7,8]),Fr(g=null==i.batchSize?32:i.batchSize),!1,[4,e.standardizeUserData(n,r,i.sampleWeight,i.classWeight,!1,g)];case 2:if(m=s.sent(),a=m[0],o=m[1],d=m[2],y=!1,v=void 0,!(null!=i.validationData&&i.validationData.length>0))return[3,4];if(y=!0,2!==i.validationData.length)throw 3===i.validationData.length?new p("validationData including sample weights is not supported yet."):new h("When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; "+i.validationData+" is invalid.");return u=i.validationData[0],l=i.validationData[1],!0,[4,e.standardizeUserData(u,l,null,null,!0,g)];case 3:return b=s.sent(),c=b[0],f=b[1],v=c.concat(f),[3,5];case 4:null!=i.validationSplit&&i.validationSplit>0&&i.validationSplit<1?(y=!0,w=Math.floor(a[0].shape[0]*(1-i.validationSplit)),z=a[0].shape[0],c=_r(a,w,z),a=_r(a,0,w),f=_r(o,w,z),o=_r(o,0,w),v=c.concat(f)):null!=i.validationSteps&&(y=!0),s.label=5;case 5:return k=a.concat(o).concat(d),e.checkTrainableWeightsConsistency(),S=e.makeTrainFunction(),N=e.getDedupedMetricsNames(),C=void 0,A=void 0,y?(e.makeTestFunction(),C=e.testFunction,A=N.slice().concat(N.map(function(t){return"val_"+t}))):(C=null,v=[],A=N.slice()),I=ln(i.callbacks,i.yieldEvery),[4,Pr(e,S,k,N,g,i.epochs,i.verbose,I,C,v,i.shuffle,A,i.initialEpoch,null,null)];case 6:return[2,s.sent()];case 7:return e.isTraining=!1,Ur(a,n),Ur(o,r),Ur(c,u),Ur(f,l),null!=d&&(0,t.dispose)(d),[7];case 8:return[2]}})})}function Wr(e){var n=[];e instanceof t.Tensor&&(e=[e]);for(var r=0;r<e.length;++r){var i=e[r];if(1===i.rank)n.push(wt(i,1));else{if(0===i.rank)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");n.push(i)}}return n}function Ur(e,n){if(null!=e){var r=[];if(n instanceof t.Tensor)r.push(n.id);else if(Array.isArray(n))n.forEach(function(t){return r.push(t.id)});else if(null!=n)for(var i in n){var a=n[i];r.push(a.id)}var s=[];if(e instanceof t.Tensor)-1===r.indexOf(e.id)&&s.push(e);else if(Array.isArray(e))e.forEach(function(t){-1===r.indexOf(t.id)&&s.push(t)});else if(null!=e)for(var o in e){var u=e[o];-1===r.indexOf(u.id)&&s.push(u)}s.forEach(function(t){t.isDisposed||t.dispose()})}}function Vr(e){return e instanceof t.Tensor}function qr(t){return Array.isArray(t)}function Jr(t){return!Vr(t)&&!qr(t)}function Hr(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(qr(t)&&t.length>0)a=!0;else if(Jr(t)){for(var s in t)if(t.hasOwnProperty(s)){a=!0;break}}else a=!0;if(a)throw new h("Error when checking model "+i+" expected no data, but got "+t)}return[]}if(null==t)return e.map(function(t){return null});var o;if(Jr(t)){t=t,o=[];for(var u=0,l=e;u<l.length;u++){var c=l[u];if(null==t[c])throw new h('No data provided for "'+c+'". Need data for each key in: '+e);o.push(t[c])}}else if(qr(t)){if((t=t).length!==e.length)throw new h("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);o=t}else{if(t=t,e.length>1)throw new h("The model "+i+" expects "+e.length+" Tensor(s), but only received one Tensor. Found: Tensor with shape "+t.shape);o=[t]}if(o=Wr(o),null!=n)for(var p=0;p<e.length;++p)if(null!=n[p]){var f=o[p];if(f.shape.length!==n[p].length)throw new h("Error when checking "+i+": expected "+e[p]+" to have "+n[p].length+" dimension(s). but got array with shape "+f.shape);for(var d=0;d<n[p].length;++d)if(0!==d||r){var g=f.shape[d],m=n[p][d];if(null!=m&&m>=0&&g!==m)throw new h("Error when checking "+i+": expected "+e[p]+" to have shape ["+n[p]+"], but got array with shape ["+f.shape+"].")}}return o}function Zr(e,n,r){var i=x(e.map(function(t){return t.shape[0]}));i.sort();var a=x(n.map(function(t){return t.shape[0]}));if(a.sort(),i.length>1)throw new h("All input Tensors (x) should have the same number of samples. Got array shapes: "+JSON.stringify(e.map(function(t){return t.shape})));if(a.length>1)throw new h("All target Tensors (y) should have the same number of samples. Got array shapes: "+JSON.stringify(n.map(function(t){return t.shape})));if(i.length>0&&a.length>0&&!t.util.arraysEqual(i,a))throw new h("Input Tensors should have the same number of samples as target Tensors. Found "+i[0]+" input sample(s) and "+a[0]+" target sample(s).")}function Kr(t,e,n){for(var r=[dn,Cn,kn],i=0;i<t.length;++i){var a=t[i],s=e[i],o=n[i];if(null!=s){if(s===kn&&1===a.shape[a.shape.length-1])throw new h("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(s))for(var u=a.shape.slice(1),l=o.slice(1),c=0;c<u.length;++c){var p=u[c],f=l[c];if(null!=f&&p!==f)throw new h("A target Tensor with shape "+a.shape+" was passed for an output of shape "+o+", while using a loss function that expects targets to have the same shape as the output.")}}}}function Gr(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 h("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 h("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 s=0;s<e.length;++s)if(null!=n[s]){var o=a[s];if(o.shape.length!==n[s].length)throw new h("Error when checking "+i+": expected "+e[s]+" to have "+n[s].length+" dimension(s), but got array with shape "+JSON.stringify(o.shape));for(var u=0;u<n[s].length;++u)if(0!==u||r){var l=o.shape[u],c=n[s][u];if(null!=c&&c!==l)throw new h("Error when checking "+i+": expected "+e[s]+" to have shape "+JSON.stringify(n[s])+" but got array with shape "+JSON.stringify(o.shape)+".")}}}function Yr(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 s=a[i],o=n.hasOwnProperty(s)?n[s]:[];Array.isArray(o)||(o=[o]),r.push(o)}return r}var Xr="layers-model",$r=function(e){function r(t){var n=e.call(this,t)||this;return n.isTraining=!1,n}return n(r,e),r.prototype.summary=function(t,e,n){if(void 0===n&&(n=console.log),!this.built)throw new h("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).");nr(this,t,e,n)},r.prototype.compile=function(e){var n=this;if(null==e.loss&&(e.loss=[]),this.loss=e.loss,"string"==typeof e.optimizer)this.optimizer_=$n(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof t.Optimizer))throw new h("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}var r=[];if(Array.isArray(e.loss)||"string"==typeof e.loss||"function"==typeof e.loss)if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new h("When passing an Array as loss, it should have one entry per model output. The model has "+this.outputs.length+" output(s), but you passed loss="+e.loss+".");var i=e.loss;r=i.map(function(t){return Ln(t)})}else{var a=Ln(e.loss);this.outputs.forEach(function(t){r.push(a)})}else{for(var s in e.loss=e.loss,e.loss)if(-1===this.outputNames.indexOf(s))throw new h('Unknown entry in loss dictionary: "'+s+'". Only expected the following keys: '+this.outputNames);for(var o=0,u=this.outputNames;o<u.length;o++){var l=u[o];null==e.loss[l]&&console.warn('Output "'+l+'" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to '+l+" during training"),r.push(Ln(e.loss[l]))}}this.lossFunctions=r,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(var c=0;c<this.outputs.length;++c){var p=this.internalOutputShapes[c],f=this.outputNames[c];this.feedOutputNames.push(f),this.feedOutputShapes.push(p),this.feedLossFns.push(this.lossFunctions[c])}var d=[];this.metrics=e.metrics,this.metricsNames=["loss"],this.metricsTensors=[],ot("loss",function(){for(var t=0;t<n.outputs.length;++t)if(-1===d.indexOf(t)){var e=n.lossFunctions[t];n.outputs.length>1&&(n.metricsTensors.push([e,t]),n.metricsNames.push(n.outputNames[t]+"_loss"))}});var g=Yr(e.metrics,this.outputNames);ot("metric",function(){for(var t=function(t){if(-1!==d.indexOf(t))return"continue";!function(e){for(var r,i,a,s=function(e){if("string"==typeof e&&-1!==["accuracy","acc","crossentropy","ce"].indexOf(e)){var s=n.internalOutputShapes[t];1===s[s.length-1]||n.lossFunctions[t]===Cn?-1!==["accuracy","acc"].indexOf(e)?i=En:-1!==["crossentropy","ce"].indexOf(e)&&(i=Bn):n.lossFunctions[t]===Sn?-1!==["accuracy","acc"].indexOf(e)?i=Pn:-1!==["crossentropy","ce"].indexOf(e)&&(i=Kn):-1!==["accuracy","acc"].indexOf(e)?i=On:-1!==["crossentropy","ce"].indexOf(e)&&(i=Hn);var o=void 0;-1!==["accuracy","acc"].indexOf(e)?o="acc":-1!==["crossentropy","ce"].indexOf(e)&&(o="ce"),a=i,r=""+o}else{var u=Yn(e);a=u,r=""+Xn(e)}var l;ot(r,function(){l=a}),function(t,e,r){n.outputNames.length>1&&(e=n.outputNames[t]+"_"+e),n.metricsNames.push(e),n.metricsTensors.push([r,t])}(t,r,l)},o=0,u=g[t];o<u.length;o++)s(u[o])}()},e=0;e<n.outputs.length;++e)t(e)}),this.collectedTrainableWeights=this.trainableWeights},r.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?")},r.prototype.evaluate=function(t,e,n){void 0===n&&(n={});var r=null==n.batchSize?32:n.batchSize;Fr(r);var i=this.standardizeUserDataXY(t,e,!0,r);try{var a=i[0].concat(i[1]);this.makeTestFunction();var s=this.testFunction;return v(this.testLoop(s,a,r,n.verbose,n.steps))}finally{Ur(i[0],t),Ur(i[1],e)}},r.prototype.evaluateDataset=function(t,e){return a(this,void 0,void 0,function(){return s(this,function(n){return this.makeTestFunction(),[2,Rr(this,t,e)]})})},r.prototype.checkNumSamples=function(t,e,n,r){var i;if(void 0===r&&(r="steps"),null!=n){if(i=null,null!=e)throw new h("If "+r+" is set, batchSize must be null or undefined.Got batchSize = "+e)}else{if(null==t)throw new h("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},r.prototype.execute=function(e,n){if(Array.isArray(n)&&0===n.length)throw new h("`outputs` is an empty Array, which is not allowed.");var r=Array.isArray(n),i=r?n:[n],a=this.retrieveSymbolicTensors(i),s=new fr;if(e instanceof t.Tensor&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new h("The number of inputs provided ("+e.length+") does not match the number of inputs of this model ("+this.inputs.length+").");for(var o=0;o<this.inputs.length;++o)s.add(this.inputs[o],e[o])}else for(var u=0,l=this.inputs;u<l.length;u++){var c=l[u],p=e[c.name];if(null==p)throw new h("No value is provided for the model's input "+c.name);s.add(c,p)}var f=mr(a,s);return r?f:f[0]},r.prototype.retrieveSymbolicTensors=function(t){for(var e=g(null,t.length),n=t.length,r=0,i=this.layers;r<i.length;r++){for(var a=i[r],s=Array.isArray(a.output)?a.output:[a.output],o=s.map(function(t){return t.name}),u=0;u<t.length;++u){var l=o.indexOf(t[u]);if(-1!==l&&(e[u]=s[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 h("Cannot find SymbolicTensors for output name(s): "+JSON.stringify(c))}return e},r.prototype.predictLoop=function(e,n,r){var i=this;return void 0===n&&(n=32),void 0===r&&(r=!1),(0,t.tidy)(function(){var a=i.checkNumSamples(e);if(r)throw new p("Verbose predictLoop() is not implemented yet.");for(var s=Br(a,n),o=i.outputs.map(function(t){return[]}),u=function(n){(0,t.tidy)(function(){var t=s[n][0],r=s[n][1],a=_r(e,t,r),o=[];if(Array.isArray(a))for(var u=0;u<a.length;++u)o.push({key:i.inputs[u],value:a[u]});else o.push({key:i.inputs[0],value:a});var l=new fr(o);return mr(i.outputs,l)}).forEach(function(t,e){return o[e].push(t)})},l=0;l<s.length;++l)u(l);return v(o.map(function(e){return(0,t.concat)(e,0)}))})},r.prototype.predict=function(t,e){void 0===e&&(e={});var n=Wr(t);Gr(n,this.inputNames,this.feedInputShapes,!1);try{var r=null==e.batchSize?32:e.batchSize;return Fr(r),this.predictLoop(n,r)}finally{Ur(n,t)}},r.prototype.predictOnBatch=function(t){Gr(t,this.inputNames,this.feedInputShapes,!0);var e=(Array.isArray(t)?t[0]:t).shape[0];return this.predictLoop(t,e)},r.prototype.standardizeUserDataXY=function(t,e,n,r){if(void 0===n&&(n=!0),null==this.optimizer_)throw new c("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");for(var i=[],a=0;a<this.feedOutputShapes.length;++a){var s=this.feedOutputShapes[a];this.feedLossFns[a]===Sn?i.push(s.slice(0,s.length-1).concat([1])):i.push(s)}if(Zr(t=Hr(t,this.feedInputNames,this.feedInputShapes,!1,"input"),e=Hr(e,this.feedOutputNames,i,!1,"target"),null),Kr(e,this.feedLossFns,this.feedOutputShapes),this.stateful&&null!=r&&r>0&&t[0].shape[0]%r!=0)throw new h("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]},r.prototype.standardizeUserData=function(t,e,n,r,i,o){return void 0===i&&(i=!0),a(this,void 0,void 0,function(){var a,u,l,c,h,p,f,d;return s(this,function(s){switch(s.label){case 0:if(a=this.standardizeUserDataXY(t,e,i,o),u=a[0],l=a[1],null!=n)throw new Error("sample weight is not supported yet.");if(c=null,null==r)return[3,4];h=Sr(r,this.outputNames),c=[],p=0,s.label=1;case 1:return p<h.length?(d=(f=c).push,[4,Nr(l[p],null,h[p])]):[3,4];case 2:d.apply(f,[s.sent()]),s.label=3;case 3:return++p,[3,1];case 4:return[2,[u,l,c]]}})})},r.prototype.testLoop=function(e,n,r,i,a){var s=this;return void 0===i&&(i=0),(0,t.tidy)(function(){var o=s.checkNumSamples(n,r,a,"steps"),u=[];if(i>0)throw new p("Verbose mode is not implemented yet.");if(null!=a)throw new p("steps mode in testLoop() is not implemented yet");for(var l=Br(o,r),c=(0,t.tensor1d)(vt(0,o)),h=0;h<l.length;++h){var f=l[h][0],d=l[h][1],g=Nt(c,f,d-f),m=Mr(n,g),y=e(m);if(0===h)for(var v=0;v<y.length;++v)u.push((0,t.scalar)(0));for(v=0;v<y.length;++v){var b=y[v];u[v]=(0,t.add)(u[v],(0,t.mul)(d-f,b))}}for(v=0;v<u.length;++v)u[v]=(0,t.div)(u[v],o);return u})},r.prototype.getDedupedMetricsNames=function(){for(var t=this.metricsNames,e=[],n=0;n<t.length;++n){var r=t[n],i=r;y(t,r)>1&&(i+="_"+y(t.slice(0,n),r)),e.push(i)}return e},r.prototype.makeTrainFunction=function(){var e=this;return function(n){var r=[],i=n.slice(0,e.inputs.length),a=n.slice(e.inputs.length,e.inputs.length+e.outputs.length),s=n.slice(e.inputs.length+e.outputs.length,e.inputs.length+2*e.outputs.length),o=[],u=e.collectedTrainableWeights.map(function(t){return t.read()});return[e.optimizer_.minimize(function(){for(var n=[],u=0;u<e.inputs.length;++u)n.push({key:e.inputs[u],value:i[u]});var l,c=new fr(n),h=mr(e.outputs,c,{training:!0});for(u=0;u<e.lossFunctions.length;++u){var p=(0,e.lossFunctions[u])(a[u],h[u]);null!=s[u]&&(p=Cr(p,s[u]));var f=(0,t.mean)(p);r.push(f),l=0===u?p:(0,t.add)(l,p)}for(u=0;u<e.metricsTensors.length;++u){var d=void 0;if(e.outputs.length>1&&u<e.outputs.length)d=r[u];else{var g=e.metricsTensors[u][0],m=e.metricsTensors[u][1];d=(0,t.mean)(g(a[m],h[m]))}(0,t.keep)(d),o.push(d)}return l=(0,t.mean)(l),e.calculateLosses().forEach(function(e){l=(0,t.add)(l,e)}),l},!0,u)].concat(o)}},r.prototype.makeTestFunction=function(){var e=this;this.testFunction=function(n){return(0,t.tidy)(function(){for(var r,i=[],a=n.slice(0,e.inputs.length),s=n.slice(e.inputs.length,e.inputs.length+e.outputs.length),o=[],u=0;u<e.inputs.length;++u)o.push({key:e.inputs[u],value:a[u]});var l=new fr(o),c=mr(e.outputs,l);for(u=0;u<e.lossFunctions.length;++u){var h=e.lossFunctions[u],p=(0,t.mean)(h(s[u],c[u]));r=0===u?p:(0,t.add)(r,p),i.push(r)}for(u=0;u<e.metricsTensors.length;++u){var f=e.metricsTensors[u][0],d=e.metricsTensors[u][1],g=(0,t.mean)(f(s[d],c[d]));i.push(g)}return i})}},r.prototype.fit=function(t,e,n){return void 0===n&&(n={}),a(this,void 0,void 0,function(){return s(this,function(r){return[2,jr(this,t,e,n)]})})},r.prototype.fitDataset=function(t,e){return a(this,void 0,void 0,function(){return s(this,function(n){return[2,Lr(this,t,e)]})})},r.prototype.trainOnBatch=function(e,n){return a(this,void 0,void 0,function(){var r,i,a,o,u,l,c,h,p;return s(this,function(s){switch(s.label){case 0:return[4,this.standardizeUserData(e,n)];case 1:r=s.sent(),i=r[0],a=r[1],o=this.makeTrainFunction(),u=o(i.concat(a)),l=[],c=0,h=u,s.label=2;case 2:return c<h.length?[4,h[c].data()]:[3,5];case 3:p=s.sent(),l.push(p[0]),s.label=4;case 4:return c++,[3,2];case 5:return(0,t.dispose)(u),[2,v(l)]}})})},r.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(r.prototype,"stopTraining",{get:function(){return this.stopTraining_},set:function(t){this.stopTraining_=t},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"optimizer",{get:function(){return this.optimizer_},set:function(t){this.optimizer_!==t&&(this.optimizer_=t,this.isOptimizerOwned=!1)},enumerable:!0,configurable:!0}),r.prototype.dispose=function(){var n=e.prototype.dispose.call(this);if(0===n.refCountAfterDispose&&null!=this.optimizer&&this.isOptimizerOwned){var r=(0,t.memory)().numTensors;this.optimizer_.dispose(),n.numDisposedVariables+=r-(0,t.memory)().numTensors}return n},r.prototype.getLossIdentifiers=function(){var t;if("string"==typeof this.loss)t=w(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 w(t)})}else{var r=Object.keys(this.loss);t={};for(var i=this.loss,a=0,s=r;a<s.length;a++){var o=s[a];if("string"!=typeof i[o])throw new Error("Serialization of non-string loss is not supported.");t[o]=w(i[o])}}return t},r.prototype.getMetricIdentifiers=function(){if("string"==typeof this.metrics||"function"==typeof this.metrics)return[w(Xn(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(function(t){return w(Xn(t))});var t={};for(var e in this.metrics)t[e]=w(Xn(this.metrics[e]));return t},r.prototype.getTrainingConfig=function(){return{loss:this.getLossIdentifiers(),metrics:this.getMetricIdentifiers(),optimizer_config:{class_name:this.optimizer.getClassName(),config:this.optimizer.getConfig()}}},r.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=pn(lr(t.optimizer_config));if("string"==typeof t.loss)e=z(t.loss);else if(Array.isArray(t.loss))e=t.loss.map(function(t){return z(t)});else if(null!=t.loss)for(var i in e={},t.loss)e[i]=z(t.loss[i]);if(Array.isArray(t.metrics))n=t.metrics.map(function(t){return z(t)});else if(null!=t.metrics)for(var i in n={},t.metrics)n[i]=z(t.metrics[i]);this.compile({loss:e,metrics:n,optimizer:r})},r.prototype.save=function(e,n){return a(this,void 0,void 0,function(){var r,i,a,o,u,l,c,p,f,d,g;return s(this,function(s){switch(s.label){case 0:if("string"==typeof e){if(0===(r=t.io.getSaveHandlers(e)).length)throw new h("Cannot find any save handlers for URL '"+e+"'");if(r.length>1)throw new h("Found more than one ("+r.length+") save handlers for URL '"+e+"'");e=r[0]}if(null==e.save)throw new h("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return[4,t.io.encodeWeights(this.getNamedWeights(n))];case 1:return i=s.sent(),!1,null,a=this.toJSON(null,!1),o={modelTopology:a,format:Xr,generatedBy:"TensorFlow.js tfjs-layers v"+hr,convertedBy:null},null!=n&&n.includeOptimizer&&null!=this.optimizer?(o.trainingConfig=this.getTrainingConfig(),u="optimizer",d=(f=t.io).encodeWeights,[4,this.optimizer.getWeights()]):[3,4];case 2:return[4,d.apply(f,[s.sent(),u])];case 3:l=s.sent(),c=l.data,p=l.specs,(g=i.specs).push.apply(g,p),i.data=t.io.concatenateArrayBuffers([i.data,c]),s.label=4;case 4:return null!=this.userDefinedMetadata&&(!0,tr(this.userDefinedMetadata,this.name,!0),o.userDefinedMetadata=this.userDefinedMetadata),o.weightData=i.data,o.weightSpecs=i.specs,[2,e.save(o)]}})})},r.prototype.setUserDefinedMetadata=function(t){tr(t,this.name),this.userDefinedMetadata=t},r.prototype.getUserDefinedMetadata=function(){return this.userDefinedMetadata},r.className="Model",r}(zr);function Qr(e,n){return a(this,void 0,void 0,function(){var r,i,a,o,u,l,c,h;return s(this,function(s){switch(s.label){case 0:return"modelTopology"in e||(e={modelTopology:e}),null!=(r=(e=e).modelTopology).model_config&&(r=r.model_config),i=lr(r),a=pn(i,n),null==e.weightsManifest?[3,2]:[4,t.io.loadWeights(e.weightsManifest,e.pathPrefix,a.weights.map(function(t){return t.originalName}))];case 1:for(o=s.sent(),u={},l=0,c=a.weights;l<c.length;l++)h=c[l],u[h.originalName]=o[h.originalName];a.loadWeights(u),(0,t.dispose)(o),s.label=2;case 2:return[2,a]}})})}function ti(e,n){return a(this,void 0,void 0,function(){var r;return s(this,function(i){if(null==n&&(n={}),"string"==typeof e){if(0===(r=t.io.getLoadHandlers(e,n.onProgress)).length)r.push(t.io.browserHTTPRequest(e,n));else if(r.length>1)throw new h("Found more than one ("+r.length+") load handlers for URL '"+e+"'");e=r[0]}return[2,ei(e,void 0,n)]})})}function ei(e,n,r){return a(this,void 0,void 0,function(){var i,a,o,u,l,c,p,f,d;return s(this,function(s){switch(s.label){case 0:if(null==r&&(r={}),null==e.load)throw new h("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");return[4,e.load()];case 1:if(i=s.sent(),null!=(a=i.modelTopology).model_config&&(a=a.model_config),o=null==r.strict||r.strict,u=null!=i.weightData&&null!=i.weightSpecs&&o,l=pn(lr(a),n,u),null!=(c=i.trainingConfig)&&l.loadTrainingConfig(c),null!=i.userDefinedMetadata&&l.setUserDefinedMetadata(i.userDefinedMetadata),null==i.weightData)return[3,4];if(null==i.weightSpecs)throw new h("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");return p=ni(i.weightData,i.weightSpecs),f=p.modelWeights,d=p.optimizerWeights,l.loadWeights(f,o),null!=l.optimizer&&d.length>0?[4,l.optimizer.setWeights(d)]:[3,3];case 2:s.sent(),s.label=3;case 3:(0,t.dispose)(f),(0,t.dispose)(d.map(function(t){return t.tensor})),s.label=4;case 4:return[2,l]}})})}function ni(e,n){var r=t.io.decodeWeights(e,n),i={},a=[];return n.forEach(function(t){"optimizer"===t.group?a.push({name:t.name,tensor:r[t.name]}):i[t.name]=r[t.name]}),{modelWeights:i,optimizerWeights:a}}exports.LayersModel=$r,t.serialization.registerClass($r);var ri=function(e){function r(t){var n=e.call(this,{inputs:[],outputs:[]})||this;if(t=t||{},n.trainable=!0,n.built=!1,n.name=null!=t.name?t.name:Ee("sequential_"),null!=t.layers)for(var r=0,i=t.layers;r<i.length;r++){var a=i[r];n.add(a)}return n}return n(r,e),r.prototype.checkShape=function(t){if(t.inboundNodes[0].outputTensors[0].shape.some(function(t){return t<0}))throw new h("Negative dimension size caused by adding layer "+t.name+" with input shape ["+t.inboundNodes[0].inputTensors[0].shape+"]")},r.prototype.add=function(t){var e,n=t instanceof r||t instanceof $r;if(n){if(1!==(e=t).outputs.length)throw new h("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(1!==e.inputs.length)throw new h("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 h("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");var i=Qe({batchShape:t.batchInputShape,dtype:t.dtype,name:t.name+"_input"});t.apply(i)}if(n)this.outputs=e.outputs,this.inputs=e.inputs;else{if(1!==t.inboundNodes.length)throw new h("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 h("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=Ye(this.outputs[0])}this.inboundNodes=[],new Je({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:g(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},r.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]}},r.prototype.call=function(t,e){return null==this.model&&this.build(),this.model.call(t,e)},r.prototype.build=function(t){if(Fe(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 $r({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},r.prototype.countParams=function(){return this.built||this.build(),e.prototype.countParams.call(this)},r.prototype.summary=function(t,n,r){void 0===r&&(r=console.log),this.built||this.build(),e.prototype.summary.call(this,t,n,r)},r.prototype.setWeights=function(t){null==this.model&&this.build(),this.model.setWeights(t)},r.prototype.evaluate=function(t,e,n){if(void 0===n&&(n={}),!this.built)throw new c("The model needs to be compiled before being used.");return this.model.evaluate(t,e,n)},r.prototype.evaluateDataset=function(t,e){return a(this,void 0,void 0,function(){return s(this,function(n){if(!this.built)throw new c("The model needs to be compiled before being used.");return[2,this.model.evaluateDataset(t,e)]})})},r.prototype.predict=function(t,e){return void 0===e&&(e={}),null==this.model&&this.build(),this.model.predict(t,e)},r.prototype.predictOnBatch=function(t){return null==this.model&&this.build(),this.model.predictOnBatch(t)},r.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(r.prototype,"optimizer",{get:function(){return null==this.model?void 0:this.model.optimizer},set:function(t){this.model.optimizer=t},enumerable:!0,configurable:!0}),r.prototype.fit=function(t,e,n){return void 0===n&&(n={}),a(this,void 0,void 0,function(){return s(this,function(r){if(!this.built)throw new c("The model needs to be compiled before being used.");return[2,this.model.fit(t,e,n)]})})},r.prototype.fitDataset=function(t,e){return a(this,void 0,void 0,function(){return s(this,function(n){if(!this.built)throw new c("The model needs to be compiled before being used.");return[2,this.model.fitDataset(t,e)]})})},r.prototype.trainOnBatch=function(t,e){return a(this,void 0,void 0,function(){return s(this,function(n){return[2,this.model.trainOnBatch(t,e)]})})},r.fromConfig=function(e,n,i,a){var s;void 0===i&&(i={}),void 0===a&&(a=!1);var o={};if(n instanceof Array){if(null==n[0].className||"Merge"===n[0].className)throw new h("Legacy serialization format not supported yet.");s=n}else t.util.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."}),s=n.layers,delete n.layers,o=n;var u=new e(o);if(!(u instanceof r))throw new p("Sequential.fromConfig called on non-Sequential input: "+u);for(var l=0,c=s;l<c.length;l++){var f=pn(c[l],void 0,a);a&&f.setFastWeightInitDuringBuild(!0),u.add(f)}return u},Object.defineProperty(r.prototype,"stopTraining",{get:function(){if(null==this.model)throw new h("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 h("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=t},enumerable:!0,configurable:!0}),r.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{name:this.name,layers:t}},r.className="Sequential",r}($r);function ii(t){return new $r(t)}function ai(t){return new ri(t)}function si(t,e){return null==e&&(e={}),ti(t,e)}function oi(t){return Qe(t)}function ui(t,e){cn.registerCallbackConstructor(t,e)}exports.Sequential=ri,t.serialization.registerClass(ri);var li=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.getConfig=function(){return{}},e}(t.serialization.Serializable),ci=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.apply=function(t,e){return void 0===e&&(e=1),_t(t,e)},e.className="elu",e}(li);t.serialization.registerClass(ci);var hi=function(e){function r(){return null!==e&&e.apply(this,arguments)||this}return n(r,e),r.prototype.apply=function(e){return(0,t.selu)(e)},r.className="selu",r}(li);t.serialization.registerClass(hi);var pi=function(e){function r(){return null!==e&&e.apply(this,arguments)||this}return n(r,e),r.prototype.apply=function(e){return(0,t.relu)(e)},r.className="relu",r}(li);t.serialization.registerClass(pi);var fi=function(e){function r(){return null!==e&&e.apply(this,arguments)||this}return n(r,e),r.prototype.apply=function(e){return(0,t.tidy)(function(){return(0,t.minimum)(6,(0,t.relu)(e))})},r.className="relu6",r}(li);t.serialization.registerClass(fi);var di=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.apply=function(t){return t},e.className="linear",e}(li);t.serialization.registerClass(di);var gi=function(e){function r(){return null!==e&&e.apply(this,arguments)||this}return n(r,e),r.prototype.apply=function(e){return(0,t.sigmoid)(e)},r.className="sigmoid",r}(li);t.serialization.registerClass(gi);var mi=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.apply=function(t){return Pt(t)},e.className="hardSigmoid",e}(li);t.serialization.registerClass(mi);var yi=function(e){function r(){return null!==e&&e.apply(this,arguments)||this}return n(r,e),r.prototype.apply=function(e){return(0,t.softplus)(e)},r.className="softplus",r}(li);t.serialization.registerClass(yi);var vi=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.apply=function(t){return Mt(t)},e.className="softsign",e}(li);t.serialization.registerClass(vi);var bi=function(e){function r(){return null!==e&&e.apply(this,arguments)||this}return n(r,e),r.prototype.apply=function(e){return(0,t.tanh)(e)},r.className="tanh",r}(li);t.serialization.registerClass(bi);var wi=function(e){function r(){return null!==e&&e.apply(this,arguments)||this}return n(r,e),r.prototype.apply=function(e,n){return void 0===n&&(n=-1),(0,t.softmax)(e,n)},r.className="softmax",r}(li);t.serialization.registerClass(wi);var zi=function(e){function r(){return null!==e&&e.apply(this,arguments)||this}return n(r,e),r.prototype.apply=function(e,n){return void 0===n&&(n=-1),(0,t.logSoftmax)(e,n)},r.className="logSoftmax",r}(li);function ki(t){return t.getClassName()}function Si(e,n){return void 0===n&&(n={}),C(e,t.serialization.SerializationMap.getMap().classNameMap,n,"activation")}function Ni(t){var e;return null==t?Si(e={className:"linear",config:{}}):"string"==typeof t?((e={}).className=t,e.config={},Si(e)):t instanceof li?t:Si(t)}function Ci(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)}t.serialization.registerClass(zi);var Ai=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e}(t.serialization.Serializable),Ii=function(e){function r(t){var n=e.call(this)||this;return Ci(t),n.l1=null==t||null==t.l1?.01:t.l1,n.l2=null==t||null==t.l2?.01:t.l2,n.hasL1=0!==n.l1,n.hasL2=0!==n.l2,n}return n(r,e),r.prototype.apply=function(e){var n=this;return(0,t.tidy)(function(){var r=(0,t.zeros)([1]);return n.hasL1&&(r=(0,t.add)(r,(0,t.sum)((0,t.mul)(n.l1,(0,t.abs)(e))))),n.hasL2&&(r=(0,t.add)(r,(0,t.sum)((0,t.mul)(n.l2,Dt(e))))),r.asScalar()})},r.prototype.getConfig=function(){return{l1:this.l1,l2:this.l2}},r.fromConfig=function(t,e){return new t({l1:e.l1,l2:e.l2})},r.className="L1L2",r}(Ai);function xi(t){return Ci(t),new Ii({l1:null!=t?t.l1:null,l2:0})}function Ti(t){return Ci(t),new Ii({l2:null!=t?t.l2:null,l1:0})}t.serialization.registerClass(Ii);var Li={l1l2:"L1L2"};function Ei(t){return S(t)}function Oi(e,n){return void 0===n&&(n={}),C(e,t.serialization.SerializationMap.getMap().classNameMap,n,"regularizer")}function Di(t){return null==t?null:"string"==typeof t?Oi({className:t in Li?Li[t]:t,config:{}}):t instanceof Ai?t:Oi(t)}var Ri=function(e){function r(t){var n=e.call(this,null==t?{}:t)||this;return n.supportsMasking=!0,null!=t&&(n.maxValue=t.maxValue),n}return n(r,e),r.prototype.call=function(e,n){e=Re(e);var r=(0,t.relu)(e);return null!=this.maxValue&&(r=(0,t.clipByValue)(r,0,this.maxValue)),r},r.prototype.computeOutputShape=function(t){return t},r.prototype.getConfig=function(){var t={maxValue:this.maxValue},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},r.className="ReLU",r}(Ze);t.serialization.registerClass(Ri);var Fi=function(e){function r(t){var n=e.call(this,null==t?{}:t)||this;return n.DEFAULT_ALPHA=.3,null==t&&(t={}),n.alpha=null==t.alpha?n.DEFAULT_ALPHA:t.alpha,n}return n(r,e),r.prototype.call=function(e,n){var r=Re(e);return(0,t.leakyRelu)(r,this.alpha)},r.prototype.computeOutputShape=function(t){return t},r.prototype.getConfig=function(){var t={alpha:this.alpha},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},r.className="LeakyReLU",r}(Ze);t.serialization.registerClass(Fi);var _i=function(e){function r(t){var n=e.call(this,null==t?{}:t)||this;if(n.DEFAULT_ALPHA_INITIALIZER="zeros",null==t&&(t={}),n.supportsMasking=!0,n.alphaInitializer=he(t.alphaInitializer||n.DEFAULT_ALPHA_INITIALIZER),n.alphaRegularizer=Di(t.alphaRegularizer),n.alphaConstraint=J(t.alphaConstraint),null==t.sharedAxes)n.sharedAxes=null;else if(Array.isArray(t.sharedAxes))n.sharedAxes=t.sharedAxes;else{if("number"!=typeof t.sharedAxes)throw new h("Expected sharedAxes to be a number or an array of numbers, but got "+t.sharedAxes);n.sharedAxes=[t.sharedAxes]}return n}return n(r,e),r.prototype.build=function(t){var e=(t=Fe(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 Ue({ndim:t.length,axes:i})],this.built=!0},r.prototype.call=function(e,n){return e=Re(e),(0,t.prelu)(e,this.alpha.read())},r.prototype.getConfig=function(){var t={alphaInitializer:ce(this.alphaInitializer),alphaRegularizer:Ei(this.alphaRegularizer),alphaConstraint:V(this.alphaConstraint),sharedAxes:this.sharedAxes},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},r.className="PReLU",r}(Ze);t.serialization.registerClass(_i);var Mi=function(e){function r(t){var n=e.call(this,null==t?{}:t)||this;if(n.DEFAULT_ALPHA=1,null==t&&(t={}),null!=t.alpha&&t.alpha!==n.DEFAULT_ALPHA)throw new p("Non-default alpha value ("+t.alpha+") is not supported by the ELU layer yet.");return n.alpha=null==t.alpha?n.DEFAULT_ALPHA:t.alpha,n}return n(r,e),r.prototype.call=function(e,n){var r=Re(e);return(0,t.elu)(r)},r.prototype.computeOutputShape=function(t){return t},r.prototype.getConfig=function(){var t={alpha:this.alpha},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},r.className="ELU",r}(Ze);t.serialization.registerClass(Mi);var Bi=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 n(e,t),e.prototype.call=function(t,e){var n=Re(t);return n.mul(bt(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}(Ze);t.serialization.registerClass(Bi);var Pi=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 wi).apply,n.axis=null==e.axis?n.DEFAULT_AXIS:e.axis,n}return n(e,t),e.prototype.call=function(t,e){var n=Re(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}(Ze);function ji(t,e,n){if("number"==typeof t)return g(t,e);if(t.length!==e)throw new h("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(!ft(i))throw new h("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 Wi(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 Ui(t,e,n,r){if(null==t)return null;if("valid"===r)t=t*e+yt([n-e,0]);else{if("same"!==r)throw new h("Unsupport padding mode: "+r+".");t*=e}return t}function Vi(e,n){return(0,t.tidy)(function(){return nt(n),"channelsFirst"===n?(0,t.transpose)(e,[0,2,3,1]):e})}function qi(e,n){return(0,t.tidy)(function(){return nt(n),"channelsFirst"===n?(0,t.transpose)(e,[0,2,3,4,1]):e})}function Ji(e,n,r,i,a,s,o){return void 0===i&&(i=1),void 0===a&&(a="valid"),void 0===o&&(o=1),(0,t.tidy)(function(){if(null==s&&(s=u()),nt(s),3!==e.shape.length)throw new h("The input of a conv1dWithBias operation should be 3, but is "+e.shape.length+" instead.");if(3!==n.shape.length)throw new h("The kernel for a conv1dWithBias operation should be 3, but is "+n.shape.length+" instead");if(null!=r&&1!==r.shape.length)throw new h("The bias for a conv1dWithBias operation should be 1, but is "+n.shape.length+" instead");if("channelsFirst"===s&&(e=(0,t.transpose)(e,[0,2,1])),"causal"===a)throw new p("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");var l=(0,t.conv1d)(e,n,i,"same"===a?"same":"valid","NWC",o);return null!=r&&(l=Ft(l,r)),l})}function Hi(e,n,r,i,a,s,o,l){return void 0===i&&(i=[1,1]),void 0===a&&(a="valid"),void 0===l&&(l=null),(0,t.tidy)(function(){if(null==s&&(s=u()),nt(s),3!==e.rank&&4!==e.rank)throw new h("conv2dWithBiasActivation expects input to be of rank 3 or 4, but received "+e.rank+".");if(3!==n.rank&&4!==n.rank)throw new h("conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received "+e.rank+".");var c=Vi(e,s);if("causal"===a)throw new p("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return c=t.fused.conv2d({x:c,filter:n,strides:i,pad:"same"===a?"same":"valid",dilations:o,dataFormat:"NHWC",bias:r,activation:l}),"channelsFirst"===s&&(c=(0,t.transpose)(c,[0,3,1,2])),c})}function Zi(e,n,r,i,a,s,o){return void 0===i&&(i=[1,1,1]),void 0===a&&(a="valid"),(0,t.tidy)(function(){if(null==s&&(s=u()),nt(s),4!==e.rank&&5!==e.rank)throw new h("conv3dWithBias expects input to be of rank 4 or 5, but received "+e.rank+".");if(4!==n.rank&&5!==n.rank)throw new h("conv3dWithBias expects kernel to be of rank 4 or 5, but received "+e.rank+".");var l=qi(e,s);if("causal"===a)throw new p("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return l=(0,t.conv3d)(l,n,i,"same"===a?"same":"valid","NDHWC",o),null!=r&&(l=Ft(l,r)),"channelsFirst"===s&&(l=(0,t.transpose)(l,[0,4,1,2,3])),l})}t.serialization.registerClass(Pi);var Ki=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,O(i.rank,"rank"),1!==i.rank&&2!==i.rank&&3!==i.rank)throw new p("Convolution layer for rank other than 1, 2, or 3 ("+i.rank+") is not implemented yet.");if(i.kernelSize=ji(r.kernelSize,n,"kernelSize"),i.strides=ji(null==r.strides?1:r.strides,n,"strides"),i.padding=null==r.padding?"valid":r.padding,rt(i.padding),i.dataFormat=null==r.dataFormat?"channelsLast":r.dataFormat,nt(i.dataFormat),i.activation=Ni(r.activation),i.useBias=null==r.useBias||r.useBias,i.biasInitializer=he(r.biasInitializer||i.DEFAULT_BIAS_INITIALIZER),i.biasConstraint=J(r.biasConstraint),i.biasRegularizer=Di(r.biasRegularizer),i.activityRegularizer=Di(r.activityRegularizer),i.dilationRate=ji(null==r.dilationRate?1:r.dilationRate,n,"dilationRate"),1===i.rank&&Array.isArray(i.dilationRate)&&1!==i.dilationRate.length)throw new h("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 h("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 h("dilationRate must be a number or array of three numbers for 3D convolution, but received "+JSON.stringify(i.dilationRate));return i}return n(e,t),e.verifyArgs=function(t){if(m("kernelSize"in t,"required key 'kernelSize' not in config"),"number"!=typeof t.kernelSize&&!E(t.kernelSize,"number",1,3))throw new h("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:ki(this.activation),useBias:this.useBias,biasInitializer:ce(this.biasInitializer),biasRegularizer:Ei(this.biasRegularizer),activityRegularizer:Ei(this.activityRegularizer),biasConstraint:V(this.biasConstraint)},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e}(Ze),Gi=function(e){function r(t,n){var i=e.call(this,t,n)||this;return i.kernel=null,r.verifyArgs(n),i.filters=n.filters,O(i.filters,"filters"),i.kernelInitializer=he(n.kernelInitializer||i.DEFAULT_KERNEL_INITIALIZER),i.kernelConstraint=J(n.kernelConstraint),i.kernelRegularizer=Di(n.kernelRegularizer),i}return n(r,e),r.prototype.build=function(t){var e;t=Fe(t);var n="channelsFirst"===this.dataFormat?1:t.length-1;if(null==t[n])throw new h("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},r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){var t;e=Re(e);var n=null==r.bias?null:r.bias.read(),i=F(r.activation.getClassName());if(null!=i&&2===r.rank)t=Hi(e,r.kernel.read(),n,r.strides,r.padding,r.dataFormat,r.dilationRate,i);else{if(1===r.rank)t=Ji(e,r.kernel.read(),n,r.strides[0],r.padding,r.dataFormat,r.dilationRate[0]);else if(2===r.rank)t=Hi(e,r.kernel.read(),n,r.strides,r.padding,r.dataFormat,r.dilationRate);else{if(3!==r.rank)throw new p("convolutions greater than 3D are not implemented yet.");t=Zi(e,r.kernel.read(),n,r.strides,r.padding,r.dataFormat,r.dilationRate)}null!=r.activation&&(t=r.activation.apply(t))}return t})},r.prototype.computeOutputShape=function(t){t=Fe(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=Wi(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},r.prototype.getConfig=function(){var t={filters:this.filters,kernelInitializer:ce(this.kernelInitializer),kernelRegularizer:Ei(this.kernelRegularizer),kernelConstraint:V(this.kernelConstraint)},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},r.verifyArgs=function(t){if(!("filters"in t)||"number"!=typeof t.filters||t.filters<1)throw new h("Convolution layer expected config.filters to be a 'number' > 0 but got "+JSON.stringify(t.filters))},r}(Ki),Yi=function(t){function e(n){var r=t.call(this,2,n)||this;return e.verifyArgs(n),r}return n(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&&!E(t.kernelSize,"number",1,2))throw new h("Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received "+JSON.stringify(t.kernelSize)+".")},e.className="Conv2D",e}(Gi);t.serialization.registerClass(Yi);var Xi=function(t){function e(n){var r=t.call(this,3,n)||this;return e.verifyArgs(n),r}return n(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 h("Conv3D expects config.kernelSize to be number or [number, number, number], but received "+JSON.stringify(t.kernelSize)+".")},e.className="Conv3D",e}(Gi);t.serialization.registerClass(Xi);var $i=function(e){function r(t){var n=e.call(this,t)||this;if(n.inputSpec=[new Ue({ndim:4})],"same"!==n.padding&&"valid"!==n.padding)throw new h("Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode "+n.padding);return n}return n(r,e),r.prototype.build=function(t){var e;if(4!==(t=Fe(t)).length)throw new h("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 h("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 Ue({ndim:4,axes:(e={},e[n]=r,e)})],this.built=!0},r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){var n=Re(e);if(4!==n.shape.length)throw new h("Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-"+n.shape.length);var i,a,s=n.shape,o=s[0];"channelsFirst"===r.dataFormat?(i=2,a=3):(i=1,a=2);var u=s[i],l=s[a],c=r.kernelSize[0],p=r.kernelSize[1],f=r.strides[0],d=r.strides[1],g=[o,Ui(u,f,c,r.padding),Ui(l,d,p,r.padding),r.filters];"channelsLast"!==r.dataFormat&&(n=(0,t.transpose)(n,[0,2,3,1]));var m=(0,t.conv2dTranspose)(n,r.kernel.read(),g,r.strides,r.padding);return"channelsLast"!==r.dataFormat&&(m=(0,t.transpose)(m,[0,3,1,2])),null!=r.bias&&(m=Ft(m,r.bias.read(),r.dataFormat)),null!=r.activation&&(m=r.activation.apply(m)),m})},r.prototype.computeOutputShape=function(t){var e,n,r,i=(t=Fe(t)).slice();"channelsFirst"===this.dataFormat?(e=1,n=2,r=3):(e=3,n=1,r=2);var a=this.kernelSize[0],s=this.kernelSize[1],o=this.strides[0],u=this.strides[1];return i[e]=this.filters,i[n]=Ui(i[n],o,a,this.padding),i[r]=Ui(i[r],u,s,this.padding),i},r.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this);return delete t.dilationRate,t},r.className="Conv2DTranspose",r}(Yi);t.serialization.registerClass($i);var Qi=function(e){function r(t,n){var r=e.call(this,t,n)||this;if(r.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",r.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",r.depthwiseKernel=null,r.pointwiseKernel=null,null==n.filters)throw new h("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=n.kernelInitializer||null!=n.kernelRegularizer||null!=n.kernelConstraint)throw new h("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 h("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=he(n.depthwiseInitializer||r.DEFAULT_DEPTHWISE_INITIALIZER),r.depthwiseRegularizer=Di(n.depthwiseRegularizer),r.depthwiseConstraint=J(n.depthwiseConstraint),r.pointwiseInitializer=he(n.depthwiseInitializer||r.DEFAULT_POINTWISE_INITIALIZER),r.pointwiseRegularizer=Di(n.pointwiseRegularizer),r.pointwiseConstraint=J(n.pointwiseConstraint),r}return n(r,e),r.prototype.build=function(t){var e;if((t=Fe(t)).length<this.rank+2)throw new h("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 h("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=[],s=0;s<this.rank;++s)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 Ue({ndim:this.rank+2,axes:(e={},e[n]=r,e)})],this.built=!0},r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){var n;if(e=Re(e),1===r.rank)throw new p("1D separable convolution is not implemented yet.");return 2===r.rank&&("channelsFirst"===r.dataFormat&&(e=(0,t.transpose)(e,[0,2,3,1])),n=(0,t.separableConv2d)(e,r.depthwiseKernel.read(),r.pointwiseKernel.read(),r.strides,r.padding,r.dilationRate,"NHWC")),r.useBias&&(n=Ft(n,r.bias.read(),r.dataFormat)),null!=r.activation&&(n=r.activation.apply(n)),"channelsFirst"===r.dataFormat&&(n=(0,t.transpose)(n,[0,3,1,2])),n})},r.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this);return delete t.rank,delete t.kernelInitializer,delete t.kernelRegularizer,delete t.kernelConstraint,t.depthwiseInitializer=ce(this.depthwiseInitializer),t.pointwiseInitializer=ce(this.pointwiseInitializer),t.depthwiseRegularizer=Ei(this.depthwiseRegularizer),t.pointwiseRegularizer=Ei(this.pointwiseRegularizer),t.depthwiseConstraint=V(this.depthwiseConstraint),t.pointwiseConstraint=V(this.pointwiseConstraint),t},r.className="SeparableConv",r}(Gi),ta=function(t){function e(e){return t.call(this,2,e)||this}return n(e,t),e.className="SeparableConv2D",e}(Qi);t.serialization.registerClass(ta);var ea=function(t){function e(n){var r=t.call(this,1,n)||this;return e.verifyArgs(n),r.inputSpec=[{ndim:3}],r}return n(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&&!E(t.kernelSize,"number",1,1))throw new h("Conv1D expects config.kernelSize to be number or number[] with length 1, but received "+JSON.stringify(t.kernelSize)+".")},e.className="Conv1D",e}(Gi);t.serialization.registerClass(ea);var na=function(e){function r(t){var n=e.call(this,t)||this;return"number"==typeof t.cropping?n.cropping=[[t.cropping,t.cropping],[t.cropping,t.cropping]]:"number"==typeof t.cropping[0]?n.cropping=[[t.cropping[0],t.cropping[0]],[t.cropping[1],t.cropping[1]]]:n.cropping=t.cropping,n.dataFormat=void 0===t.dataFormat?"channelsLast":t.dataFormat,n.inputSpec=[{ndim:4}],n}return n(r,e),r.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]]},r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){return e=Re(e),"channelsLast"===r.dataFormat?At(At(e,r.cropping[0][0],e.shape[1]-r.cropping[0][0]-r.cropping[0][1],2),r.cropping[1][0],e.shape[2]-r.cropping[1][1]-r.cropping[1][0],3):At(At(e,r.cropping[0][0],e.shape[2]-r.cropping[0][0]-r.cropping[0][1],3),r.cropping[1][0],e.shape[3]-r.cropping[1][1]-r.cropping[1][0],4)})},r.prototype.getConfig=function(){var t={cropping:this.cropping,dataFormat:this.dataFormat},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},r.className="Cropping2D",r}(Ze);t.serialization.registerClass(na);var ra=function(e){function r(t){var n=e.call(this,t)||this;return n.DEFAULT_SIZE=[2,2],n.inputSpec=[{ndim:4}],n.size=null==t.size?n.DEFAULT_SIZE:t.size,n.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,n}return n(r,e),r.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]]},r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){var n=Re(e),i=n.shape;if("channelsFirst"===r.dataFormat){n=(0,t.transpose)(n,[0,2,3,1]);var a=r.size[0]*i[2],s=r.size[1]*i[3],o=n.resizeNearestNeighbor([a,s]);return(0,t.transpose)(o,[0,3,1,2])}return a=r.size[0]*i[1],s=r.size[1]*i[2],n.resizeNearestNeighbor([a,s])})},r.prototype.getConfig=function(){var t={size:this.size,dataFormat:this.dataFormat},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},r.className="UpSampling2D",r}(Ze);function ia(e,n,r,i,a,s){return void 0===r&&(r=[1,1]),void 0===i&&(i="valid"),(0,t.tidy)(function(){null==a&&(a=u()),nt(a);var o=Vi(e,a);if(4!==e.rank)throw new h("Input for depthwiseConv2d is required to be 4-D, but is instead "+e.rank+"-D");if(4!==n.rank)throw new h("depthwiseKernel is required to be 4-D, but is instead "+n.rank+"-D");return o=(0,t.depthwiseConv2d)(o,n,r,"same"===i?"same":"valid","NHWC",s),"channelsFirst"===a&&(o=(0,t.transpose)(o,[0,3,1,2])),o})}t.serialization.registerClass(ra);var aa=function(e){function r(t){var n=e.call(this,2,t)||this;return n.depthwiseKernel=null,n.depthMultiplier=null==t.depthMultiplier?1:t.depthMultiplier,n.depthwiseInitializer=he(t.depthwiseInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.depthwiseConstraint=J(t.depthwiseConstraint),n.depthwiseRegularizer=Di(t.depthwiseRegularizer),n}return n(r,e),r.prototype.build=function(t){if((t=Fe(t)).length<4)throw new h("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 h("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},r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){var t=ia(e=Re(e),r.depthwiseKernel.read(),r.strides,r.padding,r.dataFormat,null);return r.useBias&&(t=Ft(t,r.bias.read(),r.dataFormat)),null!=r.activation&&(t=r.activation.apply(t)),t})},r.prototype.computeOutputShape=function(t){t=Fe(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=Wi(e,this.kernelSize[0],this.padding,this.strides[0]),a=Wi(n,this.kernelSize[1],this.padding,this.strides[1]);return"channelsFirst"===this.dataFormat?[t[0],r,i,a]:[t[0],i,a,r]},r.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this);return t.depthMultiplier=this.depthMultiplier,t.depthwiseInitializer=ce(this.depthwiseInitializer),t.depthwiseRegularizer=Ei(this.depthwiseRegularizer),t.depthwiseConstraint=V(this.depthwiseRegularizer),t},r.className="DepthwiseConv2D",r}(Ki);t.serialization.registerClass(aa);var sa=function(e){function r(t){var n=e.call(this,t)||this;return n.rate=Math.max(Math.min(t.rate,1),0),n.noiseShape=t.noiseShape,n.seed=t.seed,n.supportsMasking=!0,n}return n(r,e),r.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},r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){r.invokeCallHook(e,n);var t=Re(e);if(0<r.rate&&r.rate<1){var i=null!=n.training&&n.training,a=r.getNoiseShape(t);return jt(function(){return Bt(t,r.rate,a,r.seed)},function(){return t},i)}return e})},r.prototype.getConfig=function(){var t={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},r.prototype.dispose=function(){return e.prototype.dispose.call(this)},r.className="Dropout",r}(Ze);t.serialization.registerClass(sa);var oa=function(t){function e(e){var n=t.call(this,e)||this;return n.inputSpec=[{ndim:3}],n}return n(e,t),e.prototype.getNoiseShape=function(t){var e=t.shape;return[e[0],1,e[2]]},e.className="SpatialDropout1D",e}(sa);t.serialization.registerClass(oa);var ua=function(e){function r(t){var n=e.call(this,t)||this;if(n.activation=null,n.useBias=!0,n.kernel=null,n.bias=null,n.DEFAULT_KERNEL_INITIALIZER="glorotNormal",n.DEFAULT_BIAS_INITIALIZER="zeros",null==t.batchInputShape&&null==t.inputShape&&null!=t.inputDim){var r=null;null!=t.batchSize&&(r=t.batchSize),n.batchInputShape=[r,t.inputDim]}return n.units=t.units,O(n.units,"units"),n.activation=Ni(t.activation),null!=t.useBias&&(n.useBias=t.useBias),n.kernelInitializer=he(t.kernelInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.biasInitializer=he(t.biasInitializer||n.DEFAULT_BIAS_INITIALIZER),n.kernelConstraint=J(t.kernelConstraint),n.biasConstraint=J(t.biasConstraint),n.kernelRegularizer=Di(t.kernelRegularizer),n.biasRegularizer=Di(t.biasRegularizer),n.activityRegularizer=Di(t.activityRegularizer),n.supportsMasking=!0,n.inputSpec=[{minNDim:2}],n}return n(r,e),r.prototype.build=function(t){var e,n=(t=Fe(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},r.prototype.computeOutputShape=function(t){var e=(t=Fe(t)).slice();return e[e.length-1]=this.units,e},r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){r.invokeCallHook(e,n);var t,i=Re(e),a=F(r.activation.getClassName());return null!=a?t=Et(i,r.kernel.read(),a,r.bias?r.bias.read():null):(t=Et(i,r.kernel.read()),null!=r.bias&&(t=Ft(t,r.bias.read())),null!=r.activation&&(t=r.activation.apply(t))),t})},r.prototype.getConfig=function(){var t={units:this.units,activation:ki(this.activation),useBias:this.useBias,kernelInitializer:ce(this.kernelInitializer),biasInitializer:ce(this.biasInitializer),kernelRegularizer:Ei(this.kernelRegularizer),biasRegularizer:Ei(this.biasRegularizer),activityRegularizer:Ei(this.activityRegularizer),kernelConstraint:V(this.kernelConstraint),biasConstraint:V(this.biasConstraint)},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},r.className="Dense",r}(Ze);t.serialization.registerClass(ua);var la=function(e){function r(t){var n=this;return t=t||{},(n=e.call(this,t)||this).inputSpec=[{minNDim:3}],n.dataFormat=t.dataFormat,n}return n(r,e),r.prototype.computeOutputShape=function(t){for(var e=0,n=(t=Fe(t)).slice(1);e<n.length;e++)if(null==n[e])throw new h('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],dt(t,1)]},r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){r.invokeCallHook(e,n);var t=Re(e);if("channelsFirst"===r.dataFormat&&t.rank>1){for(var i=[0],a=2;a<t.rank;++a)i.push(a);i.push(1),t=t.transpose(i)}return St(t)})},r.prototype.getConfig=function(){var t={};null!=this.dataFormat&&(t.dataFormat=this.dataFormat);var n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},r.className="Flatten",r}(Ze);t.serialization.registerClass(la);var ca=function(e){function r(t){var n=e.call(this,t)||this;return n.supportsMasking=!0,n.activation=Ni(t.activation),n}return n(r,e),r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){r.invokeCallHook(e,n);var t=Re(e);return r.activation.apply(t)})},r.prototype.getConfig=function(){var t={activation:ki(this.activation)},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},r.className="Activation",r}(Ze);t.serialization.registerClass(ca);var ha=function(e){function r(t){var n=e.call(this,t)||this;return n.n=t.n,n.inputSpec=[{ndim:2}],n}return n(r,e),r.prototype.computeOutputShape=function(t){return[t[0],this.n,t[1]]},r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){return zt(e=Re(e),r.n)})},r.prototype.getConfig=function(){var t={n:this.n},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},r.className="RepeatVector",r}(Ze);t.serialization.registerClass(ha);var pa=function(e){function r(t){var n=e.call(this,t)||this;n.targetShape=t.targetShape;for(var r=0;r<n.targetShape.length;++r)n.isUnknown(n.targetShape[r])&&(n.targetShape[r]=null);return n}return n(r,e),r.prototype.isUnknown=function(t){return t<0||null==t},r.prototype.fixUnknownDimension=function(t,e){for(var n="Total size of new array must be unchanged.",r=e.slice(),i=1,a=null,s=0;s<r.length;++s){var o=r[s];if(this.isUnknown(o)){if(null!==a)throw new h("Can only specifiy one unknown dimension.");a=s}else i*=o}var u=dt(t);if(null!==a){if(0===i||u%i!=0)throw new h(n);r[a]=u/i}else if(u!==i)throw new h(n);return r},r.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))},r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){r.invokeCallHook(e,n);var t=Re(e),i=t.shape,a=i.slice(0,1).concat(r.fixUnknownDimension(i.slice(1),r.targetShape));return t.reshape(a)})},r.prototype.getConfig=function(){var t={targetShape:this.targetShape},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},r.className="Reshape",r}(Ze);t.serialization.registerClass(pa);var fa=function(e){function r(n){var r=e.call(this,n)||this;if(null==n.dims)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(n.dims))throw new Error("Permute constructor requires `dims` to be an Array, but received "+n.dims+" instead.");var i=vt(1,n.dims.length+1);if(!t.util.arraysEqual(n.dims.slice().sort(),i))throw new Error("Invalid permutation `dims`: "+JSON.stringify(n.dims)+" `dims` must contain consecutive integers starting from 1.");return r.dims=n.dims,r.dimsIncludingBatch=[0].concat(r.dims),r.inputSpec=[new Ue({ndim:r.dims.length+1})],r}return n(r,e),r.prototype.computeOutputShape=function(t){var e=(t=Fe(t)).slice();return this.dims.forEach(function(n,r){e[r+1]=t[n]}),e},r.prototype.call=function(e,n){return(0,t.transpose)(Re(e),this.dimsIncludingBatch)},r.prototype.getConfig=function(){var t={dims:this.dims},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},r.className="Permute",r}(Ze);t.serialization.registerClass(fa);var da=function(e){function r(t){var n=e.call(this,null==t?{}:t)||this;return n.supportsMasking=!0,n.maskValue=null!=t?null==t.maskValue?0:t.maskValue:0,n}return n(r,e),r.prototype.computeOutputShape=function(t){return t},r.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this),n={maskValue:this.maskValue};return Object.assign(n,t),n},r.prototype.computeMask=function(e,n){var r=Re(e);return(0,t.any)((0,t.notEqual)(r,this.maskValue),-1)},r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){r.invokeCallHook(e,n);var i=Re(e),a=(0,t.any)((0,t.notEqual)(i,r.maskValue),-1,!0);return i.mul(a.asType(i.dtype))})},r.className="Masking",r}(Ze);t.serialization.registerClass(da);var ga=function(e){function r(t){var n=e.call(this,t)||this;if(n.embeddings=null,n.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",null==t.batchInputShape&&null==t.inputShape){var r=null;null!=t.batchSize&&(r=t.batchSize),null==t.inputLength?n.batchInputShape=[r,null]:n.batchInputShape=[r].concat(b(t.inputLength))}return n.inputDim=t.inputDim,O(n.inputDim,"inputDim"),n.outputDim=t.outputDim,O(n.outputDim,"outputDim"),n.embeddingsInitializer=he(t.embeddingsInitializer||n.DEFAULT_EMBEDDINGS_INITIALIZER),n.embeddingsRegularizer=Di(t.embeddingsRegularizer),n.activityRegularizer=Di(t.activityRegularizer),n.embeddingsConstraint=J(t.embeddingsConstraint),n.maskZero=t.maskZero,n.supportsMasking=t.maskZero,n.inputLength=t.inputLength,n}return n(r,e),r.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},r.prototype.warnOnIncompatibleInputShape=function(t){},r.prototype.computeMask=function(e,n){var r=this;return(0,t.tidy)(function(){return r.maskZero?(e=Re(e),(0,t.notEqual)(e,(0,t.zerosLike)(e))):null})},r.prototype.computeOutputShape=function(t){if(t=Fe(t),null==this.inputLength)return t.concat([this.outputDim]);var e=b(this.inputLength);if(e.length!==t.length-1)throw new h('"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 h('"inputLength" is '+this.inputLength+", but received input shape has shape "+t);null==i&&(e[n]=a),n++}return[t[0]].concat(e,[this.outputDim])},r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){r.invokeCallHook(e,n);var t=Re(e);return"int32"!==t.dtype&&(t=bt(t,"int32")),Ot(r.embeddings.read(),t.as1D()).reshape(Fe(r.computeOutputShape(t.shape)))})},r.prototype.getConfig=function(){var t={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:ce(this.embeddingsInitializer),embeddingsRegularizer:Ei(this.embeddingsRegularizer),activityRegularizer:Ei(this.activityRegularizer),embeddingsConstraint:V(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},r.className="Embedding",r}(Ze);t.serialization.registerClass(ga);var ma=function(e){function r(t){var n=e.call(this,t||{})||this;return n.supportsMasking=!0,n}return n(r,e),r.prototype.mergeFunction=function(t){throw new p},r.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 h("Operands could not be broadcast together with shapes "+JSON.stringify(t)+" "+JSON.stringify(e));n.push(i)}}return n},r.prototype.build=function(t){if(Array.isArray(t)&&!Array.isArray(t[0])&&(t=[Fe(t)]),(t=t).length<2)throw new h("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!=(s=r[n])&&null!==s[0]&&e.push(s[0]);if((e=x(e)).length>1)throw new h("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 s=null==t[a]?null:t[a].slice(1);i=this.computeElementwiseOpOutputShape(i,s)}var o=t.map(function(t){return t.length});-1===t.indexOf(null)&&1===x(o).length?this.reshapeRequired=!1:this.reshapeRequired=!0},r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){if(e=e,r.reshapeRequired){var n=[],i=e.map(function(t){return t.rank});if(-1===i.indexOf(null)){for(var a=yt(i),s=0,o=e;s<o.length;s++){for(var u=(f=o[s]).rank,l=0;l<a-u;++l)f=wt(f,1);n.push(f)}return r.mergeFunction(n)}for(var c=!1,h=0,p=e;h<p.length;h++){var f;if(null==(u=(f=p[h]).rank)){var d=f.shape,g=d[0],m=d.slice(1).concat([g]),y=f.reshape([g].concat(dt(d.slice(1))));y=(y=(0,t.transpose)(y,[1,0])).reshape(m),n.push(y),c=!0}else if(u>1){var v=vt(1,u).concat([0]);n.push((0,t.transpose)(f,v)),c=!0}else n.push(f)}var b=r.mergeFunction(n),w=b.rank;if(c)if(null==w){var z=b.shape;m=[g=z[z.length-1]].concat(z.slice(0,z.length-1)),b=(0,t.transpose)(b.reshape([-1,g]),[1,0]).reshape(m)}else w>1&&(v=[w-1].concat(vt(0,w-1)),b=(0,t.transpose)(b,v));return b}return r.mergeFunction(e)})},r.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,s=t;a<s.length;a++)null!=(r=s[a])&&null!==r[0]&&i.push(r[0]);return 1===(i=x(i)).length?i.concat(e):[null].concat(e)},r.prototype.computeMask=function(e,n){return(0,t.tidy)(function(){if(null==n)return null;if(!Array.isArray(n))throw new h("`mask` should be an Array");if(!Array.isArray(e))throw new h("`inputs` should be an Array");if(n.length!==e.length)throw new h("The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths ("+e.length+" vs "+n.length+")");if(n.every(function(t){return null==t}))return null;for(var r=(n=n.map(function(e){return null==e?e:(0,t.expandDims)(e,0)}))[0],i=1;i<n.length-1;++i)r=(0,t.logicalAnd)(r,n[i]);return r})},r}(Ze),ya=function(e){function r(t){return e.call(this,t)||this}return n(r,e),r.prototype.mergeFunction=function(e){return(0,t.tidy)(function(){for(var n=e[0].clone(),r=1;r<e.length;++r)n=(0,t.add)(n,e[r]);return n})},r.className="Add",r}(ma);t.serialization.registerClass(ya);var va=function(e){function r(t){return e.call(this,t)||this}return n(r,e),r.prototype.mergeFunction=function(e){return(0,t.tidy)(function(){for(var n=e[0].clone(),r=1;r<e.length;++r)n=(0,t.mul)(n,e[r]);return n})},r.className="Multiply",r}(ma);t.serialization.registerClass(va);var ba=function(e){function r(t){return e.call(this,t)||this}return n(r,e),r.prototype.mergeFunction=function(e){return(0,t.tidy)(function(){for(var n=e[0].clone(),r=1;r<e.length;++r)n=(0,t.add)(n,e[r]);return(0,t.mul)(1/e.length,n)})},r.className="Average",r}(ma);t.serialization.registerClass(ba);var wa=function(e){function r(t){return e.call(this,t)||this}return n(r,e),r.prototype.mergeFunction=function(e){return(0,t.tidy)(function(){for(var n=e[0],r=1;r<e.length;++r)n=(0,t.maximum)(n,e[r]);return n})},r.className="Maximum",r}(ma);t.serialization.registerClass(wa);var za=function(e){function r(t){return e.call(this,t)||this}return n(r,e),r.prototype.mergeFunction=function(e){return(0,t.tidy)(function(){for(var n=e[0],r=1;r<e.length;++r)n=(0,t.minimum)(n,e[r]);return n})},r.className="Minimum",r}(ma);t.serialization.registerClass(za);var ka=function(e){function r(t){var n=e.call(this,t)||this;return n.DEFAULT_AXIS=-1,null==t&&(t={}),n.axis=null==t.axis?n.DEFAULT_AXIS:t.axis,n.supportsMasking=!0,n.reshapeRequired=!1,n}return n(r,e),r.prototype.build=function(e){if(!Array.isArray(e)||!Array.isArray(e[0])||1===e.length)throw new h("A `Concatenate` layer should be called on a list of at least 2 inputs");for(var n=!0,r=0,i=e=e;r<i.length;r++)if(null!=(p=i[r])){n=!1;break}if(!n){for(var a=[],s=0;s<e.length;++s){var o=e[s].slice();o.splice(this.axis,1);for(var u=!1,l=0,c=a;l<c.length;l++){var p=c[l];if(t.util.arraysEqual(p,o)){u=!0;break}}u||a.push(o)}if(a.length>1)throw new h("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}},r.prototype.mergeFunction=function(e){var n=this;return(0,t.tidy)(function(){return It(e,n.axis)})},r.prototype.computeOutputShape=function(t){if(!Array.isArray(t)||!Array.isArray(t[0]))throw new h("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 s=a[i];if(null==n[r]||null==s[r]){n[r]=null;break}n[r]+=s[r]}return n},r.prototype.computeMask=function(e,n){var r=this;if(null==n)return null;if(!Array.isArray(n))throw new h("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new h("`inputs` should be an array for Concatenate");if(n.length!==e.length)throw new h("Mismatch in the length of mask ("+n.length+") and the legnth of inputs ("+e.length+")");return(0,t.tidy)(function(){var i=!0;if(n.forEach(function(t){null==t||(i=!1)}),i)return null;for(var a=[],s=0;s<e.length;++s)null==n[s]?a.push((0,t.onesLike)(e[s]).asType("bool")):n[s].rank<e[s].rank?a.push((0,t.expandDims)(n[s],-1)):a.push(n[s]);var o=(0,t.concat)(a,r.axis);return(0,t.all)(o,-1,!1)})},r.prototype.getConfig=function(){var t={axis:this.axis},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},r.className="Concatenate",r}(ma);function Sa(t,e){for(;t<0;)t+=e;return t}function Na(e,n,r){if(e.shape.length>3||n.shape.length>3)throw new p("batchDot is not implemented for tensors of 4D or higher rank yet");if(t.util.assert(e.shape.length>=2,function(){return"batchDot requires the rank of x to be >= 2, but got "+e.shape.length}),t.util.assert(e.shape.length>=2,function(){return"batchDot requires the rank of y to be >= 2, but got "+n.shape.length}),"number"==typeof r&&(r=[r,r]),"complex64"===e.dtype||"complex64"===n.dtype)throw new p("batchDot is not implemented for complex64-type Tensors yet.");var i=e.shape.length,a=n.shape.length;null==r&&(r=[i-1,a-2]);var s=r;return(0,t.tidy)(function(){var t,r;if(i>a){t=i-a;for(var o=[],u=0;u<t;++u)o.push(1);n=n.reshape(n.shape.concat(o))}else if(a>i){for(t=a-i,o=[],u=0;u<t;++u)o.push(1);e=e.reshape(e.shape.concat(o))}else t=0;if(2===e.shape.length&&2===n.shape.length)r=s[0]===s[1]?e.mulStrict(n).sum(s[0]):e.transpose([1,0]).mulStrict(n).sum(s[1]);else{var l=s[0]!==e.shape.length-1,c=s[1]===n.shape.length-1;r=e.matMul(n,l,c)}if(t>0){var h,p=[];for(u=h=i>a?i+a-3:i-1;u<h+t;++u)p.push(u);r=r.squeeze(p)}return 1===r.shape.length&&(r=r.expandDims(1)),r})}t.serialization.registerClass(ka);var Ca=function(e){function r(t){var n=e.call(this,t)||this;return n.axes=t.axes,n.normalize=null!=t.normalize&&t.normalize,n.supportsMasking=!0,n.reshapeRequired=!1,n}return n(r,e),r.prototype.build=function(e){t.util.assert(Array.isArray(e)&&2===e.length&&Array.isArray(e[0])&&Array.isArray(e[1]),function(){return"A `Dot` layer should be called on a list of exactly 2 inputs."});var n=e[0],r=e[1];if(n.length>3||r.length>3)throw new p("Dot layer does not support tensors of 4D or higher rank yet.");var i=this.interpretAxes(n,r);if(n[i[0]]!==r[i[1]])throw new h("Dimension incompatibility: "+n[i[0]]+" !== "+r[i[1]])},r.prototype.mergeFunction=function(t){if(2!==t.length)throw new h("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 Sa(e,t[n].shape.length)}):[Sa(this.axes,n.shape.length),Sa(this.axes,r.shape.length)],this.normalize&&(n=fn(n,e[0]),r=fn(r,e[1])),Na(n,r,e)},r.prototype.interpretAxes=function(t,e){return Array.isArray(this.axes)?this.axes:[Sa(this.axes,t.length),Sa(this.axes,e.length)]},r.prototype.computeOutputShape=function(e){t.util.assert(Array.isArray(e)&&2===e.length&&Array.isArray(e[0])&&Array.isArray(e[1]),function(){return"A `Dot` layer should be called on a list of exactly 2 inputs."});var n=e[0].slice(),r=e[1].slice();if(n.length>3||r.length>3)throw new p("Dot layer does not support tensors of 4D or higher rank yet.");var i=this.interpretAxes(n,r);n.splice(i[0],1),r.splice(i[1],1),r.splice(0,1);var a=n.concat(r);return 1===a.length&&a.push(1),a},r.prototype.computeMask=function(t,e){return null},r.prototype.getConfig=function(){var t={axes:this.axes,normalize:this.normalize},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},r.className="Dot",r}(ma);t.serialization.registerClass(Ca);var Aa=function(e){function r(t){var n=e.call(this,t)||this;return n.supportsMasking=!0,n.stddev=t.stddev,n}return n(r,e),r.prototype.computeOutputShape=function(t){return t},r.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this),n={stddev:this.stddev};return Object.assign(n,t),n},r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){r.invokeCallHook(e,n);var t=Re(e);return jt(function(){return Lt(t.shape,0,r.stddev).add(t)},function(){return t},n.training||!1)})},r.className="GaussianNoise",r}(Ze);t.serialization.registerClass(Aa);var Ia=function(e){function r(t){var n=e.call(this,t)||this;return n.supportsMasking=!0,n.rate=t.rate,n}return n(r,e),r.prototype.computeOutputShape=function(t){return t},r.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this),n={rate:this.rate};return Object.assign(n,t),n},r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){r.invokeCallHook(e,n);var t=Re(e);return r.rate>0&&r.rate<1?jt(function(){var e=Math.sqrt(r.rate/(1-r.rate));return t.mul(Lt(t.shape,1,e))},function(){return t},n.training||!1):t})},r.className="GaussianDropout",r}(Ze);t.serialization.registerClass(Ia);var xa=function(e){function r(t){var n=e.call(this,t)||this;return n.supportsMasking=!0,n.rate=t.rate,n.noiseShape=t.noiseShape,n}return n(r,e),r.prototype._getNoiseShape=function(t){return this.noiseShape||Re(t).shape},r.prototype.computeOutputShape=function(t){return t},r.prototype.getConfig=function(){var t=e.prototype.getConfig.call(this),n={rate:this.rate};return Object.assign(n,t),n},r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){if(r.rate<1&&r.rate>0){var i=r._getNoiseShape(e);return jt(function(){var n=Re(e),a=-1.7580993408473766,s=(0,t.greaterEqual)((0,t.randomUniform)(i),r.rate);s=bt(s,"float32");var o=Math.pow((1-r.rate)*(1+r.rate*Math.pow(a,2)),-.5),u=-o*a*r.rate;return n.mul(s).add(s.add(-1).mul(a)).mul(o).add(u)},function(){return Re(e)},n.training||!1)}return e})},r.className="AlphaDropout",r}(Ze);function Ta(e,n,r,i,a,s){var o;if(void 0===s&&(s=.001),2===e.rank)o=(0,t.batchNorm2d)(e,n,r,i,a,s);else if(3===e.rank)o=(0,t.batchNorm3d)(e,n,r,i,a,s);else{if(4!==e.rank)throw new p("batchNormalization is not implemented for array of rank "+e.rank+" yet");o=(0,t.batchNorm4d)(e,n,r,i,a,s)}return o}function La(e,n,r,i,a){return void 0===a&&(a=.001),(0,t.tidy)(function(){var s=(0,t.moments)(e,i),o=s.mean,u=s.variance;return[Ta(e,o,u,r,n,a),o,u]})}function Ea(e,n,r,i,a){return void 0===a&&(a=.001),(0,t.tidy)(function(){for(var s=(0,t.moments)(e,i),o=s.mean,u=s.variance,l=[],c=0,h=vt(0,e.rank);c<h.length;c++){var p=h[c];-1!==i.indexOf(p)?l.push(1):l.push(e.shape[p])}var f=o.reshape(l),d=u.reshape(l),g=null==n?null:n.reshape(l),m=null==r?null:r.reshape(l);return[Ta(e,f,d,m,g,a),o,u]})}function Oa(e,n,r,i,a){return void 0===a&&(a=.001),t.util.arraysEqual(i.slice().sort(),vt(0,e.rank-1))?La(e,n,r,i,a):Ea(e,n,r,i,a)}t.serialization.registerClass(xa);var Da=function(e){function r(t){var n=this;return null==t&&(t={}),(n=e.call(this,t)||this).supportsMasking=!0,n.axis=null==t.axis?-1:t.axis,n.momentum=null==t.momentum?.99:t.momentum,n.epsilon=null==t.epsilon?.001:t.epsilon,n.center=null==t.center||t.center,n.scale=null==t.scale||t.scale,n.betaInitializer=he(t.betaInitializer||"zeros"),n.gammaInitializer=he(t.gammaInitializer||"ones"),n.movingMeanInitializer=he(t.movingMeanInitializer||"zeros"),n.movingVarianceInitializer=he(t.movingVarianceInitializer||"ones"),n.betaConstraint=J(t.betaConstraint),n.gammaConstraint=J(t.gammaConstraint),n.betaRegularizer=Di(t.betaRegularizer),n.gammaRegularizer=Di(t.gammaRegularizer),n}return n(r,e),r.prototype.build=function(t){var e;t=Fe(t);var n=this.axis>=0?this.axis:this.axis+t.length,r=t[n];if(null==r)throw new h("Axis "+n+" of input tensor should have a defined dimension but the layer received an input with shape "+JSON.stringify(t)+".");this.inputSpec=[new Ue({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},r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){var i=null!=n.training&&n.training,a=Re(e),s=a.shape,o=s.length,u=vt(0,o),l=r.axis>=0?r.axis:r.axis+o;u.splice(l,1);var c=g(1,o);c[l]=s[l];var h=u.slice();h.sort();var p=!t.util.arraysEqual(h,vt(0,o).slice(0,o-1));if(!i)return function(){if(p){var t=r.movingMean.read().reshape(c),e=r.movingVariance.read().reshape(c),n=r.center?r.beta.read().reshape(c):null,i=r.scale?r.gamma.read().reshape(c):null;return Ta(a,t,e,n,i,r.epsilon)}return Ta(a,r.movingMean.read(),r.movingVariance.read(),null==r.beta?null:r.beta.read(),null==r.gamma?null:r.gamma.read(),r.epsilon)}();var f=Oa(a,r.gamma.read(),r.beta.read(),u,r.epsilon),d=f[0],m=f[1],y=f[2],v=function(e,n,r){(0,t.tidy)(function(){var t=1-r,i=e.read(),a=i.sub(n).mul(t);e.write(i.sub(a))})};return v(r.movingMean,m,r.momentum),v(r.movingVariance,y,r.momentum),d})},r.prototype.getConfig=function(){var t={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:ce(this.betaInitializer),gammaInitializer:ce(this.gammaInitializer),movingMeanInitializer:ce(this.movingMeanInitializer),movingVarianceInitializer:ce(this.movingVarianceInitializer),betaRegularizer:Ei(this.betaRegularizer),gammaRegularizer:Ei(this.gammaRegularizer),betaConstraint:V(this.betaConstraint),gammaConstraint:V(this.gammaConstraint)},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},r.className="BatchNormalization",r}(Ze);t.serialization.registerClass(Da);var Ra=function(e){function r(t){var n=this;if(null==t&&(t={}),(n=e.call(this,t)||this).axis=null==t.axis?-1:t.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==t.epsilon?.001:t.epsilon,n.center=null==t.center||t.center,n.scale=null==t.scale||t.scale,n.betaInitializer=he(t.betaInitializer||"zeros"),n.gammaInitializer=he(t.gammaInitializer||"ones"),n.betaRegularizer=Di(t.betaRegularizer),n.gammaRegularizer=Di(t.gammaRegularizer),n.supportsMasking=!0,n}return n(r,e),r.prototype.build=function(t){var e=(t=Fe(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!==x(this.axis).length)throw new Error("Found duplicate axes in: "+this.axis);var s=this.axis.map(function(e){return t[e]});this.scale?this.gamma=this.addWeight("gamma",s,"float32",this.gammaInitializer,this.gammaRegularizer,!0):this.gamma=null,this.center?this.beta=this.addWeight("beta",s,"float32",this.betaInitializer,this.betaRegularizer,!0):this.beta=null,this.built=!0},r.prototype.call=function(e,n){var r=this,i=Re(e),a=i.shape,s=a.length;return(0,t.tidy)(function(){for(var e=(0,t.moments)(i,r.axis,!0),n=e.mean,o=e.variance,u=g(1,s),l=0,c=r.axis;l<c.length;l++){var h=c[l];u[h]=a[h]}for(var p=function(t){return null!=t&&t.shape.length!==s&&r.axis!==[s-1]?t.reshape(u):t},f=p(r.gamma.read()),d=p(r.beta.read()),m=[],y=[],v=0;v<s;++v)-1!==r.axis.indexOf(v)?(m.push(a[v]),y.push(1)):(m.push(1),y.push(a[v]));return n=n.tile(m),o=o.tile(m),f=f.tile(y),d=d.tile(y),Ta(i,n,o,d,f,r.epsilon)})},r.prototype.getConfig=function(){var t={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:ce(this.betaInitializer),gammaInitializer:ce(this.gammaInitializer),betaRegularizer:Ei(this.betaRegularizer),gammaRegularizer:Ei(this.gammaRegularizer)},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},r.className="LayerNormalization",r}(Ze);function Fa(e,n,r){return(0,t.tidy)(function(){if(4!==e.rank)throw new h("temporalPadding expects input tensor to be 4-D, but received a "+e.rank+"-D tensor.");if(null==n&&(n=[[1,1],[1,1]]),2!==n.length||2!==n[0].length||2!==n[1].length)throw new h("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(null==r&&(r=u()),"channelsLast"!==r&&"channelsFirst"!==r)throw new h("Unknown data format: "+r+". Supported data formats are 'channelsLast' and 'channelsFirst.");var i;return i="channelsFirst"===r?[[0,0],[0,0],n[0],n[1]]:[[0,0],n[0],n[1],[0,0]],(0,t.pad)(e,i)})}t.serialization.registerClass(Ra);var _a=function(e){function r(t){var n=this;if(null==t&&(t={}),(n=e.call(this,t)||this).dataFormat=null==t.dataFormat?u():t.dataFormat,null==t.padding)n.padding=[[1,1],[1,1]];else if("number"==typeof t.padding)n.padding=[[t.padding,t.padding],[t.padding,t.padding]];else{if(t.padding=t.padding,2!==t.padding.length)throw new h("ZeroPadding2D expects padding to be a length-2 array, but received a length-"+t.padding.length+" array.");var r=void 0,i=void 0;if("number"==typeof t.padding[0])r=[t.padding[0],t.padding[0]],i=[t.padding[1],t.padding[1]];else{if(t.padding=t.padding,2!==t.padding[0].length)throw new h("ZeroPadding2D expects height padding to be a length-2 array, but received a length-"+t.padding[0].length+" array.");if(r=t.padding[0],2!==t.padding[1].length)throw new h("ZeroPadding2D expects width padding to be a length-2 array, but received a length-"+t.padding[1].length+" array.");i=t.padding[1]}n.padding=[r,i]}return n.inputSpec=[new Ue({ndim:4})],n}return n(r,e),r.prototype.computeOutputShape=function(t){var e,n;return t=Fe(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]])},r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){return Fa(Re(e),r.padding,r.dataFormat)})},r.prototype.getConfig=function(){var t={padding:this.padding,dataFormat:this.dataFormat},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},r.className="ZeroPadding2D",r}(Ze);function Ma(e,n,r,i,a,s){return(0,t.tidy)(function(){var o;nt(a),it(s),rt(i),null==r&&(r=[1,1]),null==i&&(i="valid"),null==a&&(a=u()),null==s&&(s="max"),e=Vi(e,a);var l="same"===i?"same":"valid";return o="max"===s?(0,t.maxPool)(e,n,r,l):(0,t.avgPool)(e,n,r,l),"channelsFirst"===a&&(o=(0,t.transpose)(o,[0,3,1,2])),o})}function Ba(e,n,r,i,a,s){return(0,t.tidy)(function(){var o;nt(a),it(s),rt(i),null==r&&(r=[1,1,1]),null==i&&(i="valid"),null==a&&(a=u()),null==s&&(s="max"),e=qi(e,a);var l="same"===i?"same":"valid";return o="max"===s?(0,t.maxPool3d)(e,n,r,l):(0,t.avgPool3d)(e,n,r,l),"channelsFirst"===a&&(o=(0,t.transpose)(o,[0,4,1,2,3])),o})}t.serialization.registerClass(_a);var Pa=function(e){function r(t){var n=this;if(null==t.poolSize&&(t.poolSize=2),n=e.call(this,t)||this,"number"==typeof t.poolSize)n.poolSize=[t.poolSize];else{if(!Array.isArray(t.poolSize)||1!==t.poolSize.length||"number"!=typeof t.poolSize[0])throw new h("poolSize for 1D convolutional layer must be a number or an Array of a single number, but received "+JSON.stringify(t.poolSize));n.poolSize=t.poolSize}if(O(n.poolSize,"poolSize"),null==t.strides)n.strides=n.poolSize;else if("number"==typeof t.strides)n.strides=[t.strides];else{if(!Array.isArray(t.strides)||1!==t.strides.length||"number"!=typeof t.strides[0])throw new h("strides for 1D convolutional layer must be a number or an Array of a single number, but received "+JSON.stringify(t.strides));n.strides=t.strides}return O(n.strides,"strides"),n.padding=null==t.padding?"valid":t.padding,rt(n.padding),n.inputSpec=[new Ue({ndim:3})],n}return n(r,e),r.prototype.computeOutputShape=function(t){var e=Wi((t=Fe(t))[1],this.poolSize[0],this.padding,this.strides[0]);return[t[0],e,t[2]]},r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){r.invokeCallHook(e,n),e=wt(Re(e),2);var i=r.poolingFunction(Re(e),[r.poolSize[0],1],[r.strides[0],1],r.padding,"channelsLast");return(0,t.squeeze)(i,[2])})},r.prototype.getConfig=function(){var t={poolSize:this.poolSize,padding:this.padding,strides:this.strides},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},r}(Ze),ja=function(t){function e(e){return t.call(this,e)||this}return n(e,t),e.prototype.poolingFunction=function(t,e,n,r,i){return nt(i),rt(r),Ma(t,e,n,r,i,"max")},e.className="MaxPooling1D",e}(Pa);t.serialization.registerClass(ja);var Wa=function(t){function e(e){return t.call(this,e)||this}return n(e,t),e.prototype.poolingFunction=function(t,e,n,r,i){return nt(i),rt(r),Ma(t,e,n,r,i,"avg")},e.className="AveragePooling1D",e}(Pa);t.serialization.registerClass(Wa);var Ua=function(e){function r(t){var n=this;if(null==t.poolSize&&(t.poolSize=[2,2]),(n=e.call(this,t)||this).poolSize=Array.isArray(t.poolSize)?t.poolSize:[t.poolSize,t.poolSize],null==t.strides)n.strides=n.poolSize;else if(Array.isArray(t.strides)){if(2!==t.strides.length)throw new h("If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length "+t.strides.length+".");n.strides=t.strides}else n.strides=[t.strides,t.strides];return O(n.poolSize,"poolSize"),O(n.strides,"strides"),n.padding=null==t.padding?"valid":t.padding,n.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,nt(n.dataFormat),rt(n.padding),n.inputSpec=[new Ue({ndim:4})],n}return n(r,e),r.prototype.computeOutputShape=function(t){t=Fe(t);var e="channelsFirst"===this.dataFormat?t[2]:t[1],n="channelsFirst"===this.dataFormat?t[3]:t[2];return e=Wi(e,this.poolSize[0],this.padding,this.strides[0]),n=Wi(n,this.poolSize[1],this.padding,this.strides[1]),"channelsFirst"===this.dataFormat?[t[0],t[1],e,n]:[t[0],e,n,t[3]]},r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){return r.invokeCallHook(e,n),r.poolingFunction(Re(e),r.poolSize,r.strides,r.padding,r.dataFormat)})},r.prototype.getConfig=function(){var t={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},r}(Ze),Va=function(t){function e(e){return t.call(this,e)||this}return n(e,t),e.prototype.poolingFunction=function(t,e,n,r,i){return nt(i),rt(r),Ma(t,e,n,r,i,"max")},e.className="MaxPooling2D",e}(Ua);t.serialization.registerClass(Va);var qa=function(t){function e(e){return t.call(this,e)||this}return n(e,t),e.prototype.poolingFunction=function(t,e,n,r,i){return nt(i),rt(r),Ma(t,e,n,r,i,"avg")},e.className="AveragePooling2D",e}(Ua);t.serialization.registerClass(qa);var Ja=function(e){function r(t){var n=this;if(null==t.poolSize&&(t.poolSize=[2,2,2]),(n=e.call(this,t)||this).poolSize=Array.isArray(t.poolSize)?t.poolSize:[t.poolSize,t.poolSize,t.poolSize],null==t.strides)n.strides=n.poolSize;else if(Array.isArray(t.strides)){if(3!==t.strides.length)throw new h("If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length "+t.strides.length+".");n.strides=t.strides}else n.strides=[t.strides,t.strides,t.strides];return O(n.poolSize,"poolSize"),O(n.strides,"strides"),n.padding=null==t.padding?"valid":t.padding,n.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,nt(n.dataFormat),rt(n.padding),n.inputSpec=[new Ue({ndim:5})],n}return n(r,e),r.prototype.computeOutputShape=function(t){t=Fe(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=Wi(e,this.poolSize[0],this.padding,this.strides[0]),n=Wi(n,this.poolSize[1],this.padding,this.strides[1]),r=Wi(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]]},r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){return r.invokeCallHook(e,n),r.poolingFunction(Re(e),r.poolSize,r.strides,r.padding,r.dataFormat)})},r.prototype.getConfig=function(){var t={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},r}(Ze),Ha=function(t){function e(e){return t.call(this,e)||this}return n(e,t),e.prototype.poolingFunction=function(t,e,n,r,i){return nt(i),rt(r),Ba(t,e,n,r,i,"max")},e.className="MaxPooling3D",e}(Ja);t.serialization.registerClass(Ha);var Za=function(t){function e(e){return t.call(this,e)||this}return n(e,t),e.prototype.poolingFunction=function(t,e,n,r,i){return nt(i),rt(r),Ba(t,e,n,r,i,"avg")},e.className="AveragePooling3D",e}(Ja);t.serialization.registerClass(Za);var Ka=function(t){function e(e){var n=t.call(this,e)||this;return n.inputSpec=[new Ue({ndim:3})],n}return n(e,t),e.prototype.computeOutputShape=function(t){return[t[0],t[2]]},e.prototype.call=function(t,e){throw new p},e}(Ze),Ga=function(e){function r(t){return e.call(this,t||{})||this}return n(r,e),r.prototype.call=function(e,n){return(0,t.tidy)(function(){var n=Re(e);return(0,t.mean)(n,1)})},r.className="GlobalAveragePooling1D",r}(Ka);t.serialization.registerClass(Ga);var Ya=function(e){function r(t){return e.call(this,t||{})||this}return n(r,e),r.prototype.call=function(e,n){return(0,t.tidy)(function(){var n=Re(e);return(0,t.max)(n,1)})},r.className="GlobalMaxPooling1D",r}(Ka);t.serialization.registerClass(Ya);var Xa=function(t){function e(e){var n=t.call(this,e)||this;return n.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,nt(n.dataFormat),n.inputSpec=[new Ue({ndim:4})],n}return n(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 p},e.prototype.getConfig=function(){var e={dataFormat:this.dataFormat},n=t.prototype.getConfig.call(this);return Object.assign(e,n),e},e}(Ze),$a=function(e){function r(){return null!==e&&e.apply(this,arguments)||this}return n(r,e),r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){var n=Re(e);return"channelsLast"===r.dataFormat?(0,t.mean)(n,[1,2]):(0,t.mean)(n,[2,3])})},r.className="GlobalAveragePooling2D",r}(Xa);t.serialization.registerClass($a);var Qa=function(e){function r(){return null!==e&&e.apply(this,arguments)||this}return n(r,e),r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){var n=Re(e);return"channelsLast"===r.dataFormat?(0,t.max)(n,[1,2]):(0,t.max)(n,[2,3])})},r.className="GlobalMaxPooling2D",r}(Xa);function ts(t,e,n,r){if(Array.isArray(t)){if(null!=e||null!=n)throw new h("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 es(e,n,r,i,a,s,o,u){return void 0===i&&(i=!1),void 0===o&&(o=!1),void 0===u&&(u=!1),(0,t.tidy)(function(){var l=n.shape.length;if(l<3)throw new h("Input should be at least 3D, but is "+l+"D.");var c=[1,0].concat(vt(2,l));if(n=(0,t.transpose)(n,c),null!=s)throw new p("The rnn() functoin of the deeplearn.js backend does not support constants yet.");o&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),null!=a&&((a=a.asType("bool").asType("float32")).rank===l-1&&(a=(0,t.expandDims)(a,-1)),a=(0,t.transpose)(a,c)),i&&(n=(0,t.reverse)(n,0),null!=a&&(a=(0,t.reverse)(a,0)));var f,d,g=[],m=r,y=n.shape[0],v=(0,t.unstack)(n);null!=a&&(d=(0,t.unstack)(a));for(var b,w=function(n){var r=v[n],i=(0,t.tidy)(function(){return e(r,m)});if(null==a)f=i[0],m=i[1];else{var s=(0,t.tidy)(function(){var e=d[n],r=(0,t.onesLike)(e).sub(e);return{output:i[0].mul(e).addStrict(m[0].mul(r)),newStates:m.map(function(t,n){return i[1][n].mul(e).addStrict(t.mul(r))})}});f=s.output,m=s.newStates}u&&g.push(f)},z=0;z<y;++z)w(z);return u&&(b=(0,t.stack)(g,1)),[f,b,m]})}t.serialization.registerClass(Qa);var ns=function(e){function r(t){var n,r=e.call(this,t)||this;if(null==t.cell)throw new h("cell property is missing for the constructor of RNN.");if(null==(n=Array.isArray(t.cell)?new cs({cells:t.cell}):t.cell).stateSize)throw new h("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");return r.cell=n,r.returnSequences=null!=t.returnSequences&&t.returnSequences,r.returnState=null!=t.returnState&&t.returnState,r.goBackwards=null!=t.goBackwards&&t.goBackwards,r._stateful=null!=t.stateful&&t.stateful,r.unroll=null!=t.unroll&&t.unroll,r.supportsMasking=!0,r.inputSpec=[new Ue({ndim:3})],r.stateSpec=null,r.states_=null,r.numConstants=null,r.keptStates=[],r}return n(r,e),r.prototype.getStates=function(){return null==this.states_?vt(0,Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1).map(function(t){return null}):this.states_},r.prototype.setStates=function(t){this.states_=t},r.prototype.computeOutputShape=function(t){Oe(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,s=e;a<s.length;a++){var o=s[a];i.push([t[0],o])}return[n].concat(i)}return n},r.prototype.computeMask=function(e,n){var r=this;return(0,t.tidy)(function(){Array.isArray(n)&&(n=n[0]);var t=r.returnSequences?n:null;if(r.returnState){var e=r.states.map(function(t){return null});return[t].concat(e)}return t})},Object.defineProperty(r.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}),r.prototype.build=function(e){if(null!=this.numConstants)throw new p("Constants support is not implemented in RNN yet.");Oe(e)&&(e=e[0]),e=e;var n=this.stateful?e[0]:null,r=e[e.length-1];this.inputSpec[0]=new Ue({shape:[n,null,r]});var i,a=[e[0]].concat(e.slice(2));if(this.cell.build(a),i=Array.isArray(this.cell.stateSize)?this.cell.stateSize:[this.cell.stateSize],null!=this.stateSpec){if(!t.util.arraysEqual(this.stateSpec.map(function(t){return t.shape[t.shape.length-1]}),i))throw new h("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=i.map(function(t){return new Ue({shape:[null,t]})});this.stateful&&this.resetStates()},r.prototype.resetStates=function(e,n){var r=this;void 0===n&&(n=!1),(0,t.tidy)(function(){if(!r.stateful)throw new l("Cannot call resetStates() on an RNN Layer that is not stateful.");var i=r.inputSpec[0].shape[0];if(null==i)throw new h("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==r.states_)Array.isArray(r.cell.stateSize)?r.states_=r.cell.stateSize.map(function(e){return(0,t.zeros)([i,e])}):r.states_=[(0,t.zeros)([i,r.cell.stateSize])];else if(null==e)(0,t.dispose)(r.states_),null!=r.keptStates&&((0,t.dispose)(r.keptStates),r.keptStates=[]),Array.isArray(r.cell.stateSize)?r.states_=r.cell.stateSize.map(function(e){return(0,t.zeros)([i,e])}):r.states_[0]=(0,t.zeros)([i,r.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==r.states_.length)throw new h("Layer "+r.name+" expects "+r.states_.length+" state(s), but it received "+e.length+" state value(s). Input received: "+e);!0===n?r.keptStates.push(r.states_.slice()):(0,t.dispose)(r.states_);for(var a=0;a<r.states_.length;++a){var s=e[a],o=Array.isArray(r.cell.stateSize)?r.cell.stateSize[a]:r.cell.stateSize,u=[i,o];if(!t.util.arraysEqual(s.shape,u))throw new h("State "+a+" is incompatible with layer "+r.name+": expected shape="+u+", received shape="+s.shape);r.states_[a]=s}}r.states_=r.states_.map(function(e){return(0,t.keep)(e.clone())})})},r.prototype.apply=function(t,n){var r=null==n?null:n.initialState,i=null==n?null:n.constants;null==n&&(n={});var a=ts(t,r,i,this.numConstants);t=a.inputs,r=a.initialState,i=a.constants;var s=[],o=[];if(null!=r){n.initialState=r,s=s.concat(r),this.stateSpec=[];for(var u=0,l=r;u<l.length;u++){var c=l[u];this.stateSpec.push(new Ue({shape:c.shape}))}o=o.concat(this.stateSpec)}if(null!=i&&(n.constants=i,s=s.concat(i),this.numConstants=i.length),s[0]instanceof Ve){var h=[t].concat(s),p=this.inputSpec.concat(o),f=this.inputSpec;this.inputSpec=p;var d=e.prototype.apply.call(this,h,n);return this.inputSpec=f,d}return e.prototype.apply.call(this,t,n)},r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){var t=null==n?null:n.mask,i=null==n?null:n.training,a=null==n?null:n.initialState;e=Re(e),null==a&&(a=r.stateful?r.states_:r.getInitialState(e));var s=Array.isArray(r.cell.stateSize)?r.cell.stateSize.length:1;if(a.length!==s)throw new h("RNN Layer has "+s+" state(s) but was passed "+a.length+" initial state(s).");r.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");var o={training:i},u=es(function(t,e){var n=r.cell.call([t].concat(e),o);return[n[0],n.slice(1)]},e,a,r.goBackwards,t,null,r.unroll,r.returnSequences),l=u[0],c=u[1],p=u[2];r.stateful&&r.resetStates(p,i);var f=r.returnSequences?c:l;return r.returnState?[f].concat(p):f})},r.prototype.getInitialState=function(e){var n=this;return(0,t.tidy)(function(){var r=(0,t.zeros)(e.shape);return r=wt(r=(0,t.sum)(r,[1,2])),Array.isArray(n.cell.stateSize)?n.cell.stateSize.map(function(t){return t>1?Tt(r,[1,t]):r}):n.cell.stateSize>1?[Tt(r,[1,n.cell.stateSize])]:[r]})},Object.defineProperty(r.prototype,"trainableWeights",{get:function(){return this.trainable?this.cell.trainableWeights:[]},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"nonTrainableWeights",{get:function(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights},enumerable:!0,configurable:!0}),r.prototype.setFastWeightInitDuringBuild=function(t){e.prototype.setFastWeightInitDuringBuild.call(this,t),null!=this.cell&&this.cell.setFastWeightInitDuringBuild(t)},r.prototype.getConfig=function(){var t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};null!=this.numConstants&&(t.numConstants=this.numConstants);var n=this.cell.getConfig();t.cell={className:this.cell.getClassName(),config:n};var r=e.prototype.getConfig.call(this);return Object.assign(t,r),t},r.fromConfig=function(t,e,n){void 0===n&&(n={});var r=pn(e.cell,n);return new t(Object.assign(e,{cell:r}))},r.className="RNN",r}(Ze);exports.RNN=ns,t.serialization.registerClass(ns);var rs=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e}(Ze),is=function(e){function r(t){var n=e.call(this,t)||this;return n.DEFAULT_ACTIVATION="tanh",n.DEFAULT_KERNEL_INITIALIZER="glorotNormal",n.DEFAULT_RECURRENT_INITIALIZER="orthogonal",n.DEFAULT_BIAS_INITIALIZER="zeros",n.units=t.units,O(n.units,"units"),n.activation=Ni(null==t.activation?n.DEFAULT_ACTIVATION:t.activation),n.useBias=null==t.useBias||t.useBias,n.kernelInitializer=he(t.kernelInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.recurrentInitializer=he(t.recurrentInitializer||n.DEFAULT_RECURRENT_INITIALIZER),n.biasInitializer=he(t.biasInitializer||n.DEFAULT_BIAS_INITIALIZER),n.kernelRegularizer=Di(t.kernelRegularizer),n.recurrentRegularizer=Di(t.recurrentRegularizer),n.biasRegularizer=Di(t.biasRegularizer),n.kernelConstraint=J(t.kernelConstraint),n.recurrentConstraint=J(t.recurrentConstraint),n.biasConstraint=J(t.biasConstraint),n.dropout=mt([1,yt([0,null==t.dropout?0:t.dropout])]),n.recurrentDropout=mt([1,yt([0,null==t.recurrentDropout?0:t.recurrentDropout])]),n.stateSize=n.units,n.dropoutMask=null,n.recurrentDropoutMask=null,n}return n(r,e),r.prototype.build=function(t){t=Fe(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},r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){if(2!==(e=e).length)throw new h("SimpleRNNCell expects 2 input Tensors, got "+e.length+".");var i=e[1];e=e[0];var a,s=null!=n.training&&n.training;0<r.dropout&&r.dropout<1&&null==r.dropoutMask&&(r.dropoutMask=hs(function(){return(0,t.onesLike)(e)},r.dropout,s)),0<r.recurrentDropout&&r.recurrentDropout<1&&null==r.recurrentDropoutMask&&(r.recurrentDropoutMask=hs(function(){return(0,t.onesLike)(i)},r.recurrentDropout,s));var o=r.dropoutMask,u=r.recurrentDropoutMask;a=Et(null!=o?(0,t.mul)(e,o):e,r.kernel.read()),null!=r.bias&&(a=Ft(a,r.bias.read())),null!=u&&(i=(0,t.mul)(i,u));var l=(0,t.add)(a,Et(i,r.recurrentKernel.read()));return null!=r.activation&&(l=r.activation.apply(l)),[l,l]})},r.prototype.getConfig=function(){var t={units:this.units,activation:ki(this.activation),useBias:this.useBias,kernelInitializer:ce(this.kernelInitializer),recurrentInitializer:ce(this.recurrentInitializer),biasInitializer:ce(this.biasInitializer),kernelRegularizer:Ei(this.kernelRegularizer),recurrentRegularizer:Ei(this.recurrentRegularizer),biasRegularizer:Ei(this.biasRegularizer),activityRegularizer:Ei(this.activityRegularizer),kernelConstraint:V(this.kernelConstraint),recurrentConstraint:V(this.recurrentConstraint),biasConstraint:V(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},r.className="SimpleRNNCell",r}(rs);t.serialization.registerClass(is);var as=function(e){function r(t){return t.cell=new is(t),e.call(this,t)||this}return n(r,e),r.prototype.call=function(n,r){var i=this;return(0,t.tidy)(function(){null!=i.cell.dropoutMask&&((0,t.dispose)(i.cell.dropoutMask),i.cell.dropoutMask=null),null!=i.cell.recurrentDropoutMask&&((0,t.dispose)(i.cell.recurrentDropoutMask),i.cell.recurrentDropoutMask=null);var a=null==r?null:r.mask,s=null==r?null:r.training,o=null==r?null:r.initialState;return e.prototype.call.call(i,n,{mask:a,training:s,initialState:o})})},Object.defineProperty(r.prototype,"units",{get:function(){return this.cell.units},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"activation",{get:function(){return this.cell.activation},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"useBias",{get:function(){return this.cell.useBias},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"kernelInitializer",{get:function(){return this.cell.kernelInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"recurrentInitializer",{get:function(){return this.cell.recurrentInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"biasInitializer",{get:function(){return this.cell.biasInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"kernelRegularizer",{get:function(){return this.cell.kernelRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"recurrentRegularizer",{get:function(){return this.cell.recurrentRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"biasRegularizer",{get:function(){return this.cell.biasRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"kernelConstraint",{get:function(){return this.cell.kernelConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"recurrentConstraint",{get:function(){return this.cell.recurrentConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"biasConstraint",{get:function(){return this.cell.biasConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"dropout",{get:function(){return this.cell.dropout},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"recurrentDropout",{get:function(){return this.cell.recurrentDropout},enumerable:!0,configurable:!0}),r.prototype.getConfig=function(){var t={units:this.units,activation:ki(this.activation),useBias:this.useBias,kernelInitializer:ce(this.kernelInitializer),recurrentInitializer:ce(this.recurrentInitializer),biasInitializer:ce(this.biasInitializer),kernelRegularizer:Ei(this.kernelRegularizer),recurrentRegularizer:Ei(this.recurrentRegularizer),biasRegularizer:Ei(this.biasRegularizer),activityRegularizer:Ei(this.activityRegularizer),kernelConstraint:V(this.kernelConstraint),recurrentConstraint:V(this.recurrentConstraint),biasConstraint:V(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout},n=e.prototype.getConfig.call(this);return delete n.cell,Object.assign(t,n),t},r.fromConfig=function(t,e){return new t(e)},r.className="SimpleRNN",r}(ns);t.serialization.registerClass(as);var ss=function(e){function r(t){var n=e.call(this,t)||this;return n.DEFAULT_ACTIVATION="tanh",n.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",n.DEFAULT_KERNEL_INITIALIZER="glorotNormal",n.DEFAULT_RECURRENT_INITIALIZER="orthogonal",n.DEFAULT_BIAS_INITIALIZER="zeros",n.units=t.units,O(n.units,"units"),n.activation=Ni(void 0===t.activation?n.DEFAULT_ACTIVATION:t.activation),n.recurrentActivation=Ni(void 0===t.recurrentActivation?n.DEFAULT_RECURRENT_ACTIVATION:t.recurrentActivation),n.useBias=null==t.useBias||t.useBias,n.kernelInitializer=he(t.kernelInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.recurrentInitializer=he(t.recurrentInitializer||n.DEFAULT_RECURRENT_INITIALIZER),n.biasInitializer=he(t.biasInitializer||n.DEFAULT_BIAS_INITIALIZER),n.kernelRegularizer=Di(t.kernelRegularizer),n.recurrentRegularizer=Di(t.recurrentRegularizer),n.biasRegularizer=Di(t.biasRegularizer),n.kernelConstraint=J(t.kernelConstraint),n.recurrentConstraint=J(t.recurrentConstraint),n.biasConstraint=J(t.biasConstraint),n.dropout=mt([1,yt([0,null==t.dropout?0:t.dropout])]),n.recurrentDropout=mt([1,yt([0,null==t.recurrentDropout?0:t.recurrentDropout])]),n.implementation=t.implementation,n.stateSize=n.units,n.dropoutMask=null,n.recurrentDropoutMask=null,n}return n(r,e),r.prototype.build=function(t){var e=(t=Fe(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},r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){if(2!==(e=e).length)throw new h("GRUCell expects 2 input Tensors (inputs, h, c), got "+e.length+".");var i=null!=n.training&&n.training,a=e[1];e=e[0],0<r.dropout&&r.dropout<1&&null==r.dropoutMask&&(r.dropoutMask=hs(function(){return(0,t.onesLike)(e)},r.dropout,i,3)),0<r.recurrentDropout&&r.recurrentDropout<1&&null==r.recurrentDropoutMask&&(r.recurrentDropoutMask=hs(function(){return(0,t.onesLike)(a)},r.recurrentDropout,i,3));var s,o,u,l=r.dropoutMask,c=r.recurrentDropoutMask;0<r.dropout&&r.dropout<1&&(e=(0,t.mul)(e,l[0]));var p=Et(e,r.kernel.read());r.useBias&&(p=Ft(p,r.bias.read())),0<r.recurrentDropout&&r.recurrentDropout<1&&(a=(0,t.mul)(a,c[0]));var f=r.recurrentKernel.read(),d=(0,t.split)(f,[2*r.units,r.units],f.rank-1),g=d[0],m=d[1],y=Et(a,g),v=(0,t.split)(p,3,p.rank-1),b=v[0],w=v[1],z=v[2],k=(0,t.split)(y,2,y.rank-1),S=k[0],N=k[1];s=r.recurrentActivation.apply((0,t.add)(b,S)),o=r.recurrentActivation.apply((0,t.add)(w,N));var C=Et((0,t.mul)(o,a),m);u=r.activation.apply((0,t.add)(z,C));var A=(0,t.add)((0,t.mul)(s,a),(0,t.mul)((0,t.add)(1,(0,t.neg)(s)),u));return[A,A]})},r.prototype.getConfig=function(){var t={units:this.units,activation:ki(this.activation),recurrentActivation:ki(this.recurrentActivation),useBias:this.useBias,kernelInitializer:ce(this.kernelInitializer),recurrentInitializer:ce(this.recurrentInitializer),biasInitializer:ce(this.biasInitializer),kernelRegularizer:Ei(this.kernelRegularizer),recurrentRegularizer:Ei(this.recurrentRegularizer),biasRegularizer:Ei(this.biasRegularizer),activityRegularizer:Ei(this.activityRegularizer),kernelConstraint:V(this.kernelConstraint),recurrentConstraint:V(this.recurrentConstraint),biasConstraint:V(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},r.className="GRUCell",r}(rs);t.serialization.registerClass(ss);var os=function(e){function r(t){return 0===t.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),t.cell=new ss(t),e.call(this,t)||this}return n(r,e),r.prototype.call=function(n,r){var i=this;return(0,t.tidy)(function(){null!=i.cell.dropoutMask&&((0,t.dispose)(i.cell.dropoutMask),i.cell.dropoutMask=null),null!=i.cell.recurrentDropoutMask&&((0,t.dispose)(i.cell.recurrentDropoutMask),i.cell.recurrentDropoutMask=null);var a=null==r?null:r.mask,s=null==r?null:r.training,o=null==r?null:r.initialState;return e.prototype.call.call(i,n,{mask:a,training:s,initialState:o})})},Object.defineProperty(r.prototype,"units",{get:function(){return this.cell.units},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"activation",{get:function(){return this.cell.activation},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"recurrentActivation",{get:function(){return this.cell.recurrentActivation},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"useBias",{get:function(){return this.cell.useBias},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"kernelInitializer",{get:function(){return this.cell.kernelInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"recurrentInitializer",{get:function(){return this.cell.recurrentInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"biasInitializer",{get:function(){return this.cell.biasInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"kernelRegularizer",{get:function(){return this.cell.kernelRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"recurrentRegularizer",{get:function(){return this.cell.recurrentRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"biasRegularizer",{get:function(){return this.cell.biasRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"kernelConstraint",{get:function(){return this.cell.kernelConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"recurrentConstraint",{get:function(){return this.cell.recurrentConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"biasConstraint",{get:function(){return this.cell.biasConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"dropout",{get:function(){return this.cell.dropout},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"recurrentDropout",{get:function(){return this.cell.recurrentDropout},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"implementation",{get:function(){return this.cell.implementation},enumerable:!0,configurable:!0}),r.prototype.getConfig=function(){var t={units:this.units,activation:ki(this.activation),recurrentActivation:ki(this.recurrentActivation),useBias:this.useBias,kernelInitializer:ce(this.kernelInitializer),recurrentInitializer:ce(this.recurrentInitializer),biasInitializer:ce(this.biasInitializer),kernelRegularizer:Ei(this.kernelRegularizer),recurrentRegularizer:Ei(this.recurrentRegularizer),biasRegularizer:Ei(this.biasRegularizer),activityRegularizer:Ei(this.activityRegularizer),kernelConstraint:V(this.kernelConstraint),recurrentConstraint:V(this.recurrentConstraint),biasConstraint:V(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},n=e.prototype.getConfig.call(this);return delete n.cell,Object.assign(t,n),t},r.fromConfig=function(t,e){return 0===e.implmentation&&(e.implementation=1),new t(e)},r.className="GRU",r}(ns);t.serialization.registerClass(os);var us=function(e){function r(t){var n=e.call(this,t)||this;return n.DEFAULT_ACTIVATION="tanh",n.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",n.DEFAULT_KERNEL_INITIALIZER="glorotNormal",n.DEFAULT_RECURRENT_INITIALIZER="orthogonal",n.DEFAULT_BIAS_INITIALIZER="zeros",n.units=t.units,O(n.units,"units"),n.activation=Ni(void 0===t.activation?n.DEFAULT_ACTIVATION:t.activation),n.recurrentActivation=Ni(void 0===t.recurrentActivation?n.DEFAULT_RECURRENT_ACTIVATION:t.recurrentActivation),n.useBias=null==t.useBias||t.useBias,n.kernelInitializer=he(t.kernelInitializer||n.DEFAULT_KERNEL_INITIALIZER),n.recurrentInitializer=he(t.recurrentInitializer||n.DEFAULT_RECURRENT_INITIALIZER),n.biasInitializer=he(t.biasInitializer||n.DEFAULT_BIAS_INITIALIZER),n.unitForgetBias=t.unitForgetBias,n.kernelRegularizer=Di(t.kernelRegularizer),n.recurrentRegularizer=Di(t.recurrentRegularizer),n.biasRegularizer=Di(t.biasRegularizer),n.kernelConstraint=J(t.kernelConstraint),n.recurrentConstraint=J(t.recurrentConstraint),n.biasConstraint=J(t.biasConstraint),n.dropout=mt([1,yt([0,null==t.dropout?0:t.dropout])]),n.recurrentDropout=mt([1,yt([0,null==t.recurrentDropout?0:t.recurrentDropout])]),n.implementation=t.implementation,n.stateSize=[n.units,n.units],n.dropoutMask=null,n.recurrentDropoutMask=null,n}return n(r,e),r.prototype.build=function(t){var e,r,i=(t=Fe(t))[t.length-1];if(this.kernel=this.addWeight("kernel",[i,4*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,4*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){if(this.unitForgetBias){var a=this.biasInitializer,s=this.units;r=new((e=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return n(e,t),e.prototype.apply=function(t,e){var n=a.apply([s]),r=(new Zt).apply([s]),i=a.apply([2*s]);return xt(xt(n,r),i)},e}(Jt)).className="CustomInit",e)}else r=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.units],null,r,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0},r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){var i=null!=n.training&&n.training;if(3!==(e=e).length)throw new h("LSTMCell expects 3 input Tensors (inputs, h, c), got "+e.length+".");var a=e[1],s=e[2];e=e[0],0<r.dropout&&r.dropout<1&&null==r.dropoutMask&&(r.dropoutMask=hs(function(){return(0,t.onesLike)(e)},r.dropout,i,4)),0<r.recurrentDropout&&r.recurrentDropout<1&&null==r.recurrentDropoutMask&&(r.recurrentDropoutMask=hs(function(){return(0,t.onesLike)(a)},r.recurrentDropout,i,4));var o,u,l,c,p=r.dropoutMask,f=r.recurrentDropoutMask;0<r.dropout&&r.dropout<1&&(e=(0,t.mul)(e,p[0]));var d=Et(e,r.kernel.read());0<r.recurrentDropout&&r.recurrentDropout<1&&(a=(0,t.mul)(a,f[0])),d=(0,t.add)(d,Et(a,r.recurrentKernel.read())),r.useBias&&(d=Ft(d,r.bias.read()));var g=(0,t.split)(d,4,d.rank-1),m=g[0],y=g[1],v=g[2],b=g[3];o=r.recurrentActivation.apply(m),u=r.recurrentActivation.apply(y),l=(0,t.add)((0,t.mul)(u,s),(0,t.mul)(o,r.activation.apply(v))),c=r.recurrentActivation.apply(b);var w=(0,t.mul)(c,r.activation.apply(l));return[w,w,l]})},r.prototype.getConfig=function(){var t={units:this.units,activation:ki(this.activation),recurrentActivation:ki(this.recurrentActivation),useBias:this.useBias,kernelInitializer:ce(this.kernelInitializer),recurrentInitializer:ce(this.recurrentInitializer),biasInitializer:ce(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:Ei(this.kernelRegularizer),recurrentRegularizer:Ei(this.recurrentRegularizer),biasRegularizer:Ei(this.biasRegularizer),activityRegularizer:Ei(this.activityRegularizer),kernelConstraint:V(this.kernelConstraint),recurrentConstraint:V(this.recurrentConstraint),biasConstraint:V(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},r.className="LSTMCell",r}(rs);t.serialization.registerClass(us);var ls=function(e){function r(t){return 0===t.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),t.cell=new us(t),e.call(this,t)||this}return n(r,e),r.prototype.call=function(n,r){var i=this;return(0,t.tidy)(function(){null!=i.cell.dropoutMask&&((0,t.dispose)(i.cell.dropoutMask),i.cell.dropoutMask=null),null!=i.cell.recurrentDropoutMask&&((0,t.dispose)(i.cell.recurrentDropoutMask),i.cell.recurrentDropoutMask=null);var a=null==r?null:r.mask,s=null==r?null:r.training,o=null==r?null:r.initialState;return e.prototype.call.call(i,n,{mask:a,training:s,initialState:o})})},Object.defineProperty(r.prototype,"units",{get:function(){return this.cell.units},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"activation",{get:function(){return this.cell.activation},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"recurrentActivation",{get:function(){return this.cell.recurrentActivation},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"useBias",{get:function(){return this.cell.useBias},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"kernelInitializer",{get:function(){return this.cell.kernelInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"recurrentInitializer",{get:function(){return this.cell.recurrentInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"biasInitializer",{get:function(){return this.cell.biasInitializer},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"unitForgetBias",{get:function(){return this.cell.unitForgetBias},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"kernelRegularizer",{get:function(){return this.cell.kernelRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"recurrentRegularizer",{get:function(){return this.cell.recurrentRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"biasRegularizer",{get:function(){return this.cell.biasRegularizer},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"kernelConstraint",{get:function(){return this.cell.kernelConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"recurrentConstraint",{get:function(){return this.cell.recurrentConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"biasConstraint",{get:function(){return this.cell.biasConstraint},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"dropout",{get:function(){return this.cell.dropout},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"recurrentDropout",{get:function(){return this.cell.recurrentDropout},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"implementation",{get:function(){return this.cell.implementation},enumerable:!0,configurable:!0}),r.prototype.getConfig=function(){var t={units:this.units,activation:ki(this.activation),recurrentActivation:ki(this.recurrentActivation),useBias:this.useBias,kernelInitializer:ce(this.kernelInitializer),recurrentInitializer:ce(this.recurrentInitializer),biasInitializer:ce(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:Ei(this.kernelRegularizer),recurrentRegularizer:Ei(this.recurrentRegularizer),biasRegularizer:Ei(this.biasRegularizer),activityRegularizer:Ei(this.activityRegularizer),kernelConstraint:V(this.kernelConstraint),recurrentConstraint:V(this.recurrentConstraint),biasConstraint:V(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation},n=e.prototype.getConfig.call(this);return delete n.cell,Object.assign(t,n),t},r.fromConfig=function(t,e){return 0===e.implmentation&&(e.implementation=1),new t(e)},r.className="LSTM",r}(ns);t.serialization.registerClass(ls);var cs=function(e){function r(t){var n=e.call(this,t)||this;return n.cells=t.cells,n}return n(r,e),Object.defineProperty(r.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}),r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){for(var t=(e=e).slice(1),i=[],a=0,s=r.cells.slice().reverse();a<s.length;a++){var o=s[a];Array.isArray(o.stateSize)?i.push(t.splice(0,o.stateSize.length)):i.push(t.splice(0,1))}i.reverse();for(var u,l=[],c=0;c<r.cells.length;++c)o=r.cells[c],t=i[c],u=0===c?[e[0]].concat(t):[u[0]].concat(t),u=o.call(u,n),l.push(u.slice(1));t=[];for(var h=0,p=l.slice().reverse();h<p.length;h++){var f=p[h];t.push.apply(t,f)}return[u[0]].concat(t)})},r.prototype.build=function(t){var e;Oe(t)&&(t=t[0]),t=t,this.cells.forEach(function(n,r){ot("RNNCell_"+r,function(){n.build(t),e=Array.isArray(n.stateSize)?n.stateSize[0]:n.stateSize,t=[t[0],e]})}),this.built=!0},r.prototype.getConfig=function(){for(var t=[],n=0,r=this.cells;n<r.length;n++){var i=r[n];t.push({className:i.getClassName(),config:i.getConfig()})}var a={cells:t},s=e.prototype.getConfig.call(this);return Object.assign(a,s),a},r.fromConfig=function(t,e,n){void 0===n&&(n={});for(var r=[],i=0,a=e.cells;i<a.length;i++){var s=a[i];r.push(pn(s,n))}return new t({cells:r})},Object.defineProperty(r.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(r.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,s=this.cells;a<s.length;a++)r=s[a],i.push.apply(i,r.trainableWeights);return i.concat(t)}return t},enumerable:!0,configurable:!0}),r.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 je(t)},r.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,s=t.splice(a),o=0;o<i.weights.length;++o)e.push([i.weights[o],s[o]]);We(e)},r.className="StackedRNNCells",r}(rs);function hs(e,n,r,i){function a(){return Bt(e(),n)}if(void 0===r&&(r=null),void 0===i&&(i=1),i>1){for(var s=[],o=0;o<i;o++)s.push(jt(a,e,r));return s.map(function(e){return(0,t.keep)(e.clone())})}return(0,t.keep)(jt(a,e,r).clone())}t.serialization.registerClass(cs);var ps=function(t){function e(e){var n=t.call(this,e)||this;return n.layer=e.layer,n}return n(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=pn(e.layer,n);delete e.layer;var i={layer:r};return Object.assign(i,e),new t(i)},e}(Ze),fs=function(e){function r(t){var n=e.call(this,t)||this;return n.supportsMasking=!0,n}return n(r,e),r.prototype.build=function(t){if((t=Fe(t)).length<3)throw new h("TimeDistributed layer expects an input shape >= 3D, but received input shape "+JSON.stringify(t));this.inputSpec=[{shape:t}];var n=[t[0]].concat(t.slice(2));this.layer.built||(this.layer.build(n),this.layer.built=!0),e.prototype.build.call(this,t)},r.prototype.computeOutputShape=function(t){var e=[(t=Fe(t))[0]].concat(t.slice(2)),n=this.layer.computeOutputShape(e),r=t[1];return[n[0],r].concat(n.slice(1))},r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){return es(function(t,e){return[Re(r.layer.call(t,n)),[]]},e=Re(e),[],!1,null,null,!1,!0)[1]})},r.className="TimeDistributed",r}(ps);function ds(t){L(tt,"BidirectionalMergeMode",t)}t.serialization.registerClass(fs);var gs="concat",ms=function(e){function r(t){var n=e.call(this,t)||this,r=t.layer.getConfig(),i={};i.className=t.layer.getClassName(),i.config=r,n.forwardLayer=pn(i),r.goBackwards=!0!==r.goBackwards;var a={};if(a.className=t.layer.getClassName(),a.config=r,n.backwardLayer=pn(a),n.forwardLayer.name="forward_"+n.forwardLayer.name,n.backwardLayer.name="backward_"+n.backwardLayer.name,n.mergeMode=void 0===t.mergeMode?gs:t.mergeMode,ds(n.mergeMode),t.weights)throw new p("weights support is not implemented for Bidirectional layer yet.");return n._stateful=t.layer.stateful,n.returnSequences=t.layer.returnSequences,n.returnState=t.layer.returnState,n.supportsMasking=!0,n._trainable=!0,n.inputSpec=t.layer.inputSpec,n.numConstants=null,n}return n(r,e),Object.defineProperty(r.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}),r.prototype.getWeights=function(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())},r.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))},r.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()):v(n)},r.prototype.apply=function(t,n){var r=null==n?null:n.initialState,i=null==n?null:n.constants;null==n&&(n={});var a=ts(t,r,i,this.numConstants);if(t=a.inputs,r=a.initialState,i=a.constants,Array.isArray(t)&&(r=t.slice(1),t=t[0]),(null==r||0===r.length)&&null==i)return e.prototype.apply.call(this,t,n);var s=[],o=[];if(null!=r){var u=r.length;if(u%2>0)throw new h("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");n.initialState=r,s.push.apply(s,r);var l=r.map(function(t){return new Ue({shape:t.shape})});this.forwardLayer.stateSpec=l.slice(0,u/2),this.backwardLayer.stateSpec=l.slice(u/2),o.push.apply(o,l)}if(null!=i)throw new p("Support for constants in Bidirectional layers is not implemented yet.");for(var c=s[0]instanceof Ve,f=0,d=s;f<d.length;f++)if(d[f]instanceof Ve!==c)throw new h("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(c){var g=[t].concat(s),m=this.inputSpec.concat(o),y=this.inputSpec;this.inputSpec=m;var v=e.prototype.apply.call(this,g,n);return this.inputSpec=y,v}return e.prototype.apply.call(this,t,n)},r.prototype.call=function(e,n){var r=this;return(0,t.tidy)(function(){var i,a,s,o,u=n.initialState;if(null==u)i=r.forwardLayer.call(e,n),a=r.backwardLayer.call(e,n);else{var l=u.slice(0,u.length/2),c=u.slice(u.length/2);i=r.forwardLayer.call(e,Object.assign(n,{initialState:l})),a=r.backwardLayer.call(e,Object.assign(n,{initialState:c}))}return r.returnState&&(Array.isArray(i)&&(s=i.slice(1).concat(a.slice(1))),i=i[0],a=a[0]),r.returnSequences&&(a=(0,t.reverse)(a,1)),"concat"===r.mergeMode?o=It([i,a]):"sum"===r.mergeMode?o=(0,t.add)(i,a):"ave"===r.mergeMode?o=(0,t.mul)(.5,(0,t.add)(i,a)):"mul"===r.mergeMode?o=(0,t.mul)(i,a):null==r.mergeMode&&(o=[i,a]),r.returnState?null==r.mergeMode?o.concat(s):[o].concat(s):o})},r.prototype.resetStates=function(t){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()},r.prototype.build=function(t){var e=this;ot(this.forwardLayer.name,function(){e.forwardLayer.build(t)}),ot(this.backwardLayer.name,function(){e.backwardLayer.build(t)}),this.built=!0},r.prototype.computeMask=function(t,e){var n;if(Array.isArray(e)&&(e=e[0]),n=this.returnSequences?null==this.mergeMode?[e,e]:e:null==this.mergeMode?[null,null]:null,this.returnState){var r=this.forwardLayer.states.map(function(t){return null});return Array.isArray(n)?n.concat(r).concat(r):[n].concat(r).concat(r)}return n},Object.defineProperty(r.prototype,"trainableWeights",{get:function(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"nonTrainableWeights",{get:function(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)},enumerable:!0,configurable:!0}),r.prototype.setFastWeightInitDuringBuild=function(t){e.prototype.setFastWeightInitDuringBuild.call(this,t),null!=this.forwardLayer&&this.forwardLayer.setFastWeightInitDuringBuild(t),null!=this.backwardLayer&&this.backwardLayer.setFastWeightInitDuringBuild(t)},r.prototype.getConfig=function(){var t={mergeMode:this.mergeMode},n=e.prototype.getConfig.call(this);return Object.assign(t,n),t},r.fromConfig=function(t,e){var n=pn(e.layer);if(delete e.layer,null!=e.numConstants)throw new p("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");var r=e;return r.layer=n,new t(r)},r.className="Bidirectional",r}(ps);function ys(t){return new $e(t)}function vs(t){return new Mi(t)}function bs(t){return new Ri(t)}function ws(t){return new Fi(t)}function zs(t){return new _i(t)}function ks(t){return new Pi(t)}function Ss(t){return new Bi(t)}function Ns(t){return new ea(t)}function Cs(t){return new Yi(t)}function As(t){return new $i(t)}function Is(t){return new Xi(t)}function xs(t){return new ta(t)}function Ts(t){return new na(t)}function Ls(t){return new ra(t)}function Es(t){return new aa(t)}function Os(t){return new ca(t)}function Ds(t){return new ua(t)}function Rs(t){return new sa(t)}function Fs(t){return new oa(t)}function _s(t){return new la(t)}function Ms(t){return new ha(t)}function Bs(t){return new pa(t)}function Ps(t){return new fa(t)}function js(t){return new ga(t)}function Ws(t){return new ya(t)}function Us(t){return new ba(t)}function Vs(t){return new ka(t)}function qs(t){return new wa(t)}function Js(t){return new za(t)}function Hs(t){return new va(t)}function Zs(t){return new Ca(t)}function Ks(t){return new Da(t)}function Gs(t){return new Ra(t)}function Ys(t){return new _a(t)}function Xs(t){return new Wa(t)}function $s(t){return Xs(t)}function Qs(t){return Xs(t)}function to(t){return new qa(t)}function eo(t){return to(t)}function no(t){return to(t)}function ro(t){return new Za(t)}function io(t){return ro(t)}function ao(t){return ro(t)}function so(t){return new Ga(t)}function oo(t){return new $a(t)}function uo(t){return new Ya(t)}function lo(t){return new Qa(t)}function co(t){return new ja(t)}function ho(t){return new Va(t)}function po(t){return new Ha(t)}function fo(t){return new os(t)}function go(t){return new ss(t)}function mo(t){return new ls(t)}function yo(t){return new us(t)}function vo(t){return new as(t)}function bo(t){return new is(t)}function wo(t){return new ns(t)}function zo(t){return new cs(t)}function ko(t){return new ms(t)}function So(t){return new fs(t)}t.serialization.registerClass(ms);var No=uo,Co=lo,Ao=co,Io=ho;function xo(t){return new Aa(t)}function To(t){return new Ia(t)}function Lo(t){return new xa(t)}function Eo(t){return new da(t)}var Oo=Object.freeze({inputLayer:ys,elu:vs,reLU:bs,leakyReLU:ws,prelu:zs,softmax:ks,thresholdedReLU:Ss,conv1d:Ns,conv2d:Cs,conv2dTranspose:As,conv3d:Is,separableConv2d:xs,cropping2D:Ts,upSampling2d:Ls,depthwiseConv2d:Es,activation:Os,dense:Ds,dropout:Rs,spatialDropout1d:Fs,flatten:_s,repeatVector:Ms,reshape:Bs,permute:Ps,embedding:js,add:Ws,average:Us,concatenate:Vs,maximum:qs,minimum:Js,multiply:Hs,dot:Zs,batchNormalization:Ks,layerNormalization:Gs,zeroPadding2d:Ys,averagePooling1d:Xs,avgPool1d:$s,avgPooling1d:Qs,averagePooling2d:to,avgPool2d:eo,avgPooling2d:no,averagePooling3d:ro,avgPool3d:io,avgPooling3d:ao,globalAveragePooling1d:so,globalAveragePooling2d:oo,globalMaxPooling1d:uo,globalMaxPooling2d:lo,maxPooling1d:co,maxPooling2d:ho,maxPooling3d:po,gru:fo,gruCell:go,lstm:mo,lstmCell:yo,simpleRNN:vo,simpleRNNCell:bo,rnn:wo,stackedRNNCells:zo,bidirectional:ko,timeDistributed:So,globalMaxPool1d:No,globalMaxPool2d:Co,maxPool1d:Ao,maxPool2d:Io,Layer:Ze,RNN:ns,RNNCell:rs,input:oi,gaussianNoise:xo,gaussianDropout:To,alphaDropout:Lo,masking:Eo});function Do(t,e){return En(t,e)}function Ro(t,e){return Bn(t,e)}function Fo(t,e){return Pn(t,e)}function _o(t,e){return On(t,e)}function Mo(t,e){return Hn(t,e)}function Bo(t,e){return _n(t,e)}function Po(t,e){return Mn(t,e)}function jo(t,e){return xn(t,e)}function Wo(t,e){return gn(t,e)}function Uo(t,e){return mn(t,e)}function Vo(t,e){return mn(t,e)}function qo(t,e){return mn(t,e)}function Jo(t,e){return dn(t,e)}function Ho(t,e){return dn(t,e)}function Zo(t,e){return dn(t,e)}exports.layers=Oo;var Ko=Object.freeze({binaryAccuracy:Do,binaryCrossentropy:Ro,sparseCategoricalAccuracy:Fo,categoricalAccuracy:_o,categoricalCrossentropy:Mo,precision:Bo,recall:Po,cosineProximity:jo,meanAbsoluteError:Wo,meanAbsolutePercentageError:Uo,MAPE:Vo,mape:qo,meanSquaredError:Jo,MSE:Ho,mse:Zo}),Go=Object.freeze({modelFromJSON:Qr});function Yo(t){return new Ii(t)}function Xo(t){return xi(t)}function $o(t){return Ti(t)}exports.models=Go,exports.metrics=Ko;var Qo=Object.freeze({l1l2:Yo,l1:Xo,l2:$o}),tu=function(t){function e(){var e=null!==t&&t.apply(this,arguments)||this;return e.model=null,e}return n(e,t),e.prototype.setModel=function(t){if(!(t instanceof $r))throw new Error("model must be a LayersModel, not some other Container");this.model=t},e}(rn);function eu(t,e){return t<e}function nu(t,e){return t>e}exports.Callback=tu,exports.regularizers=Qo;var ru=function(t){function e(e){var n=t.call(this)||this;if(null==e&&(e={}),e.restoreBestWeights)throw new p("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=eu:"max"===n.mode?n.monitorFunc=nu:-1!==n.monitor.indexOf("acc")?n.monitorFunc=nu:n.monitorFunc=eu,n.monitorFunc===eu&&(n.minDelta*=-1),n}return n(e,t),e.prototype.onTrainBegin=function(t){return a(this,void 0,void 0,function(){return s(this,function(t){return this.wait=0,this.stoppedEpoch=0,null!=this.baseline?this.best=this.baseline:this.best=this.monitorFunc===eu?1/0:-1/0,[2]})})},e.prototype.onEpochEnd=function(t,e){return a(this,void 0,void 0,function(){var n;return s(this,function(r){switch(r.label){case 0:return[4,tn(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 a(this,void 0,void 0,function(){return s(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}(tu);function iu(t){return new ru(t)}exports.EarlyStopping=ru;var au={earlyStopping:iu};exports.callbacks=au;
  },{"@tensorflow/tfjs-core":"PqBP"}],"ewAU":[function(require,module,exports) {
  var global = arguments[3];
  var Buffer = require("buffer").Buffer;
  var t=arguments[3],e=require("buffer").Buffer;Object.defineProperty(exports,"__esModule",{value:!0}),exports.array=et,exports.zip=nt,exports.csv=Tt,exports.func=kt,exports.generator=Ft,exports.microphone=Dt,exports.webcam=Nt,exports.version_data=exports.URLDataSource=exports.FileDataSource=exports.TextLineDataset=exports.CSVDataset=exports.Dataset=void 0;var n=require("@tensorflow/tfjs-core"),r=function(t,e){return(r=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])})(t,e)};function i(t,e){function n(){this.constructor=t}r(t,e),t.prototype=null===e?Object.create(e):(n.prototype=e.prototype,new n)}function o(t,e,n,r){return new(n||(n=Promise))(function(i,o){function s(t){try{a(r.next(t))}catch(t){o(t)}}function u(t){try{a(r.throw(t))}catch(t){o(t)}}function a(t){t.done?i(t.value):new n(function(e){e(t.value)}).then(s,u)}a((r=r.apply(t,e||[])).next())})}function s(t,e){var n,r,i,o,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return o={next:u(0),throw:u(1),return:u(2)},"function"==typeof Symbol&&(o[Symbol.iterator]=function(){return this}),o;function u(o){return function(u){return function(o){if(n)throw new TypeError("Generator is already executing.");for(;s;)try{if(n=1,r&&(i=2&o[0]?r.return:o[0]?r.throw||((i=r.return)&&i.call(r),0):r.next)&&!(i=i.call(r,o[1])).done)return i;switch(r=0,i&&(o=[2&o[0],i.value]),o[0]){case 0:case 1:i=o;break;case 4:return s.label++,{value:o[1],done:!1};case 5:s.label++,r=o[1],o=[0];continue;case 7:o=s.ops.pop(),s.trys.pop();continue;default:if(!(i=(i=s.trys).length>0&&i[i.length-1])&&(6===o[0]||2===o[0])){s=0;continue}if(3===o[0]&&(!i||o[1]>i[0]&&o[1]<i[3])){s.label=o[1];break}if(6===o[0]&&s.label<i[1]){s.label=i[1],i=o;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(o);break}i[2]&&s.ops.pop(),s.trys.pop();continue}o=e.call(t,s)}catch(t){o=[6,t],r=0}finally{n=i=0}if(5&o[0])throw o[1];return{value:o[0]?o[1]:void 0,done:!0}}([o,u])}}}var u="undefined"!=typeof window?window:void 0!==t?t:"undefined"!=typeof self?self:{};function a(t,e){return t(e={exports:{}},e.exports),e.exports}var c=a(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,o=n.next;return o.int32=function(){return 4294967296*n.next()|0},o.double=function(){return o()+1.1102230246251565e-16*(2097152*o()|0)},o.quick=o,i&&("object"==typeof i&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.alea=i}(0,t)}),h=a(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,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&("object"==typeof i&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.xor128=i}(0,t)}),l=a(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,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&("object"==typeof i&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.xorwow=i}(0,t)}),f=a(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,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&(i.x&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.xorshift7=i}(0,t)}),p=a(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,o=e.i;return e.w=r=r+1640531527|0,n=i[o+34&127],t=i[o=o+1&127],n^=n<<13,t^=t<<17,n^=n>>>15,t^=t>>>12,n=i[o]=n^t,e.i=o,n+(r^r>>>16)|0},function(t,e){var n,r,i,o,s,u=[],a=128;for(e===(0|e)?(r=e,e=null):(e+="\0",r=0,a=Math.max(a,e.length)),i=0,o=-32;o<a;++o)e&&(r^=e.charCodeAt((o+32)%e.length)),0===o&&(s=r),r^=r<<10,r^=r>>>15,r^=r<<4,r^=r>>>13,o>=0&&(s=s+1640531527|0,i=0==(n=u[127&o]^=r+s)?i+1:0);for(i>=128&&(u[127&(e&&e.length||0)]=-1),i=127,o=512;o>0;--o)r=u[i+34&127],n=u[i=i+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,u[i]=r^n;t.w=s,t.X=u,t.i=i}(e,t)}(t),i=e&&e.state,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&(i.X&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.xor4096=i}(0,t)}),d=a(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,o=function(){return(n.next()>>>0)/4294967296};return o.double=function(){do{var t=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===t);return t},o.int32=n.next,o.quick=o,i&&("object"==typeof i&&r(i,n),o.state=function(){return r(n,{})}),o}e&&e.exports?e.exports=i:this.tychei=i}(0,t)}),v=a(function(t){!function(e,n){var r,i=this,o=256,s=6,u="random",a=n.pow(o,s),c=n.pow(2,52),h=2*c,l=o-1;function f(t,f,m){var y=[],w=d(function t(e,n){var r,i=[],o=typeof e;if(n&&"object"==o)for(r in e)try{i.push(t(e[r],n-1))}catch(t){}return i.length?i:"string"==o?e:e+"\0"}((f=1==f?{entropy:!0}:f||{}).entropy?[t,v(e)]:null==t?function(){try{var t;return r&&(t=r.randomBytes)?t=t(o):(t=new Uint8Array(o),(i.crypto||i.msCrypto).getRandomValues(t)),v(t)}catch(t){var n=i.navigator,s=n&&n.plugins;return[+new Date,i,s,i.screen,v(e)]}}():t,3),y),b=new function(t){var e,n=t.length,r=this,i=0,s=r.i=r.j=0,u=r.S=[];for(n||(t=[n++]);i<o;)u[i]=i++;for(i=0;i<o;i++)u[i]=u[s=l&s+t[i%n]+(e=u[i])],u[s]=e;(r.g=function(t){for(var e,n=0,i=r.i,s=r.j,u=r.S;t--;)e=u[i=l&i+1],n=n*o+u[l&(u[i]=u[s=l&s+e])+(u[s]=e)];return r.i=i,r.j=s,n})(o)}(y),g=function(){for(var t=b.g(s),e=a,n=0;t<c;)t=(t+n)*o,e*=o,n=b.g(1);for(;t>=h;)t/=2,e/=2,n>>>=1;return(t+n)/e};return g.int32=function(){return 0|b.g(4)},g.quick=function(){return b.g(4)/4294967296},g.double=g,d(v(b.S),e),(f.pass||m||function(t,e,r,i){return i&&(i.S&&p(i,b),t.state=function(){return p(b,{})}),r?(n[u]=t,e):t})(g,w,"global"in f?f.global:this==n,f.state)}function p(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[l&i]=l&(n^=19*e[l&i])+r.charCodeAt(i++);return v(e)}function v(t){return String.fromCharCode.apply(0,t)}if(n["seed"+u]=f,d(n.random(),e),t.exports){t.exports=f;try{r=require("crypto")}catch(t){}}}([],Math)});v.alea=c,v.xor128=h,v.xorwow=l,v.xorshift7=f,v.xor4096=p,v.tychei=d;var m=v,y=m.alea;function w(t,e){return b(t,e)}function b(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(E(t)){var o=Array.isArray(t)?[]:{};for(var s in r.add(t),t){var u=b(t[s],e,n,r);o[s]=u}return r.delete(t),o}throw new Error("Can't recurse into non-iterable type: "+t)}return n.set(t,i.value),i.value}function g(t,e){return void 0===e&&(e=C),x(t,e)}function x(t,e,n){void 0===n&&(n=new Set);var r=t[0];if(n.has(r))throw new Error("Circular references are not supported.");var i=e(t);if(i.recurse&&null!==i.value)throw new Error("A deep zip function may not return both a value and recurse=true.");if(i.recurse){if(E(r)){var o=Array.isArray(r)?[]:{};n.add(r);var s=function(r){var i=x(t.map(function(t){return t[r]}),e,n);o[r]=i};for(var u in r)s(u);return n.delete(r),o}throw new Error("Can't recurse into non-iterable type: "+r)}return i.value}function C(t){return null===t?null:E(t[0])?{value:null,recurse:!0}:{value:t,recurse:!1}}function z(t,e){return o(this,void 0,void 0,function(){var n,r,i,o,u,a;return s(this,function(s){switch(s.label){case 0:n=new Map,b(t,e,n),r=0,i=Array.from(n.keys()),s.label=1;case 1:return r<i.length?(o=i[r],(u=n.get(o))instanceof Promise?[4,u]:[3,3]):[3,4];case 2:a=s.sent(),n.set(o,a),s.label=3;case 3:return r++,[3,1];case 4:return[2,b(t,e,n)]}})})}function E(t){return null!=t&&!ArrayBuffer.isView(t)&&(Array.isArray(t)||"object"==typeof t&&!(t instanceof n.Tensor))}function S(t){return null==t||A(t)||Array.isArray(t)||"object"==typeof t&&t instanceof n.Tensor||n.util.isTypedArray(t)}function A(t){return null===t||"object"!=typeof t&&"function"!=typeof t}function R(t){return w(t,T)}function T(t){return t instanceof n.Tensor?{value:t.clone(),recurse:!1}:E(t)?{value:null,recurse:!0}:{value:t,recurse:!1}}var k=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}(),F=function(t){function e(){return t.call(this,e.INITIAL_CAPACITY)||this}return i(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}(k);function N(t){return new L(t)}function D(t){return new _(t)}function I(t,e){return new Z(t,e)}function O(t,e){return void 0===e&&(e=M.FAIL),new J(t,e)}var M,j=function(){function t(){}return t.prototype.toArray=function(){return o(this,void 0,void 0,function(){var t,e;return s(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 o(this,void 0,void 0,function(){var t,e,n;return s(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 o(this,void 0,void 0,function(){var t;return s(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 o(this,void 0,void 0,function(){var e,n;return s(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 U(this,t)},t.prototype.filter=function(t){return new W(this,t)},t.prototype.map=function(t){return new V(this,t)},t.prototype.mapAsync=function(t){return new Q(this,t)},t.prototype.serialMapAsync=function(t){return new Q(this,t).serial()},t.prototype.flatmap=function(t){return new G(this,t)},t.prototype.forEachAsync=function(t){return o(this,void 0,void 0,function(){return s(this,function(e){return[2,this.map(t).resolveFully()]})})},t.prototype.serialForEach=function(t){return o(this,void 0,void 0,function(){return s(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 B(this,t,e)},t.prototype.columnMajorBatch=function(t,e,n){return void 0===e&&(e=!0),void 0===n&&(n=C),this.rowMajorBatch(t,e).map(function(t){return g(t,n)})},t.prototype.concatenate=function(t,e){return new Z(N([this,t]),e)},t.prototype.take=function(t){return t<0||null==t?this:new P(this,t)},t.prototype.skip=function(t){return t<0||null==t?this:new H(this,t)},t.prototype.prefetch=function(t){return new Y(this,t)},t.prototype.shuffle=function(t,e){return new K(this,t,e)},t.prototype.serial=function(){return new q(this)},t}(),L=function(t){function e(e){var n=t.call(this)||this;return n.items=e,n.trav=0,n}return i(e,t),e.prototype.summary=function(){return"Array of "+this.items.length+" items"},e.prototype.next=function(){return o(this,void 0,void 0,function(){var t;return s(this,function(e){return this.trav>=this.items.length?[2,{value:null,done:!0}]:(t=this.items[this.trav],this.trav++,[2,{value:R(t),done:!1}])})})},e}(j),_=function(t){function e(e){var n=t.call(this)||this;return n.nextFn=e,n}return i(e,t),e.prototype.summary=function(){return"Function call"},e.prototype.next=function(){return o(this,void 0,void 0,function(){return s(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}(j),q=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 i(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Serial"},e.prototype.next=function(){return o(this,void 0,void 0,function(){var t=this;return s(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return o(this,void 0,void 0,function(){return s(this,function(t){return[2,this.upstream.next()]})})},e}(j),H=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 i(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Skip"},e.prototype.next=function(){return o(this,void 0,void 0,function(){var t=this;return s(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return o(this,void 0,void 0,function(){var t;return s(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]:((0,n.dispose)(t.value),[3,0]);case 2:return[2,this.upstream.next()]}})})},e}(j),P=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.maxCount=n,r.count=0,r}return i(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Take"},e.prototype.next=function(){return o(this,void 0,void 0,function(){return s(this,function(t){return this.count++>=this.maxCount?[2,{value:null,done:!0}]:[2,this.upstream.next()]})})},e}(j),B=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 i(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> RowMajorBatch"},e.prototype.next=function(){return o(this,void 0,void 0,function(){var t=this;return s(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return o(this,void 0,void 0,function(){var t,e;return s(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}(j),W=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 i(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Filter"},e.prototype.next=function(){return o(this,void 0,void 0,function(){var t=this;return s(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return o(this,void 0,void 0,function(){var t;return s(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]:((0,n.dispose)(t.value),[3,0]);case 2:return[2]}})})},e}(j),V=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.transform=n,r}return i(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Map"},e.prototype.next=function(){return o(this,void 0,void 0,function(){var t,e,r,i,o,u,a;return s(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=n.tensor_util.getTensorsInContainer(t.value),r=this.transform(t.value),i=n.tensor_util.getTensorsInContainer(r),o=0,u=e;o<u.length;o++)a=u[o],n.tensor_util.isTensorInList(a,i)||a.dispose();return[2,{value:r,done:!1}]}})})},e}(j),U=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 i(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> handleErrors"},e.prototype.next=function(){return o(this,void 0,void 0,function(){var t=this;return s(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return o(this,void 0,void 0,function(){var t;return s(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}(j),Q=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.transform=n,r}return i(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> AsyncMap"},e.prototype.next=function(){return o(this,void 0,void 0,function(){var t,e,r,i,o,u,a;return s(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=n.tensor_util.getTensorsInContainer(t.value),[4,this.transform(t.value)]);case 2:for(r=s.sent(),i=n.tensor_util.getTensorsInContainer(r),o=0,u=e;o<u.length;o++)a=u[o],n.tensor_util.isTensorInList(a,i)||a.dispose();return[2,{value:r,done:!1}]}})})},e}(j),X=function(t){function e(){var e=t.call(this)||this;return e.outputQueue=new F,e.lastRead=Promise.resolve({value:null,done:!1}),e}return i(e,t),e.prototype.next=function(){return o(this,void 0,void 0,function(){var t=this;return s(this,function(e){return this.lastRead=this.lastRead.then(function(){return t.serialNext()}),[2,this.lastRead]})})},e.prototype.serialNext=function(){return o(this,void 0,void 0,function(){return s(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}(j),G=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.transform=n,r}return i(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Flatmap"},e.prototype.pump=function(){return o(this,void 0,void 0,function(){var t,e,r,i,o,u,a;return s(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=n.tensor_util.getTensorsInContainer(t.value),r=this.transform(t.value),i=n.tensor_util.getTensorsInContainer(r),this.outputQueue.pushAll(r),o=0,u=e;o<u.length;o++)a=u[o],n.tensor_util.isTensorInList(a,i)||a.dispose();return[2,!0]}})})},e}(X),Z=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 i(e,t),e.prototype.summary=function(){return"TODO: fill in upstream of chained summaries -> Chained"},e.prototype.next=function(){return o(this,void 0,void 0,function(){return s(this,function(t){return this.lastRead=this.readFromChain(this.lastRead),[2,this.lastRead]})})},e.prototype.readFromChain=function(t){return o(this,void 0,void 0,function(){var e,n;return s(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}(j);!function(t){t[t.FAIL=0]="FAIL",t[t.SHORTEST=1]="SHORTEST",t[t.LONGEST=2]="LONGEST"}(M||(M={}));var J=function(t){function e(e,n){void 0===n&&(n=M.FAIL);var r=t.call(this)||this;return r.iterators=e,r.mismatchMode=n,r.count=0,r.currentPromise=null,r}return i(e,t),e.prototype.summary=function(){return"{TODO: fill in upstream of zip summaries} -> Zip"},e.prototype.nextState=function(t){return o(this,void 0,void 0,function(){function e(t){return t instanceof j?{value:t.next().then(function(t){return n++,t.done&&r++,t.value}),recurse:!1}:{value:null,recurse:!0}}var n,r,i;return s(this,function(o){switch(o.label){case 0:return[4,t];case 1:return o.sent(),n=0,r=0,[4,z(this.iterators,e)];case 2:if(i=o.sent(),n===r)return[2,{value:null,done:!0}];if(r>0)switch(this.mismatchMode){case M.FAIL:throw new Error("Zipped streams should have the same length. Mismatched at element "+this.count+".");case M.SHORTEST:return[2,{value:null,done:!0}];case M.LONGEST:}return this.count++,[2,{value:i,done:!1}]}})})},e.prototype.next=function(){return o(this,void 0,void 0,function(){return s(this,function(t){return this.currentPromise=this.nextState(this.currentPromise),[2,this.currentPromise]})})},e}(j),Y=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.bufferSize=n,r.buffer=new k(n),r}return i(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}(j),K=function(t){function e(e,r,i){var o=t.call(this,e,r)||this;return o.upstream=e,o.windowSize=r,o.upstreamExhausted=!1,o.random=y(i||n.util.now().toString()),o.lastRead=Promise.resolve({value:null,done:!1}),o}return i(e,t),e.prototype.next=function(){return o(this,void 0,void 0,function(){var t=this;return s(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 o(this,void 0,void 0,function(){var t,e;return s(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}(Y),$=function(){function t(){this.size=null}return t.prototype.batch=function(t,e){var r=this;void 0===e&&(e=!0);var i=this;return n.util.assert(t>0,function(){return"batchSize needs to be positive, but it is\n      "+t}),tt(function(){return o(r,void 0,void 0,function(){return s(this,function(n){switch(n.label){case 0:return[4,i.iterator()];case 1:return[2,n.sent().columnMajorBatch(t,e,rt)]}})})},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 tt(function(){return o(e,void 0,void 0,function(){var e,r;return s(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,r=this;return tt(function(){return o(e,void 0,void 0,function(){return s(this,function(e){switch(e.label){case 0:return[4,r.iterator()];case 1:return[2,e.sent().filter(function(e){return(0,n.tidy)(function(){return t(e)})})]}})})},this.size===1/0?1/0:null)},t.prototype.forEachAsync=function(t){return o(this,void 0,void 0,function(){return s(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 o(this,void 0,void 0,function(){return s(this,function(e){return(0,n.deprecationWarn)("dataset.forEach() is deprecated and will be removed. Please use dataset.forEachAsync() instead"),[2,this.forEachAsync(t)]})})},t.prototype.map=function(t){var e=this,r=this;return tt(function(){return o(e,void 0,void 0,function(){return s(this,function(e){switch(e.label){case 0:return[4,r.iterator()];case 1:return[2,e.sent().map(function(e){return(0,n.tidy)(function(){return t(e)})})]}})})},this.size)},t.prototype.mapAsync=function(t){var e=this,n=this;return tt(function(){return o(e,void 0,void 0,function(){return s(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 tt(function(){return o(e,void 0,void 0,function(){return s(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 tt(function(){return o(e,void 0,void 0,function(){var e=this;return s(this,function(r){return[2,I(D(function(){return o(e,void 0,void 0,function(){var t;return s(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 tt(function(){return o(e,void 0,void 0,function(){return s(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,r){var i=this;if(void 0===r&&(r=!0),null==t||t<0)throw null==this.size?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError("`Dataset.shuffle()` requires bufferSize to be specified.  If your data fits in main memory (for regular JS objects), and/or GPU memory (for `tf.Tensor`s), consider setting bufferSize to the dataset size ("+this.size+" elements)");var u=this,a=y(e||n.util.now().toString());return tt(function(){return o(i,void 0,void 0,function(){var e;return s(this,function(n){switch(n.label){case 0:return e=a.int32(),r&&(e+=a.int32()),[4,u.iterator()];case 1:return[2,n.sent().shuffle(t,e.toString())]}})})},this.size)},t.prototype.take=function(t){var e=this,n=this;return tt(function(){return o(e,void 0,void 0,function(){return s(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 o(this,void 0,void 0,function(){return s(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 o(this,void 0,void 0,function(){return s(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 tt(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 i(r,n),r.prototype.iterator=function(){return o(this,void 0,void 0,function(){return s(this,function(e){return[2,t()]})})},r}($))}function et(t){var e=this;return tt(function(){return o(e,void 0,void 0,function(){return s(this,function(e){return[2,N(t)]})})},t.length)}function nt(t){var e,n=this;if(!E(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 tt(function(){return o(n,void 0,void 0,function(){return s(this,function(e){switch(e.label){case 0:return[4,z(t,function(t){if(t instanceof $)return{value:t.iterator(),recurse:!1};if(E(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,O(e.sent(),M.SHORTEST)]}})})},e)}function rt(t){return null===t?null:S(t[0])?{value:it(t),recurse:!1}:{value:null,recurse:!0}}function it(t){if(0===t.length)throw new Error("Can't make a batch of zero elements.");return t[0]instanceof n.Tensor?(0,n.stack)(t):(0,n.tensor)(t)}exports.Dataset=$;var ot=function(t){function e(e){var n=t.call(this)||this;return n.input=e,n}return i(e,t),e.prototype.iterator=function(){return o(this,void 0,void 0,function(){var t;return s(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}($),st='"',ut=Symbol("out"),at=Symbol("field"),ct=Symbol("quote"),ht=Symbol("quoteafterquote"),lt=Symbol("quoteinquote"),ft=function(t){function e(e,r){var i=t.call(this)||this;return i.input=e,i.hasHeader=!0,i.fullColumnNames=null,i.columnNamesValidated=!1,i.columnConfigs=null,i.configuredColumnsOnly=!1,i.delimiter=",",i.delimWhitespace=!1,i.base=new ot(e),r||(r={}),i.hasHeader=!1!==r.hasHeader,i.fullColumnNames=r.columnNames,i.columnConfigs=r.columnConfigs,i.configuredColumnsOnly=r.configuredColumnsOnly,r.delimWhitespace?(n.util.assert(null==r.delimiter,function(){return"Delimiter should not be provided when delimWhitespace is true."}),i.delimWhitespace=!0,i.delimiter=" "):i.delimiter=r.delimiter?r.delimiter:",",i}return i(e,t),e.prototype.columnNames=function(){return o(this,void 0,void 0,function(){return s(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 o(this,void 0,void 0,function(){var t,e,r,i,o,u,a=this;return s(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&&n.util.assert(t.length===this.fullColumnNames.length,function(){return"The length of provided columnNames ("+a.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+t.length.toString()+")."}),this.fullColumnNames||(this.fullColumnNames=t),e=this.fullColumnNames.reduce(function(t,e){return t[e]=t[e]+1||1,t},{}),r=Object.keys(e).filter(function(t){return e[t]>1}),n.util.assert(0===r.length,function(){return"Duplicate column names found: "+r.toString()}),this.columnConfigs)for(i=0,o=Object.keys(this.columnConfigs);i<o.length;i++)if(u=o[i],-1===this.fullColumnNames.indexOf(u))throw new Error('The key "'+u+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").");return this.columnNamesValidated=!0,[2]}})})},e.prototype.maybeReadHeaderLine=function(){return o(this,void 0,void 0,function(){var t,e;return s(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 o(this,void 0,void 0,function(){var t,e=this;return s(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 o=this.fullColumnNames[i],s=this.columnConfigs?this.columnConfigs[o]:null;if(!this.configuredColumnsOnly||s){var u=e[i],a=null;if(""===u)if(s&&void 0!==s.default)a=s.default;else{if(s&&(s.required||s.isLabel))throw new Error("Required column "+o+" is empty in this line: "+t);a=void 0}else{var c=Number(u);if(isNaN(c))a=s&&"bool"===s.dtype?this.getBoolean(u):u;else if(s&&s.dtype)switch(s.dtype){case"float32":a=c;break;case"int32":a=Math.floor(c);break;case"bool":a=this.getBoolean(u);break;default:a=c}else a=c}s&&s.isLabel?r[o]=a:n[o]=a}}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,o=ut,s=0;s<i;s++)switch(o){case ut:switch(t.charAt(s)){case st:r=s+1,o=ct;break;case this.delimiter:if(r=s+1," "===this.delimiter&&this.delimWhitespace)break;n.push(""),o=ut;break;default:o=at,r=s}break;case at:switch(t.charAt(s)){case this.delimiter:n.push(t.substring(r,s)),o=ut,r=s+1}break;case ct:switch(t.charAt(s)){case st:o=ht}break;case ht:switch(t.charAt(s)){case this.delimiter:n.push(t.substring(r,s-1)),o=ut,r=s+1;break;case st:o=ct;break;default:o=lt}break;case lt:switch(t.charAt(s)){case st:o=ct}}if(o===ht?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}($),pt=function(t){function e(e){var n=t.call(this)||this;n.microphoneConfig=e,n.isClosed=!1,n.fftSize=e.fftSize||1024;var r=Math.log2(n.fftSize);if(n.fftSize<0||r<4||r>14||!Number.isInteger(r))throw new Error("Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got "+n.fftSize);if(n.numFrames=e.numFramesPerSpectrogram||43,n.sampleRateHz=e.sampleRateHz,n.columnTruncateLength=e.columnTruncateLength||n.fftSize,n.audioTrackConstraints=e.audioTrackConstraints,n.smoothingTimeConstant=e.smoothingTimeConstant||0,n.includeSpectrogram=!1!==e.includeSpectrogram,n.includeWaveform=!0===e.includeWaveform,!n.includeSpectrogram&&!n.includeWaveform)throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.");return n}return i(e,t),e.prototype.summary=function(){return"microphone"},e.create=function(t){return void 0===t&&(t={}),o(this,void 0,void 0,function(){var r;return s(this,function(i){switch(i.label){case 0:if((0,n.env)().get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");return[4,(r=new e(t)).start()];case 1:return i.sent(),[2,r]}})})},e.prototype.start=function(){return o(this,void 0,void 0,function(){var t,e,n,r;return s(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]}})})},e.prototype.next=function(){return o(this,void 0,void 0,function(){var t,e,n,r,i;return s(this,function(o){switch(o.label){case 0:return this.isClosed?[2,{value:null,done:!0}]:[4,this.getAudioData()];case 1:return n=o.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}]}})})},e.prototype.capture=function(){return o(this,void 0,void 0,function(){return s(this,function(t){switch(t.label){case 0:return[4,this.next()];case 1:return[2,t.sent().value]}})})},e.prototype.getAudioData=function(){return o(this,void 0,void 0,function(){var t,e,n,r=this;return s(this,function(i){return t=[],e=[],n=0,[2,new Promise(function(i){var o=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(o),i({freqDataQueue:t,timeDataQueue:e}))},r.fftSize/r.sampleRateHz*1e3)})]})})},e.prototype.stop=function(){this.isClosed||(this.isClosed=!0,this.analyser.disconnect(),this.audioContext.close(),null!=this.stream&&this.stream.getTracks().length>0&&this.stream.getTracks()[0].stop())},e.prototype.toArray=function(){throw new Error("Can not convert infinite audio stream to array.")},e.prototype.getSampleRate=function(){return this.sampleRateHz},e.prototype.flattenQueue=function(t){var e=t[0].length,n=new Float32Array(t.length*e);return t.forEach(function(t,r){return n.set(t,r*e)}),n},e.prototype.getTensorFromAudioDataArray=function(t,e){var r=new Float32Array(n.util.sizeFromShape(e));return r.set(t,r.length-t.length),(0,n.tensor)(r,e)},e}(j),dt=function(t){function e(e,r){var i=t.call(this)||this;if(i.webcamVideoElement=e,i.webcamConfig=r,i.isClosed=!0,i.resize=!1,i.needToResize())if(i.resize=!0,i.cropSize=[i.webcamConfig.resizeHeight,i.webcamConfig.resizeWidth],i.cropBoxInd=(0,n.tensor1d)([0],"int32"),i.webcamConfig.centerCrop){var o=1*i.webcamConfig.resizeWidth/i.webcamVideoElement.width,s=1*i.webcamConfig.resizeHeight/i.webcamVideoElement.height,u=(1-o)/2,a=(1-s)/2,c=u+o,h=s+a;i.cropBox=(0,n.tensor2d)([a,u,h,c],[1,4])}else i.cropBox=(0,n.tensor2d)([0,0,1,1],[1,4]);return i}return i(e,t),e.prototype.summary=function(){return"webcam"},e.create=function(t,r){return void 0===r&&(r={}),o(this,void 0,void 0,function(){var i;return s(this,function(o){switch(o.label){case 0:if((0,n.env)().get("IS_NODE"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!t){if(t=document.createElement("video"),!r.resizeWidth||!r.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");t.width=r.resizeWidth,t.height=r.resizeHeight}return[4,(i=new e(t,r)).start()];case 1:return o.sent(),[2,i]}})})},e.prototype.start=function(){return o(this,void 0,void 0,function(){var t,e,r=this;return s(this,function(i){switch(i.label){case 0:this.webcamConfig.facingMode&&n.util.assert("user"===this.webcamConfig.facingMode||"environment"===this.webcamConfig.facingMode,function(){return"Invalid webcam facing mode: "+r.webcamConfig.facingMode+". Please provide 'user' or 'environment'"}),i.label=1;case 1:return i.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=i.sent(),[3,4];case 3:throw(e=i.sent()).message="Error thrown while initializing video stream: "+e.message,e;case 4:if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream}catch(t){console.log(t),this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}return this.webcamVideoElement.play(),this.isClosed=!1,[2,new Promise(function(t){r.webcamVideoElement.onloadedmetadata=function(){t()}})]}})})},e.prototype.next=function(){return o(this,void 0,void 0,function(){var t;return s(this,function(e){if(this.isClosed)return[2,{value:null,done:!0}];try{t=n.browser.fromPixels(this.webcamVideoElement)}catch(t){throw new Error("Error thrown converting video to pixels: "+JSON.stringify(t))}if(!this.resize)return[2,{value:t,done:!1}];try{return[2,{value:this.cropAndResizeFrame(t),done:!1}]}catch(t){throw new Error("Error thrown cropping the video: "+t.message)}finally{t.dispose()}return[2]})})},e.prototype.needToResize=function(){return!(!this.webcamConfig.resizeWidth||!this.webcamConfig.resizeHeight||this.webcamVideoElement.width===this.webcamConfig.resizeWidth&&this.webcamVideoElement.height===this.webcamConfig.resizeHeight)},e.prototype.cropAndResizeFrame=function(t){var e=this;return(0,n.tidy)(function(){var r,i=t.toFloat().expandDims(0),o=(r=n.image.cropAndResize(i,e.cropBox,e.cropBoxInd,e.cropSize,"bilinear")).shape;return r.reshape(o.slice(1))})},e.prototype.capture=function(){return o(this,void 0,void 0,function(){return s(this,function(t){switch(t.label){case 0:return[4,this.next()];case 1:return[2,t.sent().value]}})})},e.prototype.stop=function(){this.stream.getTracks().forEach(function(t){return t.stop()});try{this.webcamVideoElement.srcObject=null}catch(t){console.log(t),this.webcamVideoElement.src=null}this.isClosed=!0},e.prototype.toArray=function(){throw new Error("Can not convert infinite video stream to array.")},e}(j),vt=function(){},mt=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return i(e,t),e.prototype.split=function(t){return new yt(this,t)},e}(j),yt=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.impl=new wt(e,n),r}return i(e,t),e.prototype.summary=function(){return this.impl.summary()},e.prototype.next=function(){return o(this,void 0,void 0,function(){return s(this,function(t){return[2,this.impl.next()]})})},e}(mt),wt=function(t){function e(e,n){var r=t.call(this)||this;return r.upstream=e,r.separator=n,r.carryover="",r}return i(e,t),e.prototype.summary=function(){return this.upstream.summary()+" -> Split('"+this.separator+"')"},e.prototype.pump=function(){return o(this,void 0,void 0,function(){var t,e,n,r,i;return s(this,function(o){switch(o.label){case 0:return[4,this.upstream.next()];case 1:if((t=o.sent()).done)return""===this.carryover?[2,!1]:(this.outputQueue.push(this.carryover),this.carryover="",[2,!0]);for((e=t.value.split(this.separator))[0]=this.carryover+e[0],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}(X),bt=function(t){function e(){return null!==t&&t.apply(this,arguments)||this}return i(e,t),e.prototype.decodeUTF8=function(){return new gt(this)},e}(j),gt=function(t){function e(e){var n=t.call(this)||this;return n.upstream=e,n.impl=new xt(e),n}return i(e,t),e.prototype.summary=function(){return this.impl.summary()},e.prototype.next=function(){return o(this,void 0,void 0,function(){return s(this,function(t){return[2,this.impl.next()]})})},e}(mt),xt=function(t){function r(e){var r=t.call(this)||this;if(r.upstream=e,(0,n.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 i(r,t),r.prototype.summary=function(){return this.upstream.summary()+" -> Utf8"},r.prototype.pump=function(){return o(this,void 0,void 0,function(){var t,r,i;return s(this,function(o){switch(o.label){case 0:return[4,this.upstream.next()];case 1:return(t=o.sent()).done?[2,!1]:(r=t.value,i=(0,n.env)().get("IS_BROWSER")?this.decoder.decode(r,{stream:!0}):this.decoder.write(e.from(r.buffer)),this.outputQueue.push(i),[2,!0])}})})},r}(X),Ct=function(t){function e(e,r){void 0===r&&(r={});var i=t.call(this)||this;return i.file=e,i.options=r,n.util.assert(e instanceof Uint8Array||!!(0,n.env)().get("IS_BROWSER")&&(e instanceof File||e 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 i(e,t),e.prototype.summary=function(){return"FileChunks "+this.file},e.prototype.next=function(){return o(this,void 0,void 0,function(){var t,e,n=this;return s(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 o=n.file.slice(n.offset,r);i.readAsArrayBuffer(o)}n.offset=r}),e={},[4,t]);case 1:return[2,(e.value=r.sent(),e.done=!1,e)]}})})},e}(bt);function zt(t,e){return void 0===e&&(e={}),o(this,void 0,void 0,function(){var r,i,o,u,a;return s(this,function(s){switch(s.label){case 0:return"string"==typeof t?r=t:(r=t.url,i=Et(t)),[4,n.util.fetch(r,i)];case 1:return(o=s.sent()).ok?(a=Uint8Array.bind,[4,o.arrayBuffer()]):[3,3];case 2:return u=new(a.apply(Uint8Array,[void 0,s.sent()])),[2,new Ct(u,e)];case 3:throw new Error(o.statusText)}})})}exports.CSVDataset=ft,exports.TextLineDataset=ot;var Et=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 St(t){return"string"==typeof t&&"file://"===t.substr(0,7)}var At=function(t){function e(e,n){void 0===n&&(n={});var r=t.call(this)||this;return r.input=e,r.options=n,r}return i(e,t),e.prototype.iterator=function(){return o(this,void 0,void 0,function(){var t;return s(this,function(e){return St(this.input)&&(0,n.env)().get("IS_NODE")&&(t=require("fs"),this.input=t.readFileSync(this.input.substr(7))),[2,new Ct(this.input,this.options)]})})},e}(vt),Rt=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 i(e,t),e.prototype.iterator=function(){return o(this,void 0,void 0,function(){return s(this,function(t){return St(this.url)?[2,new At(this.url,this.fileOptions).iterator()]:[2,zt(this.url,this.fileOptions)]})})},e}(vt);function Tt(t,e){return void 0===e&&(e={}),new ft(new Rt(t),e)}function kt(t){var e=this,n=D(t);return tt(function(){return o(e,void 0,void 0,function(){return s(this,function(t){return[2,n]})})})}function Ft(t){var e=this;return tt(function(){return o(e,void 0,void 0,function(){var e;return s(this,function(n){switch(n.label){case 0:return[4,t()];case 1:return e=n.sent(),[2,D(function(){return e.next()})]}})})})}function Nt(t,e){return o(this,void 0,void 0,function(){return s(this,function(n){return[2,dt.create(t,e)]})})}function Dt(t){return o(this,void 0,void 0,function(){return s(this,function(e){return[2,pt.create(t)]})})}exports.URLDataSource=Rt,exports.FileDataSource=At;var It="1.3.2";exports.version_data=It;
  },{"@tensorflow/tfjs-core":"PqBP","crypto":"sC8V","string_decoder":"sC8V","fs":"sC8V","buffer":"aMB2"}],"cHV2":[function(require,module,exports) {
  "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e={version:!0,data:!0};exports.data=exports.version=void 0;var r=require("@tensorflow/tfjs-core");Object.keys(r).forEach(function(t){"default"!==t&&"__esModule"!==t&&(Object.prototype.hasOwnProperty.call(e,t)||Object.defineProperty(exports,t,{enumerable:!0,get:function(){return r[t]}}))});var t=require("@tensorflow/tfjs-layers");Object.keys(t).forEach(function(r){"default"!==r&&"__esModule"!==r&&(Object.prototype.hasOwnProperty.call(e,r)||Object.defineProperty(exports,r,{enumerable:!0,get:function(){return t[r]}}))});var o=require("@tensorflow/tfjs-converter");Object.keys(o).forEach(function(r){"default"!==r&&"__esModule"!==r&&(Object.prototype.hasOwnProperty.call(e,r)||Object.defineProperty(exports,r,{enumerable:!0,get:function(){return o[r]}}))});var n=s(require("@tensorflow/tfjs-data"));function a(){if("function"!=typeof WeakMap)return null;var e=new WeakMap;return a=function(){return e},e}function s(e){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var r=a();if(r&&r.has(e))return r.get(e);var t={},o=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var n in e)if(Object.prototype.hasOwnProperty.call(e,n)){var s=o?Object.getOwnPropertyDescriptor(e,n):null;s&&(s.get||s.set)?Object.defineProperty(t,n,s):t[n]=e[n]}return t.default=e,r&&r.set(e,t),t}exports.data=n;var f="1.3.2",c={"tfjs-core":r.version_core,"tfjs-data":n.version_data,"tfjs-layers":t.version_layers,"tfjs-converter":o.version_converter,tfjs:f};exports.version=c;
  },{"@tensorflow/tfjs-core":"PqBP","@tensorflow/tfjs-layers":"KLDv","@tensorflow/tfjs-converter":"rGPK","@tensorflow/tfjs-data":"ewAU"}],"FOZT":[function(require,module,exports) {
  "use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.isMobile=y,exports.updateTryResNetButtonDatGuiCss=h,exports.toggleLoadingUI=x,exports.drawPoint=P,exports.drawSegment=w,exports.drawCircle=b,exports.getWrists=v,exports.drawWrists=N,exports.angleBetween=B,exports.renderToCanvas=I,exports.renderImageToCanvas=M,exports.tryResNetButtonText=exports.tryResNetButtonName=void 0;var t=o(require("@tensorflow-models/posenet")),e=o(require("@tensorflow/tfjs"));function n(){if("function"!=typeof WeakMap)return null;var t=new WeakMap;return n=function(){return t},t}function o(t){if(t&&t.__esModule)return t;if(null===t||"object"!=typeof t&&"function"!=typeof t)return{default:t};var e=n();if(e&&e.has(t))return e.get(t);var o={},r=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var i in t)if(Object.prototype.hasOwnProperty.call(t,i)){var s=r?Object.getOwnPropertyDescriptor(t,i):null;s&&(s.get||s.set)?Object.defineProperty(o,i,s):o[i]=t[i]}return o.default=t,e&&e.set(t,o),o}const r="aqua",i="red",s=2,a="tryResNetButton";exports.tryResNetButtonName="tryResNetButton";const u="[New] Try ResNet50";exports.tryResNetButtonText=u;const l="width:100%;text-decoration:underline;",c="background:#e61d5f;",p=["leftWrist","rightWrist"];function d(){return/Android/i.test(navigator.userAgent)}function f(){return/iPhone|iPad|iPod/i.test(navigator.userAgent)}function y(){return d()||f()}function g(t,e,n=""){for(var o=document.getElementsByClassName("property-name"),r=0;r<o.length;r++){(o[r].textContent||o[r].innerText)==t&&(o[r].parentNode.parentNode.style=e,""!==n&&(o[r].style=n))}}function h(){g(u,c,l)}function x(t,e="loading",n="main"){t?(document.getElementById(e).style.display="block",document.getElementById(n).style.display="none"):(document.getElementById(e).style.display="none",document.getElementById(n).style.display="block")}function m({y:t,x:e}){return[t,e]}function P(t,e,n,o,r){t.beginPath(),t.arc(n,e,o,0,2*Math.PI),t.fillStyle=r,t.fill()}function w([t,e],[n,o],r,i,a){a.beginPath(),a.moveTo(e*i,t*i),a.lineTo(o*i,n*i),a.lineWidth=s,a.strokeStyle=r,a.stroke()}function b([t,e],n,o,r){r.beginPath(),r.arc(e,t,n,0,2*Math.PI),r.lineWidth=s,r.strokeStyle=o,r.stroke()}function v(t,e){let n=[];for(let o=0;o<t.length;o++){const r=t[o];!p.includes(r.part)||r.score<e||n.push(r)}return n}function N(t,e,n=1){if(t.length>=2){const o=t[0],i=t[1],s=o.position.x,a=o.position.y,u=i.position.x,l=i.position.y,c=(a+l)/2,p=(s+u)/2;P(e,a*n,s*n,3,r),P(e,l*n,u*n,3,r),w(m(t[0].position),m(t[1].position),r,n,e);const d=s-u,f=a-l,y=Math.hypot(d,f),g=y/2;w([c,p],[-(f/y)*g,d/y*g],r,n,e),b([c,p],g,r,e)}}function B(t){if(t.length<2)return 0;const e=t[0],n=t[1],o=e.position.x,r=e.position.y,i=n.position.x;var s=n.position.y-r,a=i-o,u=Math.atan2(s,a);return u*=-180/Math.PI}async function I(t,e){const[n,o]=t.shape,r=new ImageData(o,n),i=await t.data();for(let s=0;s<n*o;++s){const t=4*s,e=3*s;r.data[t+0]=i[e+0],r.data[t+1]=i[e+1],r.data[t+2]=i[e+2],r.data[t+3]=255}e.putImageData(r,0,0)}function M(t,e,n){n.width=e[0],n.height=e[1],n.getContext("2d").drawImage(t,0,0)}function k(t,e,n,o){const r=e.buffer().values;for(let i=0;i<r.length;i+=2){const e=r[i],s=r[i+1];0!==s&&0!==e&&(t.beginPath(),t.arc(s,e,n,0,2*Math.PI),t.fillStyle=o,t.fill())}}
  },{"@tensorflow-models/posenet":"yqJr","@tensorflow/tfjs":"cHV2"}],"Focm":[function(require,module,exports) {
  "use strict";var t=a(require("@tensorflow-models/posenet")),e=o(require("dat.gui")),i=o(require("stats.js")),n=require("./utils");function o(t){return t&&t.__esModule?t:{default:t}}function s(){if("function"!=typeof WeakMap)return null;var t=new WeakMap;return s=function(){return t},t}function a(t){if(t&&t.__esModule)return t;if(null===t||"object"!=typeof t&&"function"!=typeof t)return{default:t};var e=s();if(e&&e.has(t))return e.get(t);var i={},n=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var o in t)if(Object.prototype.hasOwnProperty.call(t,o)){var a=n?Object.getOwnPropertyDescriptor(t,o):null;a&&(a.get||a.set)?Object.defineProperty(i,o,a):i[o]=t[o]}return i.default=t,e&&e.set(t,i),i}let r;const h=257,d=200,l=new i.default;var c=!1;const u=1,y=1,f=16,m=250,w=25;var p=!1,v=!1;const g={algorithm:"single-pose",input:{architecture:"ResNet50",outputStride:16,inputResolution:250,multiplier:1,quantBytes:1},singlePoseDetection:{minPoseConfidence:.1,minPartConfidence:.5},multiPoseDetection:{maxPoseDetections:5,minPoseConfidence:.15,minPartConfidence:.1,nmsRadius:30},output:{showVideo:!0,showSkeleton:!0,showPoints:!0,showBoundingBox:!1},net:null};function M(t,e){const i=document.getElementById("output"),o=i.getContext("2d"),s=!0;i.width=h,i.height=d,async function i(){l.begin();let a,r,c=[];const u=await e.estimatePoses(t,{flipHorizontal:s,decodingMethod:"single-person"});c=c.concat(u),a=+g.singlePoseDetection.minPoseConfidence,r=+g.singlePoseDetection.minPartConfidence,o.clearRect(0,0,h,d),g.output.showVideo&&(o.save(),o.scale(-1,1),o.translate(-h,0),o.drawImage(t,0,0,h,d),o.restore()),c.forEach(({score:t,keypoints:e})=>{if(t>=a&&g.output.showPoints){let t=[];if((t=(0,n.getWrists)(e,r)).length>=2){(0,n.drawWrists)(t,o);let e=0;(e=(0,n.angleBetween)(t))<-w?(v=!1,p=!0):p&&(p=!1),e>w?(v=!0,p=!1):v&&(v=!1)}}}),l.end(),requestAnimationFrame(i)}()}async function E(){const e=await t.load({architecture:g.input.architecture,outputStride:g.input.outputStride,inputResolution:g.input.inputResolution,multiplier:g.input.multiplier,quantBytes:g.input.quantBytes});let i;try{M(i=await I(),e),document.getElementById("ldc").innerHTML="",document.getElementById("ldc").style.display="none",document.getElementById("playBtn").innerHTML="PLAY"}catch(n){let t=document.getElementById("info");throw t.textContent="this browser does not support video capture,or this device does not have a camera",t.style.display="block",n}c=!0}async function I(){const t=await P();return t.play(),t}async function P(){if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new Error("Browser API navigator.mediaDevices.getUserMedia not available");const t=document.getElementById("video");t.width=h,t.height=d;const e=(0,n.isMobile)(),i=await navigator.mediaDevices.getUserMedia({audio:!1,video:{facingMode:"user",width:e?void 0:h,height:e?void 0:d}});return console.log("before setup video"),t.srcObject=i,console.log("after setup video"),new Promise(e=>{t.onloadedmetadata=(()=>{e(t)})})}!function(){var t=window.innerWidth||360,e=window.innerHeight||560;if(e>t){var i=e;e=t,t=i,document.getElementById("mainContainer").style.transform="translateX("+e+"px) rotate(90deg)"}document.getElementById("mainContainer").style.width=t+"px",document.getElementById("mainContainer").style.height=e+"px",document.getElementById("city").style.height=.3*e+"px",document.getElementById("city").style.width=t+"px";var n=document.getElementById("myCanvas");n.height=e,n.width=t;var o=n.getContext("2d");function s(){var i=5*t/36,s=(t-i)/2,a=s/(e-(e-.7*e)),r=0,h=document.getElementById("score");function d(t){r+=t,h.textContent=r}d(0);var l=[],c=.8,u=20,y=e*(1-c)/(2.25*(1-Math.pow(c,u))),f=y,m=.7*e,w=1,g=26-w,M=Math.pow(c,u)/(1-c),E=e-m,I=20*e/36/s;function P(t,e,i,n){this.src=b[t],this.src2=b[e],this.y=i,this.x=0,this.h=0,this.w=0,this.dy=.01,this.r=1.009,this.left=n}function B(t){return document.getElementById(t)}P.prototype.draw=function(){this.y+=this.dy,this.dy*=this.r,this.x=(e-this.y)*a-this.w-this.w*this.left,this.h=(s-this.x-this.w*this.left)*I,this.w=2*this.h/3,o.drawImage(this.src,this.x,this.y-this.h,this.w,this.h),o.drawImage(this.src2,t-this.x-this.w,this.y-this.h,this.w,this.h),this.y>=e&&(this.y=E,this.h=0,this.w=0,this.left=3*Math.random(),this.dy=.5)};for(var b=[B("t1"),B("t2"),B("t3"),B("t4")],x=[],C=0;C<.7*e/50-2;C++)x.push(new P(Math.floor(4*Math.random()),Math.floor(4*Math.random()),E+50*C,2));var T=2*s/m,k=t>560?120:90,D=2*k/3;function L(t,e,i){this.src=O[t],this.y=e,this.x=0,this.h=0,this.w=0,this.dy=.5,this.lane=i}L.prototype.draw=function(){this.dy*=1.01,this.y+=this.dy,this.x=T/2*(e-this.y)+(t-T*(e-this.y))*this.lane/8,this.w=k-k*T*(e-this.y)/t,this.h=1.7*this.w/3,o.drawImage(this.src,this.x,this.y-this.h,this.w,this.h),this.y>=e-20&&Math.abs(this.x-_)<=D&&Math.abs(this.y-e+D)<=D&&(clearInterval(Y),setTimeout(function(){document.getElementById("mainContainer").style.display="none",document.getElementById("startPage").style.display="block"},1e3)),this.y>=e+100&&(this.y=E,this.h=0,this.w=0,this.left=3*Math.random(),this.dy=.5,this.lane=1+5*Math.random())};var O=[B("c1"),B("c1"),B("c1")],j=[];for(C=0;C<(.7*e+100)/100;C++)j.push(new L(Math.floor(3*Math.random()),E+100*C,1));var q=t>560?75:60;function R(t,e){this.src=S,this.y=t,this.x=0,this.h=0,this.w=0,this.dy=.5,this.lane=e}R.prototype.draw=function(){this.dy*=1.01,this.y+=this.dy,this.x=T/2*(e-this.y)+(t-T*(e-this.y))*this.lane/8,this.w=q-q*T*(e-this.y)/t,this.h=this.w,o.drawImage(this.src,this.x,this.y-this.h,this.w,this.h),this.y>=e-20&&Math.abs(this.x-_)<=q&&Math.abs(this.y-e+q)<=q&&(this.y=E,this.h=0,this.w=0,this.left=3*Math.random(),this.dy=.5,this.lane=Math.floor(1+5*Math.random()),d(1)),this.y>=e+100&&(this.y=E,this.h=0,this.w=0,this.left=3*Math.random(),this.dy=.5,this.lane=Math.floor(1+5*Math.random()))};var S=B("cn"),W=[];for(C=0;C<(.7*e+100)/50;C++)W.push(new R(E+50*C,6));function H(t,e){t=u-t-1;var i=E+f*M*(Math.pow(1/c,t)-1),n=s-a*(i-E),o=i,r=n+w+(i-E)*g/m,h=i+f*M*(Math.pow(1/c,t+1)-1),d=s-a*(h-E);return[n,i,r,o,d+w+(h-E)*g/m,h,d,h]}for(C=0;C<u;C++)l.push(H(C)),l[C][8]=C%2==0?"#000":"#fff";var _=(t-k)/2,A=B("c1"),U=3*t/560;var V=0,Y=setInterval(function(){try{o.clearRect(0,0,t,e),(f+=.5)*M*(Math.pow(1/c,u-1)-1)>=m&&(f=y,V++);for(var n=0;n<u;n++)l[n]=H(n),l[n][8]=V%2==0?n%2==0?"#000":"#fff":n%2==1?"#000":"#fff";!function(){o.beginPath(),o.moveTo((t-i)/2,E),o.lineTo((t-i)/2+i,E),o.lineTo(t,e),o.lineTo(0,e),o.fillStyle="#555",o.fill(),o.closePath();for(var n=0;n<u;n++)o.beginPath(),o.moveTo(l[n][0],l[n][1]),o.lineTo(l[n][2],l[n][3]),o.lineTo(l[n][4],l[n][5]),o.lineTo(l[n][6],l[n][7]),o.lineTo(l[n][0],l[n][1]),o.lineWidth=2,o.fillStyle=l[n][8],o.fill(),o.closePath(),o.beginPath(),o.moveTo(t-l[n][0],l[n][1]),o.lineTo(t-l[n][2],l[n][3]),o.lineTo(t-l[n][4],l[n][5]),o.lineTo(t-l[n][6],l[n][7]),o.lineTo(t-l[n][0],l[n][1]),o.lineWidth=2,o.fillStyle=l[n][8],o.fill(),o.closePath()}();for(n=0;n<x.length;n++)x[n].draw();for(n=0;n<W.length;n++)W[n].draw();for(n=0;n<j.length;n++)j[n].draw();p&&_+k+50<t&&(_+=U),v&&_-50>0&&(_-=U),o.drawImage(A,_,e-D,k,D)}catch(s){}},10);function z(t){t.preventDefault();var i=t.changedTouches[0];parseInt(i.clientY)>e/2?p=!0:v=!0}function F(){p=!1,v=!1}function G(t){t.preventDefault();var e=t.keyCode;39===e?(v=!1,p=!0):37===e&&(p=!1,v=!0)}function N(t){var e=t.keyCode;39===e?p=!1:37===e&&(v=!1)}function X(e){var i=e.accelerationIncludingGravity.y;i>0?_+k+50<t&&(_+=i*U):_-50>0&&(_+=i*U)}n.removeEventListener("touchstart",z),n.removeEventListener("touchend",F),n.addEventListener("touchstart",z),n.addEventListener("touchend",F),document.body.removeEventListener("keydown",G),document.body.removeEventListener("keyup",N),document.body.addEventListener("keydown",G),document.body.addEventListener("keyup",N),window.DeviceMotionEvent&&(window.removeEventListener("devicemotion",X),window.addEventListener("devicemotion",X,!1))}r=function(){c&&(document.getElementById("startPage").style.display="none",document.getElementById("mainContainer").style.display="block",s())}}(),document.getElementById("body").onload=E,document.getElementById("playBtn").onclick=r;
  },{"@tensorflow-models/posenet":"yqJr","dat.gui":"ArXC","stats.js":"ZsAW","./utils":"FOZT"}]},{},["Focm"], null)
  //# sourceMappingURL=/CarDrivingPoseNetController.34fd5844.js.map