UNPKG

231 kBJavaScriptView Raw
1/**
2 * @license
3 * Copyright 2021 Google LLC. All Rights Reserved.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 * =============================================================================
16 */
17!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e=e||self).tf=e.tf||{})}(this,(function(e){"use strict";class t{refCount(e){return n("refCount")}incRef(e){return n("incRef")}timerAvailable(){return!0}time(e){return n("time")}read(e){return n("read")}readSync(e){return n("readSync")}numDataIds(){return n("numDataIds")}disposeData(e,t){return n("disposeData")}write(e,t,r){return n("write")}move(e,t,r,s,o){return n("move")}memory(){return n("memory")}floatPrecision(){return n("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return n("dispose")}}function n(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function r(e){let t=e.length,n=0,r=0;for(;t>0;)r=Math.random()*t|0,t--,n=e[t],e[t]=e[r],e[r]=n}function s(e,t,n){return Math.max(e,Math.min(t,n))}function o(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function a(e,t,n=""){o(c(e,t),()=>n+` Shapes ${e} and ${t} must match`)}function i(e){o(null!=e,()=>"The input to the tensor constructor must be a non-null value.")}function l(e,t=[],n=!1){if(null==t&&(t=[]),Array.isArray(e)||w(e)&&!n)for(let r=0;r<e.length;++r)l(e[r],t,n);else t.push(e);return t}function u(e){if(0===e.length)return 1;let t=e[0];for(let n=1;n<e.length;n++)t*=e[n];return t}function c(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function h(e){return e%1==0}function d(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function p(e,t){const n=t.length;return o((e=null==e?t.map((e,t)=>t):[].concat(e)).every(e=>e>=-n&&e<n),()=>`All values in axis param must be in range [-${n}, ${n}) but got axis `+e),o(e.every(e=>h(e)),()=>"All values in axis param must be integers but got axis "+e),e.map(e=>e<0?n+e:e)}function f(e,t){const n=[],r=[],s=null!=t&&Array.isArray(t)&&0===t.length,o=null==t||s?null:p(t,e).sort();let a=0;for(let t=0;t<e.length;++t){if(null!=o){if(o[a]===t&&1!==e[t])throw new Error(`Can't squeeze axis ${t} since its dim '${e[t]}' is not 1`);(null==o[a]||o[a]>t)&&1===e[t]&&(n.push(e[t]),r.push(t)),o[a]<=t&&a++}1!==e[t]&&(n.push(e[t]),r.push(t))}return{newShape:n,keptDims:r}}function m(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else{if("bool"!==e)throw new Error("Unknown data type "+e);n=new Uint8Array(t)}return n}function g(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else if("bool"===e)n=new Uint8Array(t);else{if("string"!==e)throw new Error("Unknown data type "+e);n=new Array(t)}return n}function b(e,t){for(let n=0;n<e.length;n++){const r=e[n];if(isNaN(r)||!isFinite(r))throw Error(`A tensor of type ${t} being uploaded contains ${r}.`)}}function y(e){return"bool"===e||"complex64"===e||"float32"===e||"int32"===e||"string"===e}function w(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array}function k(e){if("float32"===e||"int32"===e)return 4;if("complex64"===e)return 8;if("bool"===e)return 1;throw new Error("Unknown dtype "+e)}function v(e){if(null==e)return 0;let t=0;return e.forEach(e=>t+=e.length),t}function x(e){return"string"==typeof e||e instanceof String}function E(e){return"boolean"==typeof e}function S(e){return"number"==typeof e}function A(e){return Array.isArray(e)?A(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array?"int32":S(e)?"float32":x(e)?"string":E(e)?"bool":"float32"}function _(e){return!!(e&&e.constructor&&e.call&&e.apply)}function N(e,t){for(let n=t;n<e;++n)if(e%n==0)return n;return e}function I(e){const t=e.length;if(t<2)return[];const n=new Array(t-1);n[t-2]=e[t-1];for(let r=t-3;r>=0;--r)n[r]=n[r+1]*e[r+1];return n}function M(e,t,n=!1){if(0===e.length)return t[0];const r=e.reduce((e,t)=>e*t)*(n?2:1);if(0===r)return[];if(r!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return function e(t,n,r,s=!1){const o=new Array;if(1===n.length){const e=n[0]*(s?2:1);for(let n=0;n<e;n++)o[n]=r[t+n]}else{const a=n[0],i=n.slice(1),l=i.reduce((e,t)=>e*t)*(s?2:1);for(let n=0;n<a;n++)o[n]=e(t+n*l,i,r,s)}return o}(0,e,t,n)}function $(e,t){const n=T(e,t);for(let e=0;e<n.length;e++)n[e]=1;return n}function T(e,t){if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t)return new Uint8Array(e);throw new Error("Unknown data type "+t)}function D(e){e.forEach(t=>{o(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function R(e){return e&&e.then&&"function"==typeof e.then}class B{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=F,this.populateURLFlags()}setPlatform(e,t){null!=this.platform&&console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${t}.`),this.platformName=e,this.platform=t}registerFlag(e,t,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},null!=this.urlFlags[e]){const t=this.urlFlags[e];console.warn(`Setting feature override from URL ${e}: ${t}.`),this.set(e,t)}}async getAsync(e){return e in this.flags||(this.flags[e]=await this.evaluateFlag(e)),this.flags[e]}get(e){if(e in this.flags)return this.flags[e];const t=this.evaluateFlag(e);if(R(t))throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(null==this.flagRegistry[e])throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,null!=this.flagRegistry[e].setHook&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(null==this.flagRegistry[e])throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(void 0===this.global||void 0===this.global.location||void 0===this.global.location.search)return;const e=this.getQueryParams(this.global.location.search);if("tfjsflags"in e){e.tfjsflags.split(",").forEach(e=>{const[t,n]=e.split(":");this.urlFlags[t]=function(e,t){if("true"===(t=t.toLowerCase())||"false"===t)return"true"===t;if(""+ +t===t)return+t;throw new Error(`Could not parse value flag value ${t} for flag ${e}.`)}(t,n)})}}}function F(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(e,...n)=>(function(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}(t,n[0],n[1]),n.join("="))),t}function C(){return e.ENV}let P;function L(){if(null==P){let e;if("undefined"!=typeof window)e=window;else if("undefined"!=typeof global)e=global;else if("undefined"!=typeof process)e=process;else{if("undefined"==typeof self)throw new Error("Could not find a global object");e=self}P=e}return P}function O(e,t){const n=function(){const e=L();return null==e._tfGlobals&&(e._tfGlobals=new Map),e._tfGlobals}();if(n.has(e))return n.get(e);{const r=t();return n.set(e,r),n.get(e)}}e.ENV=null;const z=O("kernelRegistry",()=>new Map),q=O("gradRegistry",()=>new Map);function K(e,t){const n=V(e,t);return z.get(n)}function W(e){return q.get(e)}function U(e){const t=z.entries(),n=[];for(;;){const{done:r,value:s}=t.next();if(r)break;const[o,a]=s,[i]=o.split("_");i===e&&n.push(a)}return n}function G(e){const{kernelName:t,backendName:n}=e,r=V(t,n);z.has(r)&&console.warn(`The kernel '${t}' for backend '${n}' is already registered`),z.set(r,e)}function V(e,t){return`${t}_${e}`}var H=Z,j=null;try{j=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(e){}function Z(e,t,n){this.low=0|e,this.high=0|t,this.unsigned=!!n}function J(e){return!0===(e&&e.__isLong__)}Z.prototype.__isLong__,Object.defineProperty(Z.prototype,"__isLong__",{value:!0}),Z.isLong=J;var Y={},X={};function Q(e,t){var n,r,s;return t?(s=0<=(e>>>=0)&&e<256)&&(r=X[e])?r:(n=te(e,(0|e)<0?-1:0,!0),s&&(X[e]=n),n):(s=-128<=(e|=0)&&e<128)&&(r=Y[e])?r:(n=te(e,e<0?-1:0,!1),s&&(Y[e]=n),n)}function ee(e,t){if(isNaN(e))return t?ce:ue;if(t){if(e<0)return ce;if(e>=ae)return me}else{if(e<=-ie)return ge;if(e+1>=ie)return fe}return e<0?ee(-e,t).neg():te(e%oe|0,e/oe|0,t)}function te(e,t,n){return new Z(e,t,n)}Z.fromInt=Q,Z.fromNumber=ee,Z.fromBits=te;var ne=Math.pow;function re(e,t,n){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return ue;if("number"==typeof t?(n=t,t=!1):t=!!t,(n=n||10)<2||36<n)throw RangeError("radix");var r;if((r=e.indexOf("-"))>0)throw Error("interior hyphen");if(0===r)return re(e.substring(1),t,n).neg();for(var s=ee(ne(n,8)),o=ue,a=0;a<e.length;a+=8){var i=Math.min(8,e.length-a),l=parseInt(e.substring(a,a+i),n);if(i<8){var u=ee(ne(n,i));o=o.mul(u).add(ee(l))}else o=(o=o.mul(s)).add(ee(l))}return o.unsigned=t,o}function se(e,t){return"number"==typeof e?ee(e,t):"string"==typeof e?re(e,t):te(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}Z.fromString=re,Z.fromValue=se;var oe=4294967296,ae=oe*oe,ie=ae/2,le=Q(1<<24),ue=Q(0);Z.ZERO=ue;var ce=Q(0,!0);Z.UZERO=ce;var he=Q(1);Z.ONE=he;var de=Q(1,!0);Z.UONE=de;var pe=Q(-1);Z.NEG_ONE=pe;var fe=te(-1,2147483647,!1);Z.MAX_VALUE=fe;var me=te(-1,-1,!0);Z.MAX_UNSIGNED_VALUE=me;var ge=te(0,-2147483648,!1);Z.MIN_VALUE=ge;var be=Z.prototype;be.toInt=function(){return this.unsigned?this.low>>>0:this.low},be.toNumber=function(){return this.unsigned?(this.high>>>0)*oe+(this.low>>>0):this.high*oe+(this.low>>>0)},be.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(ge)){var t=ee(e),n=this.div(t),r=n.mul(t).sub(this);return n.toString(e)+r.toInt().toString(e)}return"-"+this.neg().toString(e)}for(var s=ee(ne(e,6),this.unsigned),o=this,a="";;){var i=o.div(s),l=(o.sub(i.mul(s)).toInt()>>>0).toString(e);if((o=i).isZero())return l+a;for(;l.length<6;)l="0"+l;a=""+l+a}},be.getHighBits=function(){return this.high},be.getHighBitsUnsigned=function(){return this.high>>>0},be.getLowBits=function(){return this.low},be.getLowBitsUnsigned=function(){return this.low>>>0},be.getNumBitsAbs=function(){if(this.isNegative())return this.eq(ge)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&0==(e&1<<t);t--);return 0!=this.high?t+33:t+1},be.isZero=function(){return 0===this.high&&0===this.low},be.eqz=be.isZero,be.isNegative=function(){return!this.unsigned&&this.high<0},be.isPositive=function(){return this.unsigned||this.high>=0},be.isOdd=function(){return 1==(1&this.low)},be.isEven=function(){return 0==(1&this.low)},be.equals=function(e){return J(e)||(e=se(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},be.eq=be.equals,be.notEquals=function(e){return!this.eq(e)},be.neq=be.notEquals,be.ne=be.notEquals,be.lessThan=function(e){return this.comp(e)<0},be.lt=be.lessThan,be.lessThanOrEqual=function(e){return this.comp(e)<=0},be.lte=be.lessThanOrEqual,be.le=be.lessThanOrEqual,be.greaterThan=function(e){return this.comp(e)>0},be.gt=be.greaterThan,be.greaterThanOrEqual=function(e){return this.comp(e)>=0},be.gte=be.greaterThanOrEqual,be.ge=be.greaterThanOrEqual,be.compare=function(e){if(J(e)||(e=se(e)),this.eq(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},be.comp=be.compare,be.negate=function(){return!this.unsigned&&this.eq(ge)?ge:this.not().add(he)},be.neg=be.negate,be.add=function(e){J(e)||(e=se(e));var t=this.high>>>16,n=65535&this.high,r=this.low>>>16,s=65535&this.low,o=e.high>>>16,a=65535&e.high,i=e.low>>>16,l=0,u=0,c=0,h=0;return c+=(h+=s+(65535&e.low))>>>16,u+=(c+=r+i)>>>16,l+=(u+=n+a)>>>16,l+=t+o,te((c&=65535)<<16|(h&=65535),(l&=65535)<<16|(u&=65535),this.unsigned)},be.subtract=function(e){return J(e)||(e=se(e)),this.add(e.neg())},be.sub=be.subtract,be.multiply=function(e){if(this.isZero())return ue;if(J(e)||(e=se(e)),j)return te(j.mul(this.low,this.high,e.low,e.high),j.get_high(),this.unsigned);if(e.isZero())return ue;if(this.eq(ge))return e.isOdd()?ge:ue;if(e.eq(ge))return this.isOdd()?ge:ue;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(le)&&e.lt(le))return ee(this.toNumber()*e.toNumber(),this.unsigned);var t=this.high>>>16,n=65535&this.high,r=this.low>>>16,s=65535&this.low,o=e.high>>>16,a=65535&e.high,i=e.low>>>16,l=65535&e.low,u=0,c=0,h=0,d=0;return h+=(d+=s*l)>>>16,c+=(h+=r*l)>>>16,h&=65535,c+=(h+=s*i)>>>16,u+=(c+=n*l)>>>16,c&=65535,u+=(c+=r*i)>>>16,c&=65535,u+=(c+=s*a)>>>16,u+=t*l+n*i+r*a+s*o,te((h&=65535)<<16|(d&=65535),(u&=65535)<<16|(c&=65535),this.unsigned)},be.mul=be.multiply,be.divide=function(e){if(J(e)||(e=se(e)),e.isZero())throw Error("division by zero");var t,n,r;if(j)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?te((this.unsigned?j.div_u:j.div_s)(this.low,this.high,e.low,e.high),j.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?ce:ue;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return ce;if(e.gt(this.shru(1)))return de;r=ce}else{if(this.eq(ge))return e.eq(he)||e.eq(pe)?ge:e.eq(ge)?he:(t=this.shr(1).div(e).shl(1)).eq(ue)?e.isNegative()?he:pe:(n=this.sub(e.mul(t)),r=t.add(n.div(e)));if(e.eq(ge))return this.unsigned?ce:ue;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();r=ue}for(n=this;n.gte(e);){t=Math.max(1,Math.floor(n.toNumber()/e.toNumber()));for(var s=Math.ceil(Math.log(t)/Math.LN2),o=s<=48?1:ne(2,s-48),a=ee(t),i=a.mul(e);i.isNegative()||i.gt(n);)i=(a=ee(t-=o,this.unsigned)).mul(e);a.isZero()&&(a=he),r=r.add(a),n=n.sub(i)}return r},be.div=be.divide,be.modulo=function(e){return J(e)||(e=se(e)),j?te((this.unsigned?j.rem_u:j.rem_s)(this.low,this.high,e.low,e.high),j.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},be.mod=be.modulo,be.rem=be.modulo,be.not=function(){return te(~this.low,~this.high,this.unsigned)},be.and=function(e){return J(e)||(e=se(e)),te(this.low&e.low,this.high&e.high,this.unsigned)},be.or=function(e){return J(e)||(e=se(e)),te(this.low|e.low,this.high|e.high,this.unsigned)},be.xor=function(e){return J(e)||(e=se(e)),te(this.low^e.low,this.high^e.high,this.unsigned)},be.shiftLeft=function(e){return J(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?te(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):te(0,this.low<<e-32,this.unsigned)},be.shl=be.shiftLeft,be.shiftRight=function(e){return J(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?te(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):te(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},be.shr=be.shiftRight,be.shiftRightUnsigned=function(e){if(J(e)&&(e=e.toInt()),0===(e&=63))return this;var t=this.high;return e<32?te(this.low>>>e|t<<32-e,t>>>e,this.unsigned):te(32===e?t:t>>>e-32,0,this.unsigned)},be.shru=be.shiftRightUnsigned,be.shr_u=be.shiftRightUnsigned,be.toSigned=function(){return this.unsigned?te(this.low,this.high,!1):this},be.toUnsigned=function(){return this.unsigned?this:te(this.low,this.high,!0)},be.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},be.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},be.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},Z.fromBytes=function(e,t,n){return n?Z.fromBytesLE(e,t):Z.fromBytesBE(e,t)},Z.fromBytesLE=function(e,t){return new Z(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},Z.fromBytesBE=function(e,t){return new Z(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};const ye=H||Object.freeze({__proto__:null,default:H,__moduleExports:H});function we(e){return ye.fromString(e,!0,16)}const ke=we("c3a5c85c97cb3127"),ve=we("b492b66fbe98f273"),xe=we("9ae16a3b2f90404f");function Ee(e){return e.xor(e.shru(47))}function Se(e,t,n){const r=e.slice(t,t+n);return ye.fromBytes(Array.from(r),!0,!0)}function Ae(e,t){return Se(e,t,8)}function _e(e,t){return Se(e,t,4)}function Ne(e,t){return 0===t?e:e.shru(t).or(e.shl(64-t))}function Ie(e,t,n=we("9ddfea08eb382d69")){let r=e.xor(t).mul(n);r=r.xor(r.shru(47));let s=t.xor(r).mul(n);return s=s.xor(s.shru(47)),s=s.mul(n),s}function Me(e,t,n,r){return function(e,t,n,r,s,o){s=s.add(e),o=Ne(o.add(s).add(r),21);const a=s;return s=(s=s.add(t)).add(n),o=o.add(Ne(s,44)),[s.add(r),o.add(a)]}(Ae(e,t),Ae(e,t+8),Ae(e,t+16),Ae(e,t+24),n,r)}function $e(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=l(e)),C().getBool("DEBUG")&&b(e,t),function(e,t){return e instanceof Float32Array&&"float32"===t||e instanceof Int32Array&&"int32"===t||e instanceof Uint8Array&&"bool"===t}(e,t))return e;if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t){const t=new Uint8Array(e.length);for(let n=0;n<t.length;++n)0!==Math.round(e[n])&&(t[n]=1);return t}throw new Error("Unknown data type "+t)}function Te(){return C().platform.now()}function De(e,t="utf-8"){return t=t||"utf-8",C().platform.encode(e,t)}function Re(e,t="utf-8"){return t=t||"utf-8",C().platform.decode(e,t)}var Be=Object.freeze({__proto__:null,createScalarValue:function(e,t){return"string"===t?De(e):$e([e],t)},toTypedArray:$e,now:Te,fetch:function(e,t){return C().platform.fetch(e,t)},encodeString:De,decodeString:Re,shuffle:r,shuffleCombo:function(e,t){if(e.length!==t.length)throw new Error("Array sizes must match to be shuffled together First array length was "+e.length+"Second array length was "+t.length);let n,r,s=e.length,o=0;for(;s>0;)o=Math.random()*s|0,s--,n=e[s],r=t[s],e[s]=e[o],t[s]=t[o],e[o]=n,t[o]=r},clamp:s,nearestLargerEven:function(e){return e%2==0?e:e+1},sum:function(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t},randUniform:function(e,t){const n=Math.random();return t*n+(1-n)*e},distSquared:function(e,t){let n=0;for(let r=0;r<e.length;r++){const s=Number(e[r])-Number(t[r]);n+=s*s}return n},assert:o,assertShapesMatch:a,assertNonNull:i,flatten:l,sizeFromShape:u,isScalarShape:function(e){return 0===e.length},arraysEqual:c,isInt:h,tanh:function(e){if(null!=Math.tanh)return Math.tanh(e);if(e===1/0)return 1;if(e===-1/0)return-1;{const t=Math.exp(2*e);return(t-1)/(t+1)}},sizeToSquarishShape:function(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]},createShuffledIndices:function(e){const t=new Uint32Array(e);for(let n=0;n<e;++n)t[n]=n;return r(t),t},rightPad:d,repeatedTry:function(e,t=(e=>0),n){return new Promise((r,s)=>{let o=0;const a=()=>{if(e())return void r();o++;const i=t(o);null!=n&&o>=n?s():setTimeout(a,i)};a()})},inferFromImplicitShape:function(e,t){let n=1,r=-1;for(let t=0;t<e.length;++t)if(e[t]>=0)n*=e[t];else if(-1===e[t]){if(-1!==r)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${r} and dim ${t}`);r=t}else if(e[t]<0)throw Error(`Shapes can not be < 0. Found ${e[t]} at dim ${t}`);if(-1===r){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(0===n)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%n!=0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${n}`);const s=e.slice();return s[r]=t/n,s},parseAxisParam:p,squeezeShape:f,getTypedArrayFromDType:m,getArrayFromDType:g,checkConversionForErrors:b,isValidDtype:y,hasEncodingLoss:function(e,t){return"complex64"!==t&&(("float32"!==t||"complex64"===e)&&(("int32"!==t||"float32"===e||"complex64"===e)&&("bool"!==t||"bool"!==e)))},isTypedArray:w,bytesPerElement:k,bytesFromStringArray:v,isString:x,isBoolean:E,isNumber:S,inferDtype:A,isFunction:_,nearestDivisor:N,computeStrides:I,toNestedArray:M,makeOnesTypedArray:$,makeZerosTypedArray:T,makeZerosNestedTypedArray:function(e,t){const n=e.reduce((e,t)=>e*t,1);if(null==t||"float32"===t)return M(e,new Float32Array(n));if("int32"===t)return M(e,new Int32Array(n));if("bool"===t)return M(e,new Uint8Array(n));throw new Error("Unknown data type "+t)},assertNonNegativeIntegerDimensions:D,locToIndex:function(e,t,n){if(0===t)return 0;if(1===t)return e[0];let r=e[e.length-1];for(let t=0;t<e.length-1;++t)r+=n[t]*e[t];return r},indexToLoc:function(e,t,n){if(0===t)return[];if(1===t)return[e];const r=new Array(t);for(let t=0;t<r.length-1;++t)r[t]=Math.floor(e/n[t]),e-=r[t]*n[t];return r[r.length-1]=e,r},isPromise:R,hexToLong:we,fingerPrint64:function(e,t=e.length){const n=ye.fromNumber(81,!0);if(t<=32)return t<=16?function(e,t=e.length){if(t>=8){const n=xe.add(2*t),r=Ae(e,0).add(xe),s=Ae(e,t-8);return Ie(Ne(s,37).mul(n).add(r),Ne(r,25).add(s).mul(n),n)}if(t>=4){const n=xe.add(2*t);return Ie(_e(e,0).shl(3).add(t),_e(e,t-4),n)}if(t>0){const n=e[0]+(e[t>>1]<<8),r=t+(e[t-1]<<2);return Ee(xe.mul(n).xor(ke.mul(r))).mul(xe)}return xe}(e,t):function(e,t=e.length){const n=xe.add(2*t),r=Ae(e,0).mul(ve),s=Ae(e,8),o=Ae(e,t-8).mul(n),a=Ae(e,t-16).mul(xe);return Ie(Ne(r.add(s),43).add(Ne(o,30)).add(a),r.add(Ne(s.add(xe),18)).add(o),n)}(e,t);if(t<=64)return function(e,t=e.length){const n=xe.add(2*t),r=Ae(e,0).mul(xe),s=Ae(e,8),o=Ae(e,t-8).mul(n),a=Ae(e,t-16).mul(xe),i=Ne(r.add(s),43).add(Ne(o,30)).add(a),l=Ie(i,r.add(Ne(s.add(xe),18)).add(o),n),u=Ae(e,16).mul(n),c=Ae(e,24),h=i.add(Ae(e,t-32)).mul(n),d=l.add(Ae(e,t-24)).mul(n);return Ie(Ne(u.add(c),43).add(Ne(h,30)).add(d),u.add(Ne(c.add(r),18)).add(h),n)}(e,t);let r=n,s=n.mul(ve).add(113),o=Ee(s.mul(xe).add(113)).mul(xe),a=[ye.UZERO,ye.UZERO],i=[ye.UZERO,ye.UZERO];r=r.mul(xe).add(Ae(e,0));let l=0;const u=64*(t-1>>6),c=u+(t-1&63)-63;do{r=Ne(r.add(s).add(a[0]).add(Ae(e,l+8)),37).mul(ve),s=Ne(s.add(a[1]).add(Ae(e,l+48)),42).mul(ve),r=r.xor(i[1]),s=s.add(a[0]).add(Ae(e,l+40)),o=Ne(o.add(i[0]),33).mul(ve),a=Me(e,l,a[1].mul(ve),r.add(i[0])),i=Me(e,l+32,o.add(i[1]),s.add(Ae(e,l+16))),[o,r]=[r,o],l+=64}while(l!==u);const h=ve.add(o.and(255).shl(1));return l=c,i[0]=i[0].add(t-1&63),a[0]=a[0].add(i[0]),i[0]=i[0].add(a[0]),r=Ne(r.add(s).add(a[0]).add(Ae(e,l+8)),37).mul(h),s=Ne(s.add(a[1]).add(Ae(e,l+48)),42).mul(h),r=r.xor(i[1].mul(9)),s=s.add(a[0].mul(9).add(Ae(e,l+40))),o=Ne(o.add(i[0]),33).mul(h),a=Me(e,l,a[1].mul(h),r.add(i[0])),i=Me(e,l+32,o.add(i[1]),s.add(Ae(e,l+16))),[o,r]=[r,o],Ie(Ie(a[0],i[0],h).add(Ee(s).mul(ke)).add(o),Ie(a[1],i[1],h).add(r),h)}});class Fe{constructor(e,t){this.backendTimer=e,this.logger=t,null==t&&(this.logger=new Pe)}profileKernel(e,t,n){let r;const s=()=>{r=n()};let o;const a=Te();if(this.backendTimer.timerAvailable())o=this.backendTimer.time(s);else{s();for(const e of r)e.dataSync();o=Promise.resolve({kernelMs:Te()-a})}if(C().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let t=0;t<r.length;t++){const n=r[t];n.data().then(t=>{Ce(t,n.dtype,e)})}return{kernelName:e,outputs:r,inputs:t,timeMs:o.then(e=>e.kernelMs),extraInfo:o.then(e=>null!=e.getExtraProfileInfo?e.getExtraProfileInfo():"")}}logKernelProfile(e){const{kernelName:t,outputs:n,timeMs:r,inputs:s,extraInfo:o}=e;n.forEach(e=>{Promise.all([e.data(),r,o]).then(n=>{this.logger.logKernelProfile(t,e,n[0],n[1],s,n[2])})})}}function Ce(e,t,n){if("float32"!==t)return!1;for(let t=0;t<e.length;t++){const r=e[t];if(isNaN(r)||!isFinite(r))return console.warn(`Found ${r} in the result of '${n}'`),!0}return!1}class Pe{logKernelProfile(e,t,n,r,s,o){const a="number"==typeof r?d(r+"ms",9):r.error,i=d(e,25),l=t.rank,u=t.size,c=d(t.shape.toString(),14);let h="";for(const e in s){const n=s[e];if(null!=n){const r=n.shape||t.shape,s=r.length;h+=`${e}: ${s}D ${s>0?r:""} `}}console.log(`%c${i}\t%c${a}\t%c${l}D ${c}\t%c${u}\t%c${h}\t%c${o}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function Le(e,t,n,r){const s=I(t),o=function(e,t,n,r){const s=u(t),o=r[r.length-1],a=new Array(o).fill(0),i=t.length,l="complex64"===n?qe(e):e;if(i>1)for(let e=0;e<s/o;e++){const t=e*o;for(let e=0;e<o;e++)a[e]=Math.max(a[e],Oe(l[t+e],0,n).length)}return a}(e,t,n,s),a=t.length,i=function e(t,n,r,s,o,a=!0){const i="complex64"===r?2:1,l=n[0],u=n.length;if(0===u){if("complex64"===r){return[Oe(qe(t)[0],0,r)]}return"bool"===r?[ze(t[0])]:[t[0].toString()]}if(1===u){if(l>20){const e=3*i;let n=Array.from(t.slice(0,e)),s=Array.from(t.slice((l-3)*i,l*i));return"complex64"===r&&(n=qe(n),s=qe(s)),["["+n.map((e,t)=>Oe(e,o[t],r)).join(", ")+", ..., "+s.map((e,t)=>Oe(e,o[l-3+t],r)).join(", ")+"]"]}return["["+("complex64"===r?qe(t):Array.from(t)).map((e,t)=>Oe(e,o[t],r)).join(", ")+"]"]}const c=n.slice(1),h=s.slice(1),d=s[0]*i,p=[];if(l>20){for(let n=0;n<3;n++){const s=n*d,a=s+d;p.push(...e(t.slice(s,a),c,r,h,o,!1))}p.push("...");for(let n=l-3;n<l;n++){const s=n*d,a=s+d;p.push(...e(t.slice(s,a),c,r,h,o,n===l-1))}}else for(let n=0;n<l;n++){const s=n*d,a=s+d;p.push(...e(t.slice(s,a),c,r,h,o,n===l-1))}const f=2===u?",":"";p[0]="["+p[0]+f;for(let e=1;e<p.length-1;e++)p[e]=" "+p[e]+f;let m=",\n";for(let e=2;e<u;e++)m+="\n";return p[p.length-1]=" "+p[p.length-1]+"]"+(a?"":m),p}(e,t,n,s,o),l=["Tensor"];return r&&(l.push(" dtype: "+n),l.push(" rank: "+a),l.push(` shape: [${t}]`),l.push(" values:")),l.push(i.map(e=>" "+e).join("\n")),l.join("\n")}function Oe(e,t,n){let r;return r=Array.isArray(e)?parseFloat(e[0].toFixed(7))+" + "+parseFloat(e[1].toFixed(7))+"j":x(e)?`'${e}'`:"bool"===n?ze(e):parseFloat(e.toFixed(7)).toString(),d(r,t)}function ze(e){return 0===e?"false":"true"}function qe(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}class Ke{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=u(e),null!=n){const e=n.length;o(e===this.size,()=>`Length of values '${e}' does not match the size inferred by the shape '${this.size}'.`)}if("complex64"===t)throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||g(t,this.size),this.strides=I(e)}set(e,...t){0===t.length&&(t=[0]),o(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);const n=this.locToIndex(t);this.values[n]=e}get(...e){0===e.length&&(e=[0]);let t=0;for(const n of e){if(n<0||n>=this.shape[t]){const t=`Requested out of range element at ${e}. Buffer shape=`+this.shape;throw new Error(t)}t++}let n=e[e.length-1];for(let t=0;t<e.length-1;++t)n+=this.strides[t]*e[t];return this.values[n]}locToIndex(e){if(0===this.rank)return 0;if(1===this.rank)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(0===this.rank)return[];if(1===this.rank)return[e];const t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return We().makeTensor(this.values,this.shape,this.dtype)}}let We=null,Ue=null;class Ge{constructor(e,t,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=u(e),this.strides=I(e),this.dataId=n,this.id=r,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const e=await this.data();return Ue.buffer(this.shape,this.dtype,e)}bufferSync(){return Ue.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return M(this.shape,e,"complex64"===this.dtype)}arraySync(){return M(this.shape,this.dataSync(),"complex64"===this.dtype)}async data(){this.throwIfDisposed();const e=We().read(this.dataId);if("string"===this.dtype){const t=await e;try{return t.map(e=>Re(e))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataSync(){this.throwIfDisposed();const e=We().readSync(this.dataId);if("string"===this.dtype)try{return e.map(e=>Re(e))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();const e=await We().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(We().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Ue.print(this,e)}clone(){return this.throwIfDisposed(),Ue.clone(this)}toString(e=!1){return Le(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Ue.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),We().makeVariable(this,e,t,n)}}Object.defineProperty(Ge,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),O("Tensor",()=>Ge);class Ve extends Ge{constructor(e,t,n,r){super(e.shape,e.dtype,e.dataId,r),this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!c(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);We().disposeTensor(this),this.dataId=e.dataId,We().incRef(this,null)}dispose(){We().disposeVariable(this),this.isDisposedInternal=!0}}var He,je,Ze,Je,Ye;Object.defineProperty(Ve,Symbol.hasInstance,{value:e=>e instanceof Ge&&null!=e.assign&&e.assign instanceof Function}),(He=e.Rank||(e.Rank={})).R0="R0",He.R1="R1",He.R2="R2",He.R3="R3",He.R4="R4",He.R5="R5",He.R6="R6",function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"}(je||(je={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"}(Ze||(Ze={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"}(Je||(Je={})),function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"}(Ye||(Ye={}));const Xe={float32:Je,int32:je,bool:Ze,complex64:Ye};function Qe(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return Xe[e][t]}function et(e,t){if(e.dtype===t.dtype)return[e,t];const n=Qe(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function tt(e,t){o(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function nt(e){const t=[];return function e(t,n,r){if(null==t)return;if(t instanceof Ge)return void n.push(t);if(s=t,!Array.isArray(s)&&"object"!=typeof s)return;var s;const o=t;for(const t in o){const s=o[t];r.has(s)||(r.add(s),e(s,n,r))}}(e,t,new Set),t}var rt=Object.freeze({__proto__:null,makeTypesMatch:et,assertTypesMatch:tt,isTensorInList:function(e,t){return t.some(t=>t.id===e.id)},getTensorsInContainer:nt});function st(e){return null!=e.kernelName}class ot{constructor(){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,get kernelNames(){return Array.from(new Set(this.kernels.map(e=>e.name)))}}}dispose(){for(const e in this.registeredVariables)this.registeredVariables[e].dispose()}}class at{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new ot}async ready(){if(null!=this.pendingBackendInit)return this.pendingBackendInit.then(()=>{});if(null!=this.backendInstance)return;const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t];if(await this.initializeBackend(n).success)return void await this.setBackend(n)}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(null!=this.pendingBackendInit)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(null==this.backendInstance){const{name:e,asyncInit:t}=this.initializeBackendsAndReturnBest();if(t)throw new Error(`The highest priority backend '${e}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(e)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(e){if(!(e in this.registry)){if(!(e in this.registryFactory))return null;{const{asyncInit:t}=this.initializeBackend(e);if(t)return null}}return this.registry[e]}findBackendFactory(e){return e in this.registryFactory?this.registryFactory[e].factory:null}registerBackend(e,t,n=1){return e in this.registryFactory?(console.warn(e+" backend was already registered. Reusing existing backend factory."),!1):(this.registryFactory[e]={factory:t,priority:n},!0)}async setBackend(e){if(null==this.registryFactory[e])throw new Error(`Backend name '${e}' not found in registry`);if(this.backendName=e,null==this.registry[e]){this.backendInstance=null;const{success:t,asyncInit:n}=this.initializeBackend(e);if(!(n?await t:t))return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new Fe(this.backendInstance),!0}setupRegisteredKernels(){U(this.backendName).forEach(e=>{null!=e.setupFunc&&e.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){U(e).forEach(t=>{null!=t.disposeFunc&&t.disposeFunc(this.registry[e])})}initializeBackend(e){const n=this.registryFactory[e];if(null==n)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const r=n.factory();if(!r||r instanceof t||"function"!=typeof r.then)return this.registry[e]=r,{success:!0,asyncInit:!1};{const t=++this.pendingBackendInitId,n=r.then(n=>!(t<this.pendingBackendInitId)&&(this.registry[e]=n,this.pendingBackendInit=null,!0)).catch(n=>(t<this.pendingBackendInitId||(this.pendingBackendInit=null,console.warn(`Initialization of backend ${e} failed`),console.warn(n.stack||n.message)),!1));return this.pendingBackendInit=n,{success:n,asyncInit:!0}}}catch(t){return console.warn(`Initialization of backend ${e} failed`),console.warn(t.stack||t.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(e+" backend not found in registry");this.backendName===e&&null!=this.pendingBackendInit&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(0===Object.keys(this.registryFactory).length)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t],{success:r,asyncInit:s}=this.initializeBackend(n);if(s||r)return{name:n,asyncInit:s}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){const n=this.state.tensorInfo.get(t),r=n.backend,s=this.readSync(t),o=r.refCount(t);r.disposeData(t,!0),n.backend=e,e.move(t,s,n.shape,n.dtype,o),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let n,r=null;if(null==t){if("function"!=typeof e)throw new Error("Please provide a function to tidy()");t=e}else{if("string"!=typeof e&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!=typeof t)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");r=e}return this.scopedRun(()=>this.startScope(r),()=>this.endScope(n),()=>(n=t(),n instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n))}scopedRun(e,t,n){e();try{const e=n();return t(),e}catch(e){throw t(),e}}nextTensorId(){return at.nextTensorId++}nextVariableId(){return at.nextVariableId++}clone(e){const t=lt.runKernel("Identity",{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],e=>({x:()=>{const t={x:e},n={dtype:"float32"};return lt.runKernel("Cast",t,n)}}),[],{}),t}runKernel(e,t,n){if(!(null!=K(e,this.backendName)))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){const r=this.backend.numDataIds();let s=0;n.forEach(e=>{s+="complex64"===e.dtype?3:1});const o=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],a=r-t-s-o;if(a>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${a} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[];const r=this.isTapeOn(),s=this.state.numBytes,a=this.state.numTensors;let i,l;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0),null==this.backendName&&this.backend;const u=st(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(st(e)){const{kernelName:t,inputs:s,attrs:a}=e;null==this.backendName&&this.backend;const u=K(t,this.backendName);o(null!=u,()=>`Cannot find registered kernel '${t}' for backend '${this.backendName}'`),i=()=>{const e=this.backend.numDataIds();l=u.kernelFunc({inputs:s,attrs:a,backend:this.backend});const o=Array.isArray(l)?l:[l];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(t,e,o);const i=o.map(e=>{if(null!=e.rank)return e;const{dataId:t,shape:n,dtype:r}=e;return this.makeTensorFromDataId(t,n,r)});if(r){const e=this.getTensorsForGradient(t,s,i);n=this.saveTensorsForBackwardMode(e)}return i}}else{const{forwardFunc:t}=e,s=e=>{r&&(n=e.map(e=>this.keep(this.clone(e))))};i=()=>{const e=this.backend.numDataIds();l=this.tidy(()=>t(this.backend,s));const n=Array.isArray(l)?l:[l];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(u,e,n),n}}const{inputs:c,attrs:h}=e,d=st(e)?null:e.backwardsFunc;let p;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{this.ENV.getBool("DEBUG")||this.state.profiling?(p=this.profiler.profileKernel(u,c,()=>i()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(p),t=p.outputs):t=i()}),r&&this.addTapeNode(u,c,t,d,n,h),this.state.profiling&&this.state.activeProfile.kernels.push({name:u,bytesAdded:this.state.numBytes-s,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-a,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(c).map(e=>null!=c[e]?c[e].shape:null),outputShapes:t.map(e=>e.shape),kernelTimeMs:p.timeMs,extraInfo:p.extraInfo}),Array.isArray(l)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(e=>this.keep(this.clone(e)))}getTensorsForGradient(e,t,n){const r=W(e);if(null!=r){const e=r.inputsToSave||[],s=r.outputsToSave||[];let a;r.saveAllInputs?(o(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),a=Object.keys(t).map(e=>t[e])):a=e.map(e=>t[e]);const i=n.filter((e,t)=>s[t]);return a.concat(i)}return[]}makeTensor(e,t,n,r){if(null==e)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",r=r||this.backend;let s=e;"string"===n&&x(e[0])&&(s=e.map(e=>De(e)));const o=r.write(s,t,n),a=new Ge(t,n,o,this.nextTensorId());if(this.trackTensor(a,r),"string"===n){const e=this.state.tensorInfo.get(o),t=v(s);this.state.numBytes+=t-e.bytes,e.bytes=t}return a}makeTensorFromDataId(e,t,n,r){const s=new Ge(t,n=n||"float32",e,this.nextTensorId());return this.trackTensor(s,r),s}makeVariable(e,t=!0,n,r){n=n||this.nextVariableId().toString(),null!=r&&r!==e.dtype&&(e=e.cast(r));const s=new Ve(e,t,n,this.nextTensorId());if(null!=this.state.registeredVariables[s.name])throw new Error(`Variable with name ${s.name} was already registered`);return this.state.registeredVariables[s.name]=s,this.incRef(s,this.backend),s}trackTensor(e,t){this.state.numTensors++,"string"===e.dtype&&this.state.numStringTensors++;let n=0;"complex64"!==e.dtype&&"string"!==e.dtype&&(n=e.size*k(e.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n})),e instanceof Ve||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;const t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,"string"===e.dtype&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),"complex64"!==e.dtype&&"string"!==e.dtype){const t=e.size*k(e.dtype);this.state.numBytes-=t}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(const e in this.state.registeredVariables){const t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),null!=this.state.registeredVariables[e.name]&&delete this.state.registeredVariables[e.name]}memory(){const e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,null==e.reasons&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;const t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(e=>e.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(const e of this.state.activeProfile.kernels)e.kernelTimeMs=await e.kernelTimeMs,e.extraInfo=await e.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&0===this.state.kernelDepth}addTapeNode(e,t,n,r,s,o){const a={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:s},i=W(e);null!=i&&(r=i.gradFunc),null!=r&&(a.gradient=e=>(e=e.map((e,t)=>{if(null==e){const e=n[t],r=T(e.size,e.dtype);return this.makeTensor(r,e.shape,e.dtype)}return e}),r(e.length>1?e:e[0],s,o))),this.state.activeTape.push(a)}keep(e){return e.kept=!0,e}startTape(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){const t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){const t=nt(e),n=new Set(t.map(e=>e.id));for(let e=0;e<this.state.activeScope.track.length;e++){const t=this.state.activeScope.track[e];t.kept||n.has(t.id)||t.dispose()}const r=this.state.scopeStack.pop();this.state.activeScope=0===this.state.scopeStack.length?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach(e=>{e.kept||e.scopeId!==r.id||this.track(e)})}gradients(e,t,n,r=!1){if(o(t.length>0,()=>"gradients() received an empty list of xs."),null!=n&&"float32"!==n.dtype)throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);const s=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));o(s instanceof Ge,()=>"The result y returned by f() must be a tensor.");const a=function(e,t,n){const r={},s={};for(let e=0;e<t.length;e++)r[t[e].id]=!0;for(let n=0;n<e.length;n++){const o=e[n],a=o.inputs;for(const e in a){const n=a[e];let i=!1;for(let e=0;e<t.length;e++)if(r[n.id]){o.outputs.forEach(e=>r[e.id]=!0),i=!0,s[o.id]=!0;break}if(i)break}}const o={};o[n.id]=!0;const a={};for(let t=e.length-1;t>=0;t--){const n=e[t],r=n.inputs;for(let e=0;e<n.outputs.length;e++)if(o[n.outputs[e].id]){for(const e in r)o[r[e].id]=!0,a[n.id]=!0;break}}const i=[];for(let t=0;t<e.length;t++){const n=e[t];if(s[n.id]&&a[n.id]){const e={};for(const t in n.inputs){const s=n.inputs[t];r[s.id]&&(e[t]=s)}const t=Object.assign({},n);t.inputs=e,t.outputs=n.outputs,i.push(t)}}return i}(this.state.activeTape,t,s);if(!r&&0===a.length&&t.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",()=>{const e={};e[s.id]=null==n?function(e){const t=$(u(e),"float32");return lt.makeTensor(t,e,"float32")}(s.shape):n,function(e,t,n,r){for(let s=t.length-1;s>=0;s--){const o=t[s],a=[];if(o.outputs.forEach(t=>{const n=e[t.id];null!=n?a.push(n):a.push(null)}),null==o.gradient)throw new Error(`Cannot compute gradient: gradient function not found for ${o.kernelName}.`);const i=o.gradient(a);for(const t in o.inputs){if(!(t in i))throw new Error(`Cannot backprop through input ${t}. Available gradients found: ${Object.keys(i)}.`);const s=n(()=>i[t]());if("float32"!==s.dtype)throw new Error(`Error in gradient for op ${o.kernelName}. The gradient of input ${t} must have 'float32' dtype, but has '${s.dtype}'`);const a=o.inputs[t];if(!c(s.shape,a.shape))throw new Error(`Error in gradient for op ${o.kernelName}. The gradient of input '${t}' has shape '${s.shape}', which does not match the shape of the input '${a.shape}'`);if(null==e[a.id])e[a.id]=s;else{const t=e[a.id];e[a.id]=r(t,s),t.dispose()}}}}(e,a,e=>this.tidy(e),ut);const r=t.map(t=>e[t.id]);return 0===this.state.gradientDepth&&(this.state.activeTape.forEach(e=>{for(const t of e.saved)t.dispose()}),this.state.activeTape=null),{value:s,grads:r}})}customGrad(e){return o(_(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{let n;o(t.every(e=>e instanceof Ge),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");const r={};t.forEach((e,t)=>{r[t]=e});return this.runKernelFunc({forwardFunc:(r,s)=>(n=e(...t,s),o(n.value instanceof Ge,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),o(_(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),backwardsFunc:(e,r)=>{const s=n.gradFunc(e,r),a=Array.isArray(s)?s:[s];o(a.length===t.length,()=>"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(...)."),o(a.every(e=>e instanceof Ge),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");const i={};return a.forEach((e,t)=>{i[t]=()=>e}),i},inputs:r})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}async time(e){const t=Te(),n=await this.backend.time(e);return n.wallMs=Te()-t,n}track(e){return null!=this.state.activeScope&&(e.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(e)),e}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new ot;for(const e in this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}}function it(){const t=L();if(null==t._tfengine){const e=new B(t);t._tfengine=new at(e)}var n;return n=t._tfengine.ENV,e.ENV=n,We=()=>t._tfengine,t._tfengine}at.nextTensorId=0,at.nextVariableId=0;const lt=it();function ut(e,t){const n={a:e,b:t};return lt.runKernel("Add",n)}function ct(){return"undefined"!=typeof window&&null!=window.document||"undefined"!=typeof WorkerGlobalScope}var ht=Object.freeze({__proto__:null,isMobile:function(e){if(e||"undefined"!=typeof navigator&&null!=navigator){if(e||(e=navigator),"ReactNative"===e.product)return!0;const t=e.userAgent||e.vendor||window.opera;return/(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))}return!1},isBrowser:ct});const dt=C();function pt(e,t){let n=e;if(w(e))return"string"===t?[]:[e.length];if(!Array.isArray(e))return[];const r=[];for(;Array.isArray(n)||w(n)&&"string"!==t;)r.push(n.length),n=n[0];return Array.isArray(e)&&C().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&function e(t,n,r){if(r=r||[],!Array.isArray(t)&&!w(t))return void o(0===n.length,()=>`Element arr[${r.join("][")}] is a primitive, but should be an array/TypedArray of ${n[0]} elements`);o(n.length>0,()=>`Element arr[${r.join("][")}] should be a primitive, but is an array of ${t.length} elements`),o(t.length===n[0],()=>`Element arr[${r.join("][")}] should have ${n[0]} elements, but has ${t.length} elements`);const s=n.slice(1);for(let n=0;n<t.length;++n)e(t[n],s,r.concat(n))}(e,r,[]),r}function ft(e,t,n,r){if("string_or_numeric"!==e){if(null==e)throw new Error("Expected dtype cannot be null.");if("numeric"!==e&&e!==t||"numeric"===e&&"string"===t)throw new Error(`Argument '${n}' passed to '${r}' must be ${e} tensor, but got ${t} tensor`)}}function mt(e,t,n,r="numeric"){if(e instanceof Ge)return ft(r,e.dtype,t,n),e;let s=A(e);if("string"!==s&&["bool","int32","float32"].indexOf(r)>=0&&(s=r),ft(r,s,t,n),null==e||!w(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e){const r=null==e?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${r}'`)}const o=pt(e,s);w(e)||Array.isArray(e)||(e=[e]);const a="string"!==s?$e(e,s):l(e,[],!0);return lt.makeTensor(a,o,s)}function gt(e,t,n,r="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map((e,s)=>mt(e,`${t}[${s}]`,n,r))}dt.registerFlag("DEBUG",()=>!1,e=>{e&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")}),dt.registerFlag("IS_BROWSER",()=>ct()),dt.registerFlag("IS_NODE",()=>"undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node),dt.registerFlag("IS_CHROME",()=>"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor)),dt.registerFlag("PROD",()=>!1),dt.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>dt.getBool("DEBUG")),dt.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0),dt.registerFlag("IS_TEST",()=>!1),dt.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>!0),dt.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);function bt(e){const t=Object.keys(e);if(1!==t.length)throw new Error("Please provide an object with a single key (operation name) mapping to a function. Got an object with "+t.length+" keys.");let n=t[0];const r=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n+="__op";const s=(...e)=>{lt.startScope(n);try{const t=r(...e);return R(t)&&console.error("Cannot return a Promise inside of tidy."),lt.endScope(t),t}catch(e){throw lt.endScope(null),e}};return Object.defineProperty(s,"name",{value:n,configurable:!0}),s}const yt=bt({complex_:function(e,t){const n=mt(e,"real","complex"),r=mt(t,"imag","complex");a(n.shape,r.shape,`real and imag shapes, ${n.shape} and ${r.shape}, must match in call to tf.complex().`);const s={real:n,imag:r};return lt.runKernel("Complex",s)}});function wt(e,t,n,r){if(null==r&&(r=A(e)),"complex64"===r)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!w(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e)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!=t){D(t);const e=u(t),r=u(n);o(e===r,()=>`Based on the provided shape, [${t}], the tensor should have ${e} values but has ${r}`);for(let e=0;e<n.length;++e){const r=n[e],s=e!==n.length-1||r!==u(t.slice(e));o(n[e]===t[e]||!s,()=>`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `)}}return w(e)||Array.isArray(e)||(e=[e]),t=t||n,e="string"!==r?$e(e,r):l(e,[],!0),lt.makeTensor(e,t,r)}function kt(e,t,n){return wt(e,t,pt(e,n),n)}const vt={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};function xt(e,t){const n={};let r,s=0;for(const o of t){const t=o.name,a=o.dtype,i=o.shape,l=u(i);let c;if("quantization"in o){const n=o.quantization;if("uint8"===n.dtype||"uint16"===n.dtype){if(!("min"in n)||!("scale"in n))throw new Error(`Weight ${o.name} with quantization ${n.dtype} doesn't have corresponding metadata min and scale.`)}else{if("float16"!==n.dtype)throw new Error(`Weight ${o.name} has unknown quantization dtype ${n.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);if("float32"!==a)throw new Error(`Weight ${o.name} is quantized with ${n.dtype} which only supports weights of type float32 not ${a}.`)}const i=vt[n.dtype],u=e.slice(s,s+l*i),h="uint8"===n.dtype?new Uint8Array(u):new Uint16Array(u);if("float32"===a)if("uint8"===n.dtype||"uint16"===n.dtype){c=new Float32Array(h.length);for(let e=0;e<h.length;e++){const t=h[e];c[e]=t*n.scale+n.min}}else{if("float16"!==n.dtype)throw new Error(`Unsupported quantization type ${n.dtype} for weight type float32.`);void 0===r&&(r=Mt()),c=r(h)}else{if("int32"!==a)throw new Error(`Unsupported dtype in weight '${t}': ${a}`);if("uint8"!==n.dtype&&"uint16"!==n.dtype)throw new Error(`Unsupported quantization type ${n.dtype} for weight type int32.`);c=new Int32Array(h.length);for(let e=0;e<h.length;e++){const t=h[e];c[e]=Math.round(t*n.scale+n.min)}}s+=l*i}else if("string"===a){const t=u(o.shape);c=[];for(let n=0;n<t;n++){const t=new Uint32Array(e.slice(s,s+4))[0];s+=4;const n=new Uint8Array(e.slice(s,s+t));c.push(n),s+=t}}else{const r=vt[a],o=e.slice(s,s+l*r);if("float32"===a)c=new Float32Array(o);else if("int32"===a)c=new Int32Array(o);else if("bool"===a)c=new Uint8Array(o);else{if("complex64"!==a)throw new Error(`Unsupported dtype in weight '${t}': ${a}`);{c=new Float32Array(o);const e=new Float32Array(c.length/2),r=new Float32Array(c.length/2);for(let t=0;t<e.length;t++)e[t]=c[2*t],r[t]=c[2*t+1];const s=kt(e,i,"float32"),a=kt(r,i,"float32");n[t]=yt(s,a),s.dispose(),a.dispose()}}s+=l*r}"complex64"!==a&&(n[t]=kt(c,i,a))}return n}function Et(e){if(null===e)throw new Error("Invalid input value: "+JSON.stringify(e));let t=0;const n=[];e.forEach(e=>{if(t+=e.byteLength,n.push(e.byteLength===e.buffer.byteLength?e:new e.constructor(e)),!(e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array))throw new Error("Unsupported TypedArray subtype: "+e.constructor.name)});const r=new Uint8Array(t);let s=0;return n.forEach(e=>{r.set(new Uint8Array(e.buffer),s),s+=e.byteLength}),r.buffer}const St="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function At(e){return St?Buffer.byteLength(e):new Blob([e]).size}function _t(e){if(1===e.length)return e[0];let t=0;e.forEach(e=>{t+=e.byteLength});const n=new Uint8Array(t);let r=0;return e.forEach(e=>{n.set(new Uint8Array(e),r),r+=e.byteLength}),n.buffer}function Nt(e){for(e=e.trim();e.endsWith("/");)e=e.slice(0,e.length-1);const t=e.split("/");return t[t.length-1]}function It(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:null==e.modelTopology?0:At(JSON.stringify(e.modelTopology)),weightSpecsBytes:null==e.weightSpecs?0:At(JSON.stringify(e.weightSpecs)),weightDataBytes:null==e.weightData?0:e.weightData.byteLength}}function Mt(){const e=function(){const e=e=>{let t=e<<13,n=0;for(;0==(8388608&t);)n-=8388608,t<<=1;return t&=-8388609,n+=947912704,t|n},t=new Uint32Array(2048);t[0]=0;for(let n=1;n<1024;n++)t[n]=e(n);for(let e=1024;e<2048;e++)t[e]=939524096+(e-1024<<13);return t}(),t=function(){const e=new Uint32Array(64);e[0]=0,e[31]=1199570944,e[32]=2147483648,e[63]=3347054592;for(let t=1;t<31;t++)e[t]=t<<23;for(let t=33;t<63;t++)e[t]=2147483648+(t-32<<23);return e}(),n=function(){const e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}();return r=>{const s=new ArrayBuffer(4*r.length),o=new Uint32Array(s);for(let s=0;s<r.length;s++){const a=r[s],i=e[n[a>>10]+(1023&a)]+t[a>>10];o[s]=i}return new Float32Array(s)}}class $t{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return null==$t.instance&&($t.instance=new $t),$t.instance}static registerSaveRouter(e){$t.getInstance().saveRouters.push(e)}static registerLoadRouter(e){$t.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return $t.getHandlers(e,"save")}static getLoadHandlers(e,t){return $t.getHandlers(e,"load",t)}static getHandlers(e,t,n){const r=[];return("load"===t?$t.getInstance().loadRouters:$t.getInstance().saveRouters).forEach(t=>{const s=t(e,n);null!==s&&r.push(s)}),r}}function Tt(){if(!C().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");const e="undefined"==typeof window?self:window,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(null==t)throw new Error("The current browser does not appear to support IndexedDB.");return t}function Dt(e){const t=e.result;t.createObjectStore("models_store",{keyPath:"modelPath"}),t.createObjectStore("model_info_store",{keyPath:"modelPath"})}class Rt{constructor(e){if(this.indexedDB=Tt(),null==e||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,e)}async load(){return this.databaseAction(this.modelPath)}databaseAction(e,t){return new Promise((e,n)=>{const r=this.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=()=>Dt(r),r.onsuccess=()=>{const s=r.result;if(null==t){const t=s.transaction("models_store","readonly"),r=t.objectStore("models_store").get(this.modelPath);r.onsuccess=()=>{if(null==r.result)return s.close(),n(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));e(r.result.modelArtifacts)},r.onerror=e=>(s.close(),n(r.error)),t.oncomplete=()=>s.close()}else{const r=It(t),o=s.transaction("model_info_store","readwrite");let a=o.objectStore("model_info_store");const i=a.put({modelPath:this.modelPath,modelArtifactsInfo:r});let l;i.onsuccess=()=>{l=s.transaction("models_store","readwrite");const i=l.objectStore("models_store").put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:r});i.onsuccess=()=>e({modelArtifactsInfo:r}),i.onerror=e=>{a=o.objectStore("model_info_store");const t=a.delete(this.modelPath);t.onsuccess=()=>(s.close(),n(i.error)),t.onerror=e=>(s.close(),n(i.error))}},i.onerror=e=>(s.close(),n(i.error)),o.oncomplete=()=>{null==l?s.close():l.oncomplete=()=>s.close()}}},r.onerror=e=>n(r.error)})}}Rt.URL_SCHEME="indexeddb://";const Bt=e=>{return C().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Rt.URL_SCHEME)?(t=e.slice(Rt.URL_SCHEME.length),new Rt(t)):null;var t};$t.registerSaveRouter(Bt),$t.registerLoadRouter(Bt);class Ft{constructor(){this.indexedDB=Tt()}async listModels(){return new Promise((e,t)=>{const n=this.indexedDB.open("tensorflowjs",1);n.onupgradeneeded=()=>Dt(n),n.onsuccess=()=>{const r=n.result,s=r.transaction("model_info_store","readonly"),o=s.objectStore("model_info_store").getAll();o.onsuccess=()=>{const t={};for(const e of o.result)t[e.modelPath]=e.modelArtifactsInfo;e(t)},o.onerror=e=>(r.close(),t(o.error)),s.oncomplete=()=>r.close()},n.onerror=e=>t(n.error)})}async removeModel(e){var t;return e=(t=e).startsWith(Rt.URL_SCHEME)?t.slice(Rt.URL_SCHEME.length):t,new Promise((t,n)=>{const r=this.indexedDB.open("tensorflowjs",1);r.onupgradeneeded=()=>Dt(r),r.onsuccess=()=>{const s=r.result,o=s.transaction("model_info_store","readwrite"),a=o.objectStore("model_info_store"),i=a.get(e);let l;i.onsuccess=()=>{if(null==i.result)return s.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{const r=a.delete(e),o=()=>{l=s.transaction("models_store","readwrite");const r=l.objectStore("models_store").delete(e);r.onsuccess=()=>t(i.result.modelArtifactsInfo),r.onerror=e=>n(i.error)};r.onsuccess=o,r.onerror=e=>(o(),s.close(),n(i.error))}},i.onerror=e=>(s.close(),n(i.error)),o.oncomplete=()=>{null==l?s.close():l.oncomplete=()=>s.close()}},r.onerror=e=>n(r.error)})}}const Ct="tensorflowjs_models",Pt="info",Lt="model_topology",Ot="weight_specs",zt="weight_data",qt="model_metadata";function Kt(e){return{info:[Ct,e,Pt].join("/"),topology:[Ct,e,Lt].join("/"),weightSpecs:[Ct,e,Ot].join("/"),weightData:[Ct,e,zt].join("/"),modelMetadata:[Ct,e,qt].join("/")}}function Wt(e){const t=e.split("/");if(t.length<3)throw new Error("Invalid key format: "+e);return t.slice(1,t.length-1).join("/")}class Ut{constructor(e){if(!C().getBool("IS_BROWSER")||"undefined"==typeof window||void 0===window.localStorage)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,null==e||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=Kt(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{const t=JSON.stringify(e.modelTopology),n=JSON.stringify(e.weightSpecs),r=It(e);try{this.LS.setItem(this.keys.info,JSON.stringify(r)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,function(e){if(St)return Buffer.from(e).toString("base64");const t=new Uint8Array(e);let n="";for(let e=0,r=t.length;e<r;e++)n+=String.fromCharCode(t[e]);return btoa(n)}(e.weightData));const s={format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};return null!=e.signature&&(s.signature=e.signature),null!=e.userDefinedMetadata&&(s.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(s.modelInitializer=e.modelInitializer),this.LS.setItem(this.keys.modelMetadata,JSON.stringify(s)),{modelArtifactsInfo:r}}catch(e){throw this.LS.removeItem(this.keys.info),this.LS.removeItem(this.keys.topology),this.LS.removeItem(this.keys.weightSpecs),this.LS.removeItem(this.keys.weightData),this.LS.removeItem(this.keys.modelMetadata),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${r.modelTopologyBytes}, weightSpecsBytes=${r.weightSpecsBytes}, weightDataBytes=${r.weightDataBytes}.`)}}}async load(){const e=JSON.parse(this.LS.getItem(this.keys.info));if(null==e)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if("JSON"!==e.modelTopologyType)throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");const t={},n=JSON.parse(this.LS.getItem(this.keys.topology));if(null==n)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);t.modelTopology=n;const r=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(null==r)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=r;const s=this.LS.getItem(this.keys.modelMetadata);if(null!=s){const e=JSON.parse(s);t.format=e.format,t.generatedBy=e.generatedBy,t.convertedBy=e.convertedBy,null!=e.signature&&(t.signature=e.signature),null!=e.userDefinedMetadata&&(t.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(t.modelInitializer=e.modelInitializer)}const o=this.LS.getItem(this.keys.weightData);if(null==o)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=function(e){if(St){const t=Buffer.from(e,"base64");return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n.set([t.charCodeAt(e)],e);return n.buffer}(o),t}}Ut.URL_SCHEME="localstorage://";const Gt=e=>{return C().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Ut.URL_SCHEME)?(t=e.slice(Ut.URL_SCHEME.length),new Ut(t)):null;var t};$t.registerSaveRouter(Gt),$t.registerLoadRouter(Gt);class Vt{constructor(){o(C().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),o("undefined"==typeof window||void 0!==window.localStorage,()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){const e={},t=Ct+"/",n="/"+Pt;for(let r=0;r<this.LS.length;++r){const s=this.LS.key(r);if(s.startsWith(t)&&s.endsWith(n)){e[Wt(s)]=JSON.parse(this.LS.getItem(s))}}return e}async removeModel(e){var t;const n=Kt(e=(t=e).startsWith(Ut.URL_SCHEME)?t.slice(Ut.URL_SCHEME.length):t);if(null==this.LS.getItem(n.info))throw new Error(`Cannot find model at path '${e}'`);const r=JSON.parse(this.LS.getItem(n.info));return this.LS.removeItem(n.info),this.LS.removeItem(n.topology),this.LS.removeItem(n.weightSpecs),this.LS.removeItem(n.weightData),r}}class Ht{constructor(){this.managers={}}static getInstance(){return null==Ht.instance&&(Ht.instance=new Ht),Ht.instance}static registerManager(e,t){o(null!=e,()=>"scheme must not be undefined or null."),e.endsWith("://")&&(e=e.slice(0,e.indexOf("://"))),o(e.length>0,()=>"scheme must not be an empty string.");const n=Ht.getInstance();o(null==n.managers[e],()=>`A model store manager is already registered for scheme '${e}'.`),n.managers[e]=t}static getManager(e){const t=this.getInstance().managers[e];if(null==t)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(this.getInstance().managers)}}function jt(e){if(-1===e.indexOf("://"))throw new Error("The url string provided does not contain a scheme. Supported schemes are: "+Ht.getSchemes().join(","));return{scheme:e.split("://")[0],path:e.split("://")[1]}}async function Zt(e,t,n=!1){o(e!==t,()=>`Old path and new path are the same: '${e}'`);const r=$t.getLoadHandlers(e);o(r.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),o(r.length<2,()=>`Copying failed because more than one (${r.length}) load handlers for source URL ${e}.`);const s=r[0],a=$t.getSaveHandlers(t);o(a.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),o(a.length<2,()=>`Copying failed because more than one (${r.length}) save handlers for destination URL ${t}.`);const i=a[0],l=jt(e).scheme,u=jt(e).path,c=l===jt(e).scheme,h=await s.load();n&&c&&await Ht.getManager(l).removeModel(u);const d=await i.save(h);return n&&!c&&await Ht.getManager(l).removeModel(u),d.modelArtifactsInfo}class Jt{fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error("Browser's encoder only supports utf-8, but got "+t);return null==this.textEncoder&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}}if(C().get("IS_BROWSER")){C().setPlatform("browser",new Jt);try{Ht.registerManager(Ut.URL_SCHEME,new Vt)}catch(e){}try{Ht.registerManager(Rt.URL_SCHEME,new Ft)}catch(e){}}const Yt=()=>require("node-fetch");let Xt;class Qt{constructor(){this.util=require("util"),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return null!=C().global.fetch?C().global.fetch(e,t):(null==Xt&&(Xt=Yt()),Xt(e,t))}now(){const e=process.hrtime();return 1e3*e[0]+e[1]/1e6}encode(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error("Node built-in encoder only supports utf-8, but got "+t);return this.textEncoder.encode(e)}decode(e,t){return 0===e.length?"":new this.util.TextDecoder(t).decode(e)}}function en(e,t="float32",n){return t=t||"float32",D(e),new Ke(e,t,n)}C().get("IS_NODE")&&C().setPlatform("node",new Qt);const tn=bt({cast_:function(e,t){const n=mt(e,"x","cast");if(!y(t))throw new Error("Failed to cast to unknown dtype "+t);if("string"===t&&"string"!==n.dtype||"string"!==t&&"string"===n.dtype)throw new Error("Only strings can be casted to strings");const r={x:n},s={dtype:t};return lt.runKernel("Cast",r,s)}});const nn=bt({clone_:function(e){const t={x:mt(e,"x","clone","string_or_numeric")};return lt.runKernel("Identity",t)}});function rn(e,t=!1){console.log(e.toString(t))}it();Ue={buffer:en,cast:tn,clone:nn,print:rn};function sn(e){return new Promise(e=>setTimeout(e)).then(e)}class on{constructor(e){if(!C().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(on.URL_SCHEME)&&(e=e.slice(on.URL_SCHEME.length)),null!=e&&0!==e.length||(e="model"),this.modelTopologyFileName=e+".json",this.weightDataFileName=e+".weights.bin"}async save(e){if("undefined"==typeof document)throw new Error("Browser downloads are not supported in this environment since `document` is not present");const t=window.URL.createObjectURL(new Blob([e.weightData],{type:"application/octet-stream"}));if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{const n=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}],r={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:n};null!=e.signature&&(r.signature=e.signature),null!=e.userDefinedMetadata&&(r.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(r.modelInitializer=e.modelInitializer);const s=window.URL.createObjectURL(new Blob([JSON.stringify(r)],{type:"application/json"})),o=null==this.jsonAnchor?document.createElement("a"):this.jsonAnchor;if(o.download=this.modelTopologyFileName,o.href=s,await sn(()=>o.dispatchEvent(new MouseEvent("click"))),null!=e.weightData){const e=null==this.weightDataAnchor?document.createElement("a"):this.weightDataAnchor;e.download=this.weightDataFileName,e.href=t,await sn(()=>e.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:It(e)}}}}on.URL_SCHEME="downloads://";class an{constructor(e){if(null==e||e.length<1)throw new Error("When calling browserFiles, at least 1 file is required, but received "+e);this.files=e}async load(){const e=this.files[0],t=this.files.slice(1);return new Promise((n,r)=>{const s=new FileReader;s.onload=s=>{const o=JSON.parse(s.target.result),a=o.modelTopology;if(null==a)return void r(new Error("modelTopology field is missing from file "+e.name));0===t.length&&n({modelTopology:a});const i=o.weightsManifest;if(null==i)return void r(new Error("weightManifest field is missing from file "+e.name));let l;try{l=this.checkManifestAndWeightFiles(i,t)}catch(e){return void r(e)}const u=[],c=[],h=[];i.forEach(e=>{e.paths.forEach(e=>{c.push(e),h.push(null)}),u.push(...e.weights)}),i.forEach(e=>{e.paths.forEach(e=>{const t=new FileReader;t.onload=t=>{const r=t.target.result,s=c.indexOf(e);if(h[s]=r,-1===h.indexOf(null)){const e={modelTopology:a,weightSpecs:u,weightData:_t(h),format:o.format,generatedBy:o.generatedBy,convertedBy:o.convertedBy};null!=o.signature&&(e.signature=o.signature),null!=o.userDefinedMetadata&&(e.userDefinedMetadata=o.userDefinedMetadata),null!=o.modelInitializer&&(e.modelInitializer=o.modelInitializer),n(e)}},t.onerror=t=>r(`Failed to weights data from file of path '${e}'.`),t.readAsArrayBuffer(l[e])})})},s.onerror=t=>r(`Failed to read model topology and weights manifest JSON from file '${e.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),s.readAsText(e)})}checkManifestAndWeightFiles(e,t){const n=[],r=t.map(e=>Nt(e.name)),s={};for(const o of e)o.paths.forEach(e=>{const o=Nt(e);if(-1!==n.indexOf(o))throw new Error(`Duplicate file basename found in weights manifest: '${o}'`);if(n.push(o),-1===r.indexOf(o))throw new Error(`Weight file with basename '${o}' is not provided.`);s[e]=t[r.indexOf(o)]});if(n.length!==t.length)throw new Error(`Mismatch in the number of files in weights manifest (${n.length}) and the number of weight files provided (${t.length}).`);return s}}function ln(e,t,n,r){!function(e){o(null!=e&&Array.isArray(e)&&e.length>0,()=>"promises must be a none empty array")}(e),function(e,t){o(e>=0&&e<=1,()=>"Progress fraction must be in range [0, 1], but got startFraction "+e),o(t>=0&&t<=1,()=>"Progress fraction must be in range [0, 1], but got endFraction "+t),o(t>=e,()=>`startFraction must be no more than endFraction, but got startFraction ${e} and endFraction `+t)}(n=null==n?0:n,r=null==r?1:r);let s=0;return Promise.all(e.map(o=>(o.then(o=>{const a=n+ ++s/e.length*(r-n);return t(a),o}),o)))}async function un(e,t){null==t&&(t={});const n=null==t.fetchFunc?C().platform.fetch:t.fetchFunc,r=e.map(e=>n(e,t.requestInit,{isBinary:!0})),s=(null==t.onProgress?await Promise.all(r):await ln(r,t.onProgress,0,.5)).map(e=>e.arrayBuffer());return null==t.onProgress?await Promise.all(s):await ln(s,t.onProgress,.5,1)}function cn(e){return async(t,n="",r)=>{const s=t.map(()=>!1),o={},a=null!=r?r.map(()=>!1):[],i=[];if(t.forEach((e,t)=>{let n=0;e.weights.forEach(e=>{const l="quantization"in e?e.quantization.dtype:e.dtype,c=vt[l]*u(e.shape),h=()=>{s[t]=!0,null==o[t]&&(o[t]=[]),o[t].push({manifestEntry:e,groupOffset:n,sizeBytes:c})};null!=r?r.forEach((t,n)=>{t===e.name&&(h(),a[n]=!0)}):h(),i.push(e.name),n+=c})}),!a.every(e=>e)){const e=r.filter((e,t)=>!a[t]);throw new Error("Could not find weights in manifest with names: "+e.join(", ")+". \nManifest JSON has weights with names: "+i.join(", ")+".")}const l=s.reduce((e,t,n)=>(t&&e.push(n),e),[]),c=[];l.forEach(e=>{t[e].paths.forEach(e=>{const t=n+(n.endsWith("/")?"":"/")+e;c.push(t)})});const h=await e(c),d={};let p=0;return l.forEach(e=>{const n=t[e].paths.length;let r=0;for(let e=0;e<n;e++)r+=h[p+e].byteLength;const s=new ArrayBuffer(r),a=new Uint8Array(s);let i=0;for(let e=0;e<n;e++){const t=new Uint8Array(h[p+e]);a.set(t,i),i+=t.byteLength}o[e].forEach(e=>{const t=xt(s.slice(e.groupOffset,e.groupOffset+e.sizeBytes),[e.manifestEntry]);for(const e in t)d[e]=t[e]}),p+=n}),d}}$t.registerSaveRouter(e=>C().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(on.URL_SCHEME)?function(e="model"){return new on(e)}(e.slice(on.URL_SCHEME.length)):null);class hn{constructor(e,t){if(this.DEFAULT_METHOD="POST",null==t&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,null!=t.fetchFunc?(o("function"==typeof t.fetchFunc,()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=C().platform.fetch,o(null!=e&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&o(2===e.length,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,null!=t.requestInit&&null!=t.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");const t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;const n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],r={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:n};null!=e.signature&&(r.signature=e.signature),null!=e.userDefinedMetadata&&(r.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(r.modelInitializer=e.modelInitializer),t.body.append("model.json",new Blob([JSON.stringify(r)],{type:"application/json"}),"model.json"),null!=e.weightData&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:"application/octet-stream"}),"model.weights.bin");const s=await this.fetch(this.path,t);if(s.ok)return{modelArtifactsInfo:It(e),responses:[s]};throw new Error("BrowserHTTPRequest.save() failed due to HTTP response status "+s.status+".")}async load(){const e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code `+e.status+". Please verify this URL points to the model JSON of the model to load.");let t;try{t=await e.json()}catch(e){let t=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?t+=" 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.":t+=" Please make sure the server is serving valid JSON for this request.",new Error(t)}const n=t.modelTopology,r=t.weightsManifest,s=t.generatedBy,o=t.convertedBy,a=t.format,i=t.signature,l=t.userDefinedMetadata;if(null==n&&null==r)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);let u,c;if(null!=r){const e=await this.loadWeights(r);[u,c]=e}const h={modelTopology:n,weightSpecs:u,weightData:c,generatedBy:s,convertedBy:o,format:a};null!=i&&(h.signature=i),null!=l&&(h.userDefinedMetadata=l);const d=t.modelInitializer;return d&&(h.modelInitializer=d),h}async loadWeights(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[n,r]=function(e){const t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),r=e.substring(0,t),s=n>t?e.substring(n):"";return[r+"/",s]}(t),s=this.weightPathPrefix||n,o=[];for(const t of e)o.push(...t.weights);const a=[],i=[];for(const t of e)for(const e of t.paths)null!=this.weightUrlConverter?i.push(this.weightUrlConverter(e)):a.push(s+e+r);this.weightUrlConverter&&a.push(...await Promise.all(i));return[o,_t(await un(a,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress}))]}}function dn(e){return null!=e.match(hn.URL_SCHEME_REGEX)}hn.URL_SCHEME_REGEX=/^https?:\/\//;const pn=(e,t)=>{if("undefined"==typeof fetch&&(null==t||null==t.fetchFunc))return null;{let n=!0;if(n=Array.isArray(e)?e.every(e=>dn(e)):dn(e),n)return fn(e,t)}return null};function fn(e,t){return new hn(e,t)}$t.registerSaveRouter(pn),$t.registerLoadRouter(pn);class mn{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}}class gn{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}}var bn=Object.freeze({__proto__:null,browserFiles:function(e){return new an(e)},browserHTTPRequest:function(e,t){return fn(e,t)},concatenateArrayBuffers:_t,decodeWeights:xt,encodeWeights:async function(e,t){const n=[],r=[],s=Array.isArray(e)?e.map(e=>e.name):Object.keys(e);for(let o=0;o<s.length;++o){const a=s[o],i=Array.isArray(e)?e[o].tensor:e[a];if("float32"!==i.dtype&&"int32"!==i.dtype&&"bool"!==i.dtype&&"string"!==i.dtype&&"complex64"!==i.dtype)throw new Error(`Unsupported dtype in weight '${a}': ${i.dtype}`);const l={name:a,shape:i.shape,dtype:i.dtype};if("string"===i.dtype){const e=new Promise(async e=>{const t=await i.bytes(),n=t.reduce((e,t)=>e+t.length,0)+4*t.length,r=new Uint8Array(n);let s=0;for(let e=0;e<t.length;e++){const n=t[e],o=new Uint8Array(new Uint32Array([n.length]).buffer);r.set(o,s),s+=4,r.set(n,s),s+=n.length}e(r)});r.push(e)}else r.push(i.data());null!=t&&(l.group=t),n.push(l)}return{data:Et(await Promise.all(r)),specs:n}},fromMemory:function(e,t,n,r){if(1===arguments.length){return null!=e.modelTopology||null!=e.weightSpecs?new mn(e):(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 mn({modelTopology:e}))}return 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 mn({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:r})},getLoadHandlers:(e,t)=>$t.getLoadHandlers(e,t),getModelArtifactsInfoForJSON:It,getSaveHandlers:e=>$t.getSaveHandlers(e),http:fn,isHTTPScheme:dn,loadWeights:async function(e,t="",n,r){return cn(e=>un(e,{requestInit:r}))(e,t,n)},registerLoadRouter:e=>$t.registerLoadRouter(e),registerSaveRouter:e=>$t.registerSaveRouter(e),weightsLoaderFactory:cn,withSaveHandler:function(e){return new gn(e)},copyModel:async function(e,t){return Zt(e,t,!1)},listModels:async function(){const e=Ht.getSchemes(),t={};for(const n of e){const e=await Ht.getManager(n).listModels();for(const r in e){t[n+"://"+r]=e[r]}}return t},moveModel:async function(e,t){return Zt(e,t,!0)},removeModel:async function(e){const t=jt(e);return Ht.getManager(t.scheme).removeModel(t.path)}});const yn=bt({matMul_:function(e,t,n=!1,r=!1){let s=mt(e,"a","matMul"),o=mt(t,"b","matMul");[s,o]=et(s,o);const a={a:s,b:o},i={transposeA:n,transposeB:r};return lt.runKernel("BatchMatMul",a,i)}});const wn=bt({oneHot_:function(e,t,n=1,r=0){if(t<2)throw new Error("Error in oneHot: depth must be >=2, but it is "+t);const s={indices:mt(e,"indices","oneHot","int32")},o={depth:t,onValue:n,offValue:r};return lt.runKernel("OneHot",s,o)}});const kn=bt({transpose_:function(e,t){const n=mt(e,"x","transpose");if(null==t&&(t=n.shape.map((e,t)=>t).reverse()),o(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of perm ${t}.`),t.forEach(e=>{o(e>=0&&e<n.rank,()=>"All entries in 'perm' must be between 0 and "+(n.rank-1)+" but got "+t)}),n.rank<=1)return n.clone();const r={x:n},s={perm:t};return lt.runKernel("Transpose",r,s)}});const vn=bt({confusionMatrix_:function(e,t,n){const r=mt(e,"labels","confusionMatrix"),s=mt(t,"predictions","confusionMatrix");o(null==n||n>0&&Number.isInteger(n),()=>"If provided, numClasses must be a positive integer, but got "+n),o(1===r.rank,()=>"Expected the rank of labels to be 1, but got "+r.rank),o(1===s.rank,()=>"Expected the rank of predictions to be 1, but got "+s.rank),o(r.shape[0]===s.shape[0],()=>`Mismatch in the number of examples: ${r.shape[0]} vs. ${s.shape[0]}. Labels and predictions should have the same number of elements.`),o(n>0&&Number.isInteger(n),()=>"numClasses is required to be a positive integer, but got "+n);const a=wn(tn(r,"int32"),n),i=wn(tn(s,"int32"),n),l=kn(a),u=yn(l,i);return tn(u,"int32")}});var xn=Object.freeze({__proto__:null,confusionMatrix:vn});function En(e,t,n){if(i(e),null!=t&&3!==t.length)throw new Error("tensor3d() requires shape to have three numbers");const r=pt(e,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==t)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return wt(e,t,r,n)}let Sn;function An(e,t=3){if(t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(null==e)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let n=!1,r=!1,s=!1,o=!1,a=!1,i=!1;if(e.data instanceof Uint8Array)n=!0;else if("undefined"!=typeof ImageData&&e instanceof ImageData)r=!0;else if("undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement)s=!0;else if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)o=!0;else if(null!=e.getContext)a=!0;else{if(!("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap))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 "+e.constructor.name);i=!0}if(s){const t=2;if(s&&e.readyState<t)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.")}if(null!=K("FromPixels",lt.backendName)){const n={pixels:e},r={numChannels:t};return lt.runKernel("FromPixels",n,r)}const[l,u]=s?[e.videoWidth,e.videoHeight]:[e.width,e.height];let c,h;if(a?c=e.getContext("2d").getImageData(0,0,l,u).data:r||n?c=e.data:(o||s||i)&&(null==Sn&&(Sn=document.createElement("canvas").getContext("2d")),Sn.canvas.width=l,Sn.canvas.height=u,Sn.drawImage(e,0,0,l,u),c=Sn.getImageData(0,0,l,u).data),4===t)h=new Int32Array(c);else{const e=l*u;h=new Int32Array(e*t);for(let n=0;n<e;n++)for(let e=0;e<t;++e)h[n*t+e]=c[4*n+e]}return En(h,[u,l,t],"int32")}function _n(e){return"undefined"!=typeof window&&"undefined"!=typeof ImageBitmap&&window.hasOwnProperty("createImageBitmap")&&!(e instanceof ImageBitmap)&&function(e){return null!=e&&0!==e.width&&0!==e.height}(e)&&!function(e){return null!=e&&e.data instanceof Uint8Array}(e)}const Nn=bt({fromPixels_:An});var In=Object.freeze({__proto__:null,fromPixelsAsync:async function(e,t=3){let n=null;if(C().getBool("WRAP_TO_IMAGEBITMAP")&&_n(e)){let t;try{t=await createImageBitmap(e,{premultiplyAlpha:"none"})}catch(e){t=null}n=null!=t&&t.width===e.width&&t.height===e.height?t:e}else n=e;return An(n,t)},toPixels:async function(e,t){let n=mt(e,"img","toPixels");if(!(e instanceof Ge)){const e=n;n=tn(e,"int32"),e.dispose()}if(2!==n.rank&&3!==n.rank)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${n.rank}.`);const[r,s]=n.shape.slice(0,2),o=2===n.rank?1:n.shape[2];if(o>4||2===o)throw new Error("toPixels only supports depth of size 1, 3 or 4 but got "+o);if("float32"!==n.dtype&&"int32"!==n.dtype)throw new Error(`Unsupported type for toPixels: ${n.dtype}. Please use float32 or int32 tensors.`);const a=await n.data(),i="float32"===n.dtype?255:1,l=new Uint8ClampedArray(s*r*4);for(let e=0;e<r*s;++e){const t=[0,0,0,255];for(let r=0;r<o;r++){const s=a[e*o+r];if("float32"===n.dtype){if(s<0||s>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${s}.`)}else if("int32"===n.dtype&&(s<0||s>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${s}.`);1===o?(t[0]=s*i,t[1]=s*i,t[2]=s*i):t[r]=s*i}const r=4*e;l[r+0]=Math.round(t[0]),l[r+1]=Math.round(t[1]),l[r+2]=Math.round(t[2]),l[r+3]=Math.round(t[3])}if(null!=t){t.width=s,t.height=r;const e=t.getContext("2d"),n=new ImageData(l,s,r);e.putImageData(n,0,0)}return n!==e&&n.dispose(),l},fromPixels:Nn});function Mn(e,t){const n=e.shape.length,r=t.shape.length;if(n<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${n}.`);if(r<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${r}.`);if("int32"!==t.dtype)throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[r-1]>n)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[r-1]} vs. ${n}`);if(0===u(e.shape))throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);const s=t.shape,o=s[s.length-1];let a=1;for(let e=0;e<s.length-1;++e)a*=s[e];const i=e.shape,l=s.slice();l.pop();let c=1;for(let e=o;e<n;++e)c*=i[e],l.push(i[e]);const h=[...I(e.shape).map(e=>e/c),1].slice(0,o);return[l,a,c,h]}var $n=Object.freeze({__proto__:null,prepareAndValidate:Mn});function Tn(e,t,n){const r=t.rank>1?t.shape[t.rank-1]:1,s=t.rank>1?t.rank-1:1,o="Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: "+n.shape+`, indices.shape: ${t.shape}, shape: ${e}`+`, sliceDim: ${r}, and batchDim: ${s}.`;if(n.rank<s)throw new Error(o+` update.rank < ${s}. `);if(e.length<r+(n.rank-s))throw new Error(o+" Output shape length < "+(r+(n.rank-s)));if(n.rank!==s+e.length-r)throw new Error(o+" update.rank != "+(s+e.length-r));for(let e=0;e<s;++e)if(n.shape[e]!==t.shape[e])throw new Error(o+` updates.shape[${e}] (${n.shape[e]}) != indices.shape[${e}] (${t.shape[e]}).`);for(let t=0;t<n.rank-s;++t)if(n.shape[t+s]!==e[t+r])throw new Error(o+` updates.shape[${t+s}] (${n.shape[t+s]}) != shape[${t+s}] (${e[t+s]})`)}function Dn(e,t,n){if(t.rank<1)throw new Error(`tf.scatterND() expects the indices to be rank 1 or higher, but the rank was ${t.rank}.`);if(e.rank<1)throw new Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was ${e.rank}.`);if("int32"!==t.dtype)throw new Error("The dtype of 'indices' should be int32, but got dtype: "+t.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===t.size)throw new Error("Indices specified for empty output. indices shape: "+t.shape);if(0===e.size)throw new Error("Updates specified for empty output. updates shape: "+e.shape)}Tn(n,t,e)}function Rn(e,t,n){const r=t.shape.length,s=r>1?t.shape[r-1]:1,o=n.length;let a=1;for(let e=s;e<o;++e)a*=n[e];const i=s<1?1:s;return{sliceRank:s,numUpdates:u(t.shape)/i,sliceSize:a,strides:[...I(n.slice(0,s)),1],outputSize:u(n)}}var Bn=Object.freeze({__proto__:null,validateUpdateShape:Tn,validateInput:Dn,calculateShapes:Rn});function Fn(e){const t=[];let n=0;for(;e>0;)1&e&&t.push(n),e/=2,n++;return t}function Cn(e,t,n){const r=[];for(let s=0;s<e.length;s++)r[s]=Math.ceil((t[s]-e[s])/n[s]);return r}function Pn(e,t,n,r){const s=[...e];for(let e=s.length;e<r.length;e++)s.push(1);for(let e=0;e<n;e++)0===e?s[t]=1:(s.splice(t,0,1),s.pop());return s}function Ln(e,t,n){return n<=e?n:n-(t-1)}function On(e,t){const n=[];for(let r=0;r<e;r++)n.push(t+r);return n}function zn(e,t,n,r,s,o,a,i,l){const u=e.length;let c=new Array(u),h=new Array(u),d=new Array(u);if(t.length&&n>0){const l=t[0],u=n+1;c=qn(a,l,u,r,e),h=Kn(i,l,u,s,e),d=Pn(o,l,u,e)}else for(let t=0;t<u;t++)c[t]=Un(a,r,o,e,t,l),h[t]=Gn(i,s,o,e,t,l),d[t]=Wn(o,t,l);return{begin:c,end:h,strides:d}}function qn(e,t,n,r,s){const o=[...s],a=On(n,t);for(let s=0;s<o.length;s++)if(a.indexOf(s)>-1)o[s]=0;else{const a=Ln(t,n,s);let i=r[a];e&1<<a&&(i=0),o[s]=i}return o}function Kn(e,t,n,r,o){const a=[...o],i=On(n,t);for(let s=0;s<a.length;s++)if(i.indexOf(s)>-1)a[s]=Number.MAX_SAFE_INTEGER;else{const o=Ln(t,n,s);let i=r[o];e&1<<o&&(i=Number.MAX_SAFE_INTEGER),a[s]=i}for(let e=0;e<a.length;e++){const t=o[e];a[e]<0&&(a[e]+=t),a[e]=s(0,a[e],o[e])}return a}function Wn(e,t,n){let r=e[t];return(n&1<<t||null==r)&&(r=1),r}function Un(e,t,n,r,o,a){let i=t[o];const l=n[o]||1;(e&1<<o||a&1<<o||null==i)&&(i=l>0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);const u=r[o];return i<0&&(i+=u),i=s(0,i,u-1),i}function Gn(e,t,n,r,o,a){let i=t[o];const l=n[o]||1;(e&1<<o||a&1<<o||null==i)&&(i=l>0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);const u=r[o];return i<0&&(i+=u),i=l>0?s(0,i,u):s(-1,i,u-1),i}var Vn=Object.freeze({__proto__:null,assertParamsValid:function(e,t,n){const r=e.shape.length;o(r===t.length,()=>`Error in slice${r}D: Length of begin ${t} must match the rank of the array (${r}).`),o(r===n.length,()=>`Error in slice${r}D: Length of size ${n} must match the rank of the array (${r}).`);for(let s=0;s<r;++s)o(t[s]+n[s]<=e.shape[s],()=>`Error in slice${r}D: begin[${s}] + size[${s}] (${t[s]+n[s]}) would overflow input.shape[${s}] (${e.shape[s]})`)},maskToAxes:Fn,computeOutShape:Cn,stridesWithElidedDims:Pn,getNormalizedAxes:zn,startIndicesWithElidedDims:qn,stopIndicesWithElidedDims:Kn,stridesForAxis:Wn,startForAxis:Un,stopForAxis:Gn,isSliceContinous:function(e,t,n){let r=n.length;for(let e=0;e<n.length;e++)if(n[e]>1){r=e;break}for(let s=r+1;s<n.length;s++)if(t[s]>0||n[s]!==e[s])return!1;return!0},computeFlatOffset:function(e,t){let n=e.length>0?e[e.length-1]:1;for(let r=0;r<e.length-1;r++)n+=e[r]*t[r];return n},parseSliceParams:function(e,t,n){let r;const s=e.shape.length;let a;return r="number"==typeof t?[t,...new Array(s-1).fill(0)]:t.length<s?t.concat(new Array(s-t.length).fill(0)):t.slice(),r.forEach(e=>{o(-1!==e,()=>"slice() does not support negative begin indexing.")}),a=null==n?new Array(s).fill(-1):"number"==typeof n?[n,...new Array(s-1).fill(-1)]:n.length<s?n.concat(new Array(s-n.length).fill(-1)):n,a=a.map((t,n)=>t>=0?t:(o(-1===t,()=>`Negative size values should be exactly -1 but got ${t} for the slice() size at index ${n}.`),e.shape[n]-r[n])),[r,a]},sliceInfo:function(e,t,n,r,s,o,a,i,l){let u=t.slice(),c=n.slice(),h=r;null==r&&(h=new Array(u.length));const d=Fn(a);if(d.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(0!==a&&0!==i)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(0!==a&&0!==l)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");const p=e.length-u.length,f=Fn(i),m=e.slice();f.forEach(e=>{u[e]=0,c[e]=1,m.splice(e,0,1)});const{begin:g,end:b,strides:y}=zn(m,d,p,u,c,h,s,o,a);u=g,c=b,h=y;const w=Fn(l);w.forEach(e=>{c[e]=u[e]+1,h[e]=1});const k=Cn(u,c,h),v=k.filter((e,t)=>-1===w.indexOf(t));return{nonStrided:h.every(e=>1===e),$begin:u,$end:c,$strides:h,size:k,newShape:m,outShape:v}}});class Hn{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class jn{constructor(){this.classNameMap={}}static getMap(){return null==jn.instance&&(jn.instance=new jn),jn.instance}static register(e){jn.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function Zn(e){o(null!=e.className,()=>"Class being registered does not have the static className property defined."),o("string"==typeof e.className,()=>"className is required to be a string, but got type "+typeof e.className),o(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),jn.register(e)}var Jn=Object.freeze({__proto__:null,Serializable:Hn,SerializationMap:jn,registerClass:Zn});function Yn(){return 32===lt.backend.floatPrecision()?.001:.1}function Xn(e,t,n){let r=!0;if((w(e)||w(t))&&(r=!1),w(e)&&w(t)&&(r=!0),r){const n=e.constructor.name,r=t.constructor.name;if(n!==r)throw new Error(`Arrays are of different type. Actual: ${n}. Expected: `+r)}if(Array.isArray(e)&&Array.isArray(t)){const n=pt(e),r=pt(t);if(!c(n,r))throw new Error(`Arrays have different shapes. Actual: [${n}]. Expected: [${r}]`)}const s=w(e)?e:l(e),o=w(t)?t:l(t);if(s.length!==o.length)throw new Error(`Arrays have different lengths actual: ${s.length} vs expected: ${o.length}.\nActual: ${s}.\nExpected: ${o}.`);for(let e=0;e<o.length;++e){const t=s[e],r=o[e];if(!n(t,r))throw new Error(`Arrays differ: actual[${e}] = ${t}, expected[${e}] = ${r}.\nActual: ${s}.\nExpected: ${o}.`)}}function Qn(e,t,n){return!isFinite(e)&&!isFinite(t)||!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}var er=Object.freeze({__proto__:null,TEST_EPSILON_FLOAT16:.1,expectArraysClose:function(e,t,n){return null==n&&(n=Yn()),Xn(e,t,(e,t)=>Qn(e,t,n))},testEpsilon:Yn,expectPromiseToFail:function(e,t){e().then(()=>t.fail(),()=>t())},expectArraysEqual:function(e,t){const n="string"==typeof t||"number"==typeof t||"boolean"==typeof t?[t]:t;return x(e)||x(e[0])||x(t)||x(t[0])?Xn(e,n,(e,t)=>e==t):Xn(e,t,(e,t)=>Qn(e,t,0))},expectNumbersClose:function(e,t,n){if(null==n&&(n=Yn()),!Qn(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)},expectValuesInRange:function(e,t,n){for(let r=0;r<e.length;r++)if(e[r]<t||e[r]>n)throw new Error(`Value out of range:${e[r]} low: ${t}, high: ${n}`)},expectArrayBuffersEqual:function(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))},encodeStrings:function e(t){for(let n=0;n<t.length;n++){const r=t[n];Array.isArray(r)?e(r):t[n]=De(r)}return t}});function tr(e,t){return lt.tidy(e,t)}function nr(e){nt(e).forEach(e=>e.dispose())}function rr(e){return lt.keep(e)}const sr=bt({add_:function(e,t){let n=mt(e,"a","add"),r=mt(t,"b","add");[n,r]=et(n,r);const s={a:n,b:r};return lt.runKernel("Add",s)}});const or=bt({floorDiv_:function(e,t){let n=mt(e,"a","floorDiv"),r=mt(t,"b","floorDiv");[n,r]=et(n,r);const s={a:n,b:r};return lt.runKernel("FloorDiv",s)}});const ar=bt({div_:function(e,t){let n=mt(e,"a","div"),r=mt(t,"b","div");if([n,r]=et(n,r),"int32"===n.dtype&&"int32"===r.dtype)return or(n,r);const s={a:n,b:r};return lt.runKernel("RealDiv",s,{})}});const ir=bt({mul_:function(e,t){let n=mt(e,"a","mul"),r=mt(t,"b","mul");[n,r]=et(n,r);const s={a:n,b:r};return lt.runKernel("Multiply",s)}});const lr=bt({abs_:function(e){const t=mt(e,"x","abs");if("complex64"===t.dtype){const e={x:t};return lt.runKernel("ComplexAbs",e)}{const e={x:t};return lt.runKernel("Abs",e)}}});const ur=bt({acos_:function(e){const t={x:mt(e,"x","acos")};return lt.runKernel("Acos",t)}});const cr=bt({acosh_:function(e){const t={x:mt(e,"x","acosh")};return lt.runKernel("Acosh",t)}});const hr=bt({addN_:function(e){o(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),o(e.length>=1,()=>"Must pass at least one tensor to tf.addN(), but got "+e.length);const t=e.map((e,t)=>mt(e,"tensors"+t,"addN")),n=t[0];t.forEach(e=>{if(e.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(e=>{if(!c(e.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});const r=t;return lt.runKernel("AddN",r)}});const dr=bt({all_:function(e,t=null,n=!1){const r={x:mt(e,"x","all","bool")},s={axis:t,keepDims:n};return lt.runKernel("All",r,s)}});const pr=bt({any_:function(e,t=null,n=!1){const r={x:mt(e,"x","any","bool")},s={axis:t,keepDims:n};return lt.runKernel("Any",r,s)}});const fr=bt({argMax_:function(e,t=0){const n={x:mt(e,"x","argMax")},r={axis:t};return lt.runKernel("ArgMax",n,r)}});const mr=bt({argMin_:function(e,t=0){const n={x:mt(e,"x","argMin")},r={axis:t};return lt.runKernel("ArgMin",n,r)}});const gr=bt({asin_:function(e){const t={x:mt(e,"x","asin")};return lt.runKernel("Asin",t)}});const br=bt({asinh_:function(e){const t={x:mt(e,"x","asinh")};return lt.runKernel("Asinh",t)}});const yr=bt({atan_:function(e){const t={x:mt(e,"x","atan")};return lt.runKernel("Atan",t)}});const wr=bt({atan2_:function(e,t){let n=mt(e,"a","atan2"),r=mt(t,"b","atan2");[n,r]=et(n,r);const s={a:n,b:r};return lt.runKernel("Atan2",s)}});const kr=bt({atanh_:function(e){const t={x:mt(e,"x","atanh")};return lt.runKernel("Atanh",t)}});function vr(e,t,n,r,s,o,a="channelsLast"){const[i,l]=Ar(t);let u;if("channelsLast"===a)u=[i,l,e[3],e[3]];else{if("channelsFirst"!==a)throw new Error("Unknown dataFormat "+a);u=[i,l,e[1],e[1]]}return xr(e,u,n,r,s,o,!1,a)}function xr(e,t,n,r,s,o,a=!1,i="channelsLast"){let[l,u,c,h]=[-1,-1,-1,-1];if("channelsLast"===i)[l,u,c,h]=e;else{if("channelsFirst"!==i)throw new Error("Unknown dataFormat "+i);[l,h,u,c]=e}const[d,p,,f]=t,[m,g]=Ar(n),[b,y]=Ar(r),w=Nr(d,b),k=Nr(p,y),{padInfo:v,outHeight:x,outWidth:E}=function(e,t,n,r,s,o,a,i,l){let u,c,h;if("number"==typeof e){u={top:e,bottom:e,left:e,right:e,type:0===e?"VALID":"NUMBER"};const s=function(e,t,n,r,s){null==r&&(r=Sr(e,t,n));const o=e[0],a=e[1],i=Ir((o-t+2*r)/n+1,s),l=Ir((a-t+2*r)/n+1,s);return[i,l]}([t,n],o,r,e,i);c=s[0],h=s[1]}else if("same"===e){c=Math.ceil(t/r),h=Math.ceil(n/s);const e=Math.max(0,(c-1)*r+o-t),i=Math.max(0,(h-1)*s+a-n),l=Math.floor(e/2),d=e-l,p=Math.floor(i/2);u={top:l,bottom:d,left:p,right:i-p,type:"SAME"}}else if("valid"===e)u={top:0,bottom:0,left:0,right:0,type:"VALID"},c=Math.ceil((t-o+1)/r),h=Math.ceil((n-a+1)/s);else{if("object"!=typeof e)throw Error("Unknown padding parameter: "+e);{const d="channelsLast"===l?e[1][0]:e[2][0],p="channelsLast"===l?e[1][1]:e[2][1],f="channelsLast"===l?e[2][0]:e[3][0],m="channelsLast"===l?e[2][1]:e[3][1];u={top:d,bottom:p,left:f,right:m,type:0===d&&0===p&&0===f&&0===m?"VALID":"EXPLICIT"},c=Ir((t-o+d+p)/r+1,i),h=Ir((n-a+f+m)/s+1,i)}}return{padInfo:u,outHeight:c,outWidth:h}}(s,u,c,m,g,w,k,o,i),S=a?f*h:f;let A;return"channelsFirst"===i?A=[l,S,x,E]:"channelsLast"===i&&(A=[l,x,E,S]),{batchSize:l,dataFormat:i,inHeight:u,inWidth:c,inChannels:h,outHeight:x,outWidth:E,outChannels:S,padInfo:v,strideHeight:m,strideWidth:g,filterHeight:d,filterWidth:p,effectiveFilterHeight:w,effectiveFilterWidth:k,dilationHeight:b,dilationWidth:y,inShape:e,outShape:A,filterShape:t}}function Er(e,t,n,r,s,o=!1,a="channelsLast",i){let[l,u,c,h,d]=[-1,-1,-1,-1,-1];if("channelsLast"===a)[l,u,c,h,d]=e;else{if("channelsFirst"!==a)throw new Error("Unknown dataFormat "+a);[l,d,u,c,h]=e}const[p,f,m,,g]=t,[b,y,w]=_r(n),[k,v,x]=_r(r),E=Nr(p,k),S=Nr(f,v),A=Nr(m,x),{padInfo:_,outDepth:N,outHeight:I,outWidth:M}=function(e,t,n,r,s,o,a,i,l,u,c){let h,d,p,f;if("number"==typeof e){h={top:e,bottom:e,left:e,right:e,front:e,back:e,type:0===e?"VALID":"NUMBER"};const o=function(e,t,n,r,s,o){null==s&&(s=Sr(e,t,r));const a=e[0],i=e[1],l=e[2],u=Ir((a-t+2*s)/r+1,o),c=Ir((i-t+2*s)/r+1,o),h=Ir((l-t+2*s)/r+1,o);return[u,c,h,n]}([t,n,r,1],i,1,s,e,c);d=o[0],p=o[1],f=o[2]}else if("same"===e){d=Math.ceil(t/s),p=Math.ceil(n/o),f=Math.ceil(r/a);const e=(d-1)*s+i-t,c=(p-1)*o+l-n,m=(f-1)*a+u-r,g=Math.floor(e/2),b=e-g,y=Math.floor(c/2),w=c-y,k=Math.floor(m/2);h={top:y,bottom:w,left:k,right:m-k,front:g,back:b,type:"SAME"}}else{if("valid"!==e)throw Error("Unknown padding parameter: "+e);h={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},d=Math.ceil((t-i+1)/s),p=Math.ceil((n-l+1)/o),f=Math.ceil((r-u+1)/a)}return{padInfo:h,outDepth:d,outHeight:p,outWidth:f}}(s,u,c,h,b,y,w,E,S,A,i),$=o?g*d:g;let T;return"channelsFirst"===a?T=[l,$,N,I,M]:"channelsLast"===a&&(T=[l,N,I,M,$]),{batchSize:l,dataFormat:a,inDepth:u,inHeight:c,inWidth:h,inChannels:d,outDepth:N,outHeight:I,outWidth:M,outChannels:$,padInfo:_,strideDepth:b,strideHeight:y,strideWidth:w,filterDepth:p,filterHeight:f,filterWidth:m,effectiveFilterDepth:E,effectiveFilterHeight:S,effectiveFilterWidth:A,dilationDepth:k,dilationHeight:v,dilationWidth:x,inShape:e,outShape:T,filterShape:t}}function Sr(e,t,n,r=1){const s=Nr(t,r);return Math.floor((e[0]*(n-1)-n+s)/2)}function Ar(e){return"number"==typeof e?[e,e,e]:2===e.length?[e[0],e[1],1]:e}function _r(e){return"number"==typeof e?[e,e,e]:e}function Nr(e,t){return t<=1?e:e+(e-1)*(t-1)}function Ir(e,t){if(!t)return Math.trunc(e);switch(t){case"round":return Math.round(e);case"ceil":return Math.ceil(e);case"floor":return Math.floor(e);default:throw new Error("Unknown roundingMode "+t)}}function Mr(e){const[t,n,r]=Ar(e);return 1===t&&1===n&&1===r}function $r(e,t){return Mr(e)||Mr(t)}function Tr(e){if("NHWC"===e)return"channelsLast";if("NCHW"===e)return"channelsFirst";throw new Error("Unknown dataFormat "+e)}const Dr=bt({reshape_:function(e,t){const n={x:mt(e,"x","reshape","string_or_numeric")},r={shape:t};return lt.runKernel("Reshape",n,r)}});const Rr=bt({avgPool_:function(e,t,n,r,s){const a=mt(e,"x","avgPool","float32");o($r(n,1),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`);let i=a,l=!1;3===a.rank&&(l=!0,i=Dr(a,[1,a.shape[0],a.shape[1],a.shape[2]])),o(4===i.rank,()=>`Error in avgPool: x must be rank 4 but got rank ${i.rank}.`),null!=s&&o(h(r),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${s} but got pad ${r}.`);const u={x:i},c={filterSize:t,strides:n,pad:r,dimRoundingMode:s};let d=lt.runKernel("AvgPool",u,c);return d=tn(d,a.dtype),l?Dr(d,[d.shape[1],d.shape[2],d.shape[3]]):d}});const Br=bt({avgPool3d_:function(e,t,n,r,s,a="NDHWC"){const i=mt(e,"x","avgPool3d","float32");let l=i,u=!1;4===i.rank&&(u=!0,l=Dr(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),o(5===l.rank,()=>`Error in avgPool3d: x must be rank 5 but got rank ${l.rank}.`),o("NDHWC"===a,()=>"Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of "+a),null!=s&&o(h(r),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${s} but got pad ${r}.`);const c={x:l},d={filterSize:t,strides:n,pad:r,dimRoundingMode:s,dataFormat:a};let p=lt.runKernel("AvgPool3D",c,d);return p=tn(p,l.dtype),u?Dr(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}});const Fr=bt({concat_:function(e,t=0){o(e.length>=1,()=>"Pass at least one tensor to concat");const n=gt(e,"tensors","concat","string_or_numeric");if("complex64"===n[0].dtype&&n.forEach(e=>{if("complex64"!==e.dtype)throw new Error(`Cannot concatenate complex64 tensors with a tensor\n with dtype ${e.dtype}. `)}),1===n.length)return nn(n[0]);const r=n,s={axis:t};return lt.runKernel("Concat",r,s)}});const Cr=bt({sigmoid_:function(e){const t={x:mt(e,"x","sigmoid")};return lt.runKernel("Sigmoid",t)}});const Pr=bt({slice_:function(e,t,n){const r=mt(e,"x","slice","string_or_numeric");if(0===r.rank)throw new Error("Slicing scalar is not possible");const s={x:r},o={begin:t,size:n};return lt.runKernel("Slice",s,o)}});const Lr=bt({tanh_:function(e){const t={x:mt(e,"x","tanh")};return lt.runKernel("Tanh",t)}});const Or=bt({basicLSTMCell_:function(e,t,n,r,s,o){const a=mt(e,"forgetBias","basicLSTMCell"),i=mt(t,"lstmKernel","basicLSTMCell"),l=mt(n,"lstmBias","basicLSTMCell"),u=mt(r,"data","basicLSTMCell"),c=mt(s,"c","basicLSTMCell"),h=mt(o,"h","basicLSTMCell"),d=Fr([u,h],1),p=yn(d,i),f=sr(p,l),m=f.shape[0],g=f.shape[1]/4,b=[m,g],y=Pr(f,[0,0],b),w=Pr(f,[0,g],b),k=Pr(f,[0,2*g],b),v=Pr(f,[0,3*g],b),x=sr(ir(Cr(y),Lr(w)),ir(c,Cr(sr(a,k))));return[x,ir(Lr(x),Cr(v))]}});const zr=bt({batchToSpaceND_:function(e,t,n){const r=mt(e,"x","batchToSpaceND"),s=t.reduce((e,t)=>e*t);o(r.rank>=1+t.length,()=>`input rank is ${r.rank} but should be > than blockShape.length ${t.length}`),o(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),o(r.shape[0]%s==0,()=>`input tensor batch is ${r.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${s}`);const a={x:r},i={blockShape:t,crops:n};return lt.runKernel("BatchToSpaceND",a,i)}});const qr=bt({batchNorm_:function(e,t,n,r,s,a){null==a&&(a=.001);const i=mt(e,"x","batchNorm"),l=mt(t,"mean","batchNorm"),u=mt(n,"variance","batchNorm");let c,h;null!=s&&(c=mt(s,"scale","batchNorm")),null!=r&&(h=mt(r,"offset","batchNorm")),o(l.rank===u.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),o(null==h||l.rank===h.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),o(null==c||l.rank===c.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");const d={x:function(e){let t;return t=0===e.rank||1===e.rank?Dr(e,[1,1,1,e.size]):2===e.rank?Dr(e,[1,1,e.shape[0],e.shape[1]]):3===e.rank?Dr(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e,t}(i),scale:c,offset:h,mean:l,variance:u},p={varianceEpsilon:a},f=lt.runKernel("FusedBatchNorm",d,p);return Dr(f,i.shape)}});const Kr=bt({batchNorm2d_:function(e,t,n,r,s,a){const i=mt(e,"x","batchNorm"),l=mt(t,"mean","batchNorm"),u=mt(n,"variance","batchNorm");let c,h;return null!=s&&(c=mt(s,"scale","batchNorm")),null!=r&&(h=mt(r,"offset","batchNorm")),o(2===i.rank,()=>"Error in batchNorm2D: x must be rank 2 but got rank "+i.rank+"."),o(2===l.rank||1===l.rank,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${l.rank}.`),o(2===u.rank||1===u.rank,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${u.rank}.`),null!=c&&o(2===c.rank||1===c.rank,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${c.rank}.`),null!=h&&o(2===h.rank||1===h.rank,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${h.rank}.`),qr(i,l,u,h,c,a)}});const Wr=bt({batchNorm3d_:function(e,t,n,r,s,a){const i=mt(e,"x","batchNorm"),l=mt(t,"mean","batchNorm"),u=mt(n,"variance","batchNorm");let c,h;return null!=s&&(c=mt(s,"scale","batchNorm")),null!=r&&(h=mt(r,"offset","batchNorm")),o(3===i.rank,()=>"Error in batchNorm3D: x must be rank 3 but got rank "+i.rank+"."),o(3===l.rank||1===l.rank,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${l.rank}.`),o(3===u.rank||1===u.rank,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${u.rank}.`),null!=c&&o(3===c.rank||1===c.rank,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${c.rank}.`),null!=h&&o(3===h.rank||1===h.rank,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${h.rank}.`),qr(i,l,u,h,c,a)}});const Ur=bt({batchNorm4d_:function(e,t,n,r,s,a){const i=mt(e,"x","batchNorm"),l=mt(t,"mean","batchNorm"),u=mt(n,"variance","batchNorm");let c,h;return null!=s&&(c=mt(s,"scale","batchNorm")),null!=r&&(h=mt(r,"offset","batchNorm")),o(4===i.rank,()=>"Error in batchNorm4D: x must be rank 4 but got rank "+i.rank+"."),o(4===l.rank||1===l.rank,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${l.rank}.`),o(4===u.rank||1===u.rank,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${u.rank}.`),null!=c&&o(4===c.rank||1===c.rank,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${c.rank}.`),null!=h&&o(4===h.rank||1===h.rank,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${h.rank}.`),qr(i,l,u,h,c,a)}});const Gr=bt({bincount_:function(e,t,n){const r=mt(e,"x","bincount"),s=mt(t,"weights","bincount");o("int32"===r.dtype,()=>"Error in bincount: input dtype must be int32, but got "+r.dtype),o(n>=0,()=>`size must be non-negative, but got ${n}.`),o(s.size===r.size||0===s.size,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${r.shape}, weights shape: `+s.shape+".");const a={x:r,weights:s},i={size:n};return lt.runKernel("Bincount",a,i)}});const Vr=bt({broadcastTo_:function(e,t){let n=mt(e,"broadcastTo","x");const r=n.shape;if(t.some(e=>!(e>0)||e%1!=0))throw new Error(`broadcastTo(): Invalid broadcast shape [${t}].`);if(t.length<n.rank)throw new Error(`broadcastTo(): shape.length=${t.length} < input.rank=${n.rank}.`);if(t.length>n.rank){const e=n.shape.slice();for(;e.length<t.length;)e.unshift(1);n=Dr(n,e)}const s=n.shape,o=Array.from(t);for(let e=t.length-1;e>=0;e--)if(s[e]===t[e])o[e]=1;else if(1!==n.shape[e])throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${t}].`);if(0===o.map((e,t)=>e>1?t:-1).filter(e=>e>=0).length)return nn(n);const a={x:n},i={reps:o};return lt.runKernel("Tile",a,i)}});const Hr=bt({ceil_:function(e){const t={x:mt(e,"x","ceil")};return lt.runKernel("Ceil",t)}});const jr=bt({clipByValue_:function(e,t,n){const r=mt(e,"x","clipByValue");o(t<=n,()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`);const s={x:r},a={clipValueMin:t,clipValueMax:n};return lt.runKernel("ClipByValue",s,a)}});const Zr=bt({concat1d_:function(e){return Fr(e,0)}});const Jr=bt({concat2d_:function(e,t){return Fr(e,t)}});const Yr=bt({concat3d_:function(e,t){return Fr(e,t)}});const Xr=bt({concat4d_:function(e,t){return Fr(e,t)}});const Qr=bt({conv2d_:function(e,t,n,r,s="NHWC",a=[1,1],i){const l=mt(e,"x","conv2d"),u=mt(t,"filter","conv2d");let c=l,d=!1;3===l.rank&&(d=!0,c=Dr(l,[1,l.shape[0],l.shape[1],l.shape[2]])),o(4===c.rank,()=>`Error in conv2d: input must be rank 4, but got rank ${c.rank}.`),o(4===u.rank,()=>"Error in conv2d: filter must be rank 4, but got rank "+u.rank+"."),null!=i&&o(h(r),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${r}.`);const p="NHWC"===s?c.shape[3]:c.shape[1];o(p===u.shape[2],()=>`Error in conv2d: depth of input (${p}) must match input depth for filter ${u.shape[2]}.`),o($r(n,a),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`);const f={x:c,filter:u},m={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:i},g=lt.runKernel("Conv2D",f,m);return d?Dr(g,[g.shape[1],g.shape[2],g.shape[3]]):g}});const es=bt({conv1d_:function(e,t,n,r,s="NWC",a=1,i){const l=mt(e,"x","conv1d"),u=mt(t,"filter","conv1d");let c=l,d=!1;2===l.rank&&(d=!0,c=Dr(l,[1,l.shape[0],l.shape[1]])),o(3===c.rank,()=>`Error in conv1d: input must be rank 3, but got rank ${c.rank}.`),o(3===u.rank,()=>"Error in conv1d: filter must be rank 3, but got rank "+u.rank+"."),null!=i&&o(h(r),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${r}.`),o(c.shape[2]===u.shape[1],()=>`Error in conv1d: depth of input (${c.shape[2]}) must match input depth for filter ${u.shape[1]}.`),o($r(n,a),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${a}'`),o("NWC"===s,()=>`Error in conv1d: got dataFormat of ${s} but only NWC is currently supported.`);const p=Dr(u,[1,u.shape[0],u.shape[1],u.shape[2]]),f=Dr(c,[c.shape[0],1,c.shape[1],c.shape[2]]),m=Qr(f,p,[1,n],r,"NHWC",[1,a],i);return Dr(m,d?[m.shape[2],m.shape[3]]:[m.shape[0],m.shape[2],m.shape[3]])}});const ts=bt({conv2DBackpropInput_:function(e,t,n,r,s,a="NHWC",i){o(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let l=e,u=t,c=!1;3===t.rank&&(c=!0,u=Dr(t,[1,t.shape[0],t.shape[1],t.shape[2]]),l=[1,e[0],e[1],e[2]]),o(4===l.length,()=>"Error in conv2dDerInput: inShape must be length 4, but got length "+l.length+"."),o(4===u.rank,()=>"Error in conv2dDerInput: dy must be rank 4, but got rank "+u.rank),o(4===n.rank,()=>"Error in conv2dDerInput: filter must be rank 4, but got rank "+n.rank);const d="NHWC"===a?l[3]:l[1],p="NHWC"===a?u.shape[3]:u.shape[1];o(d===n.shape[2],()=>`Error in conv2dDerInput: depth of input (${d}) must match input depth for filter ${n.shape[2]}.`),o(p===n.shape[3],()=>`Error in conv2dDerInput: depth of output (${p}) must match output depth for filter ${n.shape[3]}.`),null!=i&&o(h(s),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);const f={dy:u,filter:n},m={strides:r,pad:s,dataFormat:a,dimRoundingMode:i,inputShape:l},g=lt.runKernel("Conv2DBackpropInput",f,m);return c?Dr(g,[g.shape[1],g.shape[2],g.shape[3]]):g}});const ns=bt({conv2dTranspose_:function(e,t,n,r,s,o){const a=mt(e,"x","conv2dTranspose"),i=mt(t,"filter","conv2dTranspose");return ts(n,a,i,r,s,"NHWC",o)}});const rs=bt({conv3d_:function(e,t,n,r,s="NDHWC",a=[1,1,1]){const i=mt(e,"x","conv3d"),l=mt(t,"filter","conv3d");let u=i,c=!1;4===i.rank&&(c=!0,u=Dr(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),o(5===u.rank,()=>`Error in conv3d: input must be rank 5, but got rank ${u.rank}.`),o(5===l.rank,()=>"Error in conv3d: filter must be rank 5, but got rank "+l.rank+"."),o(u.shape[4]===l.shape[3],()=>`Error in conv3d: depth of input (${u.shape[4]}) must match input depth for filter ${l.shape[3]}.`),o($r(n,a),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),o("NDHWC"===s,()=>`Error in conv3d: got dataFormat of ${s} but only NDHWC is currently supported.`);const h={x:u,filter:l},d={strides:n,pad:r,dataFormat:s,dilations:a},p=lt.runKernel("Conv3D",h,d);return c?Dr(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}});const ss=bt({conv3DBackpropInput_:function(e,t,n,r,s){o(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let a=e,i=t,l=!1;4===t.rank&&(l=!0,i=Dr(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),a=[1,e[0],e[1],e[2],e[3]]);const u=a[4],c=i.shape[4];o(5===a.length,()=>"Error in conv3dDerInput: inShape must be length 5, but got length "+a.length+"."),o(5===i.rank,()=>"Error in conv3dDerInput: dy must be rank 5, but got rank "+i.rank),o(5===n.rank,()=>"Error in conv3dDerInput: filter must be rank 5, but got rank "+n.rank),o(u===n.shape[3],()=>`Error in conv3dDerInput: depth of input (${u}) must match input depth for filter ${n.shape[3]}.`),o(c===n.shape[4],()=>`Error in conv3dDerInput: depth of output (${c}) must match output depth for filter ${n.shape[4]}.`);const h={dy:i,filter:n},d={pad:s,strides:r,inputShape:a},p=lt.runKernel("Conv3DBackpropInputV2",h,d);return l?Dr(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}});const os=bt({conv3dTranspose_:function(e,t,n,r,s){const o=mt(e,"x","conv3dTranspose"),a=mt(t,"filter","conv3dTranspose");return ss(n,o,a,r,s)}});const as=bt({cos_:function(e){const t={x:mt(e,"x","cos")};return lt.runKernel("Cos",t)}});const is=bt({cosh_:function(e){const t={x:mt(e,"x","cosh")};return lt.runKernel("Cosh",t)}});const ls=bt({cumsum_:function(e,t=0,n=!1,r=!1){const s={x:mt(e,"x","cumsum")},o={axis:t,exclusive:n,reverse:r};return lt.runKernel("Cumsum",s,o)}});const us=bt({denseBincount_:function(e,t,n,r=!1){const s=mt(e,"x","denseBincount"),a=mt(t,"weights","denseBincount");o("int32"===s.dtype,()=>"Error in denseBincount: input dtype must be int32, but got "+s.dtype),o(s.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${s.rank}.`),o(n>=0,()=>`size must be non-negative, but got ${n}.`),o(a.size===s.size||0===a.size,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${s.shape}, weights shape: `+a.shape+".");const i={x:s,weights:a},l={size:n,binaryOutput:r};return lt.runKernel("DenseBincount",i,l)}});const cs=bt({depthToSpace_:function(e,t,n="NHWC"){const r=mt(e,"x","depthToSpace"),s="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];o(s*t>=0,()=>`Negative dimension size caused by overflow when multiplying\n ${s} and ${t} for depthToSpace with input shape\n ${r.shape}`),o(a*t>=0,()=>`Negative dimension size caused by overflow when multiplying\n ${a} and ${t} for depthToSpace with input shape\n ${r.shape}`),o(i%(t*t)==0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${i} for depthToSpace with input shape ${r.shape}`);const l={x:r},u={blockSize:t,dataFormat:n};return lt.runKernel("DepthToSpace",l,u)}});const hs=bt({depthwiseConv2d_:function(e,t,n,r,s="NHWC",a=[1,1],i){const l=mt(e,"x","depthwiseConv2d"),u=mt(t,"filter","depthwiseConv2d");let c=l,d=!1;3===l.rank&&(d=!0,c=Dr(l,[1,l.shape[0],l.shape[1],l.shape[2]])),o(4===c.rank,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${c.rank}.`),o(4===u.rank,()=>"Error in depthwiseConv2d: filter must be rank 4, but got rank "+u.rank+"."),o(c.shape[3]===u.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${c.shape[3]}) must match the inChannels dimension in filter ${u.shape[2]}.`),null!=i&&o(h(r),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${r}.`);const p={x:c,filter:u},f={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:i},m=lt.runKernel("DepthwiseConv2dNative",p,f);return d?Dr(m,[m.shape[1],m.shape[2],m.shape[3]]):m}});const ds=bt({diag_:function(e){const t={x:mt(e,"x","diag")};return lt.runKernel("Diag",t)}});const ps=bt({dilation2d_:function(e,t,n,r,s=[1,1],a="NHWC"){const i=mt(e,"x","dilation2d"),l=mt(t,"filter","dilation2d");o(3===i.rank||4===i.rank,()=>"Error in dilation2d: input must be rank 3 or 4, but got rank "+i.rank+"."),o(3===l.rank,()=>"Error in dilation2d: filter must be rank 3, but got rank "+l.rank+"."),o("NHWC"===a,()=>"Error in dilation2d: Only NHWC is currently supported, but got dataFormat of "+a);let u=i,c=!1;3===i.rank&&(u=Dr(i,[1,i.shape[0],i.shape[1],i.shape[2]]),c=!0);const h={x:u,filter:l},d={strides:n,pad:r,dilations:s},p=lt.runKernel("Dilation2D",h,d);return c?Dr(p,[p.shape[1],p.shape[2],p.shape[3]]):p}});function fs(e,t){const n=[];for(let r=0;r<t.length;r++){const s=e[e.length-r-1],o=t.length-r-1,a=t[o];(null==s||1===s&&a>1)&&n.unshift(o)}return n}function ms(e,t){const n=[],r=Math.max(e.length,t.length);for(let s=0;s<r;s++){let r=e[e.length-s-1];null==r&&(r=1);let o=t[t.length-s-1];if(null==o&&(o=1),1===r)n.unshift(o);else if(1===o)n.unshift(r);else{if(r!==o){throw Error(`Operands could not be broadcast together with shapes ${e} and ${t}.`)}n.unshift(r)}}return n}const gs=bt({equal_:function(e,t){let n=mt(e,"a","equal","string_or_numeric"),r=mt(t,"b","equal","string_or_numeric");[n,r]=et(n,r),ms(n.shape,r.shape);const s={a:n,b:r};return lt.runKernel("Equal",s)}});const bs=bt({where_:function(e,t,n){const r=mt(t,"a","where"),s=mt(n,"b","where"),o=mt(e,"condition","where","bool"),a=ms(ms(o.shape,r.shape),s.shape),i={condition:Vr(o,a),t:Vr(r,a),e:Vr(s,a)};return lt.runKernel("Select",i)}});const ys=bt({zerosLike_:function(e){const t={x:mt(e,"x","zerosLike")};return lt.runKernel("ZerosLike",t)}});const ws=bt({divNoNan_:function(e,t){let n=mt(e,"a","div"),r=mt(t,"b","div");[n,r]=et(n,r);const s=ar(n,r),o=ys(s),a=gs(r,o);return bs(a,o,s)}});const ks=bt({dot_:function(e,t){const n=mt(e,"t1","dot"),r=mt(t,"t2","dot");o(!(1!==n.rank&&2!==n.rank||1!==r.rank&&2!==r.rank),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${r.rank}.`);const s=1===n.rank?n.size:n.shape[1],a=1===r.rank?r.size:r.shape[0];if(o(s===a,()=>`Error in dot: inner dimensions of inputs must match, but got ${s} and ${a}.`),1===n.rank&&1===r.rank){const e=Dr(n,[1,-1]),t=Dr(r,[-1,1]),s=yn(e,t);return Dr(s,[])}if(1===n.rank&&2===r.rank){const e=Dr(n,[1,-1]),t=Dr(r,[r.shape[0],r.shape[1]]),s=yn(e,t);return Dr(s,[s.size])}if(2===n.rank&&1===r.rank){const e=Dr(r,[-1,1]),t=yn(n,e);return Dr(t,[t.size])}{const e=Dr(r,[r.shape[0],r.shape[1]]);return yn(n,e)}}});const vs=bt({einsum_:function(e,...t){const n=t.map((e,t)=>mt(e,"tensors"+t,"einsum")),r={equation:e};return lt.runKernel("Einsum",n,r)}});const xs=bt({elu_:function(e){const t={x:mt(e,"x","elu")};return lt.runKernel("Elu",t)}});const Es=bt({erf_:function(e){let t=mt(e,"x","erf");o("int32"===t.dtype||"float32"===t.dtype,()=>"Input dtype must be `int32` or `float32`."),"int32"===t.dtype&&(t=tn(t,"float32"));const n={x:t};return lt.runKernel("Erf",n)}});const Ss=bt({exp_:function(e){const t={x:mt(e,"x","exp")};return lt.runKernel("Exp",t)}});const As=bt({expandDims_:function(e,t=0){const n=mt(e,"x","expandDims","string_or_numeric");o(t<=n.rank,()=>"Axis must be <= rank of the tensor");const r={input:n},s={dim:t};return lt.runKernel("ExpandDims",r,s)}});const _s=bt({expm1_:function(e){const t={x:mt(e,"x","expm1")};return lt.runKernel("Expm1",t)}});const Ns=bt({tile_:function(e,t){const n=mt(e,"x","tile","string_or_numeric");o(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`);const r={x:n},s={reps:t};return lt.runKernel("Tile",r,s)}});const Is=bt({eye_:function(e,t,n,r="float32"){null==t&&(t=e);const s=en([e,t],r),o=e<=t?e:t;for(let e=0;e<o;++e)s.set(1,e,e);const a=Dr(s.toTensor(),[e,t]);if(null==n)return a;if(1===n.length)return Ns(As(a,0),[n[0],1,1]);if(2===n.length)return Ns(As(As(a,0),0),[n[0],n[1],1,1]);if(3===n.length)return Ns(As(As(As(a,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.`)}});function Ms(e,t,n){const r={shape:e,value:t,dtype:n};return lt.runKernel("Fill",{},r)}const $s=bt({floor_:function(e){const t={x:mt(e,"x","floor")};return lt.runKernel("Floor",t)}});const Ts=bt({gather_:function(e,t,n=0,r=0){const s={x:mt(e,"x","gather"),indices:mt(t,"indices","gather","int32")},o={axis:n,batchDims:r};return lt.runKernel("GatherV2",s,o)}});const Ds=bt({greater_:function(e,t){let n=mt(e,"a","greater","string_or_numeric"),r=mt(t,"b","greater","string_or_numeric");[n,r]=et(n,r),ms(n.shape,r.shape);const s={a:n,b:r};return lt.runKernel("Greater",s)}});const Rs=bt({greaterEqual_:function(e,t){let n=mt(e,"a","greaterEqual","string_or_numeric"),r=mt(t,"b","greaterEqual","string_or_numeric");[n,r]=et(n,r),ms(n.shape,r.shape);const s={a:n,b:r};return lt.runKernel("GreaterEqual",s)}});const Bs=bt({imag_:function(e){const t={input:mt(e,"input","imag")};return lt.runKernel("Imag",t)}});const Fs=bt({isFinite_:function(e){const t={x:mt(e,"x","isFinite")};return lt.runKernel("IsFinite",t)}});const Cs=bt({isInf_:function(e){const t={x:mt(e,"x","isInf")};return lt.runKernel("IsInf",t)}});const Ps=bt({isNaN_:function(e){const t={x:mt(e,"x","isNaN")};return lt.runKernel("IsNan",t)}});const Ls=bt({leakyRelu_:function(e,t=.2){const n={x:mt(e,"x","leakyRelu")},r={alpha:t};return lt.runKernel("LeakyRelu",n,r)}});const Os=bt({less_:function(e,t){let n=mt(e,"a","less","string_or_numeric"),r=mt(t,"b","less","string_or_numeric");[n,r]=et(n,r),ms(n.shape,r.shape);const s={a:n,b:r};return lt.runKernel("Less",s)}});const zs=bt({lessEqual_:function(e,t){let n=mt(e,"a","lessEqual","string_or_numeric"),r=mt(t,"b","lessEqual","string_or_numeric");[n,r]=et(n,r),ms(n.shape,r.shape);const s={a:n,b:r};return lt.runKernel("LessEqual",s)}});const qs=bt({localResponseNormalization_:function(e,t=5,n=1,r=1,s=.5){const a=mt(e,"x","localResponseNormalization");o(4===a.rank||3===a.rank,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got\n rank ${a.rank}.`),o(h(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let i=a,l=!1;3===a.rank&&(l=!0,i=Dr(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const u={x:i},c={depthRadius:t,bias:n,alpha:r,beta:s},d=lt.runKernel("LRN",u,c);return l?Dr(d,[d.shape[1],d.shape[2],d.shape[3]]):d}});const Ks=bt({log_:function(e){const t={x:mt(e,"x","log")};return lt.runKernel("Log",t)}});const Ws=bt({log1p_:function(e){const t={x:mt(e,"x","log1p")};return lt.runKernel("Log1p",t)}});function Us(e,t){o(_(e),()=>"The f passed in variableGrads(f) must be a function"),o(null==t||Array.isArray(t)&&t.every(e=>e instanceof Ve),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");const n=null!=t;if(!n){t=[];for(const e in lt.registeredVariables)t.push(lt.registeredVariables[e])}const r=n?t.filter(e=>!e.trainable):null,s=t.length;o((t=t.filter(e=>e.trainable)).length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${s} variables is trainable.`);const{value:a,grads:i}=lt.gradients(e,t,null,!0);o(i.some(e=>null!=e),()=>"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()."),o(0===a.rank,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${a.rank} tensor`);const l={};return t.forEach((e,t)=>{null!=i[t]&&(l[e.name]=i[t])}),null!=r&&r.forEach(e=>l[e.name]=null),{value:a,grads:l}}function Gs(e){return lt.customGrad(e)}function Vs(e){if(e.filter(e=>null==e).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.")}const Hs=bt({neg_:function(e){const t={x:mt(e,"x","neg")};return lt.runKernel("Neg",t)}});const js=bt({softplus_:function(e){const t={x:mt(e,"x","softplus")};return lt.runKernel("Softplus",t)}});const Zs=bt({logSigmoid_:function(e){const t=mt(e,"x","logSigmoid");return Gs(e=>({value:Hs(js(Hs(e))),gradFunc:t=>ir(t,Cr(Hs(e)))}))(t)}});const Js=bt({max_:function(e,t=null,n=!1){const r={x:mt(e,"x","max")},s={reductionIndices:t,keepDims:n};return lt.runKernel("Max",r,s)}});const Ys=bt({sub_:function(e,t){let n=mt(e,"a","sub"),r=mt(t,"b","sub");[n,r]=et(n,r);const s={a:n,b:r};return lt.runKernel("Sub",s)}});const Xs=bt({sum_:function(e,t=null,n=!1){let r=mt(e,"x","sum");"bool"===r.dtype&&(r=tn(r,"int32"));const s={x:r},o={axis:t,keepDims:n};return lt.runKernel("Sum",s,o)}});const Qs=bt({logSoftmax_:function(e,t=-1){const n=mt(e,"logits","logSoftmax");if(-1===t&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);return Gs((e,n)=>{const r=Js(e,t,!0),s=Ys(e,r),o=Ys(tn(s,"float32"),Ks(Xs(Ss(s),t,!0)));n([o]);return{value:o,gradFunc:(e,n)=>{const[r]=n,s=Ss(r);return Ys(e,ir(Xs(e,t,!0),s))}}})(n)}});function eo(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function to(e,t,n){const r=e.length+t.length,s=[];let o=0,a=0;for(let i=0;i<r;i++)-1===n.indexOf(i)?s.push(e[o++]):s.push(t[a++]);return s}function no(e,t){return to(e,t.map(e=>1),t)}const ro=bt({logSumExp_:function(e,t=null,n=!1){const r=mt(e,"x","logSumExp"),s=p(t,r.shape),o=Js(r,s,!0),a=Ys(r,o),i=Ss(a),l=Xs(i,s),u=Ks(l),c=sr(Dr(o,u.shape),u);if(n){const e=no(c.shape,s);return Dr(c,e)}return c}});const so=bt({logicalAnd_:function(e,t){const n=mt(e,"a","logicalAnd","bool"),r=mt(t,"b","logicalAnd","bool");ms(n.shape,r.shape);const s={a:n,b:r};return lt.runKernel("LogicalAnd",s)}});const oo=bt({logicalNot_:function(e){const t={x:mt(e,"x","logicalNot","bool")};return lt.runKernel("LogicalNot",t)}});const ao=bt({logicalOr_:function(e,t){const n=mt(e,"a","logicalOr","bool"),r=mt(t,"b","logicalOr","bool");ms(n.shape,r.shape);const s={a:n,b:r};return lt.runKernel("LogicalOr",s)}});const io=bt({logicalXor_:function(e,t){const n=mt(e,"a","logicalXor","bool"),r=mt(t,"b","logicalXor","bool");return ms(n.shape,r.shape),so(ao(e,t),oo(so(e,t)))}});const lo=bt({maxPool_:function(e,t,n,r,s){const a=mt(e,"x","maxPool");let i=a,l=!1;3===a.rank&&(l=!0,i=Dr(a,[1,a.shape[0],a.shape[1],a.shape[2]])),o(4===i.rank,()=>`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`),o($r(n,1),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`),null!=s&&o(h(r),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${s} but got pad ${r}.`);const u={x:i},c={filterSize:t,strides:n,pad:r,dimRoundingMode:s},d=lt.runKernel("MaxPool",u,c);return l?Dr(d,[d.shape[1],d.shape[2],d.shape[3]]):d}});const uo=bt({maxPool3d_:function(e,t=[1,1,1],n,r,s,a="NDHWC"){const i=mt(e,"x","maxPool3d");let l=i,u=!1;4===i.rank&&(u=!0,l=Dr(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),o(5===l.rank,()=>`Error in maxPool3d: x must be rank 5 but got rank ${l.rank}.`),o("NDHWC"===a,()=>"Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of "+a),null!=s&&o(h(r),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${s} but got pad ${r}.`);const c={x:l},d={filterSize:t,strides:n,pad:r,dimRoundingMode:s,dataFormat:a},p=lt.runKernel("MaxPool3D",c,d);return u?Dr(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}});const co=bt({maxPoolWithArgmax_:function(e,t,n,r,s=!1){const o={x:mt(e,"x","maxPoolWithArgmax")},a={filterSize:t,strides:n,pad:r,includeBatchInIndex:s},i=lt.runKernel("MaxPoolWithArgmax",o,a);return{result:i[0],indexes:i[1]}}});const ho=bt({maximum_:function(e,t){let n=mt(e,"a","maximum"),r=mt(t,"b","maximum");[n,r]=et(n,r),"bool"===n.dtype&&(n=tn(n,"int32"),r=tn(r,"int32")),ms(n.shape,r.shape);const s={a:n,b:r};return lt.runKernel("Maximum",s)}});const po=bt({mean_:function(e,t=null,n=!1){const r={x:mt(e,"x","mean")},s={axis:t,keepDims:n};return lt.runKernel("Mean",r,s)}});function fo(e,t="float32"){if("complex64"===t){const t=fo(e,"float32"),n=fo(e,"float32");return yt(t,n)}const n=T(u(e),t);return lt.makeTensor(n,e,t)}function mo(e,t="float32"){if("complex64"===t){const t=mo(e,"float32"),n=fo(e,"float32");return yt(t,n)}const n=$(u(e),t);return lt.makeTensor(n,e,t)}const go=bt({min_:function(e,t=null,n=!1){const r={x:mt(e,"x","min")},s={axis:t,keepDims:n};return lt.runKernel("Min",r,s)}});const bo=bt({minimum_:function(e,t){let n=mt(e,"a","minimum"),r=mt(t,"b","minimum");[n,r]=et(n,r),"bool"===n.dtype&&(n=tn(n,"int32"),r=tn(r,"int32")),ms(n.shape,r.shape);const s={a:n,b:r};return lt.runKernel("Minimum",s)}});const yo=bt({mirrorPad_:function(e,t,n){o("reflect"===n||"symmetric"===n,()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`);const r=mt(e,"x","mirrorPad");if(0===r.rank)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");o(t.length===r.rank,()=>`Padding doesn't match input. Must be ${r.rank}. Got ${t.length}.`);const s="reflect"===n?1:0;for(let e=0;e<r.rank;e++)o(2===t[e].length,()=>"Invalid number of paddings. Must be length of 2 each."),o(t[e][0]>=0&&t[e][0]<=r.shape[e]-s&&t[e][1]>=0&&t[e][1]<=r.shape[e]-s,()=>`Padding in dimension ${e} cannot be greater than or equal to ${r.shape[e]-s} or less than 0 for input of shape `+r.shape);const a={paddings:t,mode:n},i={x:r};return lt.runKernel("MirrorPad",i,a)}});const wo=bt({mod_:function(e,t){let n=mt(e,"a","mod"),r=mt(t,"b","mod");[n,r]=et(n,r);const s={a:n,b:r};return lt.runKernel("Mod",s)}});const ko=bt({square_:function(e){const t=mt(e,"x","square");return lt.runKernel("Square",{x:t},{})}});const vo=bt({moments_:function(e,t=null,n=!1){const r=p(t,(e=mt(e,"x","moments")).shape),s=po(e,r,n);let o=s.shape;n||(o=no(s.shape,r));const a=ko(Ys(tn(e,"float32"),Dr(s,o)));return{mean:s,variance:po(a,r,n)}}});const xo=bt({multiRNNCell_:function(e,t,n,r){const s=mt(t,"data","multiRNNCell"),o=gt(n,"c","multiRNNCell"),a=gt(r,"h","multiRNNCell");let i=s;const l=[];for(let t=0;t<e.length;t++){const n=e[t](i,o[t],a[t]);l.push(n[0]),l.push(n[1]),i=n[1]}const u=[],c=[];for(let e=0;e<l.length;e+=2)u.push(l[e]),c.push(l[e+1]);return[u,c]}});const Eo=bt({multinomial_:function(e,t,n,r=!1){const s=mt(e,"logits","multinomial"),o=s.size,a=s.rank;if(o<2)throw new Error("Error in multinomial: you need at least 2 outcomes, but got "+o+".");if(a>2)throw new Error("Rank of probabilities must be 1 or 2, but is "+a);n=n||Math.random();const i={logits:1===a?Dr(s,[1,-1]):s},l={numSamples:t,seed:n,normalized:r},u=lt.runKernel("Multinomial",i,l);return 1===a?Dr(u,[u.size]):u}});const So=bt({notEqual_:function(e,t){let n=mt(e,"a","notEqual","string_or_numeric"),r=mt(t,"b","notEqual","string_or_numeric");[n,r]=et(n,r),ms(n.shape,r.shape);const s={a:n,b:r};return lt.runKernel("NotEqual",s)}});const Ao=bt({onesLike_:function(e){const t={x:mt(e,"x","onesLike")};return lt.runKernel("OnesLike",t)}});const _o=bt({outerProduct_:function(e,t){const n=mt(e,"v1","outerProduct"),r=mt(t,"v2","outerProduct");o(1===n.rank&&1===r.rank,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${r.rank}.`);const s=Dr(n,[-1,1]),a=Dr(r,[1,-1]);return yn(s,a)}});const No=bt({pad_:function(e,t,n=0){const r=mt(e,"x","pad");if(0===r.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const s={paddings:t,constantValue:n},o={x:r};return lt.runKernel("PadV2",o,s)}});const Io=bt({pad1d_:function(e,t,n=0){return o(2===t.length,()=>"Invalid number of paddings. Must be length of 2."),No(e,[t],n)}});const Mo=bt({pad2d_:function(e,t,n=0){return o(2===t.length&&2===t[0].length&&2===t[1].length,()=>"Invalid number of paddings. Must be length of 2 each."),No(e,t,n)}});const $o=bt({pad3d_:function(e,t,n=0){return o(3===t.length&&2===t[0].length&&2===t[1].length&&2===t[2].length,()=>"Invalid number of paddings. Must be length of 2 each."),No(e,t,n)}});const To=bt({pad4d_:function(e,t,n=0){return o(4===t.length&&2===t[0].length&&2===t[1].length&&2===t[2].length&&2===t[3].length,()=>"Invalid number of paddings. Must be length of 2 each."),No(e,t,n)}});const Do=bt({spaceToBatchND_:function(e,t,n){const r=mt(e,"x","spaceToBatchND");o(r.rank>=1+t.length,()=>`input rank ${r.rank} should be > than [blockShape] ${t.length}`),o(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),o(r.shape.reduce((e,r,s)=>s>0&&s<=t.length?e&&(r+n[s-1][0]+n[s-1][1])%t[s-1]==0:e,!0),()=>`input spatial dimensions ${r.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`);const s={x:r},a={blockShape:t,paddings:n};return lt.runKernel("SpaceToBatchND",s,a)}});const Ro=bt({pool_:function(e,t,n,r,s,a){null==s&&(s=[1,1]),null==a&&(a=1),0===r&&(r="valid");const i=mt(e,"x","maxPool");let l=i,u=!1;3===i.rank&&(u=!0,l=Dr(i,[1,i.shape[0],i.shape[1],i.shape[2]])),o($r(a,s),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${a} and dilations '${s}'`);const c=vr(l.shape,t,a,s,r),h=[c.dilationHeight,c.dilationWidth];let d;d="same"===r?function(e,t){const n=e.map((e,n)=>e+(e-1)*(t[n]-1)).map(e=>e-1),r=n.map(e=>Math.floor(e/2)),s=n.map((e,t)=>e-r[t]);return n.map((e,t)=>[r[t],s[t]])}([c.filterHeight,c.filterWidth],h):[[0,0],[0,0]];const p=1===h[0]&&1===h[1],[f,m]=function(e,t,n){const r=n.map(e=>e[0]),s=n.map(e=>e[1]),o=e.concat(r,s),a=t.map((e,t)=>(e-o[t]%e)%e),i=s.map((e,t)=>e+a[t]),l=t.map((e,t)=>[r[t],i[t]]),u=t.map((e,t)=>[0,a[t]]);return[l,u]}([c.inHeight,c.inWidth],h,d),g=p?r:"valid",b=p?l:Do(l,h,f),y=("avg"===n?()=>Rr(b,t,a,g):()=>lo(b,t,a,g))(),w=p?y:zr(y,h,m);return u?Dr(w,[w.shape[1],w.shape[2],w.shape[3]]):w}});const Bo=bt({pow_:function(e,t){let n=mt(e,"base","pow"),r=mt(t,"exp","pow");[n,r]=et(n,r);const s={a:n,b:r};return lt.runKernel("Pow",s)}});const Fo=bt({prelu_:function(e,t){const n={x:mt(e,"x","prelu"),alpha:mt(t,"alpha","prelu")};return lt.runKernel("Prelu",n)}});const Co=bt({prod_:function(e,t=null,n=!1){let r=mt(e,"x","prod");"bool"===r.dtype&&(r=tn(r,"int32"));const s={x:r},o={axis:t,keepDims:n};return lt.runKernel("Prod",s,o)}});const Po=bt({rand_:function(e,t,n){const r=u(e);let s=null;if(null==n||"float32"===n)s=new Float32Array(r);else if("int32"===n)s=new Int32Array(r);else{if("bool"!==n)throw new Error("Unknown data type "+n);s=new Uint8Array(r)}for(let e=0;e<r;e++)s[e]=t();return lt.makeTensor(s,e,n)}});"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;function Lo(e,t){return e(t={exports:{}},t.exports),t.exports}var Oo=Lo((function(e){!function(e,t,n){function r(e){var t,n=this,r=(t=4022871197,function(e){e=e.toString();for(var n=0;n<e.length;n++){var r=.02519603282416938*(t+=e.charCodeAt(n));r-=t=r>>>0,t=(r*=t)>>>0,t+=4294967296*(r-=t)}return 2.3283064365386963e-10*(t>>>0)});n.next=function(){var e=2091639*n.s0+2.3283064365386963e-10*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=e-(n.c=0|e)},n.c=1,n.s0=r(" "),n.s1=r(" "),n.s2=r(" "),n.s0-=r(e),n.s0<0&&(n.s0+=1),n.s1-=r(e),n.s1<0&&(n.s1+=1),n.s2-=r(e),n.s2<0&&(n.s2+=1),r=null}function s(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function o(e,t){var n=new r(e),o=t&&t.state,a=n.next;return a.int32=function(){return 4294967296*n.next()|0},a.double=function(){return a()+11102230246251565e-32*(2097152*a()|0)},a.quick=a,o&&("object"==typeof o&&s(o,n),a.state=function(){return s(n,{})}),a}t&&t.exports?t.exports=o:n&&n.amd?n((function(){return o})):this.alea=o}(0,e,!1)})),zo=Lo((function(e){!function(e,t,n){function r(e){var t=this,n="";t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(0|e)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++)t.x^=0|n.charCodeAt(r),t.next()}function s(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t}function o(e,t){var n=new r(e),o=t&&t.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},a.int32=n.next,a.quick=a,o&&("object"==typeof o&&s(o,n),a.state=function(){return s(n,{})}),a}t&&t.exports?t.exports=o:n&&n.amd?n((function(){return o})):this.xor128=o}(0,e,!1)})),qo=Lo((function(e){!function(e,t,n){function r(e){var t=this,n="";t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^e^e<<1)|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(0|e)?t.x=e:n+=e;for(var r=0;r<n.length+64;r++)t.x^=0|n.charCodeAt(r),r==n.length&&(t.d=t.x<<10^t.x>>>4),t.next()}function s(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function o(e,t){var n=new r(e),o=t&&t.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},a.int32=n.next,a.quick=a,o&&("object"==typeof o&&s(o,n),a.state=function(){return s(n,{})}),a}t&&t.exports?t.exports=o:n&&n.amd?n((function(){return o})):this.xorwow=o}(0,e,!1)})),Ko=Lo((function(e){!function(e,t,n){function r(e){var t=this;t.next=function(){var e,n,r=t.x,s=t.i;return e=r[s],n=(e^=e>>>7)^e<<24,n^=(e=r[s+1&7])^e>>>10,n^=(e=r[s+3&7])^e>>>3,n^=(e=r[s+4&7])^e<<7,e=r[s+7&7],n^=(e^=e<<13)^e<<9,r[s]=n,t.i=s+1&7,n},function(e,t){var n,r=[];if(t===(0|t))r[0]=t;else for(t=""+t,n=0;n<t.length;++n)r[7&n]=r[7&n]<<15^t.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],e.x=r,e.i=0,n=256;n>0;--n)e.next()}(t,e)}function s(e,t){return t.x=e.x.slice(),t.i=e.i,t}function o(e,t){null==e&&(e=+new Date);var n=new r(e),o=t&&t.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},a.int32=n.next,a.quick=a,o&&(o.x&&s(o,n),a.state=function(){return s(n,{})}),a}t&&t.exports?t.exports=o:n&&n.amd?n((function(){return o})):this.xorshift7=o}(0,e,!1)})),Wo=Lo((function(e){!function(e,t,n){function r(e){var t=this;t.next=function(){var e,n,r=t.w,s=t.X,o=t.i;return t.w=r=r+1640531527|0,n=s[o+34&127],e=s[o=o+1&127],n^=n<<13,e^=e<<17,n^=n>>>15,e^=e>>>12,n=s[o]=n^e,t.i=o,n+(r^r>>>16)|0},function(e,t){var n,r,s,o,a,i=[],l=128;for(t===(0|t)?(r=t,t=null):(t+="\0",r=0,l=Math.max(l,t.length)),s=0,o=-32;o<l;++o)t&&(r^=t.charCodeAt((o+32)%t.length)),0===o&&(a=r),r^=r<<10,r^=r>>>15,r^=r<<4,r^=r>>>13,o>=0&&(a=a+1640531527|0,s=0==(n=i[127&o]^=r+a)?s+1:0);for(s>=128&&(i[127&(t&&t.length||0)]=-1),s=127,o=512;o>0;--o)r=i[s+34&127],n=i[s=s+1&127],r^=r<<13,n^=n<<17,r^=r>>>15,n^=n>>>12,i[s]=r^n;e.w=a,e.X=i,e.i=s}(t,e)}function s(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function o(e,t){null==e&&(e=+new Date);var n=new r(e),o=t&&t.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},a.int32=n.next,a.quick=a,o&&(o.X&&s(o,n),a.state=function(){return s(n,{})}),a}t&&t.exports?t.exports=o:n&&n.amd?n((function(){return o})):this.xor4096=o}(0,e,!1)})),Uo=Lo((function(e){!function(e,t,n){function r(e){var t=this,n="";t.next=function(){var e=t.b,n=t.c,r=t.d,s=t.a;return e=e<<25^e>>>7^n,n=n-r|0,r=r<<24^r>>>8^s,s=s-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-r|0,t.d=r<<16^n>>>16^s,t.a=s-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=0|e):n+=e;for(var r=0;r<n.length+20;r++)t.b^=0|n.charCodeAt(r),t.next()}function s(e,t){return t.a=e.a,t.b=e.b,t.c=e.c,t.d=e.d,t}function o(e,t){var n=new r(e),o=t&&t.state,a=function(){return(n.next()>>>0)/4294967296};return a.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},a.int32=n.next,a.quick=a,o&&("object"==typeof o&&s(o,n),a.state=function(){return s(n,{})}),a}t&&t.exports?t.exports=o:n&&n.amd?n((function(){return o})):this.tychei=o}(0,e,!1)})),Go=Lo((function(e){!function(t,n){var r,s=this,o=n.pow(256,6),a=n.pow(2,52),i=2*a;function l(e,l,p){var f=[],m=h(function e(t,n){var r,s=[],o=typeof t;if(n&&"object"==o)for(r in t)try{s.push(e(t[r],n-1))}catch(e){}return s.length?s:"string"==o?t:t+"\0"}((l=1==l?{entropy:!0}:l||{}).entropy?[e,d(t)]:null==e?function(){try{var e;return r&&(e=r.randomBytes)?e=e(256):(e=new Uint8Array(256),(s.crypto||s.msCrypto).getRandomValues(e)),d(e)}catch(e){var n=s.navigator,o=n&&n.plugins;return[+new Date,s,o,s.screen,d(t)]}}():e,3),f),g=new u(f),b=function(){for(var e=g.g(6),t=o,n=0;e<a;)e=256*(e+n),t*=256,n=g.g(1);for(;e>=i;)e/=2,t/=2,n>>>=1;return(e+n)/t};return b.int32=function(){return 0|g.g(4)},b.quick=function(){return g.g(4)/4294967296},b.double=b,h(d(g.S),t),(l.pass||p||function(e,t,r,s){return s&&(s.S&&c(s,g),e.state=function(){return c(g,{})}),r?(n.random=e,t):e})(b,m,"global"in l?l.global:this==n,l.state)}function u(e){var t,n=e.length,r=this,s=0,o=r.i=r.j=0,a=r.S=[];for(n||(e=[n++]);s<256;)a[s]=s++;for(s=0;s<256;s++)a[s]=a[o=255&o+e[s%n]+(t=a[s])],a[o]=t;(r.g=function(e){for(var t,n=0,s=r.i,o=r.j,a=r.S;e--;)t=a[s=255&s+1],n=256*n+a[255&(a[s]=a[o=255&o+t])+(a[o]=t)];return r.i=s,r.j=o,n})(256)}function c(e,t){return t.i=e.i,t.j=e.j,t.S=e.S.slice(),t}function h(e,t){for(var n,r=e+"",s=0;s<r.length;)t[255&s]=255&(n^=19*t[255&s])+r.charCodeAt(s++);return d(t)}function d(e){return String.fromCharCode.apply(0,e)}if(n.seedrandom=l,h(n.random(),t),e.exports){e.exports=l;try{r=require("crypto")}catch(e){}}}([],Math)}));Go.alea=Oo,Go.xor128=zo,Go.xorwow=qo,Go.xorshift7=Ko,Go.xor4096=Wo,Go.tychei=Uo;var Vo=Go.alea;class Ho{constructor(e,t,n,r,s){this.mean=e,this.stdDev=t,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);const o=s||Math.random();this.random=Vo(o.toString())}nextValue(){if(!isNaN(this.nextVal)){const e=this.nextVal;return this.nextVal=NaN,e}let e,t,n=!1;for(;!n;){let r,s,o;do{r=2*this.random()-1,s=2*this.random()-1,o=r*r+s*s}while(o>=1||0===o);const a=Math.sqrt(-2*Math.log(o)/o);e=this.mean+this.stdDev*r*a,t=this.mean+this.stdDev*s*a,this.truncated&&!this.isValidTruncated(e)||(n=!0)}return this.truncated&&!this.isValidTruncated(t)||(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return null==this.dtype||"float32"===this.dtype?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}}class jo{constructor(e,t,n,r){this.alpha=e,this.beta=1/t,this.dtype=n;const s=r||Math.random();this.randu=Vo(s.toString()),this.randn=new Ho(0,1,n,!1,this.randu()),this.d=e<1?e+2/3:e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,n,r,s,o;for(;;){do{r=this.randn.nextValue(),o=1+this.c*r}while(o<=0);if(o*=o*o,e=r*r,t=1-.331*e*e,n=.5*e+this.d*(1-o+Math.log(o)),s=this.randu(),s<t||Math.log(s)<n)break}return o=1/this.beta*this.d*o,this.alpha<1&&(o*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(o)}convertValue(e){return"float32"===this.dtype?e:Math.round(e)}}class Zo{constructor(e=0,t=1,n,r){if(this.canReturnFloat=()=>null==this.dtype||"float32"===this.dtype,this.min=e,this.range=t-e,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 ${e} - ${t} <= 1 and dtype is not float`);this.random=Vo(r)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}const Jo=bt({randomGamma_:function(e,t,n=1,r="float32",s){if(null==n&&(n=1),null==r&&(r="float32"),"float32"!==r&&"int32"!==r)throw new Error("Unsupported data type "+r);const o=new jo(t,n,r,s),a=en(e,r);for(let e=0;e<a.values.length;e++)a.values[e]=o.nextValue();return a.toTensor()}});const Yo=bt({randomNormal_:function(e,t=0,n=1,r,s){if(null!=r&&"bool"===r)throw new Error("Unsupported data type "+r);const o=new Ho(t,n,r,!1,s),a=en(e,r);for(let e=0;e<a.values.length;e++)a.values[e]=o.nextValue();return a.toTensor()}});const Xo=bt({randomUniform_:function(e,t=0,n=1,r="float32",s){const o=en(e,r),a=new Zo(t,n,null,s);for(let e=0;e<o.values.length;e++)o.values[e]=a.nextValue();return o.toTensor()}});function Qo(e,t,n=1,r="float32"){if(0===n)throw new Error("Cannot have a step of zero");const s={start:e,stop:t,step:n,dtype:r};return lt.runKernel("Range",{},s)}const ea=bt({real_:function(e){const t={input:mt(e,"input","real")};return lt.runKernel("Real",t)}});const ta=bt({reciprocal_:function(e){const t={x:mt(e,"x","reciprocal")};return lt.runKernel("Reciprocal",t)}});const na=bt({relu_:function(e){const t={x:mt(e,"x","relu")};return lt.runKernel("Relu",t)}});const ra=bt({relu6_:function(e){const t={x:mt(e,"x","relu6")};return lt.runKernel("Relu6",t)}});const sa=bt({reverse_:function(e,t){const n={x:mt(e,"x","reverse")},r={dims:t};return lt.runKernel("Reverse",n,r)}});const oa=bt({reverse1d_:function(e){const t=mt(e,"x","reverse");return o(1===t.rank,()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),sa(t,0)}});const aa=bt({reverse2d_:function(e,t){const n=mt(e,"x","reverse");return o(2===n.rank,()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`),sa(n,t)}});const ia=bt({reverse3d_:function(e,t){const n=mt(e,"x","reverse");return o(3===n.rank,()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`),sa(n,t)}});const la=bt({reverse4d_:function(e,t){const n=mt(e,"x","reverse");return o(4===n.rank,()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`),sa(n,t)}});const ua=bt({round_:function(e){const t={x:mt(e,"x","round")};return lt.runKernel("Round",t)}});const ca=bt({rsqrt_:function(e){const t={x:mt(e,"x","rsqrt")};return lt.runKernel("Rsqrt",t)}});function ha(e,t){if((w(e)&&"string"!==t||Array.isArray(e))&&"complex64"!==t)throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if("string"===t&&w(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return wt(e,[],[],t)}const da=bt({selu_:function(e){const t={x:mt(e,"x","selu")};return lt.runKernel("Selu",t)}});const pa=bt({separableConv2d_:function(e,t,n,r,s,a=[1,1],i="NHWC"){const l=mt(e,"x","separableConv2d"),u=mt(t,"depthwiseFilter","separableConv2d"),c=mt(n,"pointwiseFilter","separableConv2d");let h=l,d=!1;if(3===l.rank&&(d=!0,h=Dr(l,[1,l.shape[0],l.shape[1],l.shape[2]])),"NCHW"===i)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");o(4===h.rank,()=>`Error in separableConv2d: input must be rank 4, but got rank ${h.rank}.`),o(4===u.rank,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${u.rank}.`),o(4===c.rank,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${u.rank}.`),o(1===c.shape[0],()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${c.shape[0]}.`),o(1===c.shape[1],()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${c.shape[1]}.`);const p=u.shape[2],f=u.shape[3];o(c.shape[2]===p*f,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${p*f}, but got ${c.shape[2]}.`);const m=hs(h,u,r,s,i,a),g=Qr(m,c,1,"valid",i);return d?Dr(g,[g.shape[1],g.shape[2],g.shape[3]]):g}});const fa=async function(e,t){const n=mt(e,"x","setdiff1d"),r=mt(t,"y","setdiff1d");o(n.dtype===r.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${r.dtype}).`),o(1===n.rank,()=>`x should be 1D tensor, but got x (${n.shape}).`),o(1===r.rank,()=>`y should be 1D tensor, but got y (${r.shape}).`);const s=await n.data(),a=await r.data(),i=new Set(a);let l=0;for(let e=0;e<s.length;e++)i.has(s[e])||l++;const u=new Ke([l],n.dtype),c=new Ke([l],"int32");for(let e=0,t=0;e<s.length;e++)i.has(s[e])||(u.values[t]=s[e],c.values[t]=e,t++);return[u.toTensor(),c.toTensor()]};const ma=bt({sign_:function(e){const t={x:mt(e,"x","sign")};return lt.runKernel("Sign",t)}});const ga=bt({sin_:function(e){const t={x:mt(e,"x","sin")};return lt.runKernel("Sin",t)}});const ba=bt({sinh_:function(e){const t={x:mt(e,"x","sinh")};return lt.runKernel("Sinh",t)}});const ya=bt({slice1d_:function(e,t,n){const r=mt(e,"x","slice1d");return o(1===r.rank,()=>`slice1d expects a rank-1 tensor, but got a rank-${r.rank} tensor`),Pr(r,[t],[n])}});const wa=bt({slice2d_:function(e,t,n){const r=mt(e,"x","slice2d");return o(2===r.rank,()=>`slice2d expects a rank-2 tensor, but got a rank-${r.rank} tensor`),Pr(r,t,n)}});const ka=bt({slice3d_:function(e,t,n){const r=mt(e,"x","slice3d");return o(3===r.rank,()=>`slice3d expects a rank-3 tensor, but got a rank-${r.rank} tensor`),Pr(r,t,n)}});const va=bt({slice4d_:function(e,t,n){const r=mt(e,"x","slice4d");return o(4===r.rank,()=>`slice4d expects a rank-4 tensor, but got a rank-${r.rank} tensor`),Pr(r,t,n)}});const xa=bt({softmax_:function(e,t=-1){const n=mt(e,"logits","softmax","float32");if(-1===t&&(t=n.rank-1),t!==n.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and dim was ${t}`);const r={logits:n},s={dim:t};return lt.runKernel("Softmax",r,s)}});const Ea=bt({fft_:function(e){o("complex64"===e.dtype,()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);const t={input:e};return lt.runKernel("FFT",t)}});const Sa=bt({ifft_:function(e){o("complex64"===e.dtype,()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);const t={input:e};return lt.runKernel("IFFT",t)}});const Aa=bt({irfft_:function(e){const t=e.shape[e.shape.length-1],n=e.size/t;let r;if(t<=2){const s=Dr(e,[n,t]);r=Sa(s)}else{const s=[n,2*(t-1)],o=Dr(ea(e),[n,t]),a=Dr(Bs(e),[n,t]),i=sa(Pr(o,[0,1],[n,t-2]),1),l=ir(sa(Pr(a,[0,1],[n,t-2]),1),ha(-1)),u=Fr([o,i],1),c=Fr([a,l],1),h=Dr(yt(u,c),[s[0],s[1]]);r=Sa(h)}if(r=ea(r),3===e.rank&&0!==e.shape[0]){const t=r,n=e.shape[0];r=Dr(r,[n,r.shape[0]/n,r.shape[1]]),t.dispose()}return r}});const _a=bt({split_:function(e,t,n=0){const r={x:mt(e,"x","split")},s={numOrSizeSplits:t,axis:n};return lt.runKernel("SplitV",r,s)}});const Na=bt({rfft_:function(e,t){o("float32"===e.dtype,()=>"The dtype for rfft() must be real value but got "+e.dtype);let n=e.shape[e.shape.length-1];const r=e.size/n;let s;if(null!=t&&t<n){const r=e.shape.map(e=>0),o=e.shape.map(e=>e);o[e.shape.length-1]=t,s=Pr(e,r,o),n=t}else if(null!=t&&t>n){const r=e.shape.map(e=>e);r[e.shape.length-1]=t-n,s=Fr([e,fo(r)],e.shape.length-1),n=t}else s=e;const a=ys(s),i=Dr(yt(s,a),[r,n]),l=Ea(i),u=Math.floor(n/2)+1,c=ea(l),h=Bs(l),d=_a(c,[u,n-u],c.shape.length-1),p=_a(h,[u,n-u],h.shape.length-1),f=s.shape.slice();return f[s.shape.length-1]=u,Dr(yt(d[0],p[0]),f)}});const Ia=bt({sqrt_:function(e){const t={x:mt(e,"x","sqrt")};return lt.runKernel("Sqrt",t)}});const Ma=bt({squaredDifference_:function(e,t){let n=mt(e,"a","squaredDifference"),r=mt(t,"b","squaredDifference");[n,r]=et(n,r),ms(n.shape,r.shape);const s={a:n,b:r};return lt.runKernel("SquaredDifference",s,{})}});const $a=bt({squeeze_:function(e,t){const n=mt(e,"x","squeeze");return Dr(n,f(n.shape,t).newShape)}});const Ta=bt({stack_:function(e,t=0){const n=gt(e,"tensors","stack","string_or_numeric");o(n.length>=1,()=>"Pass at least one tensor to tf.stack"),n.length>0&&o(t<=n[0].rank,()=>"Axis must be <= rank of the tensor");const r=n,s={axis:t};return lt.runKernel("Pack",r,s)}});const Da=bt({step_:function(e,t=0){const n={x:mt(e,"x","step")},r={alpha:t};return lt.runKernel("Step",n,r)}});const Ra=bt({stridedSlice_:function(e,t,n,r,s=0,o=0,a=0,i=0,l=0){const u={x:mt(e,"x","stridedSlice","string_or_numeric")},c={begin:t,end:n,strides:r,beginMask:s,endMask:o,ellipsisMask:a,newAxisMask:i,shrinkAxisMask:l};return lt.runKernel("StridedSlice",u,c)}});const Ba=bt({tan_:function(e){const t={x:mt(e,"x","tan")};return lt.runKernel("Tan",t)}});function Fa(e,t){i(e);const n=pt(e,t);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return wt(e,null,n,t)}function Ca(e,t,n){if(i(e),null!=t&&2!==t.length)throw new Error("tensor2d() requires shape to have two numbers");const r=pt(e,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==t)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return wt(e,t,r,n)}const Pa=bt({topk_:function(e,t=1,n=!0){const r=mt(e,"x","topk");if(0===r.rank)throw new Error("topk() expects the input to be of rank 1 or higher");const s=r.shape[r.shape.length-1];if(t>s)throw new Error(`'k' passed to topk() must be <= the last dimension (${s}) but got `+t);const o={x:r},a={k:t,sorted:n},[i,l]=lt.runKernel("TopK",o,a);return{values:i,indices:l}}});const La=bt({truncatedNormal_:function(e,t=0,n=1,r,s){if(null!=r&&"bool"===r)throw new Error("Unsupported data type $ { dtype }");const o=new Ho(t,n,r,!0,s),a=en(e,r);for(let e=0;e<a.values.length;e++)a.values[e]=o.nextValue();return a.toTensor()}});const Oa=bt({unique_:function(e,t=0){const n=mt(e,"x","unique","string_or_numeric");o(n.rank>0,()=>"The input tensor must be at least 1D");const r={x:n},s={axis:t},[a,i]=lt.runKernel("Unique",r,s);return{values:a,indices:i}}});const za=bt({unsortedSegmentSum_:function(e,t,n){const r=mt(e,"x","unsortedSegmentSum"),s=mt(t,"segmentIds","unsortedSegmentSum","int32");o(h(n),()=>"numSegments must be of dtype int");const a={x:r,segmentIds:s},i={numSegments:n};return lt.runKernel("UnsortedSegmentSum",a,i)}});const qa=bt({unstack_:function(e,t=0){const n=mt(e,"x","unstack","string_or_numeric");o(t>=-n.shape.length&&t<n.shape.length,()=>`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`);const r={value:n},s={axis:t};return lt.runKernel("Unpack",r,s)}});function Ka(e,t){const n=[];for(let e=0;e<t.length;e++)t[e]&&n.push(e);const r=en(e,"int32"),s=en([n.length,e.length],"int32");for(let t=0;t<n.length;t++){const o=r.indexToLoc(n[t]),a=t*e.length;s.values.set(o,a)}return s.toTensor()}const Wa=async function(e){const t=mt(e,"condition","whereAsync","bool"),n=await t.data(),r=Ka(t.shape,n);return e!==t&&t.dispose(),r};const Ua=async function(e,t,n){const r=mt(e,"tensor","boolMask"),s=mt(t,"mask","boolMask","bool"),i=null==n?0:n,l=s.rank,u=r.shape;o(l>0,()=>"mask cannot be scalar"),a(u.slice(i,i+l),s.shape,"mask's shape must match the first K dimensions of tensor's shape,");let c=1;for(let e=i;e<i+l;e++)c*=u[e];const h=u.slice(0,i).concat([c],u.slice(i+l)),d=Dr(r,h),p=Dr(s,[-1]),f=await Wa(p),m=$a(f,[1]),g=Ts(d,m,i);return e!==r&&r.dispose(),t!==s&&s.dispose(),m.dispose(),d.dispose(),p.dispose(),f.dispose(),g};const Ga=bt({norm_:function(e,t="euclidean",n=null,r=!1){const s=function e(t,n,r=null){if(0===t.rank)return lr(t);if(1!==t.rank&&null===r)return e(Dr(t,[-1]),n,r);if(1===t.rank||"number"==typeof r||Array.isArray(r)&&1===r.length){if(1===n)return Xs(lr(t),r);if(n===1/0)return Js(lr(t),r);if(n===-1/0)return go(lr(t),r);if("euclidean"===n||2===n)return Ia(Xs(Bo(lr(t),ha(2,"int32")),r));throw new Error("Error in norm: invalid ord value: "+n)}if(Array.isArray(r)&&2===r.length){if(1===n)return Js(Xs(lr(t),r[0]),r[1]-1);if(n===1/0)return Js(Xs(lr(t),r[1]),r[0]);if(n===-1/0)return go(Xs(lr(t),r[1]),r[0]);if("fro"===n||"euclidean"===n)return Ia(Xs(ko(t),r));throw new Error("Error in norm: invalid ord value: "+n)}throw new Error("Error in norm: invalid axis: "+r)}(e=mt(e,"x","norm"),t,n);let o=s.shape;if(r){const t=p(n,e.shape);o=no(s.shape,t)}return Dr(s,o)}});const Va=bt({movingAverage_:function(e,t,n,r,s=!0){const a=mt(e,"v","movingAverage"),i=mt(t,"x","movingAverage"),l=mt(n,"decay","movingAverage");tt(a,i),o(c(a.shape,i.shape),()=>"Shape mismatch in v and x");const u=ha(1),h=Ys(u,l);let d=ir(Ys(i,a),h);if(s){o(null!=r,()=>"When using zeroDebias: true, step is required.");const e=mt(r,"step","movingAverage");d=ar(d,Ys(u,Bo(l,e)))}return sr(a,d)}});const Ha=bt({scatterND_:function(e,t,n){const r=mt(e,"indices","scatterND","int32"),s=mt(t,"updates","scatterND");Dn(s,r,n);const o={indices:r,updates:s},a={shape:n};return lt.runKernel("ScatterNd",o,a)}});const ja=bt({sparseToDense_:function(e,t,n,r=0){const s=mt(e,"sparseIndices","sparseToDense","int32"),o=mt(t,"sparseValues","sparseToDense"),a=mt(r,"defaultValue","sparseToDense",o.dtype);!function(e,t,n,r){if("int32"!==e.dtype)throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${e.shape}.`);const s=e.rank>0?e.shape[0]:1,o=e.rank>1?e.shape[1]:1;if(n.length!==o)throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${o}.`);const a=t.size;if(0!==t.rank&&(1!==t.rank||a!==s))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${s}]`);if(t.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(s,o,n,a);const i={sparseIndices:s,sparseValues:o,defaultValue:a},l={outputShape:n};return lt.runKernel("SparseToDense",i,l)}});const Za=bt({gatherND_:function(e,t){const n=mt(t,"indices","gatherND","int32"),r={params:mt(e,"x","gatherND","string_or_numeric"),indices:n};return lt.runKernel("GatherNd",r)}});const Ja=bt({dropout_:function(e,t,n,r){const s=mt(e,"x","dropout");if(o("float32"===s.dtype,()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${s.dtype} tensor instead.`),o(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),0===t)return e instanceof Ge?s.clone():s;const a=function(e,t){if(null==t)return e.shape.slice();if(c(e.shape,t))return t;if(e.shape.length===t.length){const n=[];for(let r=0;r<e.shape.length;r++)null==t[r]&&null!=e.shape[r]?n.push(e.shape[r]):n.push(t[r]);return n}return t}(s,n),i=1-t,l=ar($s(sr(Xo(a,0,1,"float32",r),i)),i);return ir(s,l)}});function Ya(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function Xa(e,t,n){const r=1-e%2,s=new Float32Array(e);for(let o=0;o<e;++o){const a=2*Math.PI*o/(e+r-1);s[o]=t-n*Math.cos(a)}return Fa(s,"float32")}const Qa=async function(e,t,n=1){const r=mt(e,"predictions","inTopK"),s=mt(t,"targets","inTopK");o(r.rank>1,()=>"inTopK() expects the predictions to be of rank 2 or higher, but got "+r.rank),o(r.rank-1===s.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${r.rank} and targets rank ${s.rank}`),a(r.shape.slice(0,r.shape.length-1),s.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");const i=r.shape[r.shape.length-1];o(n>0&&n<=i,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${i}), but got ${n}`);const l=await r.data(),u=await s.data(),[c,h]=[l.length/i,i],d=m("bool",c);for(let e=0;e<c;e++){const t=e*h,r=l.subarray(t,t+h),s=[];for(let e=0;e<r.length;e++)s.push({value:r[e],index:e});s.sort((e,t)=>t.value-e.value),d[e]=0;for(let t=0;t<n;t++)if(s[t].index===u[e]){d[e]=1;break}}return e!==r&&r.dispose(),t!==s&&s.dispose(),kt(d,s.shape,"bool")};const ei=bt({conv2DBackpropFilter_:function(e,t,n,r,s,a="NHWC",i){let l=e;3===e.rank&&(l=Dr(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let u=t;3===u.rank&&(u=Dr(t,[1,t.shape[0],t.shape[1],t.shape[2]])),o(4===l.rank,()=>"Error in conv2dDerFilter: input must be rank 4, but got shape "+l.shape+"."),o(4===u.rank,()=>"Error in conv2dDerFilter: dy must be rank 4, but got shape "+u.shape+"."),o(4===n.length,()=>"Error in conv2dDerFilter: filterShape must be length 4, but got "+n+".");const c="NHWC"===a?l.shape[3]:l.shape[1],d="NHWC"===a?u.shape[3]:u.shape[1];o(c===n[2],()=>`Error in conv2dDerFilter: depth of input ${c}) must match input depth in filter (${n[2]}.`),o(d===n[3],()=>`Error in conv2dDerFilter: depth of dy (${d}) must match output depth for filter (${n[3]}).`),null!=i&&o(h(s),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);const p={x:l,dy:u},f={strides:r,pad:s,dataFormat:a,dimRoundingMode:i,filterShape:n};return lt.runKernel("Conv2DBackpropFilter",p,f)}});function ti(e,t,n){if(null==n||"linear"===n)return e;if("relu"===n)return ir(e,Da(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function ni(e,t){let n=t;const r=fs(e.shape,t.shape);return r.length>0&&(n=Xs(n,r)),Dr(n,e.shape)}function ri(e,t,n,r){if("linear"===t)return e;if("relu"===t)return na(e);if("elu"===t)return xs(e);if("relu6"===t)return ra(e);if("prelu"===t)return Fo(e,n);if("leakyrelu"===t)return Ls(e,r);if("sigmoid"===t)return Cr(e);throw new Error(`Unknown fused activation ${t}.`)}const si=(e,t)=>!(e>0)||"linear"===t;const oi=bt({fusedConv2d_:function({x:e,filter:t,strides:n,pad:r,dataFormat:s="NHWC",dilations:a=[1,1],dimRoundingMode:i,bias:l,activation:u="linear",preluActivationWeights:c,leakyreluAlpha:d}){if(u=u||"linear",!1===si(lt.state.gradientDepth,u)){let o=Qr(e,t,n,r,s,a,i);return null!=l&&(o=sr(o,l)),ri(o,u,c,d)}const p=mt(e,"x","conv2d"),f=mt(t,"filter","conv2d");let m=p,g=!1;3===p.rank&&(g=!0,m=Dr(p,[1,p.shape[0],p.shape[1],p.shape[2]])),o(4===m.rank,()=>"Error in fused conv2d: input must be rank 4, but got rank "+m.rank+"."),o(4===f.rank,()=>"Error in fused conv2d: filter must be rank 4, but got rank "+f.rank+"."),null!=i&&o(h(r),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${r}.`),o(m.shape[3]===f.shape[2],()=>`Error in conv2d: depth of input (${m.shape[3]}) must match input depth for filter ${f.shape[2]}.`),o($r(n,a),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),o("NHWC"===s,()=>`Error in conv2d: got dataFormat of ${s} but only NHWC is currently supported.`);const b=xr(m.shape,f.shape,n,a,r,i);let y,w;null!=l&&(y=mt(l,"bias","fused conv2d"),[y]=et(y,p),ms(b.outShape,y.shape)),null!=c&&(w=mt(c,"prelu weights","fused conv2d"));const k=(e,t)=>{const[s,i,l,c]=t,h=ti(e,l,u);o(Mr(a),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`);const d=[ts(i.shape,h,s,n,r),ei(i,h,s.shape,n,r)];if(null!=c){const e=ni(c,h);d.push(e)}return d},v={x:m,filter:f,bias:y,preluActivationWeights:w},x={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:i,activation:u,leakyreluAlpha:d};if(null==l){return Gs((e,t,n)=>{let r=lt.runKernel("FusedConv2D",v,x);return n([t,e,r]),g&&(r=Dr(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:k}})(m,f)}return Gs((e,t,n,r)=>{let s=lt.runKernel("FusedConv2D",v,x);return r([t,e,s,n]),g&&(s=Dr(s,[s.shape[1],s.shape[2],s.shape[3]])),{value:s,gradFunc:k}})(m,f,y)}});const ai=bt({depthwiseConv2dNativeBackpropFilter_:function(e,t,n,r,s,o=[1,1],a){let i=e;3===e.rank&&(i=Dr(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;3===l.rank&&(l=Dr(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const u={x:i,dy:l},c={strides:r,pad:s,dimRoundingMode:a,dilations:o,filterShape:n};return lt.runKernel("DepthwiseConv2dNativeBackpropFilter",u,c)}});const ii=bt({depthwiseConv2dNativeBackpropInput_:function(e,t,n,r,s,o=[1,1],a){let i=t,l=!1;3===t.rank&&(l=!0,i=Dr(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const u={dy:i,filter:n},c={strides:r,pad:s,dimRoundingMode:a,dilations:o,inputShape:e},h=lt.runKernel("DepthwiseConv2dNativeBackpropInput",u,c);return l?Dr(h,[h.shape[1],h.shape[2],h.shape[3]]):h}});const li=bt({fusedDepthwiseConv2d_:function({x:e,filter:t,strides:n,pad:r,dataFormat:s="NHWC",dilations:a=[1,1],dimRoundingMode:i,bias:l,activation:u="linear",preluActivationWeights:c,leakyreluAlpha:d}){if(!1===si(lt.state.gradientDepth,u)){let o=hs(e,t,n,r,s,a,i);return null!=l&&(o=sr(o,l)),ri(o,u,c,d)}const p=mt(e,"x","depthwiseConv2d"),f=mt(t,"filter","depthwiseConv2d");let m=p,g=!1;3===p.rank&&(g=!0,m=Dr(p,[1,p.shape[0],p.shape[1],p.shape[2]])),o(4===m.rank,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${m.rank}.`),o(4===f.rank,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${f.rank}.`),o(m.shape[3]===f.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${m.shape[3]}) must match the inChannels dimension in filter ${f.shape[2]}.`),null==a&&(a=[1,1]),o($r(n,a),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),null!=i&&o(h(r),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${i} but got pad ${r}.`);const b=xr(m.shape,f.shape,n,a,r,i,!0);let y,w;null!=l&&(y=mt(l,"bias","fused conv2d"),[y]=et(y,p),ms(b.outShape,y.shape)),null!=c&&(w=mt(c,"prelu weights","fused depthwiseConv2d"));const k=(e,t)=>{o(Mr(a),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`);const[s,l,c,h]=t,d=ti(e,c,u),p=ii(l.shape,d,s,n,r,a,i),f=ai(l,d,s.shape,n,r,a,i);if(null!=h){return[p,f,ni(y,d)]}return[p,f]},v={x:m,filter:f,bias:y,preluActivationWeights:w},x={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:i,activation:u,leakyreluAlpha:d};if(null==l){return Gs((e,t,n)=>{let r=lt.runKernel("FusedDepthwiseConv2D",v,x);return n([t,e,r]),g&&(r=Dr(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:k}})(m,f)}return Gs((e,t,n,r)=>{let s=lt.runKernel("FusedDepthwiseConv2D",v,x);return r([t,e,s,n]),g&&(s=Dr(s,[s.shape[1],s.shape[2],s.shape[3]])),{value:s,gradFunc:k}})(m,f,y)}});const ui=bt({fusedMatMul_:function({a:e,b:t,transposeA:n=!1,transposeB:r=!1,bias:s,activation:a="linear",preluActivationWeights:i,leakyreluAlpha:l}){if(!1===si(lt.state.gradientDepth,a)){let o=yn(e,t,n,r);return null!=s&&(o=sr(o,s)),ri(o,a,i,l)}let h=mt(e,"a","fused matMul"),d=mt(t,"b","fused matMul");[h,d]=et(h,d);const p=n?h.shape[h.rank-2]:h.shape[h.rank-1],f=r?d.shape[d.rank-1]:d.shape[d.rank-2],m=n?h.shape[h.rank-1]:h.shape[h.rank-2],g=r?d.shape[d.rank-2]:d.shape[d.rank-1],b=h.shape.slice(0,-2),y=d.shape.slice(0,-2),w=u(b),k=u(y);o(h.rank>=2&&d.rank>=2&&h.rank===d.rank,()=>`Error in fused matMul: inputs must have the same rank of at least 2, got ranks ${h.rank} and ${d.rank}.`),o(c(b,y),()=>`Error in fused matMul: outer dimensions (${b}) and (${y}) of Tensors with shapes ${h.shape} and `+d.shape+" must match."),o(p===f,()=>`Error in fused matMul: inner shapes (${p}) and (${f}) of Tensors with shapes ${h.shape} and ${d.shape} and transposeA=${n} and transposeB=${r} must match.`);const v=h.shape.slice(0,-2).concat([m,g]),x=Dr(h,n?[w,p,m]:[w,m,p]),E=Dr(d,r?[k,g,f]:[k,f,g]);let S,A;null!=s&&(S=mt(s,"bias","fused matMul"),[S]=et(S,h),ms(v,S.shape)),null!=i&&(A=mt(i,"prelu weights","fused matMul"));const _=(e,t)=>{const[o,i,l,u]=t,c=ti(Dr(e,l.shape),l,a);let h,d;if(n||r?!n&&r?(h=yn(c,i,!1,!1),d=yn(c,o,!0,!1)):n&&!r?(h=yn(i,c,!1,!0),d=yn(o,c,!1,!1)):(h=yn(i,c,!0,!0),d=yn(c,o,!0,!0)):(h=yn(c,i,!1,!0),d=yn(o,c,!0,!1)),null!=s){return[h,d,ni(u,c)]}return[h,d]},N={a:x,b:E,bias:S,preluActivationWeights:A},I={transposeA:n,transposeB:r,activation:a,leakyreluAlpha:l};if(null==s){return Gs((e,t,n)=>{const r=lt.runKernel("_FusedMatMul",N,I);return n([e,t,r]),{value:Dr(r,v),gradFunc:_}})(x,E)}return Gs((e,t,n,r)=>{const s=lt.runKernel("_FusedMatMul",N,I);return r([e,t,s,n]),{value:Dr(s,v),gradFunc:_}})(x,E,S)}});var ci=Object.freeze({__proto__:null,conv2d:oi,depthwiseConv2d:li,matMul:ui});const hi=bt({hammingWindow_:function(e){return Xa(e,.54,.46)}});const di=bt({hannWindow_:function(e){return Xa(e,.5,.5)}});const pi=bt({frame_:function(e,t,n,r=!1,s=0){let o=0;const a=[];for(;o+t<=e.size;)a.push(Pr(e,o,t)),o+=n;if(r)for(;o<e.size;){const r=o+t-e.size,i=Fr([Pr(e,o,t-r),Ms([r],s)]);a.push(i),o+=n}return 0===a.length?Ca([],[0,t]):Dr(Fr(a),[a.length,t])}});const fi=bt({stft_:function(e,t,n,r,s=di){null==r&&(r=Ya(t));const o=pi(e,t,n),a=ir(o,s(t));return Na(a,r)}});const mi=bt({cropAndResize_:function(e,t,n,r,s="bilinear",a=0){const i=mt(e,"image","cropAndResize"),l=mt(t,"boxes","cropAndResize","float32"),u=mt(n,"boxInd","cropAndResize","int32"),c=l.shape[0];o(4===i.rank,()=>`Error in cropAndResize: image must be rank 4,but got rank ${i.rank}.`),o(2===l.rank&&4===l.shape[1],()=>`Error in cropAndResize: boxes must be have size [${c},4] but had shape ${l.shape}.`),o(1===u.rank&&u.shape[0]===c,()=>`Error in cropAndResize: boxInd must be have size [${c}] but had shape ${l.shape}.`),o(2===r.length,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${r.length}.`),o(r[0]>=1&&r[1]>=1,()=>"cropSize must be atleast [1,1], but was "+r),o("bilinear"===s||"nearest"===s,()=>"method must be bilinear or nearest, but was "+s);const h={image:i,boxes:l,boxInd:u},d={method:s,extrapolationValue:a,cropSize:r};return lt.runKernel("CropAndResize",h,d)}});const gi=bt({flipLeftRight_:function(e){const t=mt(e,"image","flipLeftRight","float32");o(4===t.rank,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);const n={image:t};return lt.runKernel("FlipLeftRight",n,{})}});const bi=bt({rotateWithOffset_:function(e,t,n=0,r=.5){const s=mt(e,"image","rotateWithOffset","float32");o(4===s.rank,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${s.rank}.`);const a={image:s},i={radians:t,fillValue:n,center:r};return lt.runKernel("RotateWithOffset",a,i)}});function yi(e,t,n,r,s,a){null==r&&(r=.5),null==s&&(s=Number.NEGATIVE_INFINITY),null==a&&(a=0);const i=e.shape[0];return n=Math.min(n,i),o(0<=r&&r<=1,()=>`iouThreshold must be in [0, 1], but was '${r}'`),o(2===e.rank,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),o(4===e.shape[1],()=>"boxes must have 4 columns, but 2nd dimension was "+e.shape[1]),o(1===t.rank,()=>"scores must be a 1D tensor"),o(t.shape[0]===i,()=>`scores has incompatible shape with boxes. Expected ${i}, but was `+t.shape[0]),o(0<=a&&a<=1,()=>`softNmsSigma must be in [0, 1], but was '${a}'`),{maxOutputSize:n,iouThreshold:r,scoreThreshold:s,softNmsSigma:a}}const wi=bt({nonMaxSuppression_:function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY){const o=mt(e,"boxes","nonMaxSuppression"),a=mt(t,"scores","nonMaxSuppression"),i=yi(o,a,n,r,s),l={maxOutputSize:n=i.maxOutputSize,iouThreshold:r=i.iouThreshold,scoreThreshold:s=i.scoreThreshold};return lt.runKernel("NonMaxSuppressionV3",{boxes:o,scores:a},l)}});function ki(e,t,n){const r=function(e,t,n){return function(e,t,n){let r=0,s=e.length,o=0,a=!1;for(;r<s;){o=r+(s-r>>>1);const i=n(t,e[o]);i>0?r=o+1:(s=o,a=!i)}return a?r:-r-1}(e,t,n||vi)}(e,t,n),s=r<0?-(r+1):r;e.splice(s,0,t)}function vi(e,t){return e>t?1:e<t?-1:0}function xi(e,t,n,r,s){return Ai(e,t,n,r,s,0)}function Ei(e,t,n,r,s,o){return Ai(e,t,n,r,s,0,!1,o,!0)}function Si(e,t,n,r,s,o){return Ai(e,t,n,r,s,o,!0)}function Ai(e,t,n,r,s,o,a=!1,i=!1,l=!1){const u=[];for(let e=0;e<t.length;e++)t[e]>s&&u.push({score:t[e],boxIndex:e,suppressBeginIndex:0});u.sort(Ii);const c=o>0?-.5/o:0,h=[],d=[];for(;h.length<n&&u.length>0;){const t=u.pop(),{score:n,boxIndex:o,suppressBeginIndex:a}=t;if(n<s)break;let i=!1;for(let n=h.length-1;n>=a;--n){const a=_i(e,o,h[n]);if(a>=r){i=!0;break}if(t.score=t.score*Ni(r,c,a),t.score<=s)break}t.suppressBeginIndex=h.length,i||(t.score===n?(h.push(o),d.push(t.score)):t.score>s&&ki(u,t,Ii))}const p=h.length,f=n-p;i&&f>0&&(h.push(...new Array(f).fill(0)),d.push(...new Array(f).fill(0)));const m={selectedIndices:h};return a&&(m.selectedScores=d),l&&(m.validOutputs=p),m}function _i(e,t,n){const r=e.subarray(4*t,4*t+4),s=e.subarray(4*n,4*n+4),o=Math.min(r[0],r[2]),a=Math.min(r[1],r[3]),i=Math.max(r[0],r[2]),l=Math.max(r[1],r[3]),u=Math.min(s[0],s[2]),c=Math.min(s[1],s[3]),h=Math.max(s[0],s[2]),d=Math.max(s[1],s[3]),p=(i-o)*(l-a),f=(h-u)*(d-c);if(p<=0||f<=0)return 0;const m=Math.max(o,u),g=Math.max(a,c),b=Math.min(i,h),y=Math.min(l,d),w=Math.max(b-m,0)*Math.max(y-g,0);return w/(p+f-w)}function Ni(e,t,n){const r=Math.exp(t*n*n);return n<=e?r:0}function Ii(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}const Mi=async function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY){const o=mt(e,"boxes","nonMaxSuppressionAsync"),a=mt(t,"scores","nonMaxSuppressionAsync"),i=yi(o,a,n,r,s);n=i.maxOutputSize,r=i.iouThreshold,s=i.scoreThreshold;const l=await Promise.all([o.data(),a.data()]),u=l[0],c=l[1],{selectedIndices:h}=xi(u,c,n,r,s);return o!==e&&o.dispose(),a!==t&&a.dispose(),Fa(h,"int32")};const $i=bt({nonMaxSuppressionWithScore_:function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,o=0){const a=mt(e,"boxes","nonMaxSuppression"),i=mt(t,"scores","nonMaxSuppression"),l=yi(a,i,n,r,s,o),u={boxes:a,scores:i},c={maxOutputSize:n=l.maxOutputSize,iouThreshold:r=l.iouThreshold,scoreThreshold:s=l.scoreThreshold,softNmsSigma:o=l.softNmsSigma},h=lt.runKernel("NonMaxSuppressionV5",u,c);return{selectedIndices:h[0],selectedScores:h[1]}}});const Ti=async function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,o=0){const a=mt(e,"boxes","nonMaxSuppressionAsync"),i=mt(t,"scores","nonMaxSuppressionAsync"),l=yi(a,i,n,r,s,o);n=l.maxOutputSize,r=l.iouThreshold,s=l.scoreThreshold,o=l.softNmsSigma;const u=await Promise.all([a.data(),i.data()]),c=u[0],h=u[1],{selectedIndices:d,selectedScores:p}=Si(c,h,n,r,s,o);return a!==e&&a.dispose(),i!==t&&i.dispose(),{selectedIndices:Fa(d,"int32"),selectedScores:Fa(p)}};const Di=bt({nonMaxSuppressionPadded_:function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,o=!1){const a=mt(e,"boxes","nonMaxSuppression"),i=mt(t,"scores","nonMaxSuppression"),l=yi(a,i,n,r,s,null),u={boxes:a,scores:i},c={maxOutputSize:l.maxOutputSize,iouThreshold:l.iouThreshold,scoreThreshold:l.scoreThreshold,padToMaxOutputSize:o},h=lt.runKernel("NonMaxSuppressionV4",u,c);return{selectedIndices:h[0],validOutputs:h[1]}}});const Ri=async function(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,o=!1){const a=mt(e,"boxes","nonMaxSuppressionAsync"),i=mt(t,"scores","nonMaxSuppressionAsync"),l=yi(a,i,n,r,s,null),u=l.maxOutputSize,c=l.iouThreshold,h=l.scoreThreshold,[d,p]=await Promise.all([a.data(),i.data()]),{selectedIndices:f,validOutputs:m}=Ei(d,p,u,c,h,o);return a!==e&&a.dispose(),i!==t&&i.dispose(),{selectedIndices:Fa(f,"int32"),validOutputs:ha(m,"int32")}};const Bi=bt({resizeBilinear_:function(e,t,n=!1,r=!1){const s=mt(e,"images","resizeBilinear");o(3===s.rank||4===s.rank,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${s.rank}.`),o(2===t.length,()=>"Error in resizeBilinear: new shape must 2D, but got shape "+t+"."),o(!1===r||!1===n,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let a=s,i=!1;3===s.rank&&(i=!0,a=Dr(s,[1,s.shape[0],s.shape[1],s.shape[2]]));const l={images:a},u={alignCorners:n,halfPixelCenters:r,size:t},c=lt.runKernel("ResizeBilinear",l,u);return i?Dr(c,[c.shape[1],c.shape[2],c.shape[3]]):c}});const Fi=bt({resizeNearestNeighbor_:function(e,t,n=!1,r=!1){const s=mt(e,"images","resizeNearestNeighbor");o(3===s.rank||4===s.rank,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${s.rank}.`),o(2===t.length,()=>"Error in resizeNearestNeighbor: new shape must 2D, but got shape "+t+"."),o("float32"===s.dtype||"int32"===s.dtype,()=>"`images` must have `int32` or `float32` as dtype"),o(!1===r||!1===n,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let a=s,i=!1;3===s.rank&&(i=!0,a=Dr(s,[1,s.shape[0],s.shape[1],s.shape[2]]));const l={images:a},u={alignCorners:n,halfPixelCenters:r,size:t},c=lt.runKernel("ResizeNearestNeighbor",l,u);return i?Dr(c,[c.shape[1],c.shape[2],c.shape[3]]):c}});const Ci=bt({threshold_:function(e,t="binary",n=!1,r=.5){const s=mt(e,"image","threshold"),a=s.shape[0]*s.shape[1];let i,l,u,c,h=ir(Fa([r]),255);if(o(3===s.rank,()=>`Error in threshold: image must be rank 3,but got rank ${s.rank}.`),o(3===s.shape[2]||1===s.shape[2],()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${s.shape[2]}.`),o("int32"===s.dtype||"float32"===s.dtype,()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${s.dtype}.`),o("otsu"===t||"binary"===t,()=>"Method must be binary or otsu, but was "+t),3===s.shape[2]){[i,l,u]=_a(s,[1,1,1],-1);const e=ir(i,.2989),t=ir(l,.587),n=ir(u,.114);c=sr(sr(e,t),n)}else c=e;if("otsu"===t){h=function(e,t){let n,r,s,o,a,i,l=Fa([-1]),u=Fa([0]),c=Fa([0]);for(let h=0;h<e.size-1;h++){n=Pr(e,0,h+1),r=Pr(e,h+1),a=ar(Xs(n),t),i=ar(Xs(r),t);const d=Xs(ir(n,Qo(0,n.size)));s=ar(d,Xs(n));const p=Ms(r.shape,n.size),f=sr(Qo(0,r.size),p),m=ir(r,f);o=ar(Xs(m),Xs(r));const g=Ys(s,o),b=Ys(s,o),y=ir(a,i);c=ir(ir(y,g),b);const w=Ds(c,u);u=bs(w,c,u),l=bs(w,Fa([h]),l)}return l}(Gr(tn(ua(c),"int32"),kt([]),256),a)}const d=n?zs(c,h):Ds(c,h);return tn(ir(d,255),"int32")}});const Pi=bt({transform_:function(e,t,n="nearest",r="constant",s=0,a){const i=mt(e,"image","transform","float32"),l=mt(t,"transforms","transform","float32");o(4===i.rank,()=>`Error in transform: image must be rank 4,but got rank ${i.rank}.`),o(2===l.rank&&(l.shape[0]===i.shape[0]||1===l.shape[0])&&8===l.shape[1],()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),o(null==a||2===a.length,()=>`Error in transform: outputShape must be [height, width] or null, but got ${a}.`);const u={image:i,transforms:l},c={interpolation:n,fillMode:r,fillValue:s,outputShape:a};return lt.runKernel("Transform",u,c)}});const Li=bt({bandPart_:function(e,t,n){o(t%1==0,()=>`bandPart(): numLower must be an integer, got ${t}.`),o(n%1==0,()=>`bandPart(): numUpper must be an integer, got ${n}.`);const r=mt(e,"a","bandPart");o(r.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${r.rank}.`);const s=r.shape,[a,i]=r.shape.slice(-2);if(!(t<=a))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${a}).`);if(!(n<=i))throw new Error(`bandPart(): numUpper (${n}) must not be greater than the number of columns (${i}).`);t<0&&(t=a),n<0&&(n=i);const l=Dr(Qo(0,a,1,"int32"),[-1,1]),u=Qo(0,i,1,"int32"),c=Ys(l,u),h=so(zs(c,ha(+t,"int32")),Rs(c,ha(-n,"int32"))),d=fo([a,i],r.dtype);return Dr(Ta(qa(Dr(r,[-1,a,i])).map(e=>bs(h,e,d))),s)}});const Oi=bt({gramSchmidt_:function(e){let t;if(Array.isArray(e)){t=!1,o(null!=e&&e.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");const n=e[0].shape[0];for(let t=1;t<e.length;++t)o(e[t].shape[0]===n,()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[t].shape[0]} vs. ${n})`)}else t=!0,e=_a(e,e.shape[0],0).map(e=>$a(e,[0]));o(e.length<=e[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);const n=[],r=e;for(let t=0;t<e.length;++t)n.push(lt.tidy(()=>{let e=r[t];if(t>0)for(let r=0;r<t;++r){const t=ir(Xs(ir(n[r],e)),n[r]);e=Ys(e,t)}return ar(e,Ga(e,"euclidean"))}));return t?Ta(n,0):n}});function zi(e,t=!1){return lt.tidy(()=>{o(2===e.shape.length,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);const n=e.shape[0],r=e.shape[1];let s=Is(n),a=nn(e);const i=Ca([[1]],[1,1]);let l=nn(i);const u=n>=r?r:n;for(let e=0;e<u;++e){const t=a,o=l,u=s;[l,a,s]=lt.tidy(()=>{const t=Pr(a,[e,e],[n-e,1]),o=Ga(t),u=Pr(a,[e,e],[1,1]),c=bs(Ds(u,0),Ca([[-1]]),Ca([[1]])),h=Ys(u,ir(c,o)),d=ar(t,h);l=1===d.shape[0]?nn(i):Fr([i,Pr(d,[1,0],[d.shape[0]-1,d.shape[1]])],0);const p=Hs(ar(yn(c,h),o)),f=Pr(a,[e,0],[n-e,r]),m=ir(p,l),g=kn(l);if(0===e)a=Ys(f,yn(m,yn(g,f)));else{const t=Ys(f,yn(m,yn(g,f)));a=Fr([Pr(a,[0,0],[e,r]),t],0)}const b=kn(m),y=Pr(s,[0,e],[n,s.shape[1]-e]);if(0===e)s=Ys(y,yn(yn(y,l),b));else{const t=Ys(y,yn(yn(y,l),b));s=Fr([Pr(s,[0,0],[n,e]),t],1)}return[l,a,s]}),nr([t,o,u])}return!t&&n>r&&(s=Pr(s,[0,0],[n,r]),a=Pr(a,[0,0],[r,r])),[s,a]})}const qi=bt({qr_:function(e,t=!1){if(o(e.rank>=2,()=>"qr() requires input tensor to have a rank >= 2, but got rank "+e.rank),2===e.rank)return zi(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce((e,t)=>e*t),r=qa(Dr(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),s=[],o=[];r.forEach(e=>{const[n,r]=zi(e,t);s.push(n),o.push(r)});return[Dr(Ta(s,0),e.shape),Dr(Ta(o,0),e.shape)]}}});var Ki;(Ki=e.Reduction||(e.Reduction={}))[Ki.NONE=0]="NONE",Ki[Ki.MEAN=1]="MEAN",Ki[Ki.SUM=2]="SUM",Ki[Ki.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS";const Wi=bt({computeWeightedLoss_:function(t,n,r=e.Reduction.SUM_BY_NONZERO_WEIGHTS){const s=mt(t,"losses","computeWeightedLoss");let o=null;null!=n&&(o=mt(n,"weights","computeWeightedLoss"));const a=null==o?s:ir(s,o);if(r===e.Reduction.NONE)return a;if(r===e.Reduction.SUM)return Xs(a);if(r===e.Reduction.MEAN){if(null==o)return po(a);{const e=s.size/o.size,t=ar(Xs(a),Xs(o));return e>1?ar(t,ha(e)):t}}if(r===e.Reduction.SUM_BY_NONZERO_WEIGHTS){if(null==o)return ar(Xs(a),ha(s.size));{const e=ir(o,mo(s.shape)),t=tn(Xs(So(e,ha(0))),"float32");return ar(Xs(a),t)}}throw Error("Unknown reduction: "+r)}});const Ui=bt({absoluteDifference_:function(t,n,r,s=e.Reduction.SUM_BY_NONZERO_WEIGHTS){const o=mt(t,"labels","absoluteDifference"),i=mt(n,"predictions","absoluteDifference");let l=null;null!=r&&(l=mt(r,"weights","absoluteDifference")),a(o.shape,i.shape,"Error in absoluteDifference: ");const u=lr(Ys(o,i));return Wi(u,l,s)}});const Gi=bt({cosineDistance_:function(t,n,r,s,o=e.Reduction.SUM_BY_NONZERO_WEIGHTS){const i=mt(t,"labels","cosineDistance"),l=mt(n,"predictions","cosineDistance");let u=null;null!=s&&(u=mt(s,"weights","cosineDistance")),a(i.shape,l.shape,"Error in cosineDistance: ");const c=ha(1),h=Ys(c,Xs(ir(i,l),r,!0));return Wi(h,u,o)}});const Vi=bt({hingeLoss_:function(t,n,r,s=e.Reduction.SUM_BY_NONZERO_WEIGHTS){let o=mt(t,"labels","hingeLoss");const i=mt(n,"predictions","hingeLoss");let l=null;null!=r&&(l=mt(r,"weights","hingeLoss")),a(o.shape,i.shape,"Error in hingeLoss: ");const u=ha(1);o=Ys(ir(ha(2),o),u);const c=na(Ys(u,ir(o,i)));return Wi(c,l,s)}});const Hi=bt({huberLoss_:function(t,n,r,s=1,o=e.Reduction.SUM_BY_NONZERO_WEIGHTS){const i=mt(t,"labels","huberLoss"),l=mt(n,"predictions","huberLoss");let u=null;null!=r&&(u=mt(r,"weights","huberLoss")),a(i.shape,l.shape,"Error in huberLoss: ");const c=ha(s),h=lr(Ys(l,i)),d=bo(h,c),p=Ys(h,d),f=sr(ir(ha(.5),ko(d)),ir(c,p));return Wi(f,u,o)}});const ji=bt({logLoss_:function(t,n,r,s=1e-7,o=e.Reduction.SUM_BY_NONZERO_WEIGHTS){const i=mt(t,"labels","logLoss"),l=mt(n,"predictions","logLoss");let u=null;null!=r&&(u=mt(r,"weights","logLoss")),a(i.shape,l.shape,"Error in logLoss: ");const c=ha(1),h=ha(s),d=Hs(ir(i,Ks(sr(l,h)))),p=ir(Ys(c,i),Ks(sr(Ys(c,l),h))),f=Ys(d,p);return Wi(f,u,o)}});const Zi=bt({meanSquaredError_:function(t,n,r,s=e.Reduction.SUM_BY_NONZERO_WEIGHTS){const o=mt(t,"labels","meanSquaredError"),i=mt(n,"predictions","meanSquaredError");let l=null;null!=r&&(l=mt(r,"weights","meanSquaredError")),a(o.shape,i.shape,"Error in meanSquaredError: ");const u=Ma(o,i);return Wi(u,l,s)}});const Ji=bt({sigmoidCrossEntropy_:function(t,n,r,s=0,o=e.Reduction.SUM_BY_NONZERO_WEIGHTS){let i=mt(t,"multiClassLabels","sigmoidCrossEntropy");const l=mt(n,"logits","sigmoidCrossEntropy");let u=null;if(null!=r&&(u=mt(r,"weights","sigmoidCrossEntropy")),a(i.shape,l.shape,"Error in sigmoidCrossEntropy: "),s>0){const e=ha(s),t=ha(1),n=ha(.5);i=sr(ir(i,Ys(t,e)),ir(n,e))}const c=function(e,t){const n=mt(e,"labels","sigmoidCrossEntropyWithLogits"),r=mt(t,"logits","sigmoidCrossEntropyWithLogits");a(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");const s=na(r),o=ir(r,n),i=Ws(Ss(Hs(lr(r))));return sr(Ys(s,o),i)}(i,l);return Wi(c,u,o)}});const Yi=bt({softmaxCrossEntropy_:function(t,n,r,s=0,o=e.Reduction.SUM_BY_NONZERO_WEIGHTS){let i=mt(t,"onehotLabels","softmaxCrossEntropy");const l=mt(n,"logits","softmaxCrossEntropy");let u=null;if(null!=r&&(u=mt(r,"weights","softmaxCrossEntropy")),a(i.shape,l.shape,"Error in softmaxCrossEntropy: "),s>0){const e=ha(s),t=ha(1),n=ha(i.shape[1]);i=sr(ir(i,Ys(t,e)),ar(e,n))}const c=function(e,t,n=-1){if(-1===n&&(n=t.rank-1),n!==t.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${t.rank} and dim was `+n);return Gs((e,t,r)=>{const s=ro(t,[n],!0),o=Ys(tn(t,"float32"),s);r([e,o]);const a=Hs(ir(o,e));return{value:Xs(a,[n]),gradFunc:(e,t)=>{const[r,s]=t,o=no(e.shape,[n]);return[ir(Dr(e,o),Ys(tn(r,"float32"),Ss(s))),ir(Dr(e,o),Ys(Ss(s),tn(r,"float32")))]}}})(e,t)}(i,l);return Wi(c,u,o)}});const Xi=bt({sparseFillEmptyRows_:function(e,t,n,r){const s=mt(e,"indices","sparseFillEmptyRows"),o=mt(t,"values","sparseFillEmptyRows"),a=mt(n,"denseShape","sparseFillEmptyRows"),i=mt(r,"defaultValue","sparseFillEmptyRows",o.dtype);if(2!==s.rank)throw new Error("Indices should be Tensor2D but received shape\n "+s.shape);if(1!==o.rank)throw new Error("Values should be Tensor1D but received shape "+o.shape);if(1!==a.rank)throw new Error("Dense shape should be Tensor1D but received shape "+a.shape);if(0!==i.rank)throw new Error("Default value should be a scalar but received shape "+i.shape);const l={indices:s,values:o,denseShape:a,defaultValue:i},u=lt.runKernel("SparseFillEmptyRows",l);return{outputIndices:u[0],outputValues:u[1],emptyRowIndicator:u[2],reverseIndexMap:u[3]}}});const Qi=bt({sparseReshape_:function(e,t,n){const r=mt(e,"inputIndices","sparseReshape"),s=mt(t,"inputShape","sparseReshape"),o=mt(n,"newShape","sparseReshape");if(2!==r.rank)throw new Error("Input indices should be Tensor2D but received shape\n "+r.shape);if(1!==s.rank)throw new Error("Input shape should be Tensor1D but received shape "+s.shape);if(1!==o.rank)throw new Error("New shape should be Tensor1D but received shape "+o.shape);const a={inputIndices:r,inputShape:s,newShape:o},i=lt.runKernel("SparseReshape",a);return{outputIndices:i[0],outputShape:i[1]}}});const el=bt({sparseSegmentMean_:function(e,t,n){const r=mt(e,"data","sparseSegmentMean"),s=mt(t,"indices","sparseSegmentMean"),o=mt(n,"segmentIds","sparseSegmentMean");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==s.rank)throw new Error("Indices should be Tensor1D but received shape\n "+s.shape);if(1!==o.rank)throw new Error("Segment ids should be Tensor1D but received shape\n "+o.shape);const a={data:r,indices:s,segmentIds:o};return lt.runKernel("SparseSegmentMean",a)}});const tl=bt({sparseSegmentSum_:function(e,t,n){const r=mt(e,"data","sparseSegmentSum"),s=mt(t,"indices","sparseSegmentSum"),o=mt(n,"segmentIds","sparseSegmentSum");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==s.rank)throw new Error("Indices should be Tensor1D but received shape\n "+s.shape);if(1!==o.rank)throw new Error("Segment ids should be Tensor1D but received shape\n "+o.shape);const a={data:r,indices:s,segmentIds:o};return lt.runKernel("SparseSegmentSum",a)}});const nl=bt({stringNGrams_:function(e,t,n,r,s,o,a,i){const l=mt(e,"data","stringNGrams","string");if("string"!==l.dtype)throw new Error("Data must be of datatype string");if(1!==l.shape.length)throw new Error("Data must be a vector, saw: "+l.shape);const u=mt(t,"dataSplits","stringNGrams");if("int32"!==u.dtype)throw new Error("Data splits must be of datatype int32");const c={separator:n,nGramWidths:r,leftPad:s,rightPad:o,padWidth:a,preserveShortSequences:i},h={data:l,dataSplits:u},d=lt.runKernel("StringNGrams",h,c);return{nGrams:d[0],nGramsSplits:d[1]}}});const rl=bt({stringSplit_:function(e,t,n=!0){const r=mt(e,"input","stringSplit","string"),s=mt(t,"delimiter","stringSplit","string");if(1!==r.rank)throw new Error("Input should be Tensor1D but received shape "+r.shape);if(0!==s.rank)throw new Error("Delimiter should be a scalar but received shape "+s.shape);const o={skipEmpty:n},a={input:r,delimiter:s},i=lt.runKernel("StringSplit",a,o);return{indices:i[0],values:i[1],shape:i[2]}}});const sl=bt({stringToHashBucketFast_:function(e,t){const n=mt(e,"input","stringToHashBucketFast","string"),r={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");const s={input:n};return lt.runKernel("StringToHashBucketFast",s,r)}}),ol={fft:Ea,ifft:Sa,rfft:Na,irfft:Aa},al={hammingWindow:hi,hannWindow:di,frame:pi,stft:fi},il={flipLeftRight:gi,resizeNearestNeighbor:Fi,resizeBilinear:Bi,rotateWithOffset:bi,cropAndResize:mi,nonMaxSuppression:wi,nonMaxSuppressionAsync:Mi,nonMaxSuppressionWithScore:$i,nonMaxSuppressionWithScoreAsync:Ti,nonMaxSuppressionPadded:Di,nonMaxSuppressionPaddedAsync:Ri,threshold:Ci,transform:Pi},ll={bandPart:Li,gramSchmidt:Oi,qr:qi},ul={absoluteDifference:Ui,computeWeightedLoss:Wi,cosineDistance:Gi,hingeLoss:Vi,huberLoss:Hi,logLoss:ji,meanSquaredError:Zi,sigmoidCrossEntropy:Ji,softmaxCrossEntropy:Yi},cl={sparseFillEmptyRows:Xi,sparseReshape:Qi,sparseSegmentMean:el,sparseSegmentSum:tl},hl={stringNGrams:nl,stringSplit:rl,stringToHashBucketFast:sl};class dl extends Hn{minimize(e,t=!1,n){const{value:r,grads:s}=this.computeGradients(e,n);if(null!=n){const e=n.map(e=>({name:e.name,tensor:s[e.name]}));this.applyGradients(e)}else this.applyGradients(s);return nr(s),t?r:(r.dispose(),null)}get iterations(){return null==this.iterations_&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return Us(e,t)}dispose(){null!=this.iterations_&&nr(this.iterations_)}async saveIterations(){return null==this.iterations_&&(this.iterations_=0),{name:"iter",tensor:ha(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(e){throw new Error("setWeights() is not implemented for this optimizer class "+this.getClassName())}async extractIterations(e){return this.iterations_=(await e[0].tensor.data())[0],e.slice(1)}}Object.defineProperty(dl,Symbol.hasInstance,{value:e=>null!=e.minimize&&null!=e.computeGradients&&null!=e.applyGradients});class pl extends dl{constructor(e,t,n=null){super(),this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],null==n&&(this.epsilon=lt.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(e=>e.name):Object.keys(e)).forEach((t,n)=>{const r=lt.registeredVariables[t];null==this.accumulatedGrads[n]&&(this.accumulatedGrads[n]={originalName:t+"/accum_grad",variable:tr(()=>ys(r).variable(!1))}),null==this.accumulatedUpdates[n]&&(this.accumulatedUpdates[n]={originalName:t+"/accum_var",variable:tr(()=>ys(r).variable(!1))});const s=Array.isArray(e)?e[n].tensor:e[t];if(null==s)return;const o=this.accumulatedGrads[n].variable,a=this.accumulatedUpdates[n].variable;tr(()=>{const e=sr(ir(o,this.rho),ir(ko(s),1-this.rho)),t=ir(ar(Ia(sr(a,this.epsilon)),Ia(sr(o,this.epsilon))),s),n=sr(ir(a,this.rho),ir(ko(t),1-this.rho));o.assign(e),a.assign(n);const i=sr(ir(t,-this.learningRate),r);r.assign(i)})}),this.incrementIterations()}dispose(){null!=this.accumulatedUpdates&&(nr(this.accumulatedGrads.map(e=>e.variable)),nr(this.accumulatedUpdates.map(e=>e.variable)))}async getWeights(){const e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){const t=(e=await this.extractIterations(e)).length/2;this.accumulatedGrads=e.slice(0,t).map(e=>({originalName:e.name,variable:e.tensor.variable(!1)})),this.accumulatedUpdates=e.slice(t,2*t).map(e=>({originalName:e.name,variable:e.tensor.variable(!1)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}}pl.className="Adadelta",Zn(pl);class fl extends dl{constructor(e,t=.1){super(),this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map(e=>e.name):Object.keys(e)).forEach((t,n)=>{const r=lt.registeredVariables[t];if(null==this.accumulatedGrads[n]){const e=!1;this.accumulatedGrads[n]={originalName:t+"/accumulator",variable:tr(()=>Ms(r.shape,this.initialAccumulatorValue).variable(e))}}const s=Array.isArray(e)?e[n].tensor:e[t];if(null==s)return;const o=this.accumulatedGrads[n].variable;tr(()=>{const e=sr(o,ko(s));o.assign(e);const t=sr(ir(ar(s,Ia(sr(e,lt.backend.epsilon()))),-this.learningRate),r);r.assign(t)})}),this.incrementIterations()}dispose(){null!=this.accumulatedGrads&&nr(this.accumulatedGrads.map(e=>e.variable))}async getWeights(){return[await this.saveIterations()].concat(this.accumulatedGrads.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);this.accumulatedGrads=e.map(e=>({originalName:e.name,variable:e.tensor.variable(!1)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}}fl.className="Adagrad",Zn(fl);class ml extends dl{constructor(e,t,n,r=null){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=r,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],tr(()=>{this.accBeta1=ha(t).variable(),this.accBeta2=ha(n).variable()}),null==r&&(this.epsilon=lt.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(e=>e.name):Object.keys(e);tr(()=>{const n=Ys(1,this.accBeta1),r=Ys(1,this.accBeta2);t.forEach((t,s)=>{const o=lt.registeredVariables[t];null==this.accumulatedFirstMoment[s]&&(this.accumulatedFirstMoment[s]={originalName:t+"/m",variable:tr(()=>ys(o).variable(!1))}),null==this.accumulatedSecondMoment[s]&&(this.accumulatedSecondMoment[s]={originalName:t+"/v",variable:tr(()=>ys(o).variable(!1))});const a=Array.isArray(e)?e[s].tensor:e[t];if(null==a)return;const i=this.accumulatedFirstMoment[s].variable,l=this.accumulatedSecondMoment[s].variable,u=sr(ir(i,this.beta1),ir(a,1-this.beta1)),c=sr(ir(l,this.beta2),ir(ko(a),1-this.beta2)),h=ar(u,n),d=ar(c,r);i.assign(u),l.assign(c);const p=sr(ir(ar(h,sr(Ia(d),this.epsilon)),-this.learningRate),o);o.assign(p)}),this.accBeta1.assign(ir(this.accBeta1,this.beta1)),this.accBeta2.assign(ir(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&nr(this.accumulatedFirstMoment.map(e=>e.variable)),null!=this.accumulatedSecondMoment&&nr(this.accumulatedSecondMoment.map(e=>e.variable))}async getWeights(){const e=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(e.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e),tr(()=>{this.accBeta1.assign(Bo(this.beta1,this.iterations_+1)),this.accBeta2.assign(Bo(this.beta2,this.iterations_+1))});const t=e.length/2;this.accumulatedFirstMoment=e.slice(0,t).map(e=>({originalName:e.name,variable:e.tensor.variable(!1)})),this.accumulatedSecondMoment=e.slice(t,2*t).map(e=>({originalName:e.name,variable:e.tensor.variable(!1)}))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}}ml.className="Adam",Zn(ml);class gl extends dl{constructor(e,t,n,r=null,s=0){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=r,this.decay=s,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],tr(()=>{this.iteration=ha(0).variable(),this.accBeta1=ha(t).variable()}),null==r&&(this.epsilon=lt.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map(e=>e.name):Object.keys(e);tr(()=>{const n=Ys(1,this.accBeta1),r=ar(-this.learningRate,sr(ir(this.iteration,this.decay),1));t.forEach((t,s)=>{const o=lt.registeredVariables[t];null==this.accumulatedFirstMoment[s]&&(this.accumulatedFirstMoment[s]={originalName:t+"/m",variable:ys(o).variable(!1)}),null==this.accumulatedWeightedInfNorm[s]&&(this.accumulatedWeightedInfNorm[s]={originalName:t+"/v",variable:ys(o).variable(!1)});const a=Array.isArray(e)?e[s].tensor:e[t];if(null==a)return;const i=this.accumulatedFirstMoment[s].variable,l=this.accumulatedWeightedInfNorm[s].variable,u=sr(ir(i,this.beta1),ir(a,1-this.beta1)),c=ir(l,this.beta2),h=lr(a),d=ho(c,h);i.assign(u),l.assign(d);const p=sr(ir(ar(r,n),ar(u,sr(d,this.epsilon))),o);o.assign(p)}),this.iteration.assign(sr(this.iteration,1)),this.accBeta1.assign(ir(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&nr(this.accumulatedFirstMoment.map(e=>e.variable)),null!=this.accumulatedWeightedInfNorm&&nr(this.accumulatedWeightedInfNorm.map(e=>e.variable))}async getWeights(){throw new Error("getWeights() is not implemented for Adamax yet.")}async setWeights(e){throw new Error("setWeights() is not implemented for Adamax yet.")}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)}}gl.className="Adamax",Zn(gl);class bl extends dl{constructor(e){super(),this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map(e=>e.name):Object.keys(e)).forEach((t,n)=>{const r=Array.isArray(e)?e[n].tensor:e[t];if(null==r)return;const s=lt.registeredVariables[t];tr(()=>{const e=sr(ir(this.c,r),s);s.assign(e)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,null!=this.c&&this.c.dispose(),this.c=rr(ha(-e))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(e){if(0!==(e=await this.extractIterations(e)).length)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(e,t){return new e(t.learningRate)}}bl.className="SGD",Zn(bl);class yl extends bl{constructor(e,t,n=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=ha(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(e=>e.name):Object.keys(e)).forEach((t,n)=>{const r=lt.registeredVariables[t];if(null==this.accumulations[n]){const e=!1;this.accumulations[n]={originalName:t+"/momentum",variable:tr(()=>ys(r).variable(e))}}const s=this.accumulations[n].variable,o=Array.isArray(e)?e[n].tensor:e[t];null!=o&&tr(()=>{let e;const t=sr(ir(this.m,s),o);e=this.useNesterov?sr(ir(this.c,sr(o,ir(t,this.m))),r):sr(ir(this.c,t),r),s.assign(t),r.assign(e)})}),this.incrementIterations()}dispose(){this.m.dispose(),null!=this.accumulations&&nr(this.accumulations.map(e=>e.variable))}setMomentum(e){this.momentum=e}async getWeights(){return[await this.saveIterations()].concat(this.accumulations.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);this.accumulations=e.map(e=>({originalName:e.name,variable:e.tensor.variable(!1)}))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}}yl.className="Momentum",Zn(yl);class wl extends dl{constructor(e,t=.9,n=0,r=null,s=!1){if(super(),this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=r,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=s,null==r&&(this.epsilon=lt.backend.epsilon()),null==e)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map(e=>e.name):Object.keys(e)).forEach((t,n)=>{const r=lt.registeredVariables[t];null==this.accumulatedMeanSquares[n]&&(this.accumulatedMeanSquares[n]={originalName:t+"/rms",variable:tr(()=>ys(r).variable(!1))}),null==this.accumulatedMoments[n]&&(this.accumulatedMoments[n]={originalName:t+"/momentum",variable:tr(()=>ys(r).variable(!1))}),null==this.accumulatedMeanGrads[n]&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:t+"/mg",variable:tr(()=>ys(r).variable(!1))});const s=Array.isArray(e)?e[n].tensor:e[t];if(null==s)return;const o=this.accumulatedMeanSquares[n].variable,a=this.accumulatedMoments[n].variable;tr(()=>{const e=sr(ir(o,this.decay),ir(ko(s),1-this.decay));if(this.centered){const t=this.accumulatedMeanGrads[n].variable,i=sr(ir(t,this.decay),ir(s,1-this.decay)),l=ar(ir(s,this.learningRate),Ia(Ys(e,sr(ko(i),this.epsilon)))),u=sr(ir(a,this.momentum),l);o.assign(e),t.assign(i),a.assign(u);const c=Ys(r,u);r.assign(c)}else{const e=sr(ir(o,this.decay),ir(ko(s),1-this.decay)),t=sr(ir(a,this.momentum),ar(ir(s,this.learningRate),Ia(sr(e,this.epsilon))));o.assign(e),a.assign(t);const n=Ys(r,t);r.assign(n)}})}),this.incrementIterations()}dispose(){null!=this.accumulatedMeanSquares&&nr(this.accumulatedMeanSquares.map(e=>e.variable)),null!=this.accumulatedMeanGrads&&this.centered&&nr(this.accumulatedMeanGrads.map(e=>e.variable)),null!=this.accumulatedMoments&&nr(this.accumulatedMoments.map(e=>e.variable))}async getWeights(){const e=[...this.accumulatedMeanSquares,...this.accumulatedMoments];return this.centered&&e.push(...this.accumulatedMeanGrads),[await this.saveIterations()].concat(e.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);const t=this.centered?e.length/3:e.length/2;this.accumulatedMeanSquares=e.slice(0,t).map(e=>({originalName:e.name,variable:e.tensor.variable(!1)})),this.accumulatedMoments=e.slice(t,2*t).map(e=>({originalName:e.name,variable:e.tensor.variable(!1)})),this.centered&&(this.accumulatedMeanGrads=e.slice(2*t,3*t).map(e=>({originalName:e.name,variable:e.tensor.variable(!1)})))}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)}}wl.className="RMSProp",Zn(wl);class kl{static sgd(e){return new bl(e)}static momentum(e,t,n=!1){return new yl(e,t,n)}static rmsprop(e,t=.9,n=0,r=null,s=!1){return new wl(e,t,n,r,s)}static adam(e=.001,t=.9,n=.999,r=null){return new ml(e,t,n,r)}static adadelta(e=.001,t=.95,n=null){return new pl(e,t,n)}static adamax(e=.002,t=.9,n=.999,r=null,s=0){return new gl(e,t,n,r,s)}static adagrad(e,t=.1){return new fl(e,t)}}const vl={sgd:kl.sgd,momentum:kl.momentum,adadelta:kl.adadelta,adagrad:kl.adagrad,rmsprop:kl.rmsprop,adamax:kl.adamax,adam:kl.adam},xl="undefined"!=typeof requestAnimationFrame?requestAnimationFrame:"undefined"!=typeof setImmediate?setImmediate:e=>e();const El=/->/g;function Sl(e,t){const n=[];for(let r=0;r<e.length;++r)0!==e[r].length&&-1===e[r].indexOf(t)&&-1!==t||n.push(r);return n}var Al=Object.freeze({__proto__:null,segOpComputeOptimalWindowSize:function(e,t){let n,r=!1;for(e<=30?(n=e,r=!0):n=N(e,Math.floor(Math.sqrt(e)));!r;)n>t||n===e?r=!0:n=N(e,n+1);return n},computeOutShape:function(e,t,n){const r=[],s=e.length;for(let o=0;o<s;o++)o!==t?r.push(e[o]):r.push(n);return r},collectGatherOpShapeInfo:function(e,t,n,r){const s=t.shape.length,o=e.shape.length;if(0!==r&&(r<-s||r>s))throw new Error(`Expect batchDims in the range of [-${s}, ${s}], but got ${r}`);if(r<0&&(r+=s),r>o)throw new Error(`batchDims (${r}) must be less than rank(x) (\n ${o}).`);if(n<r)throw new Error(`batchDims (${r}) must be less than or equal to axis (${n}).`);for(let n=0;n<r;++n)if(e.shape[n]!==t.shape[n])throw new Error(`x.shape[${n}]: ${e.shape[n]} should be equal to indices.shape[${n}]: ${t.shape[n]}.`);const a=e.shape[n],i=[];let l=1,u=1,c=1;for(let t=0;t<r;++t)i.push(e.shape[t]),l*=e.shape[t];for(let t=r;t<n;t++)i.push(e.shape[t]),u*=e.shape[t];for(let e=r;e<s;e++)i.push(t.shape[e]);for(let t=n+1;t<o;t++)i.push(e.shape[t]),c*=e.shape[t];return{batchSize:l,sliceSize:c,outerSize:u,dimSize:a,outputShape:i}}});var _l=Object.freeze({__proto__:null,slice_util:Vn,segment_util:Al,fromUint8ToStringArray:function(e){try{return e.map(e=>Re(e))}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8, error: "+e)}},fromStringArrayToUint8:function(e){return e.map(e=>De(e))},upcastType:Qe,axesAreInnerMostDims:eo,combineLocations:to,computeOutAndReduceShapes:function(e,t){const n=[],r=e.length;for(let s=0;s<r;s++)-1===t.indexOf(s)&&n.push(e[s]);return[n,t.map(t=>e[t])]},expandShapeToKeepDim:no,assertAxesAreInnerMostDims:function(e,t,n){o(eo(t,n),()=>e+" supports only inner-most axes for now. "+`Got axes ${t} and rank-${n} input.`)},getAxesPermutation:function(e,t){if(eo(e,t))return null;const n=[];for(let r=0;r<t;++r)-1===e.indexOf(r)&&n.push(r);return e.forEach(e=>n.push(e)),n},getUndoAxesPermutation:function(e){return e.map((e,t)=>[t,e]).sort((e,t)=>e[1]-t[1]).map(e=>e[0])},getInnerMostAxes:function(e,t){const n=[];for(let r=t-e;r<t;++r)n.push(r);return n},getBroadcastDims:function(e,t){const n=e.length,r=[];for(let s=0;s<n;s++){const o=n-1-s,a=e[o]||1;(t[t.length-1-s]||1)>1&&1===a&&r.unshift(o)}return r},getReductionAxes:fs,assertAndGetBroadcastShape:ms,assertParamsConsistent:function(e,t){const n=e[0].length;e.forEach((e,t)=>{o(e.length===n,()=>`Error in concat${n}D: rank of tensors[${t}] must be the same as the rank of the rest (${n})`)}),o(t>=0&&t<n,()=>`Error in concat${n}D: axis must be between 0 and ${n-1}.`);const r=e[0];e.forEach((e,s)=>{for(let a=0;a<n;a++)o(a===t||e[a]===r[a],()=>`Error in concat${n}D: Shape of tensors[${s}] (${e}) does not match the shape of the rest (${r}) along the non-concatenated axis ${s}.`)})},computeOutShape:function(e,t){const n=e[0].slice();for(let r=1;r<e.length;r++)n[t]+=e[r][t];return n},computeDilation2DInfo:function(e,t,n,r,s="NHWC",o){return xr(e,[...t,e[3]],n,o,r,null,null,Tr(s))},computePool2DInfo:vr,computePool3DInfo:function(e,t,n,r,s,o,a="NDHWC"){const[i,l,u]=_r(t);let c,h;if("NDHWC"===a)h="channelsLast",c=[i,l,u,e[4],e[4]];else{if("NCDHW"!==a)throw new Error("Unknown dataFormat "+a);h="channelsFirst",c=[i,l,u,e[1],e[1]]}return Er(e,c,n,r,s,!1,h,o)},computeConv2DInfo:xr,computeConv3DInfo:Er,computeDefaultPad:Sr,tupleValuesAreOne:Mr,eitherStridesOrDilationsAreOne:$r,convertConv2DDataFormat:Tr,getFusedDyActivation:ti,getFusedBiasGradient:ni,applyActivation:ri,shouldFuse:si,PARALLELIZE_THRESHOLD:30,computeOptimalWindowSize:function(e){return e<=30?e:N(e,Math.floor(Math.sqrt(e)))},getImageCenter:function(e,t,n){return[n*("number"==typeof e?e:e[0]),t*("number"==typeof e?e:e[1])]},getReshaped:function(e,t,n,r=!0){let s=[];if(r)s=s.concat(t.slice(0)),s.push(e[0]/n),s=s.concat(e.slice(1));else{s=s.concat(e[0]);const n=t.length;for(let r=0;r<n;++r)s=s.concat([e[r+1]/t[r],t[r]]);s=s.concat(e.slice(n+1))}return s},getPermuted:function(e,t,n=!0){const r=[];if(n){r.push(t);for(let n=t+1;n<e;++n)n<=2*t?(r.push(n),r.push(n-(t+1))):r.push(n)}else{const n=[],s=[];for(let r=1;r<e;++r)r>=2*t+1||r%2==1?s.push(r):n.push(r);r.push(...n),r.push(0),r.push(...s)}return r},getReshapedPermuted:function(e,t,n,r=!0){const s=[];r?s.push(e[0]/n):s.push(e[0]*n);for(let n=1;n<e.length;++n)n<=t.length?r?s.push(t[n-1]*e[n]):s.push(e[n]/t[n-1]):s.push(e[n]);return s},getSliceBeginCoords:function(e,t){const n=[0];for(let r=0;r<t;++r)n.push(e[r][0]);return n},getSliceSize:function(e,t,n){const r=e.slice(0,1);for(let s=0;s<n;++s)r.push(e[s+1]-t[s][0]-t[s][1]);return r},prepareAndValidate:Mn,validateUpdateShape:Tn,validateInput:Dn,calculateShapes:Rn,SELU_SCALEALPHA:1.7580993408473768,SELU_SCALE:1.0507009873554805,ERF_P:.3275911,ERF_A1:.254829592,ERF_A2:-.284496736,ERF_A3:1.421413741,ERF_A4:-1.453152027,ERF_A5:1.061405429,warn:function(...e){C().getBool("IS_TEST")||console.warn(...e)},log:function(...e){C().getBool("IS_TEST")||console.log(...e)},mergeRealAndImagArrays:function(e,t){if(e.length!==t.length)throw new Error(`Cannot merge real and imag arrays of different lengths. real:${e.length}, imag: ${t.length}.`);const n=new Float32Array(2*e.length);for(let r=0;r<n.length;r+=2)n[r]=e[r/2],n[r+1]=t[r/2];return n},splitRealAndImagArrays:function(e){const t=new Float32Array(e.length/2),n=new Float32Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=e[r],n[r/2]=e[r+1];return{real:t,imag:n}},complexWithEvenIndex:function(e){const t=Math.ceil(e.length/4),n=new Float32Array(t),r=new Float32Array(t);for(let t=0;t<e.length;t+=4)n[Math.floor(t/4)]=e[t],r[Math.floor(t/4)]=e[t+1];return{real:n,imag:r}},complexWithOddIndex:function(e){const t=Math.floor(e.length/4),n=new Float32Array(t),r=new Float32Array(t);for(let t=2;t<e.length;t+=4)n[Math.floor(t/4)]=e[t],r[Math.floor(t/4)]=e[t+1];return{real:n,imag:r}},getComplexWithIndex:function(e,t){return{real:e[2*t],imag:e[2*t+1]}},assignToTypedArray:function(e,t,n,r){e[2*r]=t,e[2*r+1]=n},exponents:function(e,t){const n=new Float32Array(e/2),r=new Float32Array(e/2);for(let s=0;s<Math.ceil(e/2);s++){const o=(t?2:-2)*Math.PI*(s/e);n[s]=Math.cos(o),r[s]=Math.sin(o)}return{real:n,imag:r}},exponent:function(e,t,n){const r=(n?2:-2)*Math.PI*(e/t);return{real:Math.cos(r),imag:Math.sin(r)}},decodeEinsumEquation:function(e,t){const n=((e=e.replace(/\s/g,"")).length-e.replace(El,"").length)/"->".length;if(n<1)throw new Error("Equations without an arrow are not supported.");if(n>1)throw new Error('Equation must contain exactly one arrow ("->").');const[r,s]=e.split("->");o(-1===r.indexOf("..."),()=>'The ellipsis notation ("...") is not supported yet.');const a=r.split(","),i=a.length;if(t!==i)throw new Error(`Expected ${i} input tensors, received ${t}`);if(i>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");const l=[];for(let e=0;e<s.length;++e){const t=s[e];if(!a.some(e=>-1!==e.indexOf(t)))throw new Error(`Output subscripts contain the label ${t} not present in the input subscripts.`);-1===l.indexOf(t)&&l.push(t)}for(let e=0;e<r.length;++e){const t=r[e];-1===l.indexOf(t)&&","!==t&&l.push(t)}const u=new Array(a.length);for(let e=0;e<i;++e){if(new Set(a[e].split("")).size!==a[e].length)throw new Error(`Found duplicate axes in input component ${a[e]}. Support for duplicate axes in input is not implemented yet.`);u[e]=[];for(let t=0;t<a[e].length;++t)u[e].push(l.indexOf(a[e][t]))}const c=l.length,h=[];for(let e=s.length;e<c;++e)h.push(e);return{allDims:l,summedDims:h,idDims:u}},getEinsumPermutation:function(e,t){let n=new Array(e);n.fill(-1);for(let e=0;e<t.length;++e)n[t[e]]=e;const r=[];for(let t=0;t<e;++t)-1===n[t]&&r.push(t);return n=n.filter(e=>-1!==e),{permutationIndices:n,expandDims:r}},checkEinsumDimSizes:function(e,t,n){const r=new Array(e);for(let e=0;e<n.length;++e){const s=n[e].shape;for(let n=0;n<t[e].length;++n)void 0===r[t[e][n]]?r[t[e][n]]=s[n]:o(r[t[e][n]]===s[n],()=>`Expected dimension ${r[t[e][n]]} at axis ${n} of input shaped ${JSON.stringify(s)}, but got dimension `+s[n])}},getEinsumComputePath:function(e,t){const n=e,r=[];let s=0;0===e.length&&n.push(-1),s=e.length+1;for(let e=0;e<s;++e)r.push([]);const o=[];for(let e=0;e<n.length;++e){const s=Sl(t,n[e]);for(const t of s)-1===o.indexOf(t)&&(r[e].push(t),o.push(t))}return{path:n,steps:r}},isIdentityPermutation:function(e){return e.every((e,t)=>e===t)},prepareSplitSize:function(e,t,n=0){let r=[];if("number"==typeof t)o(e.shape[n]%t==0,()=>"Number of splits must evenly divide the axis."),r=new Array(t).fill(e.shape[n]/t);else{o(t.reduce((e,t)=>(-1===t&&(e+=1),e),0)<=1,()=>"There should be only one negative value in split array.");const s=t.indexOf(-1);if(-1!==s){const r=t.reduce((e,t)=>t>0?e+t:e);t[s]=e.shape[n]-r}o(e.shape[n]===t.reduce((e,t)=>e+t),()=>"The sum of sizes must match the size of the axis dimension."),r=t}return r}}),Nl=Object.freeze({__proto__:null,nonMaxSuppressionV3Impl:xi,nonMaxSuppressionV4Impl:Ei,nonMaxSuppressionV5Impl:Si,whereImpl:Ka});e.Abs="Abs",e.Acos="Acos",e.Acosh="Acosh",e.AdadeltaOptimizer=pl,e.AdagradOptimizer=fl,e.AdamOptimizer=ml,e.AdamaxOptimizer=gl,e.Add="Add",e.AddN="AddN",e.All="All",e.Any="Any",e.ArgMax="ArgMax",e.ArgMin="ArgMin",e.Asin="Asin",e.Asinh="Asinh",e.Atan="Atan",e.Atan2="Atan2",e.Atanh="Atanh",e.AvgPool="AvgPool",e.AvgPool3D="AvgPool3D",e.AvgPool3DGrad="AvgPool3DGrad",e.AvgPoolGrad="AvgPoolGrad",e.BatchMatMul="BatchMatMul",e.BatchToSpaceND="BatchToSpaceND",e.Bincount="Bincount",e.BroadcastTo="BroadcastTo",e.Cast="Cast",e.Ceil="Ceil",e.ClipByValue="ClipByValue",e.Complex="Complex",e.ComplexAbs="ComplexAbs",e.Concat="Concat",e.Conv2D="Conv2D",e.Conv2DBackpropFilter="Conv2DBackpropFilter",e.Conv2DBackpropInput="Conv2DBackpropInput",e.Conv3D="Conv3D",e.Conv3DBackpropFilterV2="Conv3DBackpropFilterV2",e.Conv3DBackpropInputV2="Conv3DBackpropInputV2",e.Cos="Cos",e.Cosh="Cosh",e.CropAndResize="CropAndResize",e.Cumsum="Cumsum",e.DataStorage=class{constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}},e.DenseBincount="DenseBincount",e.DepthToSpace="DepthToSpace",e.DepthwiseConv2dNative="DepthwiseConv2dNative",e.DepthwiseConv2dNativeBackpropFilter="DepthwiseConv2dNativeBackpropFilter",e.DepthwiseConv2dNativeBackpropInput="DepthwiseConv2dNativeBackpropInput",e.Diag="Diag",e.Dilation2D="Dilation2D",e.Dilation2DBackpropFilter="Dilation2DBackpropFilter",e.Dilation2DBackpropInput="Dilation2DBackpropInput",e.Einsum="Einsum",e.Elu="Elu",e.EluGrad="EluGrad",e.Environment=B,e.Equal="Equal",e.Erf="Erf",e.Exp="Exp",e.ExpandDims="ExpandDims",e.Expm1="Expm1",e.FFT="FFT",e.Fill="Fill",e.FlipLeftRight="FlipLeftRight",e.Floor="Floor",e.FloorDiv="FloorDiv",e.FromPixels="FromPixels",e.FusedBatchNorm="FusedBatchNorm",e.FusedConv2D="FusedConv2D",e.FusedDepthwiseConv2D="FusedDepthwiseConv2D",e.GatherNd="GatherNd",e.GatherV2="GatherV2",e.Greater="Greater",e.GreaterEqual="GreaterEqual",e.IFFT="IFFT",e.Identity="Identity",e.Imag="Imag",e.IsFinite="IsFinite",e.IsInf="IsInf",e.IsNan="IsNan",e.KernelBackend=t,e.LRN="LRN",e.LRNGrad="LRNGrad",e.LeakyRelu="LeakyRelu",e.Less="Less",e.LessEqual="LessEqual",e.LinSpace="LinSpace",e.Log="Log",e.Log1p="Log1p",e.LogSoftmax="LogSoftmax",e.LogicalAnd="LogicalAnd",e.LogicalNot="LogicalNot",e.LogicalOr="LogicalOr",e.Max="Max",e.MaxPool="MaxPool",e.MaxPool3D="MaxPool3D",e.MaxPool3DGrad="MaxPool3DGrad",e.MaxPoolGrad="MaxPoolGrad",e.MaxPoolWithArgmax="MaxPoolWithArgmax",e.Maximum="Maximum",e.Mean="Mean",e.Min="Min",e.Minimum="Minimum",e.MirrorPad="MirrorPad",e.Mod="Mod",e.MomentumOptimizer=yl,e.Multinomial="Multinomial",e.Multiply="Multiply",e.Neg="Neg",e.NonMaxSuppressionV3="NonMaxSuppressionV3",e.NonMaxSuppressionV4="NonMaxSuppressionV4",e.NonMaxSuppressionV5="NonMaxSuppressionV5",e.NotEqual="NotEqual",e.OP_SCOPE_SUFFIX="__op",e.OneHot="OneHot",e.OnesLike="OnesLike",e.Optimizer=dl,e.Pack="Pack",e.PadV2="PadV2",e.Pool="Pool",e.Pow="Pow",e.Prelu="Prelu",e.Prod="Prod",e.RMSPropOptimizer=wl,e.Range="Range",e.Real="Real",e.RealDiv="RealDiv",e.Reciprocal="Reciprocal",e.Relu="Relu",e.Relu6="Relu6",e.Reshape="Reshape",e.ResizeBilinear="ResizeBilinear",e.ResizeBilinearGrad="ResizeBilinearGrad",e.ResizeNearestNeighbor="ResizeNearestNeighbor",e.ResizeNearestNeighborGrad="ResizeNearestNeighborGrad",e.Reverse="Reverse",e.RotateWithOffset="RotateWithOffset",e.Round="Round",e.Rsqrt="Rsqrt",e.SGDOptimizer=bl,e.ScatterNd="ScatterNd",e.Select="Select",e.Selu="Selu",e.Sigmoid="Sigmoid",e.Sign="Sign",e.Sin="Sin",e.Sinh="Sinh",e.Slice="Slice",e.Softmax="Softmax",e.Softplus="Softplus",e.SpaceToBatchND="SpaceToBatchND",e.SparseFillEmptyRows="SparseFillEmptyRows",e.SparseReshape="SparseReshape",e.SparseSegmentMean="SparseSegmentMean",e.SparseSegmentSum="SparseSegmentSum",e.SparseToDense="SparseToDense",e.SplitV="SplitV",e.Sqrt="Sqrt",e.Square="Square",e.SquaredDifference="SquaredDifference",e.Step="Step",e.StridedSlice="StridedSlice",e.StringNGrams="StringNGrams",e.StringSplit="StringSplit",e.StringToHashBucketFast="StringToHashBucketFast",e.Sub="Sub",e.Sum="Sum",e.Tan="Tan",e.Tanh="Tanh",e.Tensor=Ge,e.TensorBuffer=Ke,e.Tile="Tile",e.TopK="TopK",e.Transform="Transform",e.Transpose="Transpose",e.Unique="Unique",e.Unpack="Unpack",e.UnsortedSegmentSum="UnsortedSegmentSum",e.Variable=Ve,e.ZerosLike="ZerosLike",e._FusedMatMul="_FusedMatMul",e.abs=lr,e.acos=ur,e.acosh=cr,e.add=sr,e.addN=hr,e.all=dr,e.any=pr,e.argMax=fr,e.argMin=mr,e.asin=gr,e.asinh=br,e.atan=yr,e.atan2=wr,e.atanh=kr,e.avgPool=Rr,e.avgPool3d=Br,e.backend=function(){return lt.backend},e.backend_util=_l,e.basicLSTMCell=Or,e.batchNorm=qr,e.batchNorm2d=Kr,e.batchNorm3d=Wr,e.batchNorm4d=Ur,e.batchToSpaceND=zr,e.bincount=Gr,e.booleanMaskAsync=Ua,e.broadcastTo=Vr,e.browser=In,e.buffer=en,e.cast=tn,e.ceil=Hr,e.clipByValue=jr,e.clone=nn,e.complex=yt,e.concat=Fr,e.concat1d=Zr,e.concat2d=Jr,e.concat3d=Yr,e.concat4d=Xr,e.conv1d=es,e.conv2d=Qr,e.conv2dTranspose=ns,e.conv3d=rs,e.conv3dTranspose=os,e.copyRegisteredKernels=function(e,t){U(e).forEach(e=>{G(Object.assign({},e,{backendName:t}))})},e.cos=as,e.cosh=is,e.cosineWindow=Xa,e.cumsum=ls,e.customGrad=Gs,e.denseBincount=us,e.deprecationWarn=function(e){C().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")},e.depthToSpace=cs,e.depthwiseConv2d=hs,e.device_util=ht,e.diag=ds,e.dilation2d=ps,e.disableDeprecationWarnings=function(){C().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")},e.dispose=nr,e.disposeVariables=function(){lt.disposeVariables()},e.div=ar,e.divNoNan=ws,e.dot=ks,e.dropout=Ja,e.einsum=vs,e.elu=xs,e.enableDebugMode=function(){C().set("DEBUG",!0)},e.enableProdMode=function(){C().set("PROD",!0)},e.enclosingPowerOfTwo=Ya,e.engine=function(){return lt},e.env=C,e.equal=gs,e.erf=Es,e.exp=Ss,e.expandDims=As,e.expm1=_s,e.eye=Is,e.fft=Ea,e.fill=Ms,e.findBackend=function(e){return lt.findBackend(e)},e.findBackendFactory=function(e){return lt.findBackendFactory(e)},e.floor=$s,e.floorDiv=or,e.fused=ci,e.gather=Ts,e.gatherND=Za,e.gather_util=$n,e.getBackend=function(){return lt.backendName},e.getGradient=W,e.getKernel=K,e.getKernelsForBackend=U,e.grad=function(e){return o(_(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{const r=mt(t,"x","tf.grad","string_or_numeric"),s=null!=n?mt(n,"dy","tf.grad"):null;return lt.tidy(()=>{const{value:t,grads:n}=lt.gradients(()=>e(r),[r],s);return null!=s&&a(t.shape,s.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Vs(n),n[0]})}},e.grads=function(e){return o(_(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{o(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");const r=gt(t,"args","tf.grads","string_or_numeric"),s=null!=n?mt(n,"dy","tf.grads"):null;return lt.tidy(()=>{const{value:t,grads:n}=lt.gradients(()=>e(...r),r,s);return null!=s&&a(t.shape,s.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Vs(n),n})}},e.greater=Ds,e.greaterEqual=Rs,e.ifft=Sa,e.imag=Bs,e.image=il,e.inTopKAsync=Qa,e.io=bn,e.irfft=Aa,e.isFinite=Fs,e.isInf=Cs,e.isNaN=Ps,e.keep=rr,e.kernel_impls=Nl,e.leakyRelu=Ls,e.less=Os,e.lessEqual=zs,e.linalg=ll,e.linspace=function(e,t,n){if(n<=0)throw new Error("The number of values should be positive.");const r={start:e,stop:t,num:n};return lt.runKernel("LinSpace",{},r)},e.localResponseNormalization=qs,e.log=Ks,e.log1p=Ws,e.logSigmoid=Zs,e.logSoftmax=Qs,e.logSumExp=ro,e.logicalAnd=so,e.logicalNot=oo,e.logicalOr=ao,e.logicalXor=io,e.losses=ul,e.matMul=yn,e.math=xn,e.max=Js,e.maxPool=lo,e.maxPool3d=uo,e.maxPoolWithArgmax=co,e.maximum=ho,e.mean=po,e.memory=function(){return lt.memory()},e.meshgrid=function(e,t,{indexing:n="xy"}={}){if("xy"!==n&&"ij"!==n)throw new TypeError(n+" is not a valid third argument to meshgrid");if(void 0===e)return[];let r=mt(e,"x","meshgrid",e instanceof Ge?e.dtype:"float32");if(void 0===t)return[r];let s=mt(t,"y","meshgrid",t instanceof Ge?t.dtype:"float32");const o=u(r.shape),a=u(s.shape);return"xy"===n?(r=Dr(r,[1,-1]),s=Dr(s,[-1,1]),[yn(mo([a,1],r.dtype),r),yn(s,mo([1,o],s.dtype))]):(r=Dr(r,[-1,1]),s=Dr(s,[1,-1]),[yn(r,mo([1,a],r.dtype)),yn(mo([o,1],s.dtype),s)])},e.min=go,e.minimum=bo,e.mirrorPad=yo,e.mod=wo,e.moments=vo,e.movingAverage=Va,e.mul=ir,e.multiRNNCell=xo,e.multinomial=Eo,e.neg=Hs,e.nextFrame=function(){return new Promise(e=>xl(()=>e()))},e.norm=Ga,e.notEqual=So,e.oneHot=wn,e.ones=mo,e.onesLike=Ao,e.op=bt,e.outerProduct=_o,e.pad=No,e.pad1d=Io,e.pad2d=Mo,e.pad3d=$o,e.pad4d=To,e.pool=Ro,e.pow=Bo,e.prelu=Fo,e.print=rn,e.prod=Co,e.profile=function(e){return lt.profile(e)},e.rand=Po,e.randomGamma=Jo,e.randomNormal=Yo,e.randomUniform=Xo,e.range=Qo,e.ready=function(){return lt.ready()},e.real=ea,e.reciprocal=ta,e.registerBackend=function(e,t,n=1){return lt.registerBackend(e,t,n)},e.registerGradient=function(e){const{kernelName:t}=e;q.has(t)&&C().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${t}'`),q.set(t,e)},e.registerKernel=G,e.relu=na,e.relu6=ra,e.removeBackend=function(e){lt.removeBackend(e)},e.reshape=Dr,e.reverse=sa,e.reverse1d=oa,e.reverse2d=aa,e.reverse3d=ia,e.reverse4d=la,e.rfft=Na,e.round=ua,e.rsqrt=ca,e.scalar=ha,e.scatterND=Ha,e.scatter_util=Bn,e.selu=da,e.separableConv2d=pa,e.serialization=Jn,e.setBackend=function(e){return lt.setBackend(e)},e.setPlatform=function(e,t){C().setPlatform(e,t)},e.setdiff1dAsync=fa,e.sigmoid=Cr,e.sign=ma,e.signal=al,e.sin=ga,e.sinh=ba,e.slice=Pr,e.slice1d=ya,e.slice2d=wa,e.slice3d=ka,e.slice4d=va,e.slice_util=Vn,e.softmax=xa,e.softplus=js,e.spaceToBatchND=Do,e.sparse=cl,e.sparseToDense=ja,e.spectral=ol,e.split=_a,e.sqrt=Ia,e.square=ko,e.squaredDifference=Ma,e.squeeze=$a,e.stack=Ta,e.step=Da,e.stridedSlice=Ra,e.string=hl,e.sub=Ys,e.sum=Xs,e.sumOutType=function(e){return Qe(e,"int32")},e.tan=Ba,e.tanh=Lr,e.tensor=kt,e.tensor1d=Fa,e.tensor2d=Ca,e.tensor3d=En,e.tensor4d=function(e,t,n){if(i(e),null!=t&&4!==t.length)throw new Error("tensor4d() requires shape to have four numbers");const r=pt(e,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==t)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return wt(e,t,r,n)},e.tensor5d=function(e,t,n){if(i(e),null!=t&&5!==t.length)throw new Error("tensor5d() requires shape to have five numbers");const r=pt(e,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==t)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return wt(e,t,r,n)},e.tensor6d=function(e,t,n){if(i(e),null!=t&&6!==t.length)throw new Error("tensor6d() requires shape to have six numbers");const r=pt(e,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==t)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return wt(e,t=t||r,r,n)},e.tensor_util=rt,e.test_util=er,e.tidy=tr,e.tile=Ns,e.time=function(e){return lt.time(e)},e.topk=Pa,e.train=vl,e.transpose=kn,e.truncatedNormal=La,e.unique=Oa,e.unregisterGradient=function(e){if(!q.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);q.delete(e)},e.unregisterKernel=function(e,t){const n=V(e,t);if(!z.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);z.delete(n)},e.unsortedSegmentSum=za,e.unstack=qa,e.upcastType=Qe,e.util=Be,e.valueAndGrad=function(e){return o(_(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{o(t instanceof Ge,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),o(null==n||n instanceof Ge,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");const{grads:r,value:s}=lt.gradients(()=>e(t),[t],n);return Vs(r),{grad:r[0],value:s}}},e.valueAndGrads=function(e){return o(_(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{o(Array.isArray(t)&&t.every(e=>e instanceof Ge),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),o(null==n||n instanceof Ge,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");const r=lt.gradients(()=>e(...t),t,n);return null!=n&&a(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Vs(r.grads),r}},e.variable=function(e,t=!0,n,r){return lt.makeVariable(e,t,n,r)},e.variableGrads=Us,e.version_core="3.7.0",e.where=bs,e.whereAsync=Wa,e.zeros=fo,e.zerosLike=ys,Object.defineProperty(e,"__esModule",{value:!0})}));
18//# sourceMappingURL=tf-core.es2017.min.js.map