UNPKG

291 kBJavaScriptView Raw
1/**
2 * @license
3 * Copyright 2022 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 */
17import*as t from"@tensorflow/tfjs-core";import{backend as e,util as n,serialization as s,tidy as i,tensor1d as r,zeros as a,ones as o,mul as l,scalar as u,randomUniform as h,truncatedNormal as c,eye as p,linalg as d,transpose as f,dispose as g,nextFrame as m,add as y,div as b,keep as w,train as k,memory as v,cast as S,clone as x,argMax as N,reshape as I,Tensor as A,Optimizer as C,io as T,sum as z,abs as E,relu as $,clipByValue as F,leakyRelu as D,prelu as L,elu as _,greater as R,any as M,notEqual as O,zerosLike as B,greaterEqual as P,moments as U}from"@tensorflow/tfjs-core";function W(t){throw new Error(`'${t}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function V(t,e){if(!t)throw new Error("string"==typeof e?e:e())}function j(t,e=[],n=!1){if(null==e&&(e=[]),Array.isArray(t)||J(t)&&!n)for(let s=0;s<t.length;++s)j(t[s],e,n);else e.push(t);return e}function q(t){if(0===t.length)return 1;let e=t[0];for(let n=1;n<t.length;n++)e*=t[n];return e}function K(t,e){if(t===e)return!0;if(null==t||null==e)return!1;if(t.length!==e.length)return!1;for(let n=0;n<t.length;n++)if(t[n]!==e[n])return!1;return!0}function G(t){return t%1==0}function H(t,e){return e<=t.length?t:t+" ".repeat(e-t.length)}function Z(t,e){const n=e.length;return V((t=null==t?e.map(((t,e)=>e)):[].concat(t)).every((t=>t>=-n&&t<n)),(()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${t}`)),V(t.every((t=>G(t))),(()=>`All values in axis param must be integers but got axis ${t}`)),t.map((t=>t<0?n+t:t))}function J(t){return t instanceof Float32Array||t instanceof Int32Array||t instanceof Uint8Array||t instanceof Uint8ClampedArray}function Y(t){if("float32"===t||"int32"===t)return 4;if("complex64"===t)return 8;if("bool"===t)return 1;throw new Error(`Unknown dtype ${t}`)}function X(t){return"string"==typeof t||t instanceof String}function Q(t){return Array.isArray(t)?Q(t[0]):t instanceof Float32Array?"float32":t instanceof Int32Array||t instanceof Uint8Array||t instanceof Uint8ClampedArray?"int32":"number"==typeof t?"float32":X(t)?"string":function(t){return"boolean"==typeof t}(t)?"bool":"float32"}function tt(t){return!!(t&&t.constructor&&t.call&&t.apply)}function et(t){const e=t.length;if(e<2)return[];const n=new Array(e-1);n[e-2]=t[e-1];for(let s=e-3;s>=0;--s)n[s]=n[s+1]*t[s+1];return n}function nt(t,e,n,s=!1){const i=new Array;if(1===e.length){const r=e[0]*(s?2:1);for(let e=0;e<r;e++)i[e]=n[t+e]}else{const r=e[0],a=e.slice(1),o=a.reduce(((t,e)=>t*e))*(s?2:1);for(let e=0;e<r;e++)i[e]=nt(t+e*o,a,n,s)}return i}function st(t,e,n=!1){if(0===t.length)return e[0];const s=t.reduce(((t,e)=>t*e))*(n?2:1);if(0===s)return[];if(s!==e.length)throw new Error(`[${t}] does not match the input size ${e.length}${n?" for a complex tensor":""}.`);return nt(0,t,e,n)}function it(t,e){const n=rt(t,e);for(let t=0;t<n.length;t++)n[t]=1;return n}function rt(t,e){if(null==e||"float32"===e||"complex64"===e)return new Float32Array(t);if("int32"===e)return new Int32Array(t);if("bool"===e)return new Uint8Array(t);throw new Error(`Unknown data type ${e}`)}function at(t){return t&&t.then&&"function"==typeof t.then}class ot{constructor(t){this.global=t,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=lt,this.populateURLFlags()}setPlatform(t,e){null!=this.platform&&(ut().getBool("IS_TEST")||ut().getBool("PROD")||console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${t}.`)),this.platformName=t,this.platform=e}registerFlag(t,e,n){if(this.flagRegistry[t]={evaluationFn:e,setHook:n},null!=this.urlFlags[t]){const e=this.urlFlags[t];ut().getBool("IS_TEST")||ut().getBool("PROD")||console.warn(`Setting feature override from URL ${t}: ${e}.`),this.set(t,e)}}async getAsync(t){return t in this.flags||(this.flags[t]=await this.evaluateFlag(t)),this.flags[t]}get(t){if(t in this.flags)return this.flags[t];const e=this.evaluateFlag(t);if(at(e))throw new Error(`Flag ${t} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[t]=e,this.flags[t]}getNumber(t){return this.get(t)}getBool(t){return this.get(t)}getFlags(){return this.flags}get features(){return this.flags}set(t,e){if(null==this.flagRegistry[t])throw new Error(`Cannot set flag ${t} as it has not been registered.`);this.flags[t]=e,null!=this.flagRegistry[t].setHook&&this.flagRegistry[t].setHook(e)}evaluateFlag(t){if(null==this.flagRegistry[t])throw new Error(`Cannot evaluate flag '${t}': no evaluation function found.`);return this.flagRegistry[t].evaluationFn()}setFlags(t){this.flags=Object.assign({},t)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if("undefined"==typeof this.global||"undefined"==typeof this.global.location||"undefined"==typeof this.global.location.search)return;const t=this.getQueryParams(this.global.location.search);if("tfjsflags"in t){t.tfjsflags.split(",").forEach((t=>{const[e,n]=t.split(":");this.urlFlags[e]=function(t,e){if("true"===(e=e.toLowerCase())||"false"===e)return"true"===e;if(""+ +e===e)return+e;throw new Error(`Could not parse value flag value ${e} for flag ${t}.`)}(e,n)}))}}}function lt(t){const e={};return t.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,((t,...n)=>(function(t,e,n){t[decodeURIComponent(e)]=decodeURIComponent(n||"")}(e,n[0],n[1]),n.join("=")))),e}function ut(){return ct}let ht,ct=null;function pt(){if(null==ht){let t;if("undefined"!=typeof window)t=window;else if("undefined"!=typeof global)t=global;else if("undefined"!=typeof process)t=process;else{if("undefined"==typeof self)throw new Error("Could not find a global object");t=self}ht=t}return ht}function dt(t,e){const n=function(){const t=pt();return null==t._tfGlobals&&(t._tfGlobals=new Map),t._tfGlobals}();if(n.has(t))return n.get(t);{const s=e();return n.set(t,s),n.get(t)}}function ft(...t){ut().getBool("IS_TEST")||ut().getBool("PROD")||console.warn(...t)}const gt=dt("kernelRegistry",(()=>new Map)),mt=dt("gradRegistry",(()=>new Map));function yt(t,e){const n=function(t,e){return`${e}_${t}`}(t,e);return gt.get(n)}function bt(t){return mt.get(t)}function wt(t){const e=gt.entries(),n=[];for(;;){const{done:s,value:i}=e.next();if(s)break;const[r,a]=i,[o]=r.split("_");o===t&&n.push(a)}return n}function kt(t){const{kernelName:e}=t;mt.has(e)&&ut().getBool("DEBUG")&&ft(`Overriding the gradient for '${e}'`),mt.set(e,t)}var vt=xt,St=null;try{St=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(t){}function xt(t,e,n){this.low=0|t,this.high=0|e,this.unsigned=!!n}function Nt(t){return!0===(t&&t.__isLong__)}xt.prototype.__isLong__,Object.defineProperty(xt.prototype,"__isLong__",{value:!0}),xt.isLong=Nt;var It={},At={};function Ct(t,e){var n,s,i;return e?(i=0<=(t>>>=0)&&t<256)&&(s=At[t])?s:(n=zt(t,(0|t)<0?-1:0,!0),i&&(At[t]=n),n):(i=-128<=(t|=0)&&t<128)&&(s=It[t])?s:(n=zt(t,t<0?-1:0,!1),i&&(It[t]=n),n)}function Tt(t,e){if(isNaN(t))return e?Ot:Mt;if(e){if(t<0)return Ot;if(t>=Lt)return Vt}else{if(t<=-_t)return jt;if(t+1>=_t)return Wt}return t<0?Tt(-t,e).neg():zt(t%Dt|0,t/Dt|0,e)}function zt(t,e,n){return new xt(t,e,n)}xt.fromInt=Ct,xt.fromNumber=Tt,xt.fromBits=zt;var Et=Math.pow;function $t(t,e,n){if(0===t.length)throw Error("empty string");if("NaN"===t||"Infinity"===t||"+Infinity"===t||"-Infinity"===t)return Mt;if("number"==typeof e?(n=e,e=!1):e=!!e,(n=n||10)<2||36<n)throw RangeError("radix");var s;if((s=t.indexOf("-"))>0)throw Error("interior hyphen");if(0===s)return $t(t.substring(1),e,n).neg();for(var i=Tt(Et(n,8)),r=Mt,a=0;a<t.length;a+=8){var o=Math.min(8,t.length-a),l=parseInt(t.substring(a,a+o),n);if(o<8){var u=Tt(Et(n,o));r=r.mul(u).add(Tt(l))}else r=(r=r.mul(i)).add(Tt(l))}return r.unsigned=e,r}function Ft(t,e){return"number"==typeof t?Tt(t,e):"string"==typeof t?$t(t,e):zt(t.low,t.high,"boolean"==typeof e?e:t.unsigned)}xt.fromString=$t,xt.fromValue=Ft;var Dt=4294967296,Lt=Dt*Dt,_t=Lt/2,Rt=Ct(1<<24),Mt=Ct(0);xt.ZERO=Mt;var Ot=Ct(0,!0);xt.UZERO=Ot;var Bt=Ct(1);xt.ONE=Bt;var Pt=Ct(1,!0);xt.UONE=Pt;var Ut=Ct(-1);xt.NEG_ONE=Ut;var Wt=zt(-1,2147483647,!1);xt.MAX_VALUE=Wt;var Vt=zt(-1,-1,!0);xt.MAX_UNSIGNED_VALUE=Vt;var jt=zt(0,-2147483648,!1);xt.MIN_VALUE=jt;var qt=xt.prototype;qt.toInt=function(){return this.unsigned?this.low>>>0:this.low},qt.toNumber=function(){return this.unsigned?(this.high>>>0)*Dt+(this.low>>>0):this.high*Dt+(this.low>>>0)},qt.toString=function(t){if((t=t||10)<2||36<t)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(jt)){var e=Tt(t),n=this.div(e),s=n.mul(e).sub(this);return n.toString(t)+s.toInt().toString(t)}return"-"+this.neg().toString(t)}for(var i=Tt(Et(t,6),this.unsigned),r=this,a="";;){var o=r.div(i),l=(r.sub(o.mul(i)).toInt()>>>0).toString(t);if((r=o).isZero())return l+a;for(;l.length<6;)l="0"+l;a=""+l+a}},qt.getHighBits=function(){return this.high},qt.getHighBitsUnsigned=function(){return this.high>>>0},qt.getLowBits=function(){return this.low},qt.getLowBitsUnsigned=function(){return this.low>>>0},qt.getNumBitsAbs=function(){if(this.isNegative())return this.eq(jt)?64:this.neg().getNumBitsAbs();for(var t=0!=this.high?this.high:this.low,e=31;e>0&&0==(t&1<<e);e--);return 0!=this.high?e+33:e+1},qt.isZero=function(){return 0===this.high&&0===this.low},qt.eqz=qt.isZero,qt.isNegative=function(){return!this.unsigned&&this.high<0},qt.isPositive=function(){return this.unsigned||this.high>=0},qt.isOdd=function(){return 1==(1&this.low)},qt.isEven=function(){return 0==(1&this.low)},qt.equals=function(t){return Nt(t)||(t=Ft(t)),(this.unsigned===t.unsigned||this.high>>>31!=1||t.high>>>31!=1)&&(this.high===t.high&&this.low===t.low)},qt.eq=qt.equals,qt.notEquals=function(t){return!this.eq(t)},qt.neq=qt.notEquals,qt.ne=qt.notEquals,qt.lessThan=function(t){return this.comp(t)<0},qt.lt=qt.lessThan,qt.lessThanOrEqual=function(t){return this.comp(t)<=0},qt.lte=qt.lessThanOrEqual,qt.le=qt.lessThanOrEqual,qt.greaterThan=function(t){return this.comp(t)>0},qt.gt=qt.greaterThan,qt.greaterThanOrEqual=function(t){return this.comp(t)>=0},qt.gte=qt.greaterThanOrEqual,qt.ge=qt.greaterThanOrEqual,qt.compare=function(t){if(Nt(t)||(t=Ft(t)),this.eq(t))return 0;var e=this.isNegative(),n=t.isNegative();return e&&!n?-1:!e&&n?1:this.unsigned?t.high>>>0>this.high>>>0||t.high===this.high&&t.low>>>0>this.low>>>0?-1:1:this.sub(t).isNegative()?-1:1},qt.comp=qt.compare,qt.negate=function(){return!this.unsigned&&this.eq(jt)?jt:this.not().add(Bt)},qt.neg=qt.negate,qt.add=function(t){Nt(t)||(t=Ft(t));var e=this.high>>>16,n=65535&this.high,s=this.low>>>16,i=65535&this.low,r=t.high>>>16,a=65535&t.high,o=t.low>>>16,l=0,u=0,h=0,c=0;return h+=(c+=i+(65535&t.low))>>>16,u+=(h+=s+o)>>>16,l+=(u+=n+a)>>>16,l+=e+r,zt((h&=65535)<<16|(c&=65535),(l&=65535)<<16|(u&=65535),this.unsigned)},qt.subtract=function(t){return Nt(t)||(t=Ft(t)),this.add(t.neg())},qt.sub=qt.subtract,qt.multiply=function(t){if(this.isZero())return Mt;if(Nt(t)||(t=Ft(t)),St)return zt(St.mul(this.low,this.high,t.low,t.high),St.get_high(),this.unsigned);if(t.isZero())return Mt;if(this.eq(jt))return t.isOdd()?jt:Mt;if(t.eq(jt))return this.isOdd()?jt:Mt;if(this.isNegative())return t.isNegative()?this.neg().mul(t.neg()):this.neg().mul(t).neg();if(t.isNegative())return this.mul(t.neg()).neg();if(this.lt(Rt)&&t.lt(Rt))return Tt(this.toNumber()*t.toNumber(),this.unsigned);var e=this.high>>>16,n=65535&this.high,s=this.low>>>16,i=65535&this.low,r=t.high>>>16,a=65535&t.high,o=t.low>>>16,l=65535&t.low,u=0,h=0,c=0,p=0;return c+=(p+=i*l)>>>16,h+=(c+=s*l)>>>16,c&=65535,h+=(c+=i*o)>>>16,u+=(h+=n*l)>>>16,h&=65535,u+=(h+=s*o)>>>16,h&=65535,u+=(h+=i*a)>>>16,u+=e*l+n*o+s*a+i*r,zt((c&=65535)<<16|(p&=65535),(u&=65535)<<16|(h&=65535),this.unsigned)},qt.mul=qt.multiply,qt.divide=function(t){if(Nt(t)||(t=Ft(t)),t.isZero())throw Error("division by zero");var e,n,s;if(St)return this.unsigned||-2147483648!==this.high||-1!==t.low||-1!==t.high?zt((this.unsigned?St.div_u:St.div_s)(this.low,this.high,t.low,t.high),St.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?Ot:Mt;if(this.unsigned){if(t.unsigned||(t=t.toUnsigned()),t.gt(this))return Ot;if(t.gt(this.shru(1)))return Pt;s=Ot}else{if(this.eq(jt))return t.eq(Bt)||t.eq(Ut)?jt:t.eq(jt)?Bt:(e=this.shr(1).div(t).shl(1)).eq(Mt)?t.isNegative()?Bt:Ut:(n=this.sub(t.mul(e)),s=e.add(n.div(t)));if(t.eq(jt))return this.unsigned?Ot:Mt;if(this.isNegative())return t.isNegative()?this.neg().div(t.neg()):this.neg().div(t).neg();if(t.isNegative())return this.div(t.neg()).neg();s=Mt}for(n=this;n.gte(t);){e=Math.max(1,Math.floor(n.toNumber()/t.toNumber()));for(var i=Math.ceil(Math.log(e)/Math.LN2),r=i<=48?1:Et(2,i-48),a=Tt(e),o=a.mul(t);o.isNegative()||o.gt(n);)o=(a=Tt(e-=r,this.unsigned)).mul(t);a.isZero()&&(a=Bt),s=s.add(a),n=n.sub(o)}return s},qt.div=qt.divide,qt.modulo=function(t){return Nt(t)||(t=Ft(t)),St?zt((this.unsigned?St.rem_u:St.rem_s)(this.low,this.high,t.low,t.high),St.get_high(),this.unsigned):this.sub(this.div(t).mul(t))},qt.mod=qt.modulo,qt.rem=qt.modulo,qt.not=function(){return zt(~this.low,~this.high,this.unsigned)},qt.and=function(t){return Nt(t)||(t=Ft(t)),zt(this.low&t.low,this.high&t.high,this.unsigned)},qt.or=function(t){return Nt(t)||(t=Ft(t)),zt(this.low|t.low,this.high|t.high,this.unsigned)},qt.xor=function(t){return Nt(t)||(t=Ft(t)),zt(this.low^t.low,this.high^t.high,this.unsigned)},qt.shiftLeft=function(t){return Nt(t)&&(t=t.toInt()),0==(t&=63)?this:t<32?zt(this.low<<t,this.high<<t|this.low>>>32-t,this.unsigned):zt(0,this.low<<t-32,this.unsigned)},qt.shl=qt.shiftLeft,qt.shiftRight=function(t){return Nt(t)&&(t=t.toInt()),0==(t&=63)?this:t<32?zt(this.low>>>t|this.high<<32-t,this.high>>t,this.unsigned):zt(this.high>>t-32,this.high>=0?0:-1,this.unsigned)},qt.shr=qt.shiftRight,qt.shiftRightUnsigned=function(t){if(Nt(t)&&(t=t.toInt()),0===(t&=63))return this;var e=this.high;return t<32?zt(this.low>>>t|e<<32-t,e>>>t,this.unsigned):zt(32===t?e:e>>>t-32,0,this.unsigned)},qt.shru=qt.shiftRightUnsigned,qt.shr_u=qt.shiftRightUnsigned,qt.toSigned=function(){return this.unsigned?zt(this.low,this.high,!1):this},qt.toUnsigned=function(){return this.unsigned?this:zt(this.low,this.high,!0)},qt.toBytes=function(t){return t?this.toBytesLE():this.toBytesBE()},qt.toBytesLE=function(){var t=this.high,e=this.low;return[255&e,e>>>8&255,e>>>16&255,e>>>24,255&t,t>>>8&255,t>>>16&255,t>>>24]},qt.toBytesBE=function(){var t=this.high,e=this.low;return[t>>>24,t>>>16&255,t>>>8&255,255&t,e>>>24,e>>>16&255,e>>>8&255,255&e]},xt.fromBytes=function(t,e,n){return n?xt.fromBytesLE(t,e):xt.fromBytesBE(t,e)},xt.fromBytesLE=function(t,e){return new xt(t[0]|t[1]<<8|t[2]<<16|t[3]<<24,t[4]|t[5]<<8|t[6]<<16|t[7]<<24,e)},xt.fromBytesBE=function(t,e){return new xt(t[4]<<24|t[5]<<16|t[6]<<8|t[7],t[0]<<24|t[1]<<16|t[2]<<8|t[3],e)};const Kt=vt||Object.assign(Object.create(null),vt,{default:vt});function Gt(t){return Kt.fromString(t,!0,16)}function Ht(t,e){if("string"===e)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(t)&&(t=j(t)),ut().getBool("DEBUG")&&function(t,e){for(let n=0;n<t.length;n++){const s=t[n];if(isNaN(s)||!isFinite(s))throw Error(`A tensor of type ${e} being uploaded contains ${s}.`)}}(t,e),function(t,e){return t instanceof Float32Array&&"float32"===e||t instanceof Int32Array&&"int32"===e||t instanceof Uint8Array&&"bool"===e}(t,e))return t;if(null==e||"float32"===e||"complex64"===e)return new Float32Array(t);if("int32"===e)return new Int32Array(t);if("bool"===e){const e=new Uint8Array(t.length);for(let n=0;n<e.length;++n)0!==Math.round(t[n])&&(e[n]=1);return e}throw new Error(`Unknown data type ${e}`)}function Zt(){return ut().platform.now()}function Jt(t,e="utf-8"){return e=e||"utf-8",ut().platform.decode(t,e)}Gt("c3a5c85c97cb3127"),Gt("b492b66fbe98f273"),Gt("9ae16a3b2f90404f");class Yt{constructor(t,e){this.backendTimer=t,this.logger=e,null==e&&(this.logger=new Qt)}profileKernel(t,e,n){let s;const i=()=>{s=n()};let r;const a=Zt();if(this.backendTimer.timerAvailable())r=this.backendTimer.time(i);else{i();for(const t of s)t.dataSync();r=Promise.resolve({kernelMs:Zt()-a})}if(ut().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let e=0;e<s.length;e++){const n=s[e];n.data().then((e=>{Xt(e,n.dtype,t)}))}return{kernelName:t,outputs:s,inputs:e,timeMs:r.then((t=>t.kernelMs)),extraInfo:r.then((t=>null!=t.getExtraProfileInfo?t.getExtraProfileInfo():""))}}logKernelProfile(t){const{kernelName:e,outputs:n,timeMs:s,inputs:i,extraInfo:r}=t;n.forEach((t=>{Promise.all([t.data(),s,r]).then((n=>{this.logger.logKernelProfile(e,t,n[0],n[1],i,n[2])}))}))}}function Xt(t,e,n){if("float32"!==e)return!1;for(let e=0;e<t.length;e++){const s=t[e];if(isNaN(s)||!isFinite(s))return console.warn(`Found ${s} in the result of '${n}'`),!0}return!1}class Qt{logKernelProfile(t,e,n,s,i,r){const a="number"==typeof s?H(`${s}ms`,9):s.error,o=H(t,25),l=e.rank,u=e.size,h=H(e.shape.toString(),14);let c="";for(const t in i){const n=i[t];if(null!=n){const s=n.shape||e.shape,i=s.length;c+=`${t}: ${i}D ${i>0?s:""} `}}console.log(`%c${o}\t%c${a}\t%c${l}D ${h}\t%c${u}\t%c${c}\t%c${r}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function te(t,e,n,s){const i=et(e),r=function(t,e,n,s){const i=q(e),r=s[s.length-1],a=new Array(r).fill(0),o=e.length,l="complex64"===n?ie(t):t;if(o>1)for(let t=0;t<i/r;t++){const e=t*r;for(let t=0;t<r;t++)a[t]=Math.max(a[t],ee(l[e+t],0,n).length)}return a}(t,e,n,i),a=e.length,o=se(t,e,n,i,r),l=["Tensor"];return s&&(l.push(` dtype: ${n}`),l.push(` rank: ${a}`),l.push(` shape: [${e}]`),l.push(" values:")),l.push(o.map((t=>" "+t)).join("\n")),l.join("\n")}function ee(t,e,n){let s;return s=Array.isArray(t)?`${parseFloat(t[0].toFixed(7))} + ${parseFloat(t[1].toFixed(7))}j`:X(t)?`'${t}'`:"bool"===n?ne(t):parseFloat(t.toFixed(7)).toString(),H(s,e)}function ne(t){return 0===t?"false":"true"}function se(t,e,n,s,i,r=!0){const a="complex64"===n?2:1,o=e[0],l=e.length;if(0===l){if("complex64"===n){return[ee(ie(t)[0],0,n)]}return"bool"===n?[ne(t[0])]:[t[0].toString()]}if(1===l){if(o>20){const e=3*a;let s=Array.from(t.slice(0,e)),r=Array.from(t.slice((o-3)*a,o*a));return"complex64"===n&&(s=ie(s),r=ie(r)),["["+s.map(((t,e)=>ee(t,i[e],n))).join(", ")+", ..., "+r.map(((t,e)=>ee(t,i[o-3+e],n))).join(", ")+"]"]}return["["+("complex64"===n?ie(t):Array.from(t)).map(((t,e)=>ee(t,i[e],n))).join(", ")+"]"]}const u=e.slice(1),h=s.slice(1),c=s[0]*a,p=[];if(o>20){for(let e=0;e<3;e++){const s=e*c,r=s+c;p.push(...se(t.slice(s,r),u,n,h,i,!1))}p.push("...");for(let e=o-3;e<o;e++){const s=e*c,r=s+c;p.push(...se(t.slice(s,r),u,n,h,i,e===o-1))}}else for(let e=0;e<o;e++){const s=e*c,r=s+c;p.push(...se(t.slice(s,r),u,n,h,i,e===o-1))}const d=2===l?",":"";p[0]="["+p[0]+d;for(let t=1;t<p.length-1;t++)p[t]=" "+p[t]+d;let f=",\n";for(let t=2;t<l;t++)f+="\n";return p[p.length-1]=" "+p[p.length-1]+"]"+(r?"":f),p}function ie(t){const e=[];for(let n=0;n<t.length;n+=2)e.push([t[n],t[n+1]]);return e}let re=null;class ae{constructor(t,e,n,s){this.kept=!1,this.isDisposedInternal=!1,this.shape=t.slice(),this.dtype=e||"float32",this.size=q(t),this.strides=et(t),this.dataId=n,this.id=s,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const t=await this.data();return null.buffer(this.shape,this.dtype,t)}bufferSync(){return null.buffer(this.shape,this.dtype,this.dataSync())}async array(){const t=await this.data();return st(this.shape,t,"complex64"===this.dtype)}arraySync(){return st(this.shape,this.dataSync(),"complex64"===this.dtype)}async data(){this.throwIfDisposed();const t=re().read(this.dataId);if("string"===this.dtype){const e=await t;try{return e.map((t=>Jt(t)))}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return t}dataToGPU(t){return this.throwIfDisposed(),re().readToGPU(this.dataId,t)}dataSync(){this.throwIfDisposed();const t=re().readSync(this.dataId);if("string"===this.dtype)try{return t.map((t=>Jt(t)))}catch(t){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return t}async bytes(){this.throwIfDisposed();const t=await re().read(this.dataId);return"string"===this.dtype?t:new Uint8Array(t.buffer)}dispose(){this.isDisposed||(re().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(t=!1){return null.print(this,t)}clone(){return this.throwIfDisposed(),null.clone(this)}toString(t=!1){return te(this.dataSync(),this.shape,this.dtype,t)}cast(t){return this.throwIfDisposed(),null.cast(this,t)}variable(t=!0,e,n){return this.throwIfDisposed(),re().makeVariable(this,t,e,n)}}Object.defineProperty(ae,Symbol.hasInstance,{value:t=>!!t&&null!=t.data&&null!=t.dataSync&&null!=t.throwIfDisposed}),dt("Tensor",(()=>ae));class oe extends ae{constructor(t,e,n,s){super(t.shape,t.dtype,t.dataId,s),this.trainable=e,this.name=n}assign(t){if(t.dtype!==this.dtype)throw new Error(`dtype of the new value (${t.dtype}) and previous value (${this.dtype}) must match`);if(!K(t.shape,this.shape))throw new Error(`shape of the new value (${t.shape}) and previous value (${this.shape}) must match`);re().disposeTensor(this),this.dataId=t.dataId,re().incRef(this,null)}dispose(){re().disposeVariable(this),this.isDisposedInternal=!0}}var le,ue,he,ce,pe;Object.defineProperty(oe,Symbol.hasInstance,{value:t=>t instanceof ae&&null!=t.assign&&t.assign instanceof Function}),function(t){t.R0="R0",t.R1="R1",t.R2="R2",t.R3="R3",t.R4="R4",t.R5="R5",t.R6="R6"}(le||(le={})),function(t){t.float32="float32",t.int32="int32",t.bool="int32",t.complex64="complex64"}(ue||(ue={})),function(t){t.float32="float32",t.int32="int32",t.bool="bool",t.complex64="complex64"}(he||(he={})),function(t){t.float32="float32",t.int32="float32",t.bool="float32",t.complex64="complex64"}(ce||(ce={})),function(t){t.float32="complex64",t.int32="complex64",t.bool="complex64",t.complex64="complex64"}(pe||(pe={}));const de={float32:ce,int32:ue,bool:he,complex64:pe};function fe(t,e){if(t.dtype===e.dtype)return[t,e];const n=function(t,e){if("string"===t||"string"===e){if("string"===t&&"string"===e)return"string";throw new Error(`Can not upcast ${t} with ${e}`)}return de[t][e]}(t.dtype,e.dtype);return[t.cast(n),e.cast(n)]}function ge(t){const e=[];return me(t,e,new Set),e}function me(t,e,n){if(null==t)return;if(t instanceof ae)return void e.push(t);if(s=t,!Array.isArray(s)&&"object"!=typeof s)return;var s;const i=t;for(const t in i){const s=i[t];n.has(s)||(n.add(s),me(s,e,n))}}function ye(t){return null!=t.kernelName}class be{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((t=>t.name))))}}}dispose(){for(const t in this.registeredVariables)this.registeredVariables[t].dispose()}}class we{constructor(t){this.ENV=t,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new be}async ready(){if(null!=this.pendingBackendInit)return this.pendingBackendInit.then((()=>{}));if(null!=this.backendInstance)return;const t=this.getSortedBackends();for(let e=0;e<t.length;e++){const n=t[e];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:t,asyncInit:e}=this.initializeBackendsAndReturnBest();if(e)throw new Error(`The highest priority backend '${t}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(t)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(t){if(!(t in this.registry)){if(!(t in this.registryFactory))return null;{const{asyncInit:e}=this.initializeBackend(t);if(e)return null}}return this.registry[t]}findBackendFactory(t){return t in this.registryFactory?this.registryFactory[t].factory:null}registerBackend(t,e,n=1){return t in this.registryFactory?(ft(`${t} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[t]={factory:e,priority:n},!0)}async setBackend(t){if(null==this.registryFactory[t])throw new Error(`Backend name '${t}' not found in registry`);if(this.backendName=t,null==this.registry[t]){this.backendInstance=null;const{success:e,asyncInit:n}=this.initializeBackend(t);if(!(n?await e:e))return!1}return this.backendInstance=this.registry[t],this.setupRegisteredKernels(),this.profiler=new Yt(this.backendInstance),!0}setupRegisteredKernels(){wt(this.backendName).forEach((t=>{null!=t.setupFunc&&t.setupFunc(this.backendInstance)}))}disposeRegisteredKernels(t){wt(t).forEach((e=>{null!=e.disposeFunc&&e.disposeFunc(this.registry[t])}))}initializeBackend(t){const e=this.registryFactory[t];if(null==e)throw new Error(`Cannot initialize backend ${t}, no registration found.`);try{const n=e.factory();if(!n||n instanceof class{refCount(t){return W("refCount")}incRef(t){return W("incRef")}timerAvailable(){return!0}time(t){return W("time")}read(t){return W("read")}readSync(t){return W("readSync")}readToGPU(t,e){return W("readToGPU")}numDataIds(){return W("numDataIds")}disposeData(t,e){return W("disposeData")}write(t,e,n){return W("write")}move(t,e,n,s,i){return W("move")}memory(){return W("memory")}floatPrecision(){return W("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return W("dispose")}}||"function"!=typeof n.then)return this.registry[t]=n,{success:!0,asyncInit:!1};{const e=++this.pendingBackendInitId,s=n.then((n=>!(e<this.pendingBackendInitId)&&(this.registry[t]=n,this.pendingBackendInit=null,!0))).catch((n=>(e<this.pendingBackendInitId||(this.pendingBackendInit=null,ft(`Initialization of backend ${t} failed`),ft(n.stack||n.message)),!1)));return this.pendingBackendInit=s,{success:s,asyncInit:!0}}}catch(e){return ft(`Initialization of backend ${t} failed`),ft(e.stack||e.message),{success:!1,asyncInit:!1}}}removeBackend(t){if(!(t in this.registryFactory))throw new Error(`${t} backend not found in registry`);this.backendName===t&&null!=this.pendingBackendInit&&this.pendingBackendInitId++,t in this.registry&&(this.disposeRegisteredKernels(t),this.registry[t].dispose(),delete this.registry[t]),delete this.registryFactory[t],this.backendName===t&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(0===Object.keys(this.registryFactory).length)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort(((t,e)=>this.registryFactory[e].priority-this.registryFactory[t].priority))}initializeBackendsAndReturnBest(){const t=this.getSortedBackends();for(let e=0;e<t.length;e++){const n=t[e],{success:s,asyncInit:i}=this.initializeBackend(n);if(i||s)return{name:n,asyncInit:i}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(t,e){const n=this.state.tensorInfo.get(e),s=n.backend,i=this.readSync(e),r=s.refCount(e);s.disposeData(e,!0),n.backend=t,t.move(e,i,n.shape,n.dtype,r),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(t,e){let n,s=null;if(null==e){if("function"!=typeof t)throw new Error("Please provide a function to tidy()");e=t}else{if("string"!=typeof t&&!(t instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!=typeof e)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");s=t}return this.scopedRun((()=>this.startScope(s)),(()=>this.endScope(n)),(()=>(n=e(),n instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n)))}scopedRun(t,e,n){t();try{const t=n();return e(),t}catch(t){throw e(),t}}nextTensorId(){return we.nextTensorId++}nextVariableId(){return we.nextVariableId++}clone(t){const e=ke.runKernel("Identity",{x:t}),n={x:t};return this.addTapeNode(this.state.activeScope.name,n,[e],(t=>({x:()=>{const e={x:t},n={dtype:"float32"};return ke.runKernel("Cast",e,n)}})),[],{}),e}runKernel(t,e,n){null==this.backendName&&this.backend;if(!(null!=yt(t,this.backendName)))throw new Error(`Kernel '${t}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:t,inputs:e,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(t,e,n){const s=this.backend.numDataIds();let i=0;n.forEach((t=>{i+="complex64"===t.dtype?3:1}));const r=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],a=s-e-i-r;if(a>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${a} data ids) after running '${t}'`)}runKernelFunc(t){let e,n=[];const s=this.isTapeOn(),i=this.state.numBytes,r=this.state.numTensors;let a,o;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0),null==this.backendName&&this.backend;const l=ye(t)?t.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(ye(t)){const{kernelName:e,inputs:i,attrs:r}=t;null==this.backendName&&this.backend;const l=yt(e,this.backendName);V(null!=l,(()=>`Cannot find registered kernel '${e}' for backend '${this.backendName}'`)),a=()=>{const t=this.backend.numDataIds();o=l.kernelFunc({inputs:i,attrs:r,backend:this.backend});const a=Array.isArray(o)?o:[o];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(e,t,a);const u=a.map((t=>{if(null!=t.rank)return t;const{dataId:e,shape:n,dtype:s}=t;return this.makeTensorFromDataId(e,n,s)}));if(s){const t=this.getTensorsForGradient(e,i,u);n=this.saveTensorsForBackwardMode(t)}return u}}else{const{forwardFunc:e}=t,i=t=>{s&&(n=t.map((t=>this.keep(this.clone(t)))))};a=()=>{const t=this.backend.numDataIds();o=this.tidy((()=>e(this.backend,i)));const n=Array.isArray(o)?o:[o];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,t,n),n}}const{inputs:u,attrs:h}=t,c=ye(t)?null:t.backwardsFunc;let p;return this.scopedRun((()=>this.state.kernelDepth++),(()=>this.state.kernelDepth--),(()=>{this.ENV.getBool("DEBUG")||this.state.profiling?(p=this.profiler.profileKernel(l,u,(()=>a())),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(p),e=p.outputs):e=a()})),s&&this.addTapeNode(l,u,e,c,n,h),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-i,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-r,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(u).map((t=>null!=u[t]?u[t].shape:null)),outputShapes:e.map((t=>t.shape)),kernelTimeMs:p.timeMs,extraInfo:p.extraInfo}),Array.isArray(o)?e:e[0]}saveTensorsForBackwardMode(t){return t.map((t=>this.keep(this.clone(t))))}getTensorsForGradient(t,e,n){const s=bt(t);if(null!=s){const t=s.inputsToSave||[],i=s.outputsToSave||[];let r;s.saveAllInputs?(V(Array.isArray(e),(()=>"saveAllInputs is true, expected inputs to be an array.")),r=Object.keys(e).map((t=>e[t]))):r=t.map((t=>e[t]));const a=n.filter(((t,e)=>i[e]));return r.concat(a)}return[]}makeTensor(t,e,n,s){if(null==t)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",s=s||this.backend;let i=t;"string"===n&&X(t[0])&&(i=t.map((t=>function(t,e="utf-8"){return e=e||"utf-8",ut().platform.encode(t,e)}(t))));const r=s.write(i,e,n),a=new ae(e,n,r,this.nextTensorId());if(this.trackTensor(a,s),"string"===n){const t=this.state.tensorInfo.get(r),e=function(t){if(null==t)return 0;let e=0;return t.forEach((t=>e+=t.length)),e}(i);this.state.numBytes+=e-t.bytes,t.bytes=e}return a}makeTensorFromDataId(t,e,n,s){const i=new ae(e,n=n||"float32",t,this.nextTensorId());return this.trackTensor(i,s),i}makeVariable(t,e=!0,n,s){n=n||this.nextVariableId().toString(),null!=s&&s!==t.dtype&&(t=t.cast(s));const i=new oe(t,e,n,this.nextTensorId());if(null!=this.state.registeredVariables[i.name])throw new Error(`Variable with name ${i.name} was already registered`);return this.state.registeredVariables[i.name]=i,this.incRef(i,this.backend),i}trackTensor(t,e){this.state.numTensors++,"string"===t.dtype&&this.state.numStringTensors++;let n=0;"complex64"!==t.dtype&&"string"!==t.dtype&&(n=t.size*Y(t.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(t.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(t.dataId,{backend:e||this.backend,dtype:t.dtype,shape:t.shape,bytes:n})),t instanceof oe||this.track(t)}incRef(t,e){this.trackTensor(t,e),this.backend.incRef(t.dataId)}removeDataId(t,e){this.state.tensorInfo.has(t)&&this.state.tensorInfo.get(t).backend===e&&(this.state.tensorInfo.delete(t),this.state.numDataBuffers--)}disposeTensor(t){if(!this.state.tensorInfo.has(t.dataId))return;const e=this.state.tensorInfo.get(t.dataId);if(this.state.numTensors--,"string"===t.dtype&&(this.state.numStringTensors--,this.state.numBytes-=e.bytes),"complex64"!==t.dtype&&"string"!==t.dtype){const e=t.size*Y(t.dtype);this.state.numBytes-=e}e.backend.disposeData(t.dataId)&&this.removeDataId(t.dataId,e.backend)}disposeVariables(){for(const t in this.state.registeredVariables){const e=this.state.registeredVariables[t];this.disposeVariable(e)}}disposeVariable(t){this.disposeTensor(t),null!=this.state.registeredVariables[t.name]&&delete this.state.registeredVariables[t.name]}memory(){const t=this.backend.memory();return t.numTensors=this.state.numTensors,t.numDataBuffers=this.state.numDataBuffers,t.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(t.unreliable=!0,null==t.reasons&&(t.reasons=[]),t.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),t}async profile(t){this.state.profiling=!0;const e=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await t(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map((t=>t.totalBytesSnapshot))),this.state.activeProfile.newBytes=this.state.numBytes-e,this.state.activeProfile.newTensors=this.state.numTensors-n;for(const t of this.state.activeProfile.kernels)t.kernelTimeMs=await t.kernelTimeMs,t.extraInfo=await t.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&0===this.state.kernelDepth}addTapeNode(t,e,n,s,i,r){const a={id:this.state.nextTapeNodeId++,kernelName:t,inputs:e,outputs:n,saved:i},o=bt(t);null!=o&&(s=o.gradFunc),null!=s&&(a.gradient=t=>(t=t.map(((t,e)=>{if(null==t){const t=n[e],s=rt(t.size,t.dtype);return this.makeTensor(s,t.shape,t.dtype)}return t})),s(t.length>1?t:t[0],i,r))),this.state.activeTape.push(a)}keep(t){return t.kept=!0,t}startTape(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(t){const e={track:[],name:"unnamed scope",id:this.state.nextScopeId++};t&&(e.name=t),this.state.scopeStack.push(e),this.state.activeScope=e}endScope(t){const e=ge(t),n=new Set(e.map((t=>t.id)));for(let t=0;t<this.state.activeScope.track.length;t++){const e=this.state.activeScope.track[t];e.kept||n.has(e.id)||e.dispose()}const s=this.state.scopeStack.pop();this.state.activeScope=0===this.state.scopeStack.length?null:this.state.scopeStack[this.state.scopeStack.length-1],e.forEach((t=>{t.kept||t.scopeId!==s.id||this.track(t)}))}gradients(t,e,n,s=!1){if(V(e.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 i=this.scopedRun((()=>this.startTape()),(()=>this.endTape()),(()=>this.tidy("forward",t)));V(i instanceof ae,(()=>"The result y returned by f() must be a tensor."));const r=function(t,e,n){const s={},i={};for(let t=0;t<e.length;t++)s[e[t].id]=!0;for(let n=0;n<t.length;n++){const r=t[n],a=r.inputs;for(const t in a){const n=a[t];let o=!1;for(let t=0;t<e.length;t++)if(s[n.id]){r.outputs.forEach((t=>s[t.id]=!0)),o=!0,i[r.id]=!0;break}if(o)break}}const r={};r[n.id]=!0;const a={};for(let e=t.length-1;e>=0;e--){const n=t[e],s=n.inputs;for(let t=0;t<n.outputs.length;t++)if(r[n.outputs[t].id]){for(const t in s)r[s[t].id]=!0,a[n.id]=!0;break}}const o=[];for(let e=0;e<t.length;e++){const n=t[e];if(i[n.id]&&a[n.id]){const t={};for(const e in n.inputs){const i=n.inputs[e];s[i.id]&&(t[e]=i)}const e=Object.assign({},n);e.inputs=t,e.outputs=n.outputs,o.push(e)}}return o}(this.state.activeTape,e,i);if(!s&&0===r.length&&e.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",(()=>{const t={};t[i.id]=null==n?function(t){const e=it(q(t),"float32");return ke.makeTensor(e,t,"float32")}(i.shape):n,function(t,e,n,s){for(let i=e.length-1;i>=0;i--){const r=e[i],a=[];if(r.outputs.forEach((e=>{const n=t[e.id];null!=n?a.push(n):a.push(null)})),null==r.gradient)throw new Error(`Cannot compute gradient: gradient function not found for ${r.kernelName}.`);const o=r.gradient(a);for(const e in r.inputs){if(!(e in o))throw new Error(`Cannot backprop through input ${e}. Available gradients found: ${Object.keys(o)}.`);const i=n((()=>o[e]()));if("float32"!==i.dtype)throw new Error(`Error in gradient for op ${r.kernelName}. The gradient of input ${e} must have 'float32' dtype, but has '${i.dtype}'`);const a=r.inputs[e];if(!K(i.shape,a.shape))throw new Error(`Error in gradient for op ${r.kernelName}. The gradient of input '${e}' has shape '${i.shape}', which does not match the shape of the input '${a.shape}'`);if(null==t[a.id])t[a.id]=i;else{const e=t[a.id];t[a.id]=s(e,i),e.dispose()}}}}(t,r,(t=>this.tidy(t)),ve);const s=e.map((e=>t[e.id]));return 0===this.state.gradientDepth&&(this.state.activeTape.forEach((t=>{for(const e of t.saved)e.dispose()})),this.state.activeTape=null),{value:i,grads:s}}))}customGrad(t){return V(tt(t),(()=>"The f passed in customGrad(f) must be a function.")),(...e)=>{let n;V(e.every((t=>t instanceof ae)),(()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors"));const s={};e.forEach(((t,e)=>{s[e]=t}));return this.runKernelFunc({forwardFunc:(s,i)=>(n=t(...e,i),V(n.value instanceof ae,(()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor")),V(tt(n.gradFunc),(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function.")),n.value),backwardsFunc:(t,s)=>{const i=n.gradFunc(t,s),r=Array.isArray(i)?i:[i];V(r.length===e.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(...).")),V(r.every((t=>t instanceof ae)),(()=>"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 a={};return r.forEach(((t,e)=>{a[e]=()=>t})),a},inputs:s})}}readSync(t){return this.state.tensorInfo.get(t).backend.readSync(t)}read(t){return this.state.tensorInfo.get(t).backend.read(t)}readToGPU(t,e){return this.state.tensorInfo.get(t).backend.readToGPU(t,e)}async time(t){const e=Zt(),n=await this.backend.time(t);return n.wallMs=Zt()-e,n}track(t){return null!=this.state.activeScope&&(t.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(t)),t}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new be;for(const t in this.registry)this.disposeRegisteredKernels(t),this.registry[t].dispose(),delete this.registry[t];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}}we.nextTensorId=0,we.nextVariableId=0;const ke=function(){const t=pt();if(null==t._tfengine){const e=new ot(t);t._tfengine=new we(e)}var e;return e=t._tfengine.ENV,ct=e,re=()=>t._tfengine,t._tfengine}();function ve(t,e){const n={a:t,b:e};return ke.runKernel("Add",n)}function Se(t,e){let n=t;if(J(t))return"string"===e?[]:[t.length];if(!Array.isArray(t))return[];const s=[];for(;Array.isArray(n)||J(n)&&"string"!==e;)s.push(n.length),n=n[0];return Array.isArray(t)&&ut().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&xe(t,s,[]),s}function xe(t,e,n){if(n=n||[],!Array.isArray(t)&&!J(t))return void V(0===e.length,(()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${e[0]} elements`));V(e.length>0,(()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${t.length} elements`)),V(t.length===e[0],(()=>`Element arr[${n.join("][")}] should have ${e[0]} elements, but has ${t.length} elements`));const s=e.slice(1);for(let e=0;e<t.length;++e)xe(t[e],s,n.concat(e))}function Ne(t,e,n,s){if("string_or_numeric"!==t){if(null==t)throw new Error("Expected dtype cannot be null.");if("numeric"!==t&&t!==e||"numeric"===t&&"string"===e)throw new Error(`Argument '${n}' passed to '${s}' must be ${t} tensor, but got ${e} tensor`)}}function Ie(t,e,n,s="numeric"){if(t instanceof ae)return Ne(s,t.dtype,e,n),t;let i=Q(t);if("string"!==i&&["bool","int32","float32"].indexOf(s)>=0&&(i=s),Ne(s,i,e,n),null==t||!J(t)&&!Array.isArray(t)&&"number"!=typeof t&&"boolean"!=typeof t&&"string"!=typeof t){const s=null==t?"null":t.constructor.name;throw new Error(`Argument '${e}' passed to '${n}' must be a Tensor or TensorLike, but got '${s}'`)}const r=Se(t,i);J(t)||Array.isArray(t)||(t=[t]);const a="string"!==i?Ht(t,i):j(t,[],!0);return ke.makeTensor(a,r,i)}function Ae(t,e,n,s="numeric"){if(!Array.isArray(t))throw new Error(`Argument ${e} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return t.map(((t,i)=>Ie(t,`${e}[${i}]`,n,s)))}function Ce(t){const e=Object.keys(t);if(1!==e.length)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${e.length} keys.`);let n=e[0];const s=t[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n+="__op";const i=(...t)=>{ke.startScope(n);try{const e=s(...t);return at(e)&&console.error("Cannot return a Promise inside of tidy."),ke.endScope(e),e}catch(t){throw ke.endScope(null),t}};return Object.defineProperty(i,"name",{value:n,configurable:!0}),i}const Te=Ce({cast_:function(t,e){const n=Ie(t,"x","cast");if(!function(t){return"bool"===t||"complex64"===t||"float32"===t||"int32"===t||"string"===t}(e))throw new Error(`Failed to cast to unknown dtype ${e}`);if("string"===e&&"string"!==n.dtype||"string"!==e&&"string"===n.dtype)throw new Error("Only strings can be casted to strings");const s={x:n},i={dtype:e};return ke.runKernel("Cast",s,i)}});const ze=Ce({mul_:function(t,e){let n=Ie(t,"a","mul"),s=Ie(e,"b","mul");[n,s]=fe(n,s);const i={a:n,b:s};return ke.runKernel("Multiply",i)}});const Ee=Ce({step_:function(t,e=0){const n={x:Ie(t,"x","step")},s={alpha:e};return ke.runKernel("Step",n,s)}}),$e={kernelName:"Abs",inputsToSave:["x"],gradFunc:(t,e)=>{const[n]=e;return{x:()=>ze(t,Ee(Te(n,"float32"),-1))}}};const Fe=Ce({floorDiv_:function(t,e){let n=Ie(t,"a","floorDiv"),s=Ie(e,"b","floorDiv");[n,s]=fe(n,s);const i={a:n,b:s};return ke.runKernel("FloorDiv",i)}});const De=Ce({div_:function(t,e){let n=Ie(t,"a","div"),s=Ie(e,"b","div");if([n,s]=fe(n,s),"int32"===n.dtype&&"int32"===s.dtype)return Fe(n,s);const i={a:n,b:s};return ke.runKernel("RealDiv",i,{})}});const Le=Ce({neg_:function(t){const e={x:Ie(t,"x","neg")};return ke.runKernel("Neg",e)}});function _e(t,e,n,s){if(null==s&&(s=Q(t)),"complex64"===s)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!J(t)&&!Array.isArray(t)&&"number"!=typeof t&&"boolean"!=typeof t&&"string"!=typeof t)throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(null!=e){!function(t){t.forEach((e=>{V(Number.isInteger(e)&&e>=0,(()=>`Tensor must have a shape comprised of positive integers but got shape [${t}].`))}))}(e);const t=q(e),s=q(n);V(t===s,(()=>`Based on the provided shape, [${e}], the tensor should have ${t} values but has ${s}`));for(let t=0;t<n.length;++t){const s=n[t],i=t!==n.length-1||s!==q(e.slice(t));V(n[t]===e[t]||!i,(()=>`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${e}). `))}}return J(t)||Array.isArray(t)||(t=[t]),e=e||n,t="string"!==s?Ht(t,s):j(t,[],!0),ke.makeTensor(t,e,s)}function Re(t,e){if((J(t)&&"string"!==e||Array.isArray(t))&&"complex64"!==e)throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if("string"===e&&J(t)&&!(t instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return _e(t,[],[],e)}const Me=Ce({sqrt_:function(t){const e={x:Ie(t,"x","sqrt","float32")};return ke.runKernel("Sqrt",e)}});const Oe=Ce({square_:function(t){const e=Ie(t,"x","square");return ke.runKernel("Square",{x:e},{})}});const Be=Ce({sub_:function(t,e){let n=Ie(t,"a","sub"),s=Ie(e,"b","sub");[n,s]=fe(n,s);const i={a:n,b:s};return ke.runKernel("Sub",i)}}),Pe={kernelName:"Acos",inputsToSave:["x"],gradFunc:(t,e)=>{const[n]=e;return{x:()=>{const e=Oe(Te(n,"float32")),s=Me(Be(Re(1),e));return Le(De(t,s))}}}},Ue={kernelName:"Acosh",inputsToSave:["x"],gradFunc:(t,e)=>{const[n]=e;return{x:()=>{const e=Me(Be(Oe(Te(n,"float32")),1));return De(t,e)}}}};function We(t,e){const n=[];for(let s=0;s<e.length;s++){const i=t[t.length-s-1],r=e.length-s-1,a=e[r];(null==i||1===i&&a>1)&&n.unshift(r)}return n}function Ve(t,e){const n=[],s=Math.max(t.length,e.length);for(let i=0;i<s;i++){let s=t[t.length-i-1];null==s&&(s=1);let r=e[e.length-i-1];if(null==r&&(r=1),1===s)n.unshift(r);else if(1===r)n.unshift(s);else{if(s!==r){throw Error(`Operands could not be broadcast together with shapes ${t} and ${e}.`)}n.unshift(s)}}return n}const je=Ce({reshape_:function(t,e){const n={x:Ie(t,"x","reshape","string_or_numeric")},s={shape:e};return ke.runKernel("Reshape",n,s)}});const qe=Ce({sum_:function(t,e=null,n=!1){let s=Ie(t,"x","sum");"bool"===s.dtype&&(s=Te(s,"int32"));const i={x:s},r={axis:e,keepDims:n};return ke.runKernel("Sum",i,r)}}),Ke={kernelName:"Add",inputsToSave:["a","b"],gradFunc:(t,e)=>{const[n,s]=e,i=Ve(n.shape,s.shape);return{a:()=>{let e=t;const s=We(n.shape,i);return s.length>0&&(e=qe(e,s)),je(e,n.shape)},b:()=>{let e=t;const n=We(s.shape,i);return n.length>0&&(e=qe(e,n)),je(e,s.shape)}}}},Ge={kernelName:"AddN",saveAllInputs:!0,gradFunc:(t,e)=>{const n={};return e.forEach(((e,s)=>{n[s]=()=>t.clone()})),n}};const He=Ce({zerosLike_:function(t){const e={x:Ie(t,"x","zerosLike")};return ke.runKernel("ZerosLike",e)}}),Ze={kernelName:"ArgMax",inputsToSave:["x"],gradFunc:(t,e)=>{const[n]=e;return{x:()=>He(n)}}},Je={kernelName:"ArgMin",inputsToSave:["x"],gradFunc:(t,e)=>{const[n]=e;return{x:()=>He(n)}}},Ye={kernelName:"Asin",inputsToSave:["x"],gradFunc:(t,e)=>{const[n]=e;return{x:()=>De(t,Me(Be(Re(1),Oe(Te(n,"float32")))))}}};const Xe=Ce({add_:function(t,e){let n=Ie(t,"a","add"),s=Ie(e,"b","add");[n,s]=fe(n,s);const i={a:n,b:s};return ke.runKernel("Add",i)}}),Qe={kernelName:"Asinh",inputsToSave:["x"],gradFunc:(t,e)=>{const[n]=e;return{x:()=>{const e=Me(Xe(Re(1),Oe(Te(n,"float32"))));return De(t,e)}}}},tn={kernelName:"Atan2",inputsToSave:["a","b"],gradFunc:(t,e)=>{const[n,s]=e,i=Ve(n.shape,s.shape);return{a:()=>{const e=Xe(Oe(n),Oe(s));let r=ze(t,De(s,e));const a=We(n.shape,i);return a.length>0&&(r=qe(r,a)),je(r,n.shape)},b:()=>{const e=Xe(Oe(n),Oe(s));let r=Le(ze(t,De(n,e)));const a=We(s.shape,i);return a.length>0&&(r=qe(r,a)),je(r,s.shape)}}}},en={kernelName:"Atan",inputsToSave:["x"],gradFunc:(t,e)=>{const[n]=e;return{x:()=>De(t,Xe(Oe(Te(n,"float32")),1))}}},nn={kernelName:"Atanh",inputsToSave:["x"],gradFunc:(t,e)=>{const[n]=e;return{x:()=>De(t,Be(Re(1),Oe(Te(n,"float32"))))}}};function sn(t){const[e,n,s]=function(t){return"number"==typeof t?[t,t,t]:2===t.length?[t[0],t[1],1]:t}(t);return 1===e&&1===n&&1===s}function rn(t,e){return sn(t)||sn(e)}function an(t,e,n){if(null!=n){if("string"==typeof e)throw Error(`Error in ${t}: pad must be an integer when using dimRoundingMode ${n} but got pad ${e}.`);if("number"==typeof e)V(G(e),(()=>`Error in ${t}: pad must be an integer when using dimRoundingMode ${n} but got pad ${e}.`));else{if("object"!=typeof e)throw Error(`Error in ${t}: Unknown padding parameter: ${e}`);e.forEach((e=>{e.forEach((e=>{V(G(e),(()=>`Error in ${t}: pad must be an integer when using dimRoundingMode ${n} but got pad ${e}.`))}))}))}}}const on=Ce({avgPool3dGrad_:function(t,e,n,s,i,r){const a=Ie(t,"dy","avgPool3dGrad"),o=Ie(e,"input","avgPool3dGrad");let l=a,u=o,h=!1;4===o.rank&&(h=!0,l=je(a,[1,a.shape[0],a.shape[1],a.shape[2],a.shape[3]]),u=je(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),V(5===l.rank,(()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`)),V(5===u.rank,(()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${u.rank}.`)),an("avgPool3dGrad",i,r);const c={dy:l,input:u},p={filterSize:n,strides:s,pad:i,dimRoundingMode:r},d=ke.runKernel("AvgPool3DGrad",c,p);return h?je(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}}),ln={kernelName:"AvgPool3D",inputsToSave:["x"],gradFunc:(t,e,n)=>{const[s]=e,{filterSize:i,strides:r,pad:a,dimRoundingMode:o}=n;return{x:()=>on(t,s,i,r,a,o)}}};const un=Ce({avgPoolGrad_:function(t,e,n,s,i){const r=Ie(t,"dy","avgPoolGrad"),a=Ie(e,"input","avgPoolGrad");V(a.rank===r.rank,(()=>`Rank of input (${a.rank}) does not match rank of dy (${r.rank})`));let o=a,l=r,u=!1;3===a.rank&&(u=!0,o=je(a,[1,a.shape[0],a.shape[1],a.shape[2]]),l=je(r,[1,r.shape[0],r.shape[1],r.shape[2]])),V(4===l.rank,(()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`)),V(4===o.rank,(()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${o.rank}.`));const h={dy:l,input:o},c={filterSize:n,strides:s,pad:i},p=ke.runKernel("AvgPoolGrad",h,c);return u?je(p,[p.shape[1],p.shape[2],p.shape[3]]):p}}),hn={kernelName:"AvgPool",inputsToSave:["x"],gradFunc:(t,e,n)=>{const[s]=e,{filterSize:i,strides:r,pad:a}=n;return{x:()=>un(t,s,i,r,a)}}};const cn=Ce({matMul_:function(t,e,n=!1,s=!1){let i=Ie(t,"a","matMul"),r=Ie(e,"b","matMul");[i,r]=fe(i,r);const a={a:i,b:r},o={transposeA:n,transposeB:s};return ke.runKernel("BatchMatMul",a,o)}}),pn={kernelName:"BatchMatMul",inputsToSave:["a","b"],gradFunc:(t,e,n)=>{const[s,i]=e,{transposeA:r,transposeB:a}=n;return r||a?!r&&a?{a:()=>cn(t,i,!1,!1),b:()=>cn(t,s,!0,!1)}:r&&!a?{a:()=>cn(i,t,!1,!0),b:()=>cn(s,t,!1,!1)}:{a:()=>cn(i,t,!0,!0),b:()=>cn(t,s,!0,!0)}:{a:()=>cn(t,i,!1,!0),b:()=>cn(s,t,!0,!1)}}};const dn=Ce({spaceToBatchND_:function(t,e,n){const s=Ie(t,"x","spaceToBatchND");V(s.rank>=1+e.length,(()=>`input rank ${s.rank} should be > than [blockShape] ${e.length}`)),V(n.length===e.length,(()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${e.length}`)),V(s.shape.reduce(((t,s,i)=>i>0&&i<=e.length?t&&(s+n[i-1][0]+n[i-1][1])%e[i-1]==0:t),!0),(()=>`input spatial dimensions ${s.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${e.toString()}`));const i={x:s},r={blockShape:e,paddings:n};return ke.runKernel("SpaceToBatchND",i,r)}}),fn={kernelName:"BatchToSpaceND",gradFunc:(t,e,n)=>{const{blockShape:s,crops:i}=n;return{x:()=>dn(t,s,i)}}},gn={kernelName:"BroadcastTo",gradFunc:(t,e,n)=>{const s=n,i=s.inputShape,r=s.shape,a=Array.from(r);for(let t=i.length-1;t>=0;t--)if(i[t]===r[t])a[t]=1;else if(1!==i[t])throw new Error(`broadcastTo(): [${i}] cannot be broadcast to [${r}].`);const o=[];for(let t=0;t<a.length;t++)a[t]>1&&o.push(t);return{x:()=>qe(t,o,!0)}}},mn={kernelName:"Cast",gradFunc:t=>({x:()=>t.clone()})},yn={kernelName:"Ceil",gradFunc:t=>({x:()=>He(t)})};const bn=Ce({greaterEqual_:function(t,e){let n=Ie(t,"a","greaterEqual","string_or_numeric"),s=Ie(e,"b","greaterEqual","string_or_numeric");[n,s]=fe(n,s),Ve(n.shape,s.shape);const i={a:n,b:s};return ke.runKernel("GreaterEqual",i)}});const wn=Ce({lessEqual_:function(t,e){let n=Ie(t,"a","lessEqual","string_or_numeric"),s=Ie(e,"b","lessEqual","string_or_numeric");[n,s]=fe(n,s),Ve(n.shape,s.shape);const i={a:n,b:s};return ke.runKernel("LessEqual",i)}});const kn=Ce({logicalAnd_:function(t,e){const n=Ie(t,"a","logicalAnd","bool"),s=Ie(e,"b","logicalAnd","bool");Ve(n.shape,s.shape);const i={a:n,b:s};return ke.runKernel("LogicalAnd",i)}});const vn=Ce({clone_:function(t){const e={x:Ie(t,"x","clone","string_or_numeric")};return ke.runKernel("Identity",e)}});const Sn=Ce({broadcastTo_:function(t,e){let n=Ie(t,"broadcastTo","x");const s=n.shape;if(e.some((t=>!(t>0)||t%1!=0)))throw new Error(`broadcastTo(): Invalid broadcast shape [${e}].`);if(e.length<n.rank)throw new Error(`broadcastTo(): shape.length=${e.length} < input.rank=${n.rank}.`);if(e.length>n.rank){const t=n.shape.slice();for(;t.length<e.length;)t.unshift(1);n=je(n,t)}const i=n.shape,r=Array.from(e);for(let t=e.length-1;t>=0;t--)if(i[t]===e[t])r[t]=1;else if(1!==n.shape[t])throw new Error(`broadcastTo(): [${s}] cannot be broadcast to [${e}].`);if(0===r.map(((t,e)=>t>1?e:-1)).filter((t=>t>=0)).length)return vn(n);const a={x:n},o={reps:r};return ke.runKernel("Tile",a,o)}});const xn=Ce({where_:function(t,e,n){const s=Ie(e,"a","where"),i=Ie(n,"b","where"),r=Ie(t,"condition","where","bool"),a=Ve(Ve(r.shape,s.shape),i.shape),o={condition:Sn(r,a),t:Sn(s,a),e:Sn(i,a)};return ke.runKernel("Select",o)}}),Nn={kernelName:"ClipByValue",inputsToSave:["x"],gradFunc:(t,e,n)=>{const[s]=e,{clipValueMin:i,clipValueMax:r}=n;return{x:()=>xn(kn(bn(s,i),wn(s,r)),t,He(t))}}},In={kernelName:"ComplexAbs",inputsToSave:["x"],gradFunc:$e.gradFunc};const An=Ce({split_:function(t,e,n=0){const s={x:Ie(t,"x","split")},i={numOrSizeSplits:e,axis:n};return ke.runKernel("SplitV",s,i)}}),Cn={kernelName:"Concat",saveAllInputs:!0,gradFunc:(t,e,n)=>{const s=e.map((t=>t.shape)),{axis:i}=n,r=Z(i,e[0].shape)[0],a=s.map((t=>t[r]));return An(t,a,r).map((t=>()=>t))}};const Tn=Ce({conv2DBackpropFilter_:function(t,e,n,s,i,r="NHWC",a){let o=t;3===t.rank&&(o=je(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let l=e;3===l.rank&&(l=je(e,[1,e.shape[0],e.shape[1],e.shape[2]])),V(4===o.rank,(()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${o.shape}.`)),V(4===l.rank,(()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`)),V(4===n.length,(()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`));const u="NHWC"===r?o.shape[3]:o.shape[1],h="NHWC"===r?l.shape[3]:l.shape[1];V(u===n[2],(()=>`Error in conv2dDerFilter: depth of input ${u}) must match input depth in filter (${n[2]}.`)),V(h===n[3],(()=>`Error in conv2dDerFilter: depth of dy (${h}) must match output depth for filter (${n[3]}).`)),an("conv2dDerFilter",i,a);const c={x:o,dy:l},p={strides:s,pad:i,dataFormat:r,dimRoundingMode:a,filterShape:n};return ke.runKernel("Conv2DBackpropFilter",c,p)}});const zn=Ce({conv2DBackpropInput_:function(t,e,n,s,i,r="NHWC",a){V(t.length===e.rank,(()=>`Length of inShape (${t.length}) and rank of dy (${e.rank}) must match`));let o=t,l=e,u=!1;3===e.rank&&(u=!0,l=je(e,[1,e.shape[0],e.shape[1],e.shape[2]]),o=[1,t[0],t[1],t[2]]),V(4===o.length,(()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${o.length}.`)),V(4===l.rank,(()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`)),V(4===n.rank,(()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`));const h="NHWC"===r?o[3]:o[1],c="NHWC"===r?l.shape[3]:l.shape[1];V(h===n.shape[2],(()=>`Error in conv2dDerInput: depth of input (${h}) must match input depth for filter ${n.shape[2]}.`)),V(c===n.shape[3],(()=>`Error in conv2dDerInput: depth of output (${c}) must match output depth for filter ${n.shape[3]}.`)),an("conv2dDerInput",i,a);const p={dy:l,filter:n},d={strides:s,pad:i,dataFormat:r,dimRoundingMode:a,inputShape:o},f=ke.runKernel("Conv2DBackpropInput",p,d);return u?je(f,[f.shape[1],f.shape[2],f.shape[3]]):f}}),En={kernelName:"Conv2D",inputsToSave:["x","filter"],gradFunc:(t,e,n)=>{const[s,i]=e,{dilations:r,strides:a,pad:o,dataFormat:l}=n;return V(sn(r),(()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${r}'`)),{x:()=>zn(s.shape,t,i,a,o,l),filter:()=>Tn(s,t,i.shape,a,o,l)}}};const $n=Ce({conv2d_:function(t,e,n,s,i="NHWC",r=[1,1],a){const o=Ie(t,"x","conv2d","float32"),l=Ie(e,"filter","conv2d","float32");let u=o,h=!1;3===o.rank&&(h=!0,u=je(o,[1,o.shape[0],o.shape[1],o.shape[2]])),V(4===u.rank,(()=>`Error in conv2d: input must be rank 4, but got rank ${u.rank}.`)),V(4===l.rank,(()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`)),an("conv2d",s,a);const c="NHWC"===i?u.shape[3]:u.shape[1];V(c===l.shape[2],(()=>`Error in conv2d: depth of input (${c}) must match input depth for filter ${l.shape[2]}.`)),V(rn(n,r),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${r}'`));const p={x:u,filter:l},d={strides:n,pad:s,dataFormat:i,dilations:r,dimRoundingMode:a},f=ke.runKernel("Conv2D",p,d);return h?je(f,[f.shape[1],f.shape[2],f.shape[3]]):f}}),Fn={kernelName:"Conv2DBackpropInput",inputsToSave:["dy","filter"],gradFunc:(t,e,n)=>{const[s,i]=e,{strides:r,pad:a,dataFormat:o,dimRoundingMode:l}=n;return{dy:()=>$n(t,i,r,a,o,1,l),filter:()=>Tn(t,s,i.shape,r,a,o,l)}}};const Dn=Ce({conv3DBackpropFilter_:function(t,e,n,s,i){let r=t;4===t.rank&&(r=je(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]));let a=e;4===a.rank&&(a=je(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]])),V(5===r.rank,(()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${r.shape}.`)),V(5===a.rank,(()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${a.shape}.`)),V(5===n.length,(()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`)),V(r.shape[4]===n[3],(()=>`Error in conv3dDerFilter: depth of input ${r.shape[4]}) must match input depth in filter (${n[3]}.`)),V(a.shape[4]===n[4],(()=>`Error in conv3dDerFilter: depth of dy (${a.shape[4]}) must match output depth for filter (${n[4]}).`));const o={x:r,dy:a},l={strides:s,pad:i,filterShape:n};return ke.runKernel("Conv3DBackpropFilterV2",o,l)}});const Ln=Ce({conv3DBackpropInput_:function(t,e,n,s,i){V(t.length===e.rank,(()=>`Length of inShape (${t.length}) and rank of dy (${e.rank}) must match`));let r=t,a=e,o=!1;4===e.rank&&(o=!0,a=je(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]),r=[1,t[0],t[1],t[2],t[3]]);const l=r[4],u=a.shape[4];V(5===r.length,(()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${r.length}.`)),V(5===a.rank,(()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${a.rank}`)),V(5===n.rank,(()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`)),V(l===n.shape[3],(()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[3]}.`)),V(u===n.shape[4],(()=>`Error in conv3dDerInput: depth of output (${u}) must match output depth for filter ${n.shape[4]}.`));const h={dy:a,filter:n},c={pad:i,strides:s,inputShape:r},p=ke.runKernel("Conv3DBackpropInputV2",h,c);return o?je(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}}),_n={kernelName:"Conv3D",inputsToSave:["x","filter"],gradFunc:(t,e,n)=>{const{dilations:s,strides:i,pad:r}=n;V(sn(s),(()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`));const[a,o]=e;return{x:()=>Ln(a.shape,t,o,i,r),filter:()=>Dn(a,t,o.shape,i,r)}}};const Rn=Ce({sin_:function(t){const e={x:Ie(t,"x","sin","float32")};return ke.runKernel("Sin",e)}}),Mn={kernelName:"Cos",inputsToSave:["x"],gradFunc:(t,e)=>{const[n]=e;return{x:()=>ze(Le(Rn(Te(n,"float32"))),t)}}};const On=Ce({sinh_:function(t){const e={x:Ie(t,"x","sinh")};return ke.runKernel("Sinh",e)}}),Bn={kernelName:"Cosh",inputsToSave:["x"],gradFunc:(t,e)=>{const[n]=e;return{x:()=>ze(On(Te(n,"float32")),t)}}};function Pn(t,e){return function(t,e,n){const s=t.length+e.length,i=[];let r=0,a=0;for(let o=0;o<s;o++)-1===n.indexOf(o)?i.push(t[r++]):i.push(e[a++]);return i}(t,e.map((t=>1)),e)}function Un(t){return t.map(((t,e)=>[e,t])).sort(((t,e)=>t[1]-e[1])).map((t=>t[0]))}const Wn=Ce({cumsum_:function(t,e=0,n=!1,s=!1){const i={x:Ie(t,"x","cumsum")},r={axis:e,exclusive:n,reverse:s};return ke.runKernel("Cumsum",i,r)}});const Vn=Ce({transpose_:function(t,e){const n=Ie(t,"x","transpose");if(null==e&&(e=n.shape.map(((t,e)=>e)).reverse()),V(n.rank===e.length,(()=>`Error in transpose: rank of input ${n.rank} must match length of perm ${e}.`)),e.forEach((t=>{V(t>=0&&t<n.rank,(()=>"All entries in 'perm' must be between 0 and "+(n.rank-1)+` but got ${e}`))})),n.rank<=1)return n.clone();const s={x:n},i={perm:e};return ke.runKernel("Transpose",s,i)}}),jn={kernelName:"Cumsum",inputsToSave:["x"],gradFunc:(t,e,n)=>{const[s]=e,{axis:i,exclusive:r,reverse:a}=n;return{x:()=>{const e=function(t,e){if(function(t,e){for(let n=0;n<t.length;++n)if(t[t.length-n-1]!==e-1-n)return!1;return!0}(t,e))return null;const n=[];for(let s=0;s<e;++s)-1===t.indexOf(s)&&n.push(s);return t.forEach((t=>n.push(t))),n}([i],s.rank);let n=Wn(t,i,r,!a);return null!=e&&(n=Vn(n,e)),n}}}};const qn=Ce({depthwiseConv2dNativeBackpropFilter_:function(t,e,n,s,i,r=[1,1],a){let o=t;3===t.rank&&(o=je(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let l=e;3===l.rank&&(l=je(e,[1,e.shape[0],e.shape[1],e.shape[2]]));const u={x:o,dy:l},h={strides:s,pad:i,dimRoundingMode:a,dilations:r,filterShape:n};return ke.runKernel("DepthwiseConv2dNativeBackpropFilter",u,h)}});const Kn=Ce({depthwiseConv2dNativeBackpropInput_:function(t,e,n,s,i,r=[1,1],a){let o=e,l=!1;3===e.rank&&(l=!0,o=je(e,[1,e.shape[0],e.shape[1],e.shape[2]]));const u={dy:o,filter:n},h={strides:s,pad:i,dimRoundingMode:a,dilations:r,inputShape:t},c=ke.runKernel("DepthwiseConv2dNativeBackpropInput",u,h);return l?je(c,[c.shape[1],c.shape[2],c.shape[3]]):c}}),Gn={kernelName:"DepthwiseConv2dNative",inputsToSave:["x","filter"],gradFunc:(t,e,n)=>{const{dilations:s,strides:i,pad:r,dimRoundingMode:a}=n,o=null==s?[1,1]:s;V(sn(o),(()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`));const[l,u]=e;return V(4===l.rank,(()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`)),V(4===u.rank,(()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${u.rank}.`)),V(l.shape[3]===u.shape[2],(()=>`Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${u.shape[2]}.`)),V(rn(i,o),(()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${o}'.`)),an("depthwiseConv2d",r,a),{x:()=>Kn(l.shape,t,u,i,r,o,a),filter:()=>qn(l,t,u.shape,i,r,o,a)}}},Hn={kernelName:"Dilation2D",inputsToSave:["x","filter"],gradFunc:(t,e,n)=>{const[s,i]=e,r={x:s,filter:i,dy:t},a={x:s,filter:i,dy:t};return{x:()=>ke.runKernel("Dilation2DBackpropInput",r,n),filter:()=>ke.runKernel("Dilation2DBackpropFilter",a,n)}}},Zn={kernelName:"Elu",outputsToSave:[!0],gradFunc:(t,e)=>{const[n]=e,s={dy:t,y:n};return{x:()=>ke.runKernel("EluGrad",s)}}};const Jn=Ce({exp_:function(t){const e={x:Ie(t,"x","exp")};return ke.runKernel("Exp",e)}}),Yn={kernelName:"Erf",inputsToSave:["x"],gradFunc:(t,e)=>{const[n]=e,s=ze(Jn(Le(Oe(n))),2/Math.sqrt(Math.PI));return{x:()=>ze(t,s)}}},Xn={kernelName:"Exp",outputsToSave:[!0],gradFunc:(t,e)=>{const[n]=e;return{x:()=>ze(t,n)}}},Qn={kernelName:"ExpandDims",inputsToSave:["input"],gradFunc:(t,e)=>{const[n]=e;return{input:()=>je(t,n.shape)}}},ts={kernelName:"Expm1",inputsToSave:["x"],gradFunc:(t,e)=>{const[n]=e;return{x:()=>ze(t,Jn(n))}}},es={kernelName:"Floor",gradFunc:t=>({x:()=>He(t)})},ns={kernelName:"FloorDiv",inputsToSave:["a","b"],gradFunc:(t,e)=>{const[n,s]=e,i=Ve(n.shape,s.shape);return{a:()=>{const e=De(t,Te(s,"float32")),r=We(n.shape,i);return r.length>0?je(qe(e,r),n.shape):e},b:()=>{let e=ze(t,Te(n,"float32"));const r=We(s.shape,i);r.length>0&&(e=je(qe(e,r),s.shape));const a=Oe(s);return Le(De(e,Te(a,"float32")))}}}};const ss=Ce({rsqrt_:function(t){const e={x:Ie(t,"x","rsqrt","float32")};return ke.runKernel("Rsqrt",e)}});const is=Ce({tile_:function(t,e){const n=Ie(t,"x","tile","string_or_numeric");V(n.rank===e.length,(()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${e}.`));const s={x:n},i={reps:e};return ke.runKernel("Tile",s,i)}}),rs={kernelName:"FusedBatchNorm",inputsToSave:["x","mean","variance","scale"],gradFunc:(t,e,n)=>{const{varianceEpsilon:s}=n,[i,r,a,o]=e,l=null==o?Re(1):o,u=We(r.shape,i.shape),h=[];if(1===r.rank){for(let t=0;t<i.shape.length-1;++t)h.push(i.shape[t]);h.push(1)}const c=Be(i,r),p=ze(t,l),d=ss(Xe(a,Re(s))),f=ze(ze(ze(d,d),d),Re(-.5));return{x:()=>1===r.rank?je(ze(ze(t,is(je(d,[1,1,1,r.shape[0]]),h)),l),i.shape):je(ze(ze(t,d),l),i.shape),mean:()=>{let t=ze(ze(d,Re(-1)),p);return 1===r.rank&&(t=qe(t,u)),je(t,r.shape)},variance:()=>{let t=ze(ze(f,c),p);return 1===r.rank&&(t=qe(t,u)),je(t,r.shape)},scale:()=>{const e=ze(c,d);let n=ze(t,e);return 1===r.rank&&(n=qe(n,u)),je(n,r.shape)},offset:()=>{let e=t;return 1===r.rank&&(e=qe(e,u)),je(e,r.shape)}}}};const as=Ce({unsortedSegmentSum_:function(t,e,n){const s=Ie(t,"x","unsortedSegmentSum"),i=Ie(e,"segmentIds","unsortedSegmentSum","int32");V(G(n),(()=>"numSegments must be of dtype int"));const r={x:s,segmentIds:i},a={numSegments:n};return ke.runKernel("UnsortedSegmentSum",r,a)}}),os={kernelName:"GatherV2",inputsToSave:["x","indices"],gradFunc:(t,e,n)=>{const[s,i]=e,{axis:r}=n,a=Z(r,s.shape)[0];return{x:()=>{const e=s.shape,n=i.size,o=e.slice(0,a),l=o.length,u=e.slice(r,e.length).slice(1),h=u.length,c=ls(0,l),p=ls(l+1,l+1+h),d=us([o,[n],u]),f=je(t,d),g=je(i,[n]),m=us([[l],c,p]),y=Vn(f,m);let b=as(y,g,s.shape[a]);const w=Un(m);return b=Vn(b,w),b},indices:()=>i}}};function ls(t,e){const n=[];for(let s=t;s<e;++s)n.push(s);return n}function us(t){const e=[];for(let n=0;n<t.length;++n)for(let s=0;s<t[n].length;++s)e.push(t[n][s]);return e}const hs={kernelName:"GreaterEqual",inputsToSave:["a","b"],gradFunc:(t,e)=>{const[n,s]=e;return{a:()=>He(n),b:()=>He(s)}}},cs={kernelName:"Identity",gradFunc:t=>({x:()=>Te(t,"float32")})},ps={kernelName:"IsFinite",gradFunc:t=>({x:()=>He(t)})},ds={kernelName:"IsInf",gradFunc:t=>({x:()=>He(t)})},fs={kernelName:"IsNan",gradFunc:t=>({x:()=>He(t)})};const gs=Ce({greater_:function(t,e){let n=Ie(t,"a","greater","string_or_numeric"),s=Ie(e,"b","greater","string_or_numeric");[n,s]=fe(n,s),Ve(n.shape,s.shape);const i={a:n,b:s};return ke.runKernel("Greater",i)}}),ms={kernelName:"LeakyRelu",inputsToSave:["x"],gradFunc:(t,e,n)=>{const[s]=e,{alpha:i}=n,r=gs(s,0);return{x:()=>xn(r,t,ze(t,i))}}},ys={kernelName:"Log1p",inputsToSave:["x"],gradFunc:(t,e)=>{const[n]=e;return{x:()=>De(t,Xe(n,1))}}},bs={kernelName:"Log",inputsToSave:["x"],gradFunc:(t,e)=>{const[n]=e;return{x:()=>De(t,Te(n,"float32"))}}},ws={kernelName:"LogSoftmax",inputsToSave:[],outputsToSave:[!0],gradFunc:(t,e,n)=>{const[s]=e,{axis:i}=n;return{logits:()=>{const e=Jn(s);return Be(t,ze(qe(t,i,!0),e))}}}};const ks=Ce({localResponseNormalizationBackprop_:function(t,e,n,s=5,i=1,r=1,a=.5){const o={x:t,y:e,dy:n},l={depthRadius:s,bias:i,alpha:r,beta:a};return ke.runKernel("LRNGrad",o,l)}}),vs={kernelName:"LRN",inputsToSave:["x"],outputsToSave:[!0],gradFunc:(t,e,n)=>{const[s,i]=e,{depthRadius:r,bias:a,alpha:o,beta:l}=n;return{x:()=>ks(s,i,t,r,a,o,l)}}};const Ss=Ce({equal_:function(t,e){let n=Ie(t,"a","equal","string_or_numeric"),s=Ie(e,"b","equal","string_or_numeric");[n,s]=fe(n,s),Ve(n.shape,s.shape);const i={a:n,b:s};return ke.runKernel("Equal",i)}});function xs(t,e,n,s){return e.rank<n.rank&&(e=je(e,Pn(e.shape,s))),t.rank<n.rank&&(t=je(t,Pn(t.shape,s))),{x:()=>ze(t,Te(Ss(n,e),t.dtype))}}const Ns={kernelName:"Max",inputsToSave:["x"],outputsToSave:[!0],gradFunc:(t,e,n)=>{const s=n,{reductionIndices:i}=s,r=e[0],a=xs(t,e[1],r,Z(i,r.shape));return{x:()=>a.x()}}};const Is=Ce({less_:function(t,e){let n=Ie(t,"a","less","string_or_numeric"),s=Ie(e,"b","less","string_or_numeric");[n,s]=fe(n,s),Ve(n.shape,s.shape);const i={a:n,b:s};return ke.runKernel("Less",i)}}),As={kernelName:"Maximum",inputsToSave:["a","b"],gradFunc:(t,e)=>{const[n,s]=e;return{a:()=>ze(t,Te(bn(n,s),"float32")),b:()=>ze(t,Te(Is(n,s),"float32"))}}};const Cs=Ce({maxPool3dGrad_:function(t,e,n,s,i,r,a){const o=Ie(t,"dy","maxPool3dGrad"),l=Ie(e,"input","maxPool3dGrad"),u=Ie(n,"output","maxPool3dGrad");let h=o,c=l,p=u,d=!1;4===l.rank&&(d=!0,h=je(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),c=je(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),p=je(u,[1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]])),V(5===h.rank,(()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${h.rank}.`)),V(5===c.rank,(()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${c.rank}.`)),V(5===p.rank,(()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${p.rank}.`)),an("maxPool3dGrad",r,a);const f={dy:h,input:c,output:p},g={filterSize:s,strides:i,pad:r,dimRoundingMode:a},m=ke.runKernel("MaxPool3DGrad",f,g);return d?je(m,[m.shape[1],m.shape[2],m.shape[3],m.shape[4]]):m}}),Ts={kernelName:"MaxPool3D",inputsToSave:["x"],outputsToSave:[!0],gradFunc:(t,e,n)=>{const[s,i]=e,{filterSize:r,strides:a,pad:o,dimRoundingMode:l}=n;return{x:()=>Cs(t,s,i,r,a,o,l)}}};const zs=Ce({maxPoolGrad_:function(t,e,n,s,i,r,a){const o=Ie(t,"dy","maxPoolGrad"),l=Ie(e,"input","maxPoolGrad"),u=Ie(n,"output","maxPoolGrad");V(l.rank===o.rank,(()=>`Rank of input (${l.rank}) does not match rank of dy (${o.rank})`)),V(4===o.rank,(()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${o.rank}.`)),V(4===l.rank,(()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`)),an("maxPoolGrad",r,a);const h={dy:o,input:l,output:u},c={filterSize:s,strides:i,pad:r,dimRoundingMode:a};return ke.runKernel("MaxPoolGrad",h,c)}}),Es={kernelName:"MaxPool",inputsToSave:["x"],outputsToSave:[!0],gradFunc:(t,e,n)=>{const[s,i]=e,{filterSize:r,strides:a,pad:o}=n;return{x:()=>zs(t,s,i,r,a,o)}}};const $s=Ce({complex_:function(t,e){const n=Ie(t,"real","complex"),s=Ie(e,"imag","complex");!function(t,e,n=""){V(K(t,e),(()=>n+` Shapes ${t} and ${e} must match`))}(n.shape,s.shape,`real and imag shapes, ${n.shape} and ${s.shape}, must match in call to tf.complex().`);const i={real:n,imag:s};return ke.runKernel("Complex",i)}});function Fs(t,e="float32"){if("complex64"===e){const e=Fs(t,"float32"),n=Fs(t,"float32");return $s(e,n)}const n=rt(q(t),e);return ke.makeTensor(n,t,e)}function Ds(t,e="float32"){if("complex64"===e){const e=Ds(t,"float32"),n=Fs(t,"float32");return $s(e,n)}const n=it(q(t),e);return ke.makeTensor(n,t,e)}const Ls={kernelName:"Mean",inputsToSave:["x"],gradFunc:(t,e,n)=>{const[s]=e,{axis:i}=n,r=Z(i,s.shape),a=q(function(t,e){const n=[],s=t.length;for(let i=0;i<s;i++)-1===e.indexOf(i)&&n.push(t[i]);return[n,e.map((e=>t[e]))]}(s.shape,r)[1]);return{x:()=>{const e=s.shape.slice();r.forEach((t=>{e[t]=1}));const n=je(t,e);return De(ze(n,Ds(s.shape,"float32")),a)}}}},_s={kernelName:"Min",inputsToSave:["x"],outputsToSave:[!0],gradFunc:(t,e,n)=>{const s=n,{axis:i}=s,[r,a]=e,o=xs(t,a,r,Z(i,r.shape));return{x:()=>o.x()}}},Rs={kernelName:"Minimum",inputsToSave:["a","b"],gradFunc:(t,e)=>{const[n,s]=e;return{a:()=>ze(t,Te(wn(n,s),"float32")),b:()=>ze(t,Te(gs(n,s),"float32"))}}};const Ms=Ce({slice_:function(t,e,n){const s=Ie(t,"x","slice","string_or_numeric");if(0===s.rank)throw new Error("Slicing scalar is not possible");const i={x:s},r={begin:e,size:n};return ke.runKernel("Slice",i,r)}}),Os={kernelName:"MirrorPad",inputsToSave:["x"],gradFunc:(t,e,n)=>{const s=e[0],{paddings:i}=n,r=i.map((t=>t[0]));return{x:()=>Ms(t,r,s.shape)}}};const Bs=Ce({floor_:function(t){const e={x:Ie(t,"x","floor","float32")};return ke.runKernel("Floor",e)}}),Ps={kernelName:"Mod",inputsToSave:["a","b"],gradFunc:(t,e)=>{const[n,s]=e,i=Ve(n.shape,s.shape);return{a:()=>{const e=We(n.shape,i);return e.length>0?je(qe(t,e),n.shape):t},b:()=>{const e=ze(t,Le(Bs(De(n,s)))),r=We(s.shape,i);return r.length>0?je(qe(e,r),s.shape):e}}}},Us={kernelName:"Multiply",inputsToSave:["a","b"],gradFunc:(t,e)=>{const[n,s]=e,i=Ve(n.shape,s.shape);return{a:()=>{const e=ze(t,Te(s,"float32")),r=We(n.shape,i);return r.length>0?je(qe(e,r),n.shape):e},b:()=>{const e=ze(t,Te(n,"float32")),r=We(s.shape,i);return r.length>0?je(qe(e,r),s.shape):e}}}},Ws={kernelName:"Neg",gradFunc:t=>({x:()=>Le(t)})},Vs={kernelName:"OneHot",inputsToSave:["indices"],gradFunc:(t,e)=>{const n=e[0];return{indices:()=>Fs(n.shape,"float32")}}},js={kernelName:"OnesLike",gradFunc:t=>({x:()=>He(t)})};const qs=Ce({unstack_:function(t,e=0){const n=Ie(t,"x","unstack","string_or_numeric");V(e>=-n.shape.length&&e<n.shape.length,(()=>`Axis = ${e} is not in [-${n.shape.length}, ${n.shape.length})`));const s={value:n},i={axis:e};return ke.runKernel("Unpack",s,i)}}),Ks={kernelName:"Pack",saveAllInputs:!0,gradFunc:(t,e,n)=>{const{axis:s}=n;return qs(t,s).map((t=>()=>t))}},Gs={kernelName:"PadV2",inputsToSave:["x"],gradFunc:(t,e,n)=>{const s=e[0],{paddings:i}=n,r=i.map((t=>t[0]));return{x:()=>Ms(t,r,s.shape)}}};const Hs=Ce({log_:function(t){const e={x:Ie(t,"x","log","float32")};return ke.runKernel("Log",e)}});const Zs=Ce({pow_:function(t,e){let n=Ie(t,"base","pow"),s=Ie(e,"exp","pow");[n,s]=fe(n,s);const i={a:n,b:s};return ke.runKernel("Pow",i)}}),Js={kernelName:"Pow",inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(t,e)=>{const[n,s,i]=e,r=n,a=s,o=Ve(r.shape,a.shape);return{a:()=>{const e=Te(a,"float32");let n=ze(t,ze(e,Zs(r,Be(e,Re(1)))));const s=We(r.shape,o);return s.length>0&&(n=qe(n,s)),je(n,r.shape)},b:()=>{const e=gs(r,0),n=xn(e,Hs(r),He(r));let s=ze(t,ze(i,n));const l=We(a.shape,o);return l.length>0&&(s=qe(s,l)),je(s,a.shape)}}}},Ys={kernelName:"Prelu",inputsToSave:["x","alpha"],gradFunc:(t,e)=>{const[n,s]=e,i=gs(n,0);return{x:()=>xn(i,t,ze(t,s)),alpha:()=>{let e=xn(i,He(t),ze(t,n));const r=We(s.shape,t.shape);return r.length>0&&(e=qe(e,r)),je(e,s.shape)}}}},Xs={kernelName:"RealDiv",inputsToSave:["a","b"],gradFunc:(t,e)=>{const[n,s]=e,i=Ve(n.shape,s.shape);return{a:()=>{const e=De(t,Te(s,"float32")),r=We(n.shape,i);return r.length>0?je(qe(e,r),n.shape):e},b:()=>{let e=ze(t,Te(n,"float32"));const r=We(s.shape,i);r.length>0&&(e=je(qe(e,r),s.shape));const a=Oe(s);return Le(De(e,Te(a,"float32")))}}}},Qs={kernelName:"Reciprocal",inputsToSave:["x"],gradFunc:(t,e)=>{const[n]=e;return{x:()=>De(t,Le(Oe(n)))}}},ti={kernelName:"Relu6",inputsToSave:["x"],gradFunc:(t,e)=>{const[n]=e,s=ze(wn(n,6),Ee(n));return{x:()=>ze(t,Te(s,"float32"))}}},ei={kernelName:"Relu",inputsToSave:["x"],gradFunc:(t,e)=>{const[n]=e;return{x:()=>ze(t,Te(Ee(n),"float32"))}}},ni={kernelName:"Reshape",inputsToSave:["x"],gradFunc:(t,e)=>{const[n]=e;return{x:()=>je(t,n.shape)}}},si={kernelName:"ResizeBilinear",inputsToSave:["images"],gradFunc:(t,e,n)=>{const[s]=e,i={dy:t,images:s};return{images:()=>ke.runKernel("ResizeBilinearGrad",i,n)}}},ii={kernelName:"ResizeNearestNeighbor",inputsToSave:["images"],gradFunc:(t,e,n)=>{const[s]=e,i={dy:t,images:s};return{images:()=>ke.runKernel("ResizeNearestNeighborGrad",i,n)}}};const ri=Ce({reverse_:function(t,e){const n={x:Ie(t,"x","reverse")},s={dims:e};return ke.runKernel("Reverse",n,s)}}),ai={kernelName:"Reverse",gradFunc:(t,e,n)=>{const{dims:s}=n,i=Z(s,t.shape);return{x:()=>ri(t,i)}}},oi={kernelName:"Round",gradFunc:t=>({x:()=>He(t)})},li={kernelName:"Rsqrt",inputsToSave:["x"],gradFunc:(t,e)=>{const[n]=e;return{x:()=>Le(De(t,ze(Zs(n,1.5),2)))}}};const ui=Ce({logicalNot_:function(t){const e={x:Ie(t,"x","logicalNot","bool")};return ke.runKernel("LogicalNot",e)}}),hi={kernelName:"Select",inputsToSave:["condition"],gradFunc:(t,e)=>{const[n]=e;return{condition:()=>Te(He(n),"float32"),t:()=>ze(t,Te(n,t.dtype)),e:()=>ze(t,Te(ui(n),t.dtype))}}},ci={kernelName:"Selu",inputsToSave:["x"],gradFunc:(t,e)=>{const[n]=e;return{x:()=>{const e=gs(n,Re(0)),s=Re(1.7580993408473768),i=Re(1.0507009873554805),r=ze(t,i),a=ze(ze(t,s),Jn(Te(n,"float32")));return xn(e,r,a)}}}},pi={kernelName:"Sigmoid",outputsToSave:[!0],gradFunc:(t,e)=>{const[n]=e;return{x:()=>ze(t,ze(n,Be(Re(1),n)))}}},di={kernelName:"Sign",gradFunc:t=>({x:()=>He(t)})};const fi=Ce({cos_:function(t){const e={x:Ie(t,"x","cos","float32")};return ke.runKernel("Cos",e)}}),gi={kernelName:"Sin",inputsToSave:["x"],gradFunc:(t,e)=>{const[n]=e;return{x:()=>ze(fi(Te(n,"float32")),t)}}};const mi=Ce({cosh_:function(t){const e={x:Ie(t,"x","cosh","float32")};return ke.runKernel("Cosh",e)}}),yi={kernelName:"Sinh",inputsToSave:["x"],gradFunc:(t,e)=>{const[n]=e;return{x:()=>ze(mi(Te(n,"float32")),t)}}};const bi=Ce({pad_:function(t,e,n=0){const s=Ie(t,"x","pad");if(0===s.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const i={paddings:e,constantValue:n},r={x:s};return ke.runKernel("PadV2",r,i)}});const wi={kernelName:"Slice",inputsToSave:["x"],gradFunc:(t,e,n)=>{const[s]=e,{begin:i,size:r}=n,a=s.shape,[o,l]=function(t,e,n){let s;const i=t.shape.length;let r;return s="number"==typeof e?[e,...new Array(i-1).fill(0)]:e.length<i?e.concat(new Array(i-e.length).fill(0)):e.slice(),s.forEach((t=>{V(-1!==t,(()=>"slice() does not support negative begin indexing."))})),r=null==n?new Array(i).fill(-1):"number"==typeof n?[n,...new Array(i-1).fill(-1)]:n.length<i?n.concat(new Array(i-n.length).fill(-1)):n,r=r.map(((e,n)=>e>=0?e:(V(-1===e,(()=>`Negative size values should be exactly -1 but got ${e} for the slice() size at index ${n}.`)),t.shape[n]-s[n]))),[s,r]}(s,i,r),u=[];for(let e=0;e<t.rank;e++)u.push([o[e],a[e]-o[e]-l[e]]);return{x:()=>bi(t,u)}}},ki={kernelName:"Softmax",outputsToSave:[!0],gradFunc:(t,e,n)=>{const[s]=e,{dim:i}=n,r=ze(t,s);return{logits:()=>Be(r,ze(qe(r,[i],true),s))}}};const vi=Ce({sigmoid_:function(t){const e={x:Ie(t,"x","sigmoid","float32")};return ke.runKernel("Sigmoid",e)}}),Si={kernelName:"Softplus",inputsToSave:["x"],gradFunc:(t,e)=>{const[n]=e;return{x:()=>ze(t,vi(n))}}};const xi=Ce({batchToSpaceND_:function(t,e,n){const s=Ie(t,"x","batchToSpaceND"),i=e.reduce(((t,e)=>t*e));V(s.rank>=1+e.length,(()=>`input rank is ${s.rank} but should be > than blockShape.length ${e.length}`)),V(n.length===e.length,(()=>`crops.length is ${n.length} but should be equal to blockShape.length ${e.length}`)),V(s.shape[0]%i==0,(()=>`input tensor batch is ${s.shape[0]} but is not divisible by the product of the elements of blockShape ${e.join(" * ")} === ${i}`));const r={x:s},a={blockShape:e,crops:n};return ke.runKernel("BatchToSpaceND",r,a)}}),Ni={kernelName:"SpaceToBatchND",gradFunc:(t,e,n)=>{const{blockShape:s,paddings:i}=n;return{x:()=>xi(t,s,i)}}};const Ii=Ce({concat_:function(t,e=0){V(t.length>=1,(()=>"Pass at least one tensor to concat"));const n=Ae(t,"tensors","concat","string_or_numeric");if("complex64"===n[0].dtype&&n.forEach((t=>{if("complex64"!==t.dtype)throw new Error(`Cannot concatenate complex64 tensors with a tensor\n with dtype ${t.dtype}. `)})),1===n.length)return vn(n[0]);const s=n,i={axis:e};return ke.runKernel("Concat",s,i)}}),Ai={kernelName:"SplitV",gradFunc:(t,e,n)=>{const{axis:s}=n;return{x:()=>Ii(t,s)}}},Ci={kernelName:"Sqrt",inputsToSave:["x"],gradFunc:(t,e)=>{const[n]=e;return{x:()=>De(t,ze(Me(Te(n,"float32")),2))}}},Ti={kernelName:"Square",inputsToSave:["x"],gradFunc:(t,e)=>{const[n]=e;return{x:()=>ze(t,ze(Te(n,"float32"),2))}}},zi={kernelName:"SquaredDifference",inputsToSave:["a","b"],gradFunc:(t,e)=>{const[n,s]=e,i=Re(2);return{a:()=>ze(t,ze(i,Be(n,s))),b:()=>ze(t,ze(i,Be(s,n)))}}},Ei={kernelName:"Step",gradFunc:t=>({x:()=>He(t)})},$i={kernelName:"Sub",inputsToSave:["a","b"],gradFunc:(t,e)=>{const[n,s]=e,i=Ve(n.shape,s.shape);return{a:()=>{let e=t;const s=We(n.shape,i);return s.length>0&&(e=qe(e,s)),je(e,n.shape)},b:()=>{let e=t;const n=We(s.shape,i);return n.length>0&&(e=qe(e,n)),je(Le(e),s.shape)}}}},Fi={kernelName:"Sum",inputsToSave:["x"],gradFunc:(t,e,n)=>{const[s]=e,i=s.shape.slice(),{axis:r}=n;Z(r,s.shape).forEach((t=>{i[t]=1}));const a=je(t,i),o=ze(a,Ds(s.shape,"float32"));return{x:()=>o}}},Di={kernelName:"Tan",inputsToSave:["x"],gradFunc:(t,e)=>{const[n]=e;return{x:()=>De(t,Oe(fi(n)))}}},Li={kernelName:"Tanh",outputsToSave:[!0],gradFunc:(t,e)=>{const[n]=e;return{x:()=>ze(Be(Re(1),Oe(n)),t)}}},_i={kernelName:"Tile",inputsToSave:["x"],gradFunc:(t,e,n)=>{const[s]=e,{reps:i}=n;return{x:()=>{let e=He(s);if(1===s.rank)for(let n=0;n<i[0];++n)e=Xe(e,Ms(t,[n*s.shape[0]],[s.shape[0]]));else if(2===s.rank)for(let n=0;n<i[0];++n)for(let r=0;r<i[1];++r)e=Xe(e,Ms(t,[n*s.shape[0],r*s.shape[1]],[s.shape[0],s.shape[1]]));else if(3===s.rank)for(let n=0;n<i[0];++n)for(let r=0;r<i[1];++r)for(let a=0;a<i[2];++a)e=Xe(e,Ms(t,[n*s.shape[0],r*s.shape[1],a*s.shape[2]],[s.shape[0],s.shape[1],s.shape[2]]));else{if(4!==s.rank)throw new Error(`Gradient for tile operation is not implemented for rank-${s.rank} tensors yet.`);for(let n=0;n<i[0];++n)for(let r=0;r<i[1];++r)for(let a=0;a<i[2];++a)for(let o=0;o<i[3];++o)e=Xe(e,Ms(t,[n*s.shape[0],r*s.shape[1],a*s.shape[2],o*s.shape[3]],[s.shape[0],s.shape[1],s.shape[2],s.shape[3]]))}return e}}}},Ri={kernelName:"Transpose",gradFunc:(t,e,n)=>{const s=n,{perm:i}=s,r=Un(i);return{x:()=>Vn(t,r)}}};const Mi=Ce({stack_:function(t,e=0){const n=Ae(t,"tensors","stack","string_or_numeric");V(n.length>=1,(()=>"Pass at least one tensor to tf.stack")),n.length>0&&V(e<=n[0].rank,(()=>"Axis must be <= rank of the tensor"));const s=n,i={axis:e};return ke.runKernel("Pack",s,i)}}),Oi={kernelName:"Unpack",gradFunc:(t,e,n)=>{const s=n,{axis:i}=s;return{value:()=>Mi(t,i)}}};const Bi=Ce({expandDims_:function(t,e=0){const n=Ie(t,"x","expandDims","string_or_numeric");V(e<=n.rank,(()=>"Axis must be <= rank of the tensor"));const s={input:n},i={dim:e};return ke.runKernel("ExpandDims",s,i)}});const Pi=Ce({gather_:function(t,e,n=0,s=0){const i={x:Ie(t,"x","gather"),indices:Ie(e,"indices","gather","int32")},r={axis:n,batchDims:s};return ke.runKernel("GatherV2",i,r)}});const Ui=Ce({maximum_:function(t,e){let n=Ie(t,"a","maximum"),s=Ie(e,"b","maximum");[n,s]=fe(n,s),"bool"===n.dtype&&(n=Te(n,"int32"),s=Te(s,"int32")),Ve(n.shape,s.shape);const i={a:n,b:s};return ke.runKernel("Maximum",i)}});const Wi=[$e,Pe,Ue,Ke,Ge,Ze,Je,Ye,Qe,tn,en,nn,ln,hn,pn,fn,gn,mn,yn,Nn,In,Cn,Fn,En,_n,Mn,Bn,jn,Gn,Hn,Xs,Zn,Yn,Xn,Qn,ts,ns,es,rs,os,hs,cs,ps,ds,fs,ms,ys,bs,ws,vs,Ns,Ns,As,Ts,Es,Ls,_s,Rs,Os,Ps,Us,Ws,Vs,js,Ks,Gs,Gs,Js,Ys,Qs,ti,ei,ni,si,ii,ai,oi,li,hi,ci,pi,di,gi,yi,wi,ki,Si,Ni,Ni,Ai,Ai,Ci,zi,Ti,Ei,$i,Fi,Di,Li,_i,Ri,Oi,{kernelName:"UnsortedSegmentSum",inputsToSave:["segmentIds"],gradFunc:(t,e)=>{const[n]=e;return{x:()=>function(t,e){const n=Ui(e,He(e)),s=Pi(t,n);let i=bn(e,Re(0,"int32"));const r=s.rank-i.rank;for(let t=0;t<r;++t)i=Bi(i,t+1);i=kn(i,Ds(s.shape,"bool"));const a=He(s);return xn(i,s,a)}(t,n)}}},{kernelName:"ZerosLike",gradFunc:t=>({x:()=>He(t)})}];for(const t of Wi)kt(t);let Vi;function ji(){return null==Vi&&(Vi=e().epsilon()),Vi}class qi extends Error{constructor(t){super(t),Object.setPrototypeOf(this,qi.prototype)}}class Ki extends Error{constructor(t){super(t),Object.setPrototypeOf(this,Ki.prototype)}}class Gi extends Error{constructor(t){super(t),Object.setPrototypeOf(this,Gi.prototype)}}class Hi extends Error{constructor(t){super(t),Object.setPrototypeOf(this,Hi.prototype)}}class Zi extends Error{constructor(t){super(t),Object.setPrototypeOf(this,Zi.prototype)}}function Ji(t,e){if(Array.isArray(t)){let n=[];for(let s=0;s<e;s++)n=n.concat(t);return n}{const n=new Array(e);return n.fill(t),n}}function Yi(t,e){if(!t)throw new Zi(e)}function Xi(t,e){let n=0;for(const s of t)s===e&&n++;return n}function Qi(t){return 1===t.length?t[0]:t}function tr(t){return Array.isArray(t)?t:[t]}function er(t){const e=t.replace(/(.)([A-Z][a-z0-9]+)/g,"$1_$2").replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();return"_"!==e[0]?e:"private"+e}function nr(t){return t.length<=1||-1===t.indexOf("_")?t:t.replace(/[_]+(\w|$)/g,((t,e)=>e.toUpperCase()))}let sr={};function ir(t){if(null==t)return null;const e={};return e.className=t.getClassName(),e.config=t.getConfig(),e}function rr(t){if(null!=t&&"object"==typeof t)if(Array.isArray(t))t.forEach((t=>rr(t)));else{const e=Object.keys(t);for(const n of e){const e=t[n];null!=e&&"object"==typeof e&&(Array.isArray(e)||"ndarray"!==e.type||"number"!=typeof e.value?rr(e):t[n]=e.value)}}}function ar(t,e={},n={},s="object",i=!1){if("string"==typeof t){const i=t;let r;if(i in n)r=n[i];else if(i in sr)r=sr[i];else if(r=e[i],null==r)throw new Gi(`Unknown ${s}: ${t}. This may be due to one of the following reasons:\n1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return r}{const r=t;if(null==r.className||null==r.config)throw new Gi(`${s}: Improper config format: ${JSON.stringify(r)}.\n'className' and 'config' must set.`);const a=r.className;let o,l;if(a in n?[o,l]=n[a]:a in sr?[o,l]=sr.className:a in e&&([o,l]=e[a]),null==o)throw new Gi(`Unknown ${s}: ${a}. This may be due to one of the following reasons:\n1. The ${s} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.\n2. The custom ${s} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(null!=l){const t={};for(const e of Object.keys(sr))t[e]=sr[e];for(const e of Object.keys(n))t[e]=n[e];r.config.customObjects=t;const e=Object.assign({},sr);for(const t of Object.keys(n))sr[t]=n[t];rr(r.config);const s=l(o,r.config,n,i);return sr=Object.assign({},e),s}{const t=Object.assign({},sr);for(const t of Object.keys(n))sr[t]=n[t];const e=new o(r.config);return sr=Object.assign({},t),e}}}function or(t,e){return-1*function(t,e){return t<e?-1:t>e?1:0}(t,e)}function lr(t){if(null==t)return t;const e=[];for(const n of t)-1===e.indexOf(n)&&e.push(n);return e}function ur(t){if(null==t)throw new Gi(`Invalid value in obj: ${JSON.stringify(t)}`);for(const e in t)if(t.hasOwnProperty(e))return!1;return!0}function hr(t,e,n){if(null!=n&&t.indexOf(n)<0)throw new Gi(`${n} is not a valid ${e}. Valid values are ${t} or null/undefined.`)}function cr(t,e,n=0,s=1/0){return Yi(n>=0),Yi(s>=n),Array.isArray(t)&&t.length>=n&&t.length<=s&&t.every((t=>typeof t===e))}function pr(t,e){Array.isArray(t)?(n.assert(t.length>0,(()=>`${e} is unexpectedly an empty array.`)),t.forEach(((t,n)=>pr(t,`element ${n+1} of ${e}`)))):n.assert(Number.isInteger(t)&&t>0,(()=>`Expected ${e} to be a positive integer, but got ${dr(t)}.`))}function dr(t){return null===t?"null":Array.isArray(t)?"["+t.map((t=>dr(t))).join(",")+"]":"string"==typeof t?`"${t}"`:`${t}`}function fr(t){return"relu"===t?"relu":"linear"===t?"linear":"elu"===t?"elu":null}function gr(e,n){return i((()=>t.sqrt(t.sum(t.mul(e,e),n,!0))))}class mr extends s.Serializable{getConfig(){return{}}}class yr extends mr{constructor(t){super(),this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=null!=t.maxValue?t.maxValue:this.defaultMaxValue,this.axis=null!=t.axis?t.axis:this.defaultAxis}apply(e){return i((()=>{const n=gr(e,this.axis),s=t.clipByValue(n,0,this.maxValue);return t.mul(e,t.div(s,t.add(ji(),n)))}))}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}yr.className="MaxNorm",s.registerClass(yr);class br extends mr{constructor(t){super(),this.defaultAxis=0,this.axis=null!=t.axis?t.axis:this.defaultAxis}apply(e){return i((()=>t.div(e,t.add(ji(),gr(e,this.axis)))))}getConfig(){return{axis:this.axis}}}br.className="UnitNorm",s.registerClass(br);class wr extends mr{apply(e){return t.relu(e)}}wr.className="NonNeg",s.registerClass(wr);class kr extends mr{constructor(t){super(),this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=null!=t.minValue?t.minValue:this.defaultMinValue,this.maxValue=null!=t.maxValue?t.maxValue:this.defaultMaxValue,this.rate=null!=t.rate?t.rate:this.defaultRate,this.axis=null!=t.axis?t.axis:this.defaultAxis}apply(e){return i((()=>{const n=gr(e,this.axis),s=t.add(t.mul(this.rate,t.clipByValue(n,this.minValue,this.maxValue)),t.mul(1-this.rate,n));return t.mul(e,t.div(s,t.add(ji(),n)))}))}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}kr.className="MinMaxNorm",s.registerClass(kr);const vr={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function Sr(t){return ir(t)}function xr(t,e={}){return ar(t,s.SerializationMap.getMap().classNameMap,e,"constraint")}function Nr(t){if(null==t)return null;if("string"==typeof t){return xr({className:t in vr?vr[t]:t,config:{}})}return t instanceof mr?t:xr(t)}var Ir={__proto__:null,maxNorm:function(t){return new yr(t)},unitNorm:function(t){return new br(t)},nonNeg:function(){return new wr},minMaxNorm:function(t){return new kr(t)}};const Ar=["channelsFirst","channelsLast"],Cr=["nearest","bilinear"],Tr=["valid","same","causal"],zr=["max","avg"],Er=["sum","mul","concat","ave"],$r=new Map;function Fr(t){hr(Ar,"DataFormat",t)}function Dr(t){hr(Tr,"PaddingMode",t)}function Lr(t){hr(zr,"PoolMode",t)}const _r=[];function Rr(t,e){_r.push(t);try{const t=e();return _r.pop(),t}catch(t){throw _r.pop(),t}}function Mr(t){if(!Pr(t))throw new Error("Not a valid tensor name: '"+t+"'");return(0===_r.length?"":_r.join("/")+"/")+t}function Or(t){if(!Pr(t))throw new Error("Not a valid tensor name: '"+t+"'");$r.has(t)||$r.set(t,0);const e=$r.get(t);if($r.set(t,$r.get(t)+1),e>0){const n=`${t}_${e}`;return $r.set(n,1),n}return t}const Br=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function Pr(t){return!!t.match(Br)}function Ur(t,e,n){null==e&&(e=0),null==n&&(n=t.length);let s=1;for(let i=e;i<n;++i)s*=t[i];return s}function Wr(t){if(0===t.length)return Number.NaN;let e=Number.POSITIVE_INFINITY;for(let n=0;n<t.length;n++){const s=t[n];s<e&&(e=s)}return e}function Vr(t){if(0===t.length)return Number.NaN;let e=Number.NEGATIVE_INFINITY;for(let n=0;n<t.length;n++){const s=t[n];s>e&&(e=s)}return e}function jr(t,e){if(e<t)throw new Gi(`end (${e}) < begin (${t}) is forbidden.`);const n=[];for(let s=t;s<e;++s)n.push(s);return n}function qr(e,n){return t.cast(e,n)}function Kr(e,n=-1){const s=e.shape.slice();return n<0&&(n=s.length+n+1),s.splice(n,0,1),t.reshape(e,s)}function Gr(e,n,s){return i((()=>{switch(e.rank){case 1:return t.slice1d(e,n,s);case 2:return t.slice2d(e,[n,0],[s,e.shape[1]]);case 3:return t.slice3d(e,[n,0,0],[s,e.shape[1],e.shape[2]]);case 4:return t.slice4d(e,[n,0,0,0],[s,e.shape[1],e.shape[2],e.shape[3]]);case 5:return t.slice(e,[n,0,0,0,0],[s,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return t.slice(e,[n,0,0,0,0,0],[s,e.shape[1],e.shape[2],e.shape[3],e.shape[4],e.shape[5]]);default:throw new Gi(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Hr(e,n,s){return i((()=>{switch(e.rank){case 1:return t.slice1d(e,n,s);case 2:return t.slice2d(e,[0,n],[e.shape[0],s]);case 3:return t.slice3d(e,[0,0,n],[e.shape[0],e.shape[1],s]);case 4:return t.slice4d(e,[0,0,0,n],[e.shape[0],e.shape[1],e.shape[2],s]);default:throw new Gi(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Zr(e,n,s,r){return i((()=>{switch(e.rank){case 1:return t.slice1d(e,n,s);case 2:switch(r){case 1:return Gr(e,n,s);case 2:return Hr(e,n,s);default:throw new Gi(`The axis is not within the rank of the tensor ${r}`)}case 3:switch(r){case 1:return Gr(e,n,s);case 2:return t.slice3d(e,[0,n,0],[e.shape[0],s,e.shape[2]]);case 3:return Hr(e,n,s);default:throw new Gi(`The axis is not within the rank of the tensor ${r}`)}case 4:switch(r){case 1:return Gr(e,n,s);case 2:return t.slice4d(e,[0,n,0,0],[e.shape[0],s,e.shape[2],e.shape[3]]);case 3:return t.slice4d(e,[0,0,n,0],[e.shape[0],e.shape[1],s,e.shape[3]]);case 4:return Hr(e,n,s);default:throw new Gi(`The axis is not within the rank of the tensor ${r}`)}default:throw new Gi(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Jr(e,n=-1){let s;return n<0&&(s=e[0].rank,n=0!==s?s:0),n===e[0].rank&&(n=-1),t.concat(e,n)}function Yr(e,n){switch(e.rank){case 1:return t.concat1d([e,n]);case 2:return t.concat2d([e,n],0);case 3:return t.concat3d([e,n],0);case 4:return t.concat4d([e,n],0);default:throw new Gi(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function Xr(e,n){if(Array.isArray(n)||(n=[n]),e.rank!==n.length)throw new Gi(`The length of input n (${n.length}) does not match the number of dimensions in input x (${e.rank})`);return t.tile(e,n)}function Qr(e,n=0,s=1,i,r){return t.randomNormal(e,n,s,i,r)}function ta(e,n,s,i){if(e.rank<2||n.rank<2)throw new Hi(`dot requires both inputs to be rank >= 2 but got x shape = ${e.shape} and y shape = ${n.shape}`);if(n.rank>=3){if(e.shape.slice(-1)[0]!==n.shape.slice(-2)[0])throw new Hi(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${e.shape} and y shape = ${n.shape}`)}if(2===e.rank&&2===n.rank){const r=!1,a=!1;return t.fused.matMul({a:e,b:n,transposeA:r,transposeB:a,bias:i?sa(e.rank,i,"channelsLast"):null,activation:s})}{const r=e.shape.slice(),a=r.pop();e=t.reshape(e,[-1,a]);const o=n.shape.slice(),l=o.pop(),u=o.pop(),h=[...o,l],c=Array.from({length:n.rank},((t,e)=>0===e?n.rank-2:e<=n.rank-2?e-1:e));n=t.reshape(t.transpose(n,c),[u,-1]);const p=[...r,...h],d=!1,f=!1;return t.reshape(t.fused.matMul({a:e,b:n,transposeA:d,transposeB:f,bias:i?sa(e.rank,i,"channelsLast"):null,activation:s}),p)}}function ea(e,n,s){return i((()=>(n=Array.isArray(n)?r(n,"int32"):t.cast(n,"int32"),t.gather(e,n,s))))}function na(e){return t.mul(e,e)}function sa(e,n,s){const i=n.shape;if(1!==n.rank&&n.rank!==e)throw new Gi(`Unexpected bias dimensions: ${n.rank}; expected it to be 1 or ${e}`);if(5===e){if("channelsFirst"===s)return 1===i.length?t.reshape(n,[1,i[0],1,1,1]):t.reshape(n,[1,i[3],i[0],i[1],i[2]]);if("channelsLast"===s)return 1===i.length?t.reshape(n,[1,1,1,1,i[0]]):t.reshape(n,[1].concat(i))}else if(4===e){if("channelsFirst"===s)return 1===i.length?t.reshape(n,[1,i[0],1,1]):t.reshape(n,[1,i[2],i[0],i[1]]);if("channelsLast"===s)return 1===i.length?t.reshape(n,[1,1,1,i[0]]):t.reshape(n,[1].concat(i))}else if(3===e){if("channelsFirst"===s)return 1===i.length?t.reshape(n,[1,i[0],1]):t.reshape(n,[1,i[1],i[0]]);if("channelsLast"===s)return 1===i.length?t.reshape(n,[1,1,i[0]]):t.reshape(n,[1].concat(i))}else if(e<3)return n;throw new Gi(`Unsupported input rank by biasAdd: ${n.rank}`)}function ia(e,n,s){return i((()=>(null==s&&(s="channelsLast"),Fr(s),t.add(e,sa(e.rank,n,s)))))}function ra(e,n,s,r){return i((()=>t.dropout(e,n,s,r)))}function aa(t,e,n=!1){return n?t():e()}const oa=["fanIn","fanOut","fanAvg"],la=["normal","uniform","truncatedNormal"];class ua extends s.Serializable{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}}class ha extends ua{apply(t,e){return a(t,e)}}ha.className="Zeros",s.registerClass(ha);class ca extends ua{apply(t,e){return o(t,e)}}ca.className="Ones",s.registerClass(ca);class pa extends ua{constructor(t){if(super(),"object"!=typeof t)throw new Gi(`Expected argument of type ConstantConfig but got ${t}`);if(void 0===t.value)throw new Gi(`config must have value set but got ${t}`);this.value=t.value}apply(t,e){return i((()=>l(u(this.value),o(t,e))))}getConfig(){return{value:this.value}}}pa.className="Constant",s.registerClass(pa);class da extends ua{constructor(t){super(),this.DEFAULT_MINVAL=-.05,this.DEFAULT_MAXVAL=.05,this.minval=t.minval||this.DEFAULT_MINVAL,this.maxval=t.maxval||this.DEFAULT_MAXVAL,this.seed=t.seed}apply(t,e){return h(t,this.minval,this.maxval,e)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}}da.className="RandomUniform",s.registerClass(da);class fa extends ua{constructor(t){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=t.mean||this.DEFAULT_MEAN,this.stddev=t.stddev||this.DEFAULT_STDDEV,this.seed=t.seed}apply(t,e){if("float32"!==(e=e||"float32")&&"int32"!==e)throw new Hi(`randomNormal does not support dType ${e}.`);return Qr(t,this.mean,this.stddev,e,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}fa.className="RandomNormal",s.registerClass(fa);class ga extends ua{constructor(t){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=t.mean||this.DEFAULT_MEAN,this.stddev=t.stddev||this.DEFAULT_STDDEV,this.seed=t.seed}apply(t,e){if("float32"!==(e=e||"float32")&&"int32"!==e)throw new Hi(`truncatedNormal does not support dType ${e}.`);return c(t,this.mean,this.stddev,e,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}ga.className="TruncatedNormal",s.registerClass(ga);class ma extends ua{constructor(t){super(),this.gain=null!=t.gain?t.gain:1}apply(t,e){return i((()=>{if(2!==t.length||t[0]!==t[1])throw new Gi("Identity matrix initializer can only be used for 2D square matrices.");return l(this.gain,p(t[0]))}))}getConfig(){return{gain:this.gain}}}ma.className="Identity",s.registerClass(ma);class ya extends ua{constructor(t){if(super(),t.scale<0)throw new Gi(`scale must be a positive float. Got: ${t.scale}`);var e;this.scale=null==t.scale?1:t.scale,this.mode=null==t.mode?"fanIn":t.mode,e=this.mode,hr(oa,"FanMode",e),this.distribution=null==t.distribution?"normal":t.distribution,function(t){hr(la,"Distribution",t)}(this.distribution),this.seed=t.seed}apply(t,e){const n=function(t,e="channelsLast"){let n,s;if(Fr(e),2===t.length)n=t[0],s=t[1];else if(-1!==[3,4,5].indexOf(t.length)){if("channelsFirst"===e){const e=Ur(t,2);n=t[1]*e,s=t[0]*e}else if("channelsLast"===e){const e=Ur(t,0,t.length-2);n=t[t.length-2]*e,s=t[t.length-1]*e}}else{const e=Ur(t);n=Math.sqrt(e),s=Math.sqrt(e)}return[n,s]}(t),s=n[0],i=n[1];let r=this.scale;if("fanIn"===this.mode?r/=Math.max(1,s):"fanOut"===this.mode?r/=Math.max(1,i):r/=Math.max(1,(s+i)/2),"normal"===this.distribution){const n=Math.sqrt(r);if("float32"!==(e=e||"float32")&&"int32"!==e)throw new Hi(`${this.getClassName()} does not support dType ${e}.`);return c(t,0,n,e,this.seed)}{const n=Math.sqrt(3*r);return h(t,-n,n,e)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}}ya.className="VarianceScaling",s.registerClass(ya);class ba extends ya{constructor(t){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:null==t?null:t.seed})}getClassName(){return ya.className}}ba.className="GlorotUniform",s.registerClass(ba);class wa extends ya{constructor(t){super({scale:1,mode:"fanAvg",distribution:"normal",seed:null==t?null:t.seed})}getClassName(){return ya.className}}wa.className="GlorotNormal",s.registerClass(wa);class ka extends ya{constructor(t){super({scale:2,mode:"fanIn",distribution:"normal",seed:null==t?null:t.seed})}getClassName(){return ya.className}}ka.className="HeNormal",s.registerClass(ka);class va extends ya{constructor(t){super({scale:2,mode:"fanIn",distribution:"uniform",seed:null==t?null:t.seed})}getClassName(){return ya.className}}va.className="HeUniform",s.registerClass(va);class Sa extends ya{constructor(t){super({scale:1,mode:"fanIn",distribution:"normal",seed:null==t?null:t.seed})}getClassName(){return ya.className}}Sa.className="LeCunNormal",s.registerClass(Sa);class xa extends ya{constructor(t){super({scale:1,mode:"fanIn",distribution:"uniform",seed:null==t?null:t.seed})}getClassName(){return ya.className}}xa.className="LeCunNormal",s.registerClass(xa);class Na extends ua{constructor(t){if(super(),this.DEFAULT_GAIN=1,this.gain=null==t.gain?this.DEFAULT_GAIN:t.gain,this.seed=t.seed,null!=this.seed)throw new Hi("Random seed is not implemented for Orthogonal Initializer yet.")}apply(t,e){return i((()=>{if(t.length<2)throw new Hi("Shape must be at least 2D.");t[0]*t[1]>2e3&&console.warn(`Orthogonal initializer is being called on a matrix with more than 2000 (${t[0]*t[1]}) elements: Slowness may result.`);const e=Qr(t[0]>t[1]?[t[1],t[0]]:t,0,1,"float32");let n=d.gramSchmidt(e);return t[0]>t[1]&&(n=f(n)),l(this.gain,n)}))}getConfig(){return{gain:this.gain,seed:this.seed}}}Na.className="Orthogonal",s.registerClass(Na);const Ia={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",heUniform:"HeUniform",identity:"Identity",leCunNormal:"LeCunNormal",leCunUniform:"LeCunUniform",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function Aa(t,e={}){return ar(t,s.SerializationMap.getMap().classNameMap,e,"initializer")}function Ca(t){return ir(t)}function Ta(t){if("string"==typeof t){const e=t in Ia?Ia[t]:t;if("GlorotNormal"===e)return new wa;if("GlorotUniform"===e)return new ba;if("HeNormal"===e)return new ka;if("HeUniform"===e)return new va;if("LeCunNormal"===e)return new Sa;if("LeCunUniform"===e)return new xa;{const t={};return t.className=e,t.config={},Aa(t)}}return t instanceof ua?t:Aa(t)}var za={__proto__:null,zeros:function(){return new ha},ones:function(){return new ca},constant:function(t){return new pa(t)},randomUniform:function(t){return new da(t)},randomNormal:function(t){return new fa(t)},truncatedNormal:function(t){return new ga(t)},identity:function(t){return new ma(t)},varianceScaling:function(t){return new ya(t)},glorotUniform:function(t){return new ba(t)},glorotNormal:function(t){return new wa(t)},heNormal:function(t){return new ka(t)},heUniform:function(t){return new va(t)},leCunNormal:function(t){return new Sa(t)},leCunUniform:function(t){return new xa(t)},orthogonal:function(t){return new Na(t)}};let Ea=0;function $a(){return Ea++}const Fa={};function Da(t=""){return t in Fa||(Fa[t]=0),Fa[t]+=1,t+Fa[t].toString()}function La(t){return Array.isArray(t)&&Array.isArray(t[0])}function _a(t){return 0===t.length?[]:Array.isArray(t[0])?t:[t]}function Ra(t){let e;if(Array.isArray(t)){if(1!==t.length)throw new Gi(`Expected Tensor length to be 1; got ${t.length}`);e=t[0]}else e=t;return e}function Ma(t){if(Array.isArray(t)&&Array.isArray(t[0])){if(1===t.length)return(t=t)[0];throw new Gi(`Expected exactly 1 Shape; got ${t.length}`)}return t}function Oa(t){let e=0;for(const n of t)0===n.shape.length?e+=1:e+=n.shape.reduce(((t,e)=>t*e));return e}class Ba{constructor(e,n="float32",s="Variable",i=!0,r=null){this.dtype=null==n?"float32":n,this.shape=e.shape,this.id=$a(),s=null==s?"Variable":s,this.originalName=Mr(s),this.name=Or(this.originalName),this.trainable_=i,this.constraint=r,this.val=t.variable(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(t){return this.assertNotDisposed(),function(t,e){if(t.shape.toString()!==e.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(t.shape)+" vs. "+JSON.stringify(e.shape))}(this.val,t),this.val.id!==t.id&&(this.val.assign(t),null!=this.constraint&&this.val.assign(this.constraint.apply(this.val))),this}dispose(){this.assertNotDisposed(),this.val.dispose()}assertNotDisposed(){if(this.val.isDisposed)throw new Error(`LayersVariable ${this.name} is already disposed.`)}get trainable(){return this.trainable_}set trainable(t){this.trainable_=t,this.val.trainable=t}}function Pa(t){return t.map((t=>t.read()))}function Ua(t){t.forEach((t=>{t[0].write(t[1])}))}class Wa{constructor(t){this.dtype=t.dtype,this.shape=t.shape,null!=t.shape?this.ndim=t.shape.length:this.ndim=t.ndim,this.maxNDim=t.maxNDim,this.minNDim=t.minNDim,this.axes=t.axes||{}}}class Va{constructor(t,e,n,s,i,r,a){this.dtype=t,this.shape=e,this.sourceLayer=n,this.inputs=s,this.callArgs=i,this.outputTensorIndex=a,this.id=$a(),null!=r&&(this.originalName=Mr(r),this.name=Or(this.originalName)),this.rank=e.length}}let ja=0;class qa{constructor(t,e){this.callArgs=e,this.id=ja++,this.outboundLayer=t.outboundLayer,this.inboundLayers=t.inboundLayers,this.nodeIndices=t.nodeIndices,this.tensorIndices=t.tensorIndices,this.inputTensors=t.inputTensors,this.outputTensors=t.outputTensors,this.inputMasks=t.inputMasks,this.outputMasks=t.outputMasks,this.inputShapes=t.inputShapes,this.outputShapes=t.outputShapes;for(const e of t.inboundLayers)null!=e&&e.outboundNodes.push(this);t.outboundLayer.inboundNodes.push(this)}getConfig(){const t=[];for(const e of this.inboundLayers)null!=e?t.push(e.name):t.push(null);return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:t,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}}}let Ka=0;class Ga extends s.Serializable{constructor(t={}){super(),this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=Ka++,this.activityRegularizer=null,this.inputSpec=null,this.supportsMasking=!1,this._trainableWeights=[],this._nonTrainableWeights=[],this._losses=[],this._updates=[],this._built=!1,this.inboundNodes=[],this.outboundNodes=[];let e=t.name;if(!e){const t=this.getClassName();e=er(t)+"_"+Da(t)}if(this.name=e,this.trainable_=null==t.trainable||t.trainable,null!=t.inputShape||null!=t.batchInputShape){let e;if(null!=t.batchInputShape)e=t.batchInputShape;else if(null!=t.inputShape){let n=null;null!=t.batchSize&&(n=t.batchSize),e=[n].concat(t.inputShape)}this.batchInputShape=e;let n=t.dtype;null==n&&(n=t.inputDType),null==n&&(n="float32"),this.dtype=n}null!=t.weights?this.initialWeights=t.weights:this.initialWeights=null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(t,e){return t.name+"_ib-"+e.toString()}getNodeAtIndex(t,e){if(0===this.inboundNodes.length)throw new Ki(`The layer has never been called and thus has no defined ${e}.`);if(this.inboundNodes.length<=t)throw new Gi(`Asked to get ${e} at node ${t}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[t]}getInputAt(t){return Qi(this.getNodeAtIndex(t,"input").inputTensors)}getOutputAt(t){return Qi(this.getNodeAtIndex(t,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new qi(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use \`getInputAt(nodeIndex)\` instead.`);if(0===this.inboundNodes.length)throw new qi(`Layer ${this.name} is not connected, no input to return.`);return Qi(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(0===this.inboundNodes.length)throw new qi(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new qi(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return Qi(this.getNodeAtIndex(0,"output").outputTensors)}get losses(){return this._losses}calculateLosses(){return this.losses.map((t=>t()))}get updates(){return this._updates}get built(){return this._built}set built(t){this._built=t}get trainable(){return this.trainable_}set trainable(t){this._trainableWeights.forEach((e=>e.trainable=t)),this.trainable_=t}get trainableWeights(){return this.trainable_?this._trainableWeights.filter((t=>t.trainable)):[]}set trainableWeights(t){this._trainableWeights=t}get nonTrainableWeights(){return this.trainable?this._trainableWeights.filter((t=>!t.trainable)).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)}set nonTrainableWeights(t){this._nonTrainableWeights=t}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}get stateful(){return this._stateful}resetStates(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")}assertInputCompatibility(t){if(t=tr(t),null==this.inputSpec||0===this.inputSpec.length)return;const e=tr(this.inputSpec);if(t.length!==e.length)throw new Gi(`Layer ${this.name} expects ${e.length} inputs, but it received ${t.length} input tensors. Input received: ${t}`);for(let n=0;n<t.length;n++){const s=t[n],i=e[n];if(null==i)continue;const r=s.rank;if(null!=i.ndim&&r!==i.ndim)throw new Gi(`Input ${n} is incompatible with layer ${this.name}: expected ndim=${i.ndim}, found ndim=${r}`);if(null!=i.maxNDim&&r>i.maxNDim)throw new Gi(`Input ${n} is incompatible with layer ${this.name}: expected max_ndim=${i.maxNDim}, found ndim=${r}`);if(null!=i.minNDim&&r<i.minNDim)throw new Gi(`Input ${n} is incompatible with layer ${this.name}: expected min_ndim=${i.minNDim}, found ndim=${r}.`);if(null!=i.dtype&&s.dtype!==i.dtype)throw new Gi(`Input ${n} is incompatible with layer ${this.name} : expected dtype=${i.dtype}, found dtype=${s.dtype}.`);if(i.axes){const t=s.shape;for(const e in i.axes){const s=Number(e),r=i.axes[e],a=s>=0?t[s]:t[t.length+s];if(null!=r&&-1===[r,null].indexOf(a))throw new Gi(`Input ${n} is incompatible with layer ${this.name}: expected axis ${s} of input shape to have value ${r} but got shape ${t}.`)}}if(null!=i.shape)for(let t=0;t<i.shape.length;++t){const e=i.shape[t],r=s.shape[t];if(null!=e&&null!=r&&e!==r)throw new Gi(`Input ${n} is incompatible with layer ${this.name}: expected shape=${i.shape}, found shape=${s.shape}.`)}}}call(t,e){return t}invokeCallHook(t,e){null!=this._callHook&&this._callHook(t,e)}setCallHook(t){this._callHook=t}clearCallHook(){this._callHook=null}apply(t,e){e=e||{},this.assertNotDisposed();const n=tr(t);let s=!0;for(const t of n)if(!(t instanceof Va)){s=!1;break}let i=!0;for(const t of n)if(t instanceof Va){i=!1;break}if(s===i)throw new Gi("Arguments to apply() must be all SymbolicTensors or all Tensors");return Rr(this.name,(()=>{if(!this.built){this.assertInputCompatibility(t);const e=[];for(const n of tr(t))e.push(n.shape);this.build(Qi(e)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),null===this._refCount&&i&&(this._refCount=1)}if(this.assertInputCompatibility(t),i){let s=this.call(t,e);const i=tr(s),r=[];for(let t of i)-1!==n.indexOf(t)&&(t=t.clone()),r.push(t);if(s=Qi(r),null!=this.activityRegularizer)throw new Hi("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return s}{const n=function(t){t=tr(t);const e=[];for(const n of t)e.push(n.shape);return Qi(e)}(t),s=this.computeOutputShape(n);let i;const r="float32";if(this.warnOnIncompatibleInputShape(Array.isArray(t)?n[0]:n),i=null!=s&&s.length>0&&Array.isArray(s[0])?s.map(((n,s)=>new Va(r,n,this,tr(t),e,this.name,s))):new Va(r,s,this,tr(t),e,this.name),this.addInboundNode(t,i,null,null,n,s,e),this._refCount++,null!=this.activityRegularizer)throw new Hi("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return i}}))}warnOnIncompatibleInputShape(t){if(null!=this.batchInputShape)if(t.length!==this.batchInputShape.length)console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(t)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);else{let e=!1;this.batchInputShape.forEach(((n,s)=>{null!=n&&null!=t[s]&&t[s]!==n&&(e=!0)})),e&&console.warn(`The shape of the input tensor (${JSON.stringify(t)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`)}}get outputShape(){if(null==this.inboundNodes||0===this.inboundNodes.length)throw new qi(`The layer ${this.name} has never been called and thus has no defined output shape.`);const t=[];for(const e of this.inboundNodes){const n=JSON.stringify(e.outputShapes);-1===t.indexOf(n)&&t.push(n)}if(1===t.length){const t=this.inboundNodes[0].outputShapes;return Array.isArray(t)&&Array.isArray(t[0])&&1===t.length?t[0]:t}throw new qi(`The layer ${this.name} has multiple inbound nodes with different output shapes. Hence the notion of "output shape" is ill-defined for the layer.`)}countParams(){if(!this.built)throw new Ki(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return Oa(this.weights)}build(t){this.built=!0}getWeights(t=!1){return Pa(t?this.trainableWeights:this.weights)}setWeights(t){i((()=>{const e=this.weights;if(e.length!==t.length)throw new Gi(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${t.length}, but the layer was expecting ${e.length} weights. Provided weights: ${t}...`);if(0===e.length)return;const s=[],i=Pa(e);for(let r=0;r<i.length;++r){const a=i[r],o=e[r],l=t[r];if(!n.arraysEqual(a.shape,l.shape))throw new Gi(`Layer weight shape ${a.shape} not compatible with provided weight shape ${l.shape}`);s.push([o,l])}Ua(s)}))}addWeight(t,e,n,s,i,r,a,o){if(-1!==this._addedWeightNames.indexOf(t))throw new Gi(`Duplicate weight name ${t} for layer ${this.name}`);this._addedWeightNames.push(t),null==n&&(n="float32"),this.fastWeightInitDuringBuild&&(s=null!=o?o():Ta("zeros"));const l=s.apply(e,n),u=new Ba(l,n,t,r,a);return l.dispose(),null!=i&&this.addLoss((()=>i.apply(u.read()))),null==r&&(r=!0),r?this._trainableWeights.push(u):this._nonTrainableWeights.push(u),u}setFastWeightInitDuringBuild(t){this.fastWeightInitDuringBuild=t}addLoss(t){null==t||Array.isArray(t)&&0===t.length||(t=tr(t),void 0!==this._losses&&null!==this._losses&&this.losses.push(...t))}computeOutputShape(t){return t}computeMask(t,e){if(!this.supportsMasking){if(null!=e){if(!Array.isArray(e))throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);e.forEach((t=>{if(null!=t)throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`)}))}return null}return e}addInboundNode(t,e,n,s,i,r,a=null){const o=tr(t);e=tr(e),n=tr(n),s=tr(s),i=_a(i),r=_a(r);const l=[],u=[],h=[];for(const t of o)l.push(t.sourceLayer),u.push(t.nodeIndex),h.push(t.tensorIndex);new qa({outboundLayer:this,inboundLayers:l,nodeIndices:u,tensorIndices:h,inputTensors:o,outputTensors:e,inputMasks:n,outputMasks:s,inputShapes:i,outputShapes:r},a);for(let t=0;t<e.length;t++)e[t].sourceLayer=this,e[t].nodeIndex=this.inboundNodes.length-1,e[t].tensorIndex=t}getConfig(){const t={name:this.name,trainable:this.trainable};return null!=this.batchInputShape&&(t.batchInputShape=this.batchInputShape),null!=this.dtype&&(t.dtype=this.dtype),t}disposeWeights(){return this.weights.forEach((t=>t.dispose())),this.weights.length}assertNotDisposed(){if(0===this._refCount)throw new Error(`Layer '${this.name}' is already disposed.`)}dispose(){if(!this.built)throw new Error(`Cannot dispose Layer ${this.name} because it has not been built yet.`);if(null===this._refCount)throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);this.assertNotDisposed();let t=0;return 0==--this._refCount&&(t=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:t}}}function Ha(t,e,n){if((null==e||null!=n&&n>0)&&(e=t.sourceLayer,n=t.nodeIndex),0===e.inboundNodes.length)return[t];{const t=e.inboundNodes[n];if(0===t.inboundLayers.length)return t.inputTensors;{const e=[];for(let n=0;n<t.inboundLayers.length;n++){const s=Ha(t.inputTensors[n],t.inboundLayers[n],t.nodeIndices[n]);for(const t of s)-1===e.indexOf(t)&&e.push(t)}return e}}}class Za extends Ga{constructor(t){if(super({dtype:t.dtype,name:null!=t.name?t.name:Da("input").toString()}),null==t.batchSize&&(t.batchSize=null),null==t.sparse&&(t.sparse=!1),this.trainable=!1,this.built=!0,this.sparse=t.sparse,null!=t.inputShape&&null!=t.batchInputShape)throw new Gi("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");let e=t.batchInputShape;if(null==e){if(null==t.inputShape)throw new Gi("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");e=[t.batchSize].concat(t.inputShape)}else if(null!=t.batchSize)throw new Gi("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");const n=t.dtype||"float32";this.batchInputShape=e,this.dtype=n,this.inputSpec=[{shape:e}];const s=new Va(this.dtype,this.batchInputShape,this,[],{},this.name);s.nodeIndex=0,s.tensorIndex=0,new qa({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[s],outputTensors:[s],inputMasks:[null],outputMasks:[null],inputShapes:[e],outputShapes:[e]})}apply(t,e){throw new Gi(`Cannot pass any input to an InputLayer's apply() method. InputLayer name: ${this.name}`)}dispose(){return{refCountAfterDispose:this._refCount,numDisposedVariables:0}}getConfig(){return{batchInputShape:this.batchInputShape,dtype:this.dtype,sparse:this.sparse,name:this.name}}}function Ja(t){if(null==t.batchShape&&null==t.shape)throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");if(null!=t.batchShape&&null!=t.shape)throw new Gi("Please provide either a `shape` or `batchShape` argument to Input, but not both.");let e=t.batchShape;null!=t.shape&&null==e&&(e=[null].concat(t.shape));let n=t.dtype;null==n&&(n="float32");return new Za({batchInputShape:e,name:t.name,dtype:n,sparse:t.sparse}).inboundNodes[0].outputTensors[0]}async function Ya(t){if(null==t)return;const e=[],n=[],s=[];for(const i in t){const r=t[i];if("number"!=typeof r){const t=r;e.push(t.data()),n.push(i),s.push(t)}}if(e.length>0){const i=await Promise.all(e);for(let e=0;e<i.length;++e)t[n[e]]=i[e][0];g(s)}}function Xa(t){if(null!=t)for(const e in t){const n=t[e];"number"!=typeof n&&n.dispose()}}var Qa;Za.className="InputLayer",s.registerClass(Za),function(t){t[t.SILENT=0]="SILENT",t[t.VERBOSE=1]="VERBOSE"}(Qa||(Qa={}));class to{constructor(){this.validationData=null}setParams(t){this.params=t}async onEpochBegin(t,e){}async onEpochEnd(t,e){}async onBatchBegin(t,e){}async onBatchEnd(t,e){}async onTrainBegin(t){}async onTrainEnd(t){}setModel(t){}}class eo{constructor(t,e=10){null==t&&(t=[]),this.callbacks=t,this.queueLength=e}append(t){this.callbacks.push(t)}setParams(t){for(const e of this.callbacks)e.setParams(t)}setModel(t){for(const e of this.callbacks)e.setModel(t)}async onEpochBegin(t,e){null==e&&(e={});for(const n of this.callbacks)await n.onEpochBegin(t,e)}async onEpochEnd(t,e){null==e&&(e={});for(const n of this.callbacks)await n.onEpochEnd(t,e)}async onBatchBegin(t,e){null==e&&(e={});for(const n of this.callbacks)await n.onBatchBegin(t,e)}async onBatchEnd(t,e){null==e&&(e={});for(const n of this.callbacks)await n.onBatchEnd(t,e)}async onTrainBegin(t){null==t&&(t={});for(const e of this.callbacks)await e.onTrainBegin(t)}async onTrainEnd(t){null==t&&(t={});for(const e of this.callbacks)await e.onTrainEnd(t)}}class no extends to{constructor(){super()}async onEpochBegin(t){this.seen=0,this.totals={}}async onBatchEnd(t,e){null==e&&(e={});const n=null==e.size?0:e.size;this.seen+=n;for(const t in e){const s=e[t];if("number"==typeof s)this.totals.hasOwnProperty(t)||(this.totals[t]=0),this.totals[t]=this.totals[t]+s*n;else{let e;t in this.totals?e=this.totals[t]:this.totals[t]=0;const r=i((()=>y(this.totals[t],l(s,n))));this.totals[t]=r,null!=e&&e.dispose()}}}async onEpochEnd(t,e){if(null!=e)for(const t of this.params.metrics)null!=this.totals[t]&&("number"==typeof this.totals[t]?e[t]=this.totals[t]/this.seen:i((()=>{const n=l(b(1,this.seen),this.totals[t]);e[t]=n,this.totals[t].dispose(),w(e[t])})))}}class so extends to{async onTrainBegin(t){this.epoch=[],this.history={}}async onEpochEnd(t,e){null==e&&(e={}),this.epoch.push(t);for(const t in e)null==this.history[t]&&(this.history[t]=[]),this.history[t].push(e[t])}async syncData(){const t=[],e=[],n=[];for(const s in this.history){const i=this.history[s];for(let r=0;r<i.length;++r)if("number"!=typeof i[r]){const a=i[r];t.push(a.data()),e.push(s),n.push(r)}}const s=await Promise.all(t);for(let t=0;t<s.length;++t){this.history[e[t]][n[t]].dispose(),this.history[e[t]][n[t]]=s[t][0]}}}class io extends to{constructor(t,e){if(super(),this.currentEpoch=0,this.nowFunc=t.nowFunc,this.nextFrameFunc=t.nextFrameFunc||m,this.yieldEvery=e||"auto","auto"===this.yieldEvery&&(this.yieldEvery=125),"never"===this.yieldEvery&&null!=t.onYield)throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");n.isNumber(this.yieldEvery)&&(this.maybeWait=function(t,e,s){let i,r=null!=s?s():n.now();return(...a)=>{const o=null!=s?s():n.now();return o-r<e||(r=o,i=t(...a)),i}}(this.maybeWait.bind(this),this.yieldEvery,this.nowFunc)),this.trainBegin=t.onTrainBegin,this.trainEnd=t.onTrainEnd,this.epochBegin=t.onEpochBegin,this.epochEnd=t.onEpochEnd,this.batchBegin=t.onBatchBegin,this.batchEnd=t.onBatchEnd,this.yield=t.onYield}async maybeWait(t,e,n){const s=[];null!=this.yield&&(await Ya(n),s.push(this.yield(t,e,n))),s.push(this.nextFrameFunc()),await Promise.all(s)}async onEpochBegin(t,e){this.currentEpoch=t,null!=this.epochBegin&&(await Ya(e),await this.epochBegin(t,e))}async onEpochEnd(t,e){const n=[];null!=this.epochEnd&&(await Ya(e),n.push(this.epochEnd(t,e))),"epoch"===this.yieldEvery&&n.push(this.nextFrameFunc()),await Promise.all(n)}async onBatchBegin(t,e){null!=this.batchBegin&&(await Ya(e),await this.batchBegin(t,e))}async onBatchEnd(t,e){const s=[];null!=this.batchEnd&&(await Ya(e),s.push(this.batchEnd(t,e))),"batch"===this.yieldEvery?s.push(this.nextFrameFunc()):n.isNumber(this.yieldEvery)&&s.push(this.maybeWait(this.currentEpoch,t,e)),await Promise.all(s)}async onTrainBegin(t){null!=this.trainBegin&&(await Ya(t),await this.trainBegin(t))}async onTrainEnd(t){null!=this.trainEnd&&(await Ya(t),await this.trainEnd(t))}}function ro(t,e){if(null==t&&(t={}),t instanceof to)return[t];if(Array.isArray(t)&&t[0]instanceof to)return t;return tr(t).map((t=>new io(t,e)))}class ao{constructor(){}static registerCallbackConstructor(t,e){n.assert(t>=0&&Number.isInteger(t),(()=>`Verbosity level is expected to be an integer >= 0, but got ${t}`)),ao.checkForDuplicate(e),null==ao.constructors[t]&&(ao.constructors[t]=[]),ao.constructors[t].push(e)}static checkForDuplicate(t){for(const e in ao.constructors){ao.constructors[+e].forEach((e=>{if(e===t)throw new Gi("Duplicate callback constructor.")}))}}static clear(){ao.constructors={}}static createCallbacks(t){const e=[];for(const n in ao.constructors){const s=+n;t>=s&&e.push(...ao.constructors[s])}return e.map((t=>new t))}}function oo(t,e,n,s,i,r,a,o,l){const u=new so,h=[new no,...ao.createCallbacks(e)];null!=t&&h.push(...t),h.push(u);const c=new eo(h);return c.setParams({epochs:n,initialEpoch:s,samples:i,steps:r,batchSize:a,verbose:e,doValidation:o,metrics:l}),{callbackList:c,history:u}}function lo(t,e={},n=!1){return ar(t,s.SerializationMap.getMap().classNameMap,e,"layer",n)}function uo(e,n){return i((()=>{"float32"!==e.dtype&&(e=t.cast(e,"float32"));const s=t.sum(na(e),n,!0),i=t.fill(s.shape,ji()),r=t.sqrt(t.maximum(s,i));return t.div(e,r)}))}function ho(e,n){return i((()=>t.mean(na(t.sub(n,e)),-1)))}function co(e,n){return i((()=>t.mean(t.abs(t.sub(n,e)),-1)))}function po(e,n){return i((()=>{const s=t.sub(e,n),i=t.clipByValue(t.abs(e),ji(),Number.MAX_VALUE),r=t.abs(t.div(s,i));return t.mul(100,t.mean(r,-1))}))}function fo(e,n,s=!1){return i((()=>{if(s)n=t.softmax(n);else{const e=t.sum(n,n.shape.length-1,!0);n=t.div(n,e)}return n=t.clipByValue(n,ji(),1-ji()),t.neg(t.sum(t.mul(t.cast(e,"float32"),t.log(n)),n.shape.length-1))}))}function go(e,n,s=!1){return i((()=>{const i=t.cast(t.floor(function(e){const n=[Ur(e.shape)];return t.reshape(e,n)}(e)),"int32"),r=(n=t.clipByValue(n,ji(),1-ji())).shape;return fo(t.reshape(t.oneHot(i,r[r.length-1]),r),n,s)}))}function mo(e,s){return i((()=>{let r;return r=t.clipByValue(s,ji(),1-ji()),r=t.log(t.div(r,t.sub(1,r))),t.mean(function(e,s){if(!n.arraysEqual(e.shape,s.shape))throw new Gi(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(s.shape)}`);return i((()=>{const n=t.relu(s),i=t.neg(t.abs(s));return t.add(t.sub(n,t.mul(s,e)),t.log1p(t.exp(i)))}))}(e,r),-1)}))}function yo(e,n){return i((()=>{const s=uo(e,-1),i=uo(n,-1),r=t.mul(s,i);return t.neg(t.sum(r,-1))}))}ao.constructors={};const bo={meanSquaredError:ho,meanAbsoluteError:co,meanAbsolutePercentageError:po,meanSquaredLogarithmicError:function(e,n){return i((()=>{const s=t.clipByValue(n,ji(),Number.MAX_VALUE),i=t.log(t.add(1,s)),r=t.clipByValue(e,ji(),Number.MAX_VALUE),a=t.log(t.add(1,r));return t.mean(na(t.sub(i,a)),-1)}))},squaredHinge:function(e,n){return i((()=>{const s=t.maximum(0,t.sub(1,t.mul(e,n)));return t.mean(na(s),-1)}))},hinge:function(e,n){return i((()=>{const s=t.maximum(0,t.sub(1,t.mul(e,n)));return t.mean(s,-1)}))},categoricalHinge:function(e,n){return i((()=>{const s=t.sum(t.mul(e,n),-1),i=t.max(t.mul(t.sub(1,e),n),-1);return t.maximum(0,t.add(1,t.sub(i,s)))}))},logcosh:function(e,n){return i((()=>{const s=Math.log(2),i=t.sub(n,e),r=t.sub(t.add(i,t.softplus(t.mul(-2,i))),s);return t.mean(r,-1)}))},categoricalCrossentropy:fo,sparseCategoricalCrossentropy:go,binaryCrossentropy:mo,kullbackLeiblerDivergence:function(e,n){return i((()=>{const s=t.clipByValue(e,ji(),1),i=t.clipByValue(n,ji(),1);return t.sum(t.mul(e,t.log(t.div(s,i))),-1)}))},poisson:function(e,n){return i((()=>{const s=t.log(t.add(ji(),n));return t.mean(t.sub(n,t.mul(e,s)),-1)}))},cosineProximity:yo};function wo(t){if("string"==typeof t){if(t in bo)return bo[t];let e=`Unknown loss ${t}`;throw t.toLowerCase().includes("softmaxcrossentropy")&&(e=`Unknown loss ${t}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`),new Gi(e)}return t}function ko(e,n){return i((()=>{const s=t.mul(.5,t.onesLike(n)),i=qr(t.greater(n,s),e.dtype);return t.mean(t.equal(e,i),-1)}))}function vo(e,n){return i((()=>qr(t.equal(t.argMax(e,-1),t.argMax(n,-1)),"float32")))}function So(e,n){return i((()=>t.cast(t.sum(t.logicalAnd(t.equal(e,1),t.equal(n,1))),"float32")))}function xo(e,n){return i((()=>{const s=So(e,n),r=function(e,n){return i((()=>t.cast(t.sum(t.logicalAnd(t.equal(e,0),t.equal(n,1))),"float32")))}(e,n),a=t.add(s,r);return t.cast(t.where(t.greater(a,0),t.div(s,a),0),"float32")}))}function No(e,n){return i((()=>{const s=So(e,n),r=function(e,n){return i((()=>t.cast(t.sum(t.logicalAnd(t.equal(e,1),t.equal(n,0))),"float32")))}(e,n),a=t.add(s,r);return t.cast(t.where(t.greater(a,0),t.div(s,a),0),"float32")}))}function Io(t,e){return mo(t,e)}function Ao(e,n){return e.rank===n.rank&&(e=t.squeeze(e,[e.rank-1])),(n=t.argMax(n,-1)).dtype!==e.dtype&&(n=t.cast(n,e.dtype)),t.cast(t.equal(e,n),"float32")}const Co=fo,To=go,zo={binaryAccuracy:ko,categoricalAccuracy:vo,precision:xo,categoricalCrossentropy:Co,sparseCategoricalCrossentropy:To,mse:ho,MSE:ho,mae:co,MAE:co,mape:po,MAPE:po,cosine:yo};function Eo(t){if("string"==typeof t&&t in zo)return zo[t];if("string"!=typeof t&&null!=t)return t;throw new Gi(`Unknown metric ${t}`)}function $o(t){if(Yi(null!==t,`Unknown LossOrMetricFn ${t}`),"string"==typeof t)return t;{let e;for(const n of Object.keys(bo))if(bo[n]===t){e=n;break}if(void 0!==e)return e;for(const n of Object.keys(zo))if(zo[n]===t){e=n;break}return void 0!==e?e:t.name}}function Fo(t,e,n=!1){if(null==t||"object"!=typeof t||Object.getPrototypeOf(t)!==Object.prototype||!Do(t))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(n){const n=JSON.stringify(t);n.length>1048576&&console.warn(`User-defined metadata of model "${e}" is too large in size (length=${n.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= 1048576.`)}}function Do(t){if(null===t)return!0;if("object"==typeof t){if(Object.getPrototypeOf(t)===Object.prototype){const e=Object.keys(t);for(const n of e){if("string"!=typeof n)return!1;if(!Do(t[n]))return!1}return!0}if(Array.isArray(t)){for(const e of t)if(!Do(e))return!1;return!0}return!1}{const e=typeof t;return"string"===e||"number"===e||"boolean"===e}}function Lo(t,e,n,s=console.log){const i=function(t){let e=!0;const n=[],s=[];for(const e in t.nodesByDepth)n.push(t.nodesByDepth[e]);for(const t of n){if(t.length>1||1===t.length&&t[0].inboundLayers.length>1){e=!1;break}s.push(...t)}if(e)for(const n of t.layers){let t=!1;for(const i of n.inboundNodes)if(-1!==s.indexOf(i)){if(t){e=!1;break}t=!0}if(!e)break}return e}(t),r=["Layer (type)","Input Shape","Output shape","Param #"];let a;if(i?(e=e||90,n=n||[.32,.61,.89,1]):(e=e||115,n=n||[.24,.48,.7,.8,1]),n[n.length-1]<=1&&(n=n.map((t=>Math.floor(e*t)))),!i){r.push("Receives inputs"),a=[];for(const e in t.nodesByDepth)a.push(...t.nodesByDepth[e])}s("_".repeat(e)),_o(r,n,s),s("=".repeat(e));const o=t.layers;for(let t=0;t<o.length;++t)i?Ro(o[t],n,s):Mo(o[t],n,a,s),s((t===o.length-1?"=":"_").repeat(e));t.checkTrainableWeightsConsistency();const l=function(t){let e;e=null!=t.collectedTrainableWeights?Oa(t.collectedTrainableWeights):Oa(t.trainableWeights);return e}(t),u=Oa(t.nonTrainableWeights);s(`Total params: ${l+u}`),s(`Trainable params: ${l}`),s(`Non-trainable params: ${u}`),s("_".repeat(e))}function _o(t,e,n=console.log){let s="";for(let n=0;n<t.length;++n)n>0&&(s=s.slice(0,s.length-1)+" "),s+=t[n],s=s.slice(0,e[n]),s+=" ".repeat(e[n]-s.length);n(s)}function Ro(t,e,n){let s,i;try{i=t.inboundNodes.map((t=>JSON.stringify(t.inputShapes))).join(",")}catch(t){i="multiple"}try{s=JSON.stringify(t.outputShape)}catch(t){s="multiple"}_o([`${t.name} (${t.getClassName()})`,i,s,t.countParams().toString()],e,n)}function Mo(t,e,n,s){let i,r;try{r=t.inboundNodes.map((t=>JSON.stringify(t.inputShapes))).join(",")}catch(t){r="multiple"}try{i=JSON.stringify(t.outputShape)}catch(t){i="multiple"}const a=[];for(const e of t.inboundNodes)if(!(null!=n&&n.length>0&&-1===n.indexOf(e)))for(let t=0;t<e.inboundLayers.length;++t){const n=e.inboundLayers[t].name,s=e.nodeIndices[t],i=e.tensorIndices[t];a.push(`${n}[${s}][${i}]`)}const o=t.name,l=t.getClassName(),u=0===a.length?"":a[0];_o([`${o} (${l})`,r,i,t.countParams().toString(),u],e,s);for(let t=1;t<a.length;++t)_o(["","","","",a[t]],e,s)}function Oo(t,e,n){return("inboundNodes"===t||"outputLayers"===t||"inputLayers"===t)&&0===e&&"string"==typeof n}function Bo(t,e){if(null===t)return null;if("string"==typeof t)return nr(t);if("number"==typeof t||"boolean"==typeof t)return t;if(t instanceof Array){const n=[],s=t.length;for(let i=0;i<s;++i){const s=t[i];Oo(e,i,s)?n.push(s):n.push(Bo(s,e))}return n}{const e={};for(const n of Object.keys(t)){const s=t[n];if("name"===n&&"string"==typeof s)e[n]=s;else{const t=nr(n);e[t]=Bo(s,t)}}return e}}function Po(t,e){if(null==t)return null;if("string"==typeof t)return er(t);if("number"==typeof t||"boolean"==typeof t)return t;if(t instanceof Array){const n=[],s=t.length;for(let i=0;i<s;++i){const s=t[i];Oo(e,i,s)?n.push(s):n.push(Po(s,e))}return n}{const e={};for(const n of Object.keys(t)){const s=t[n],i=er(n);e[i]="name"!==n&&"className"!==n||"string"!=typeof s?Po(s,n):s}return e}}const Uo="3.14.0";class Wo{constructor(t){if(this.id2Value={},this.id2Mask={},this.name2Id={},t instanceof Wo)for(const e in t.id2Value)this.id2Value[e]=t.id2Value[e],e in t.id2Mask&&(this.id2Mask[e]=t.id2Mask[e]);else{if(null==t)return;for(const e of t)this.add(e.key,e.value)}}add(t,e,n){if(null!=this.id2Value[t.id])throw new Gi(`Duplicate key: name=${t.name}, id=${t.id}`);return this.id2Value[t.id]=function(t,e){if(null==t.dtype||t.dtype===e.dtype)return e;try{return S(e,t.dtype)}catch(n){throw new Gi(`The dtype of the feed (${e.dtype}) can not be cast to the dtype of the key '${t.name}' (${t.dtype}).`)}}(t,e),this.name2Id[t.name]=t.id,null!=n&&(this.id2Mask[t.id]=n),this}addFeed(t){this.add(t.key,t.value)}hasKey(t){return null!=this.id2Value[t.id]}names(){return Object.keys(this.name2Id)}getValue(t){if(t instanceof Va){if(null==this.id2Value[t.id])throw new Gi(`Nonexistent key: ${t.name}`);return this.id2Value[t.id]}{const e=this.name2Id[t];if(null==e)throw new Gi(`Feed dict has no SymbolicTensor name: ${t}`);return this.id2Value[e]}}getMask(t){if(t instanceof Va){if(null==this.id2Value[t.id])throw new Gi(`Nonexistent key: ${t.name}`);return this.id2Mask[t.id]}{const e=this.name2Id[t];if(null==e)throw new Gi(`Feed dict has no SymbolicTensor name: ${t}`);return this.id2Mask[e]}}disposeMasks(){null!=this.id2Mask&&g(this.id2Mask)}}const Vo={},jo={};function qo(t,e,s,i){const r=null!=s&&s.training,a=Array.isArray(t),o=a?t:[t],l=o.map((t=>t.name)),u=[],h=e.names();for(const t of l)-1!==h.indexOf(t)?u.push(e.getValue(t)):u.push(null);null!=i&&(i.maxNumTensors=-1/0,i.minNumTensors=1/0);const c=l.join(",")+"|"+e.names().join(",");let p,d;if(null==Vo[c]){const t=function(t,e){n.assert(null!=t&&t.length>0,(()=>"Expected at least one fetch, got none"));let s=[],i={};if(1===t.length){const n=Go(t[0],e);s=n.sorted,i=n.recipientMap}else{const n=new Set;for(const r of t){const{sorted:t,recipientMap:a}=Go(r,e);for(const e of t)n.has(e.name)||(s.push(e),n.add(e.name));for(const t in a)null==i[t]&&(i[t]=new Set),a[t].forEach((e=>i[t].add(e)))}}return{sorted:s,recipientCounts:Ko(i)}}(o,e);p=t.sorted,d=t.recipientCounts,Vo[c]=p,jo[c]=d}p=Vo[c],d={},r||Object.assign(d,jo[c]);const f=new Wo(e);for(let t=0;t<p.length;++t){if(null!=i){const t=v().numTensors;t>i.maxNumTensors&&(i.maxNumTensors=t),t<i.minNumTensors&&(i.minNumTensors=t)}const n=p[t],a=n.sourceLayer;if(a instanceof Za)continue;const o=[],h=[],c=[];let m=!1;for(const t of n.inputs){const n=f.getValue(t),s=f.getMask(t);o.push(n),h.push(s),null!=s&&(m=!0),r||(d[t.name]--,0!==d[t.name]||e.hasKey(t)||-1!==l.indexOf(t.name)||n.isDisposed||!0===t.sourceLayer.stateful||c.push(n))}m&&((s=s||{}).mask=h[0]);const y=tr(a.apply(o,s));let b=null;a.supportsMasking&&(b=a.computeMask(o,h));const w=Ho(n),k=Array.isArray(w)?w:[w];for(let t=0;t<k.length;++t){f.hasKey(k[t])||f.add(k[t],y[t],Array.isArray(b)?b[0]:b);const e=l.indexOf(k[t].name);-1!==e&&(u[e]=y[t])}r||g(c)}return f.disposeMasks(),a?u:u[0]}function Ko(t){const e={};for(const n in t)e[n]=t[n].size;return e}function Go(t,e){const n=new Set,s=[],i={};for(const t of e.names())n.add(t);const r=[],a=[];for(r.push(t);r.length>0;){const t=r[r.length-1];if(n.has(t.name)){r.pop();continue}const e=a[a.length-1]===r.length-1;if(0===t.inputs.length||e)r.pop(),s.push(t),n.add(t.name),e&&a.pop();else{a.push(r.length-1);for(const e of t.inputs)null==i[e.name]&&(i[e.name]=new Set),i[e.name].add(t.name),n.has(e.name)||r.push(e)}}return{sorted:s,recipientMap:i}}function Ho(t){let e;if(1===t.sourceLayer.inboundNodes.length)e=t.sourceLayer.output;else{let n=null;for(let e=0;e<t.sourceLayer.inboundNodes.length;++e)for(const s of t.sourceLayer.inboundNodes[e].outputTensors)if(s.id===t.id){n=e;break}e=t.sourceLayer.getOutputAt(n)}return e}class Zo extends Ga{constructor(t){if(super({}),this.containerNodes=new Set,this.name=t.name,null==this.name){const t=this.getClassName().toLowerCase();this.name=Da(t)}if(this.supportsMasking=!1,this.trainable_=!0,Array.isArray(t.inputs)?this.inputs=t.inputs.slice():this.inputs=[t.inputs],Array.isArray(t.outputs)?this.outputs=t.outputs.slice():this.outputs=[t.outputs],lr(this.inputs).length!==this.inputs.length)throw new Gi(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map((t=>t.name))}`);lr(this.outputs).length!==this.outputs.length&&console.warn(`The list of outputs passed to the model is redundant. All outputs should only appear once. Found: ${this.outputs.map((t=>t.name))}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(const t of this.outputs){const e=t.sourceLayer,n=t.nodeIndex,s=t.tensorIndex;this.outputLayers.push(e),this.outputLayersNodeIndices.push(n),this.outputLayersTensorIndices.push(s)}for(const t of this.inputs){const e=t.sourceLayer,n=t.nodeIndex,s=t.tensorIndex;Yi(0===n,"input layer has >1 nodes"),Yi(0===s,"input layer has >1 tensors"),this.inputLayers.push(e),this.inputLayersNodeIndices.push(n),this.inputLayersTensorIndices.push(s)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let e=0;e<this.inputLayers.length;e++){const n=this.inputLayers[e];if(!(n instanceof Za))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${t.inputs}. Input ${e} (0-based) originates from layer type ${n.getClassName()}.`);this.inputNames.push(n.name),this.feedInputShapes.push(n.batchInputShape),this.feedInputNames.push(n.name)}for(const t of this.outputLayers)this.outputNames.push(t.name);this.internalInputShapes=this.inputs.map((t=>t.shape)),this.internalOutputShapes=this.outputs.map((t=>t.shape));const e={},n={},s={},i={},r={},a=[],o=(t,e,n,s,i,l)=>{null!=s&&null!=i&&null!=l||(s=t.sourceLayer,i=t.nodeIndex,l=t.tensorIndex);const u=s.inboundNodes[i];if(-1!==n.indexOf(u))throw new Ki(`The tensor ${t.name} at layer "${s.name}" is part of a cycle.`);if(-1!==e.indexOf(u))return;this.containerNodes.add(Zo.nodeKey(s,i)),s.id in r||(r[s.id]=Object.keys(r).length),-1===n.indexOf(u)&&n.push(u);const h=u.inboundLayers.length;for(let t=0;t<h;t++){const s=u.inputTensors[t],i=u.inboundLayers[t],r=u.nodeIndices[t],a=u.tensorIndices[t];o(s,e,n,i,r,a)}for(e.push(u);n.indexOf(u)>=0;)n.splice(n.indexOf(u),1);a.push(u)},l=[],u=[];for(const t of this.outputs)o(t,l,u);const h=a.slice().reverse();for(const t of h){n[t.id]=t,t.id in e||(e[t.id]=0);let r=e[t.id];const a=null==s[t.outboundLayer.id]?0:s[t.outboundLayer.id];r=Math.max(r,a),s[t.outboundLayer.id]=r,i[t.outboundLayer.id]=t.outboundLayer,e[t.id]=r;for(let s=0;s<t.inboundLayers.length;s++){const i=t.inboundLayers[s],a=t.nodeIndices[s],o=i.inboundNodes[a],l=null==e[o.id]?0:e[o.id];e[o.id]=Math.max(r+1,l),n[o.id]=o}}const c={};for(const t in e){const s=e[t];s in c||(c[s]=[]),c[s].push(n[t])}const p={};for(const t in s){const e=s[t];e in p||(p[e]=[]),p[e].push(i[t])}let d=Object.keys(p).map((t=>parseInt(t,10))).sort(or);this.layers=[];for(const t of d){const e=p[t];e.sort(((t,e)=>{const n=r[t.id],s=r[e.id];return n<s?-1:n>s?1:0}));for(const t of e)t instanceof Zo&&this.internalContainerRefs.push(t),this.layers.push(t)}this.layersByDepth=p,d=Object.keys(c).map((t=>parseInt(t,10))).sort(or);const f=this.inputs.slice(),g=[];for(const t of d)for(const e of c[t]){const t=e.outboundLayer;if(null!=t){for(const n of e.inputTensors)if(-1===f.indexOf(n))throw new Ki(`Graph disconnected: cannot obtain value for tensor ${n} at layer "${t.name}". The following previous layers were accessed without issue: ${g}`);for(const t of e.outputTensors)f.push(t);g.push(t.name)}}this.nodesByDepth=c;const m=this.layers.map((t=>t.name));for(const t of m){const e=m.filter((e=>e===t)).length;if(1!==e)throw new Ki(`The name "${t}" is used ${e} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(m))}this.outboundNodes=[],this.inboundNodes=[],new qa({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map((t=>null)),outputMasks:this.outputs.map((t=>null)),inputShapes:this.inputs.map((t=>t.shape)),outputShapes:this.outputs.map((t=>t.shape))}),this.built=!0,this._refCount=1}assertNotDisposed(){if(0===this._refCount)throw new Error(`Container '${this.name}' is already disposed.`)}dispose(){this.assertNotDisposed();const t={refCountAfterDispose:null,numDisposedVariables:0};if(0==--this._refCount){for(const e of this.layers)t.numDisposedVariables+=e.dispose().numDisposedVariables;for(const e of this.internalContainerRefs)t.numDisposedVariables+=e.dispose().numDisposedVariables}return t.refCountAfterDispose=this._refCount,t}get trainable(){return this.trainable_}set trainable(t){this.layers.forEach((e=>{e._trainableWeights.forEach((e=>e.trainable=t))})),this.trainable_=t}get trainableWeights(){if(this._trainableWeights.length>0)throw new Gi("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];let t=[];for(const e of this.layers)t=t.concat(e.trainableWeights);return t}get nonTrainableWeights(){const t=[];for(const e of this.layers)t.push(...e.nonTrainableWeights);if(!this.trainable){const e=[];for(const t of this.layers)e.push(...t.trainableWeights);return e.concat(t)}return t}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(t,e=!0){const n={};let s=0;for(const t of this.layers)for(const e of t.weights){if(null!=n[e.originalName])throw new Gi(`Duplicate weight name: ${e.originalName}`);n[e.originalName]=e,s++}const i=[];for(const s in t){let r=s;if(null==n[s]){const t=s.split("/");r=t.slice(0,-2).concat([t[t.length-1]]).join("/")}if(null!=n[r])i.push([n[r],t[s]]);else if(e)throw new Gi(`Provided weight data has no target variable: ${s}`);delete n[r]}if(e){const t=[];for(const e in n)t.push(e);if(t.length>0)throw new Gi(`${t.length} of ${s} weights are not set: ${t}`)}Ua(i)}updatedConfig(){const t=this.getConfig(),e={};return e.className=this.getClassName(),e.config=t,e.kerasVersion="tfjs-layers 3.14.0",e.backend="TensorFlow.js",e}toJSON(t,e=!0){const n=Po(this.updatedConfig());return e?JSON.stringify(n):n}call(t,e){return i((()=>{t=tr(t);const n=new Wo;for(let e=0;e<this.inputs.length;++e)n.add(this.inputs[e],t[e]);return qo(this.outputs,n,e)}))}computeMask(t,e){return i((()=>{let n;return t=tr(t),n=null==e?Ji(null,t.length):tr(e),this.runInternalGraph(t,n)[1]}))}computeOutputShape(t){const e=_a(t);if(e.length!==this.inputLayers.length)throw new Gi(`Invalid inputShape argument ${t}: model has ${this.inputLayers.length} tensor inputs.`);const n={};for(let t=0;t<e.length;t++){const s=this.inputLayers[t],i=e[t];n[s.name+"_0_0"]=i}const s=Object.keys(this.nodesByDepth).map((t=>parseInt(t,10))).sort(or);if(s.length>1)for(const t of s){const e=this.nodesByDepth[t];for(const t of e){const e=t.outboundLayer;if(-1!==this.inputLayers.map((t=>t.id)).indexOf(e.id))continue;const s=[];for(let e=0;e<t.inboundLayers.length;e++){const i=t.inboundLayers[e],r=t.nodeIndices[e],a=t.tensorIndices[e],o=n[`${i.name}_${r}_${a}`];s.push(o)}const i=_a(e.computeOutputShape(Qi(s))),r=e.inboundNodes.indexOf(t);for(let t=0;t<i.length;t++){n[`${e.name}_${r}_${t}`]=i[t]}}}const i=[],r=[];for(let t=0;t<this.outputLayers.length;t++){const e=this.outputLayers[t],n=this.outputLayersNodeIndices[t],s=this.outputLayersTensorIndices[t],i=`${e.name}_${n}_${s}`;r.push(i)}for(let t=0;t<r.length;t++){const e=r[t];Yi(e in n),i.push(n[e])}return Qi(i)}runInternalGraph(t,e){null==e&&(e=Ji(null,t.length));const n={};for(let s=0;s<this.inputs.length;++s){const i=this.inputs[s],r=t[s],a=e[s];n[i.id]=[r,a]}const s=Object.keys(this.nodesByDepth).map((t=>parseInt(t,10))).sort(or);for(const t of s){const e=this.nodesByDepth[t];for(const t of e){const e=t.outboundLayer,s=t.inputTensors,i=t.outputTensors,r=new Array;for(const t of s)t.id in n&&r.push(n[t.id]);if(r.length===s.length){let s,a,o,l,u={};if(null!=t.callArgs&&(u=t.callArgs),1===r.length){const[t,n]=r[0];null==u.mask&&(u.mask=n),o=tr(e.call(t,u)),l=tr(e.computeMask(t,n)),s=[t],a=[n]}else s=r.map((t=>t[0])),a=r.map((t=>t[1])),null==u.mask&&(u.mask=a),o=tr(e.call(s,u)),l=tr(e.computeMask(s,a));if(e.activityRegularizer)throw new Hi("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let t=0;t<i.length;++t){const e=i[t],s=o[t],r=l[t];n[e.id]=[s,r]}}}}const i=[],r=[],a=[];for(const t of this.outputs){Yi(t.id in n,`Could not compute output ${t.name} : ${t.id}`);const[e,s]=n[t.id];a.push(e.shape),i.push(e),r.push(s)}return[i,r,a]}buildNodeConversionMap(t){const e={};let n;for(const t of this.layers){n=t instanceof Zo?1:0;for(let s=0;s<t.inboundNodes.length;s++){const i=Zo.nodeKey(t,s);this.containerNodes.has(i)&&(e[i]=n,n+=1)}}return e}getLayer(t,e){if(null!=e){if(this.layers.length<=e)throw new Gi(`Was asked to retrieve layer at index ${e}, but model only has ${this.layers.length} layer(s).`);return this.layers[e]}if(null==t)throw new Gi("Provide either a layer name or layer index");for(const e of this.layers)if(e.name===t)return e;throw new Gi(`No such layer: ${t}`)}calculateLosses(){return i((()=>{const t=[];for(const e of this.layers)for(let n=0;n<e.inboundNodes.length;++n){const s=Zo.nodeKey(e,n);this.containerNodes.has(s)&&t.push(...e.calculateLosses())}return t}))}getConfig(){const t={name:this.name},e=this.buildNodeConversionMap(this.layers),n=[];for(const t of this.layers){const s=t.getClassName(),i=t.getConfig(),r=[];for(let n=0;n<t.inboundNodes.length;n++){const s=t.inboundNodes[n],i=Zo.nodeKey(t,n);let a={};if(this.containerNodes.has(i)){if(s.callArgs)try{JSON.stringify(s.callArgs),a=s.callArgs}catch(e){console.warn(`Layer ${t.name} was passed non-serializable keyword arguments: ${s.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`),a={}}if(s.inboundLayers.length>0){const t=[];for(let n=0;n<s.inboundLayers.length;n++){const i=s.inboundLayers[n],r=s.nodeIndices[n],o=s.tensorIndices[n];let l=e[Zo.nodeKey(i,r)];null==l&&(l=0),t.push([i.name,l,o,a])}r.push(t)}}}const a={};a.name=t.name,a.className=s,a.config=i,a.inboundNodes=r,n.push(a)}t.layers=n;const s=[];for(let t=0;t<this.inputLayers.length;t++){const n=this.inputLayers[t],i=this.inputLayersNodeIndices[t],r=Zo.nodeKey(n,i);if(!this.containerNodes.has(r))continue;let a=e[r];null==a&&(a=0);const o=this.inputLayersTensorIndices[t];s.push([n.name,a,o])}t.inputLayers=s;const i=[];for(let t=0;t<this.outputLayers.length;t++){const n=this.outputLayers[t],s=this.outputLayersNodeIndices[t],r=Zo.nodeKey(n,s);if(!this.containerNodes.has(r))continue;let a=e[r];null==a&&(a=0);const o=this.outputLayersTensorIndices[t];i.push([n.name,a,o])}return t.outputLayers=i,t}static fromConfig(t,e,n={},s=!1){const i={},r={};function a(t,e){t.name in r?r[t.name].push(e):r[t.name]=[e]}function o(t,e){const n=[];let s;for(const r of e){const o=r[0],l=r[1],u=r[2];if(s=null==r[3]?{}:r[3],!(o in i))return void a(t,e);const h=i[o];if(h.inboundNodes.length<=l)return void a(t,e);const c=h.inboundNodes[l];n.push(c.outputTensors[u])}n.length>0&&t.apply(Qi(n),s)}function l(t){const n=t.name,r=lo(t,null!=e.customObjects?e.customObjects:{});r.setFastWeightInitDuringBuild(s),i[n]=r;t.inboundNodes.forEach((t=>{if(!(t instanceof Array))throw new Gi(`Corrupted configuration, expected array for nodeData: ${t}`);a(r,t)}))}const u=e.name,h=e.layers;for(const t of h)l(t);for(;!ur(r);)for(const t of h){const e=i[t.name];if(e.name in r){const t=r[e.name];delete r[e.name];for(const n of t)o(e,n)}}const c=[],p=[],d=e.inputLayers;for(const t of d){const e=t[0],n=t[1],s=t[2];Yi(e in i);const r=i[e].inboundNodes[n].outputTensors;c.push(r[s])}const f=e.outputLayers;for(const t of f){const e=t[0],n=t[1],s=t[2];Yi(e in i);const r=i[e].inboundNodes[n].outputTensors;p.push(r[s])}return new t({inputs:c,outputs:p,name:u})}get stateful(){if(this._stateful)throw new Gi("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(const t of this.layers)if(t.stateful)return!0;return!1}resetStates(){i((()=>{this.layers.forEach((t=>{t.stateful&&t.resetStates()}))}))}}function Jo(t,e){return function(t,e,n){const s=e.length;if(null==t||Array.isArray(t)&&0===t.length)return e.map((t=>null));if(1===s)return Array.isArray(t)&&1===t.length?t:"object"==typeof t&&e[0]in t?[t[e[0]]]:[t];if(Array.isArray(t)){if(t.length!==s)throw new Error(`Provided ${n} is an array of ${t.length} element(s), but the model has ${s} outputs. Make sure a set of weights is provided for each model output.`);return t}if("object"==typeof t&&Object.keys(t).length>0&&"object"==typeof t[Object.keys(t)[0]]){const n=[];return e.forEach((e=>{e in t?n.push(t[e]):n.push(null)})),n}throw new Error(`The model has multiple (${s}) outputs, so ${n} must be either an array with ${s} elements or an object with ${e} keys. Provided ${n} not understood: ${JSON.stringify(t)}`)}(t,e,"classWeight")}async function Yo(t,e,n,s){if(null!=e||null!=s)throw new Error("Support sampleWeight is not implemented yet");if(null!=n){const e=i((()=>{if(1===t.shape.length)return x(t);if(2===t.shape.length){if(t.shape[1]>1){return N(t,1)}if(1===t.shape[1])return I(t,[t.shape[0]]);throw new Error(`Encountered unexpected last-dimension size (${t.shape[1]}) during handling of class weights. The size is expected to be >= 1.`)}throw new Error(`Unexpected rank of target (y) tensor (${t.rank}) during handling of class weights. The rank is expected to be 1 or 2.`)})),s=Array.from(await e.data());g(e);const a=[];return s.forEach((t=>{if(null==n[t])throw new Error(`classWeight must contain all classes in the training data. The class ${t} exists in the data but not in classWeight`);a.push(n[t])})),r(a,"float32")}return null}function Xo(t,e){return l(t,e)}function Qo(e,n){let s,i;const r=n;s=r.xs,i=r.ys,t.util.assert(null!=s&&null!=i,(()=>`A Dataset iterator for fitDataset() is expected to generate objects of the form \`{xs: xVal, ys: yVal}\`, where the two values may be \`tf.Tensor\`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates ${n}`));const a=tl("input",e.inputNames,s),o=tl("output",e.outputNames,i),l=a[0].shape[0];t.util.assert(a.length===e.inputs.length,(()=>`LayersModel has ${e.inputs.length} inputs, but the dataset provides ${a.length} inputs. (Expected input keys: ${JSON.stringify(e.inputNames)})`)),t.util.assert(o.length===e.outputs.length,(()=>`LayersModel has ${e.outputs.length} outputs, but the dataset provides ${o.length} outputs. (Expected output keys: ${JSON.stringify(e.outputNames)})`));for(let n=0;n<a.length;n++)t.util.assert(a[n].shape[0]===l,(()=>`Batch size mismatch: input ${e.inputNames[n]} has ${a[n].shape[0]}; expected ${l} based on input ${e.inputNames[0]}.`));for(let n=0;n<o.length;n++)t.util.assert(o[n].shape[0]===l,(()=>`Batch size mismatch: output ${e.outputNames[n]} has ${o[n].shape[0]}; expected ${l} based on input ${e.inputNames[0]}.`));return{xs:a,ys:o}}function tl(e,n,s){if(s instanceof t.Tensor)return[s];if(Array.isArray(s))return t.util.assert(s.length===n.length,(()=>`Received an array of ${s.length} Tensors, but expected ${n.length} to match the ${e} keys ${n}.`)),s;{const t=[];for(const i of n){if(null==s[i])throw new Gi(`The feature data generated by the dataset lacks the required ${e} key '${i}'.`);t.push(s[i])}return t}}async function el(e,n,s){const i=null!=s.batchesPerEpoch;if(t.util.assert(null!=e.optimizer,(()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig).")),t.util.assert(null!=s,(()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call.")),t.util.assert(null!=s.epochs&&s.epochs>0&&Number.isInteger(s.epochs),(()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${s.epochs}`)),t.util.assert(!i||s.batchesPerEpoch>0&&Number.isInteger(s.batchesPerEpoch),(()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${s.batchesPerEpoch}`)),t.util.assert(null==s.validationSplit,(()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead.")),e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;try{const r=null!=s.validationData;let a,o;if(r)if(nl(s.validationData))t.util.assert(null==s.validationBatches||s.validationBatches>0&&Number.isInteger(s.validationBatches),(()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${s.validationBatches}`));else{const t=function(t){if(3===t.length)throw new Hi("Validation with sample weights is not implemented yet.");return{xs:t[0],ys:t[1]}}(s.validationData);a=t.xs,o=t.ys}const l=e.makeTrainFunction(),u=e.getDedupedMetricsNames();let h;h=r?u.slice().concat(u.map((t=>"val_"+t))):u.slice();const c=ro(s.callbacks,s.yieldEvery),p=null==s.verbose?1:s.verbose,{callbackList:d,history:f}=oo(c,p,s.epochs,null,null,function(t,e){let n=null;null!=e.batchesPerEpoch?n=e.batchesPerEpoch:Number.isFinite(t.size)&&(n=t.size);return n}(n,s),null,r,h);d.setModel(e),e.history=f,await d.onTrainBegin(),e.stopTraining_=!1;let g=null==s.initialEpoch?0:s.initialEpoch,m=await n.iterator();for(;g<s.epochs;){const h={};await d.onEpochBegin(g);let c=0,p=0;for(i||(m=await n.iterator());!i||c<s.batchesPerEpoch;){const n=await m.next();if(i&&n.done){console.warn(`You provided \`batchesPerEpoch\` as ${s.batchesPerEpoch}, but your dataset iterator ran out of data after ${c} batches; interrupting training. Make sure that your dataset can generate at least \`batchesPerEpoch * epochs\` batches (in this case, `+s.batchesPerEpoch*s.epochs+" batches). You may need to use the repeat() function when building your dataset.");break}if(null!=n.value){const{xs:i,ys:r}=Qo(e,n.value),a={};a.batch=p,a.size=i[0].shape[0],await d.onBatchBegin(p,a);const o=[];if(null!=s.classWeight){const t=Jo(s.classWeight,e.outputNames);for(let e=0;e<t.length;++e)o.push(await Yo(r[e],null,t[e]))}const h=i.concat(r).concat(o),f=l(h);t.dispose(h);for(let e=0;e<u.length;++e){const n=u[e],s=f[e];a[n]=s,t.keep(s)}await d.onBatchEnd(p,a),Xa(a),p++,c++}if(i?c>=s.batchesPerEpoch:n.done){if(r){let t;t=nl(s.validationData)?tr(await e.evaluateDataset(s.validationData,{batches:s.validationBatches})):tr(e.evaluate(a,o,{batchSize:null==s.validationBatchSize?32:s.validationBatchSize,verbose:0}));for(let n=0;n<e.metricsNames.length;++n)h[`val_${e.metricsNames[n]}`]=t[n]}break}if(e.stopTraining_)break}if(await d.onEpochEnd(g,h),g++,e.stopTraining_)break}return await d.onTrainEnd(),await e.history.syncData(),e.history}finally{e.isTraining=!1}}function nl(t){return"function"==typeof t.iterator}function sl(e){t.util.assert(e>0&&Number.isInteger(e),(()=>`batchSize is required to be a positive integer, but got ${e}`))}function il(t,e,n){return null==t?[null]:Array.isArray(t)?t.map((t=>Gr(t,e,n-e))):Gr(t,e,n-e)}function rl(e,n){return t.tidy((()=>null==e?null:Array.isArray(e)?e.map((t=>rl(t,n))):ea(e,"int32"===n.dtype?n:t.cast(n,"int32"))))}function al(t,e){const n=[];let s=0,i=null;for(;s<t;)i=s+e,i>=t&&(i=t),n.push([s,i]),s=i;return n}async function ol(e,s,i,a={}){if(e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");let o,l,u,h,c,p,d,f,g;e.isTraining=!0;try{const m=null==a.batchSize?32:a.batchSize;sl(m);const y=!1,b=await e.standardizeUserData(s,i,a.sampleWeight,a.classWeight,y,m);o=b[0],l=b[1],g=b[2];let w,k=!1;if(null!=a.validationData&&a.validationData.length>0){if(k=!0,2!==a.validationData.length)throw 3===a.validationData.length?new Hi("validationData including sample weights is not supported yet."):new Gi(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${a.validationData} is invalid.`);c=a.validationData[0],p=a.validationData[1];const t=!0,n=await e.standardizeUserData(c,p,null,null,t,m);d=n[0],f=n[1],w=d.concat(f)}else if(null!=a.validationSplit&&a.validationSplit>0&&a.validationSplit<1){k=!0;const t=Math.floor(o[0].shape[0]*(1-a.validationSplit)),e=o[0].shape[0];d=il(o,t,e),u=o,o=il(o,0,t),f=il(l,t,e),h=l,l=il(l,0,t),w=d.concat(f)}else null!=a.validationSteps&&(k=!0);const v=o.concat(l).concat(g);e.checkTrainableWeightsConsistency();const S=e.makeTrainFunction(),x=e.getDedupedMetricsNames();let N,I;k?(e.makeTestFunction(),N=e.testFunction,I=x.slice().concat(x.map((t=>"val_"+t)))):(N=null,w=[],I=x.slice());const A=ro(a.callbacks,a.yieldEvery);return await async function(e,s,i,a,o,l,u,h,c,p,d,f,g,m,y){null==o&&(o=32),null==l&&(l=1),null==d&&(d=!0),null==g&&(g=0);let b=!1;if(null!=c&&null!=p&&(b=!0),null!=y&&(b=!0,null==m))throw new Gi("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");const w=e.checkNumSamples(i,o,m,"steps_per_epoch");let k;null!=w&&(k=jr(0,w)),null==u&&(u=1);const{callbackList:v,history:S}=oo(h,u,l,g,w,m,o,b,f);v.setModel(e),e.history=S,await v.onTrainBegin(),e.stopTraining_=!1;for(let u=g;u<l;++u){await v.onEpochBegin(u);const l={};if(null!=m)throw new Hi("stepsPerEpoch mode is not implemented yet.");{if("batch"===d)throw new Hi("batch shuffling is not implemneted yet");d&&n.shuffle(k);const u=r(k),h=al(w,o);for(let n=0;n<h.length;++n){const r={};if(await v.onBatchBegin(n,r),t.tidy((()=>{const d=h[n][0],f=h[n][1],g=Gr(u,d,f-d);r.batch=n,r.size=f-d;const m=rl(i,g),y=s(m);for(let e=0;e<a.length;++e){const n=a[e],s=y[e];r[n]=s,t.keep(s)}if(n===h.length-1&&b){const n=e.testLoop(c,p,o);for(let e=0;e<a.length;++e){const s=a[e],i=n[e];t.keep(i),l["val_"+s]=i}}})),await v.onBatchEnd(n,r),Xa(r),e.stopTraining_)break}u.dispose()}if(await v.onEpochEnd(u,l),e.stopTraining_)break}return await v.onTrainEnd(),await e.history.syncData(),e.history}(e,S,v,x,m,a.epochs,a.verbose,A,N,w,a.shuffle,I,a.initialEpoch,null,null)}finally{e.isTraining=!1,ul(o,s),ul(l,i),ul(u,s),ul(h,i),ul(d,c),ul(f,p),null!=g&&t.dispose(g)}}function ll(t){const e=[];t instanceof A&&(t=[t]);for(let n=0;n<t.length;++n){const s=t[n];if(1===s.rank)e.push(Kr(s,1));else{if(0===s.rank)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");e.push(s)}}return e}function ul(t,e){if(null==t)return;const n=[];if(e instanceof A)n.push(e.id);else if(Array.isArray(e))e.forEach((t=>n.push(t.id)));else if(null!=e)for(const t in e){const s=e[t];n.push(s.id)}const s=[];if(t instanceof A)-1===n.indexOf(t.id)&&s.push(t);else if(Array.isArray(t))t.forEach((t=>{-1===n.indexOf(t.id)&&s.push(t)}));else if(null!=t)for(const e in t){const i=t[e];-1===n.indexOf(i.id)&&s.push(i)}s.forEach((t=>{t.isDisposed||t.dispose()}))}function hl(t){return Array.isArray(t)}function cl(t){return!function(t){return t instanceof A}(t)&&!hl(t)}function pl(t,e,n,s=!0,i=""){if(null==e||0===e.length){if(null!=t){let e=!1;if(hl(t)&&t.length>0)e=!0;else if(cl(t)){for(const n in t)if(t.hasOwnProperty(n)){e=!0;break}}else e=!0;if(e)throw new Gi(`Error when checking model ${i} expected no data, but got ${t}`)}return[]}if(null==t)return e.map((t=>null));let r;if(cl(t)){t=t,r=[];for(const n of e){if(null==t[n])throw new Gi(`No data provided for "${n}". Need data for each key in: ${e}`);r.push(t[n])}}else if(hl(t)){if((t=t).length!==e.length)throw new Gi(`Error when checking model ${i}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${e.length} Tensor(s), but instead got the following list of Tensor(s): ${t}`);r=t}else{if(t=t,e.length>1)throw new Gi(`The model ${i} expects ${e.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${t.shape}`);r=[t]}if(r=ll(r),null!=n)for(let t=0;t<e.length;++t){if(null==n[t])continue;const a=r[t];if(a.shape.length!==n[t].length)throw new Gi(`Error when checking ${i}: expected ${e[t]} to have ${n[t].length} dimension(s). but got array with shape ${a.shape}`);for(let e=0;e<n[t].length;++e){if(0===e&&!s)continue;const r=a.shape[e],o=n[t][e];if(null!=o&&o>=0&&r!==o)throw new Gi(`${i} expected a batch of elements where each example has shape [${n[t].slice(1,n[t].length)}] (i.e.,tensor shape [*,${n[t].slice(1,n[t].length)}]) but the ${i} received an input with ${a.shape[0]} examples, each with shape [${a.shape.slice(1,a.shape.length)}] (tensor shape [${a.shape}])`)}}return r}function dl(t,e,n,s=!0,i=""){let r;if(Array.isArray(t)){if(t.length!==e.length)throw new Gi(`Error when checking model ${i}: the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see ${e.length} Tensor(s), but instead got ${t.length} Tensors(s).`);r=t}else{if(e.length>1)throw new Gi(`The model expects ${e.length} ${i} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(t.shape)}.`);r=[t]}if(null!=n)for(let t=0;t<e.length;++t){if(null==n[t])continue;const a=r[t];if(a.shape.length!==n[t].length)throw new Gi(`Error when checking ${i}: expected ${e[t]} to have ${n[t].length} dimension(s), but got array with shape ${JSON.stringify(a.shape)}`);for(let r=0;r<n[t].length;++r){if(0===r&&!s)continue;const o=a.shape[r],l=n[t][r];if(null!=l&&l!==o)throw new Gi(`Error when checking ${i}: expected ${e[t]} to have shape ${JSON.stringify(n[t])} but got array with shape ${JSON.stringify(a.shape)}.`)}}}class fl extends Zo{constructor(t){super(t),this.isTraining=!1}summary(t,e,n=console.log){if(!this.built)throw new Gi("This model has never been called, thus its weights have not been created yet. So no summary can be displayed. Build the model first (e.g., by calling it on some test data).");Lo(this,t,e,n)}compile(t){if(null==t.loss&&(t.loss=[]),this.loss=t.loss,"string"==typeof t.optimizer)this.optimizer_=function(t){const e={Adagrad:()=>k.adagrad(.01),Adadelta:()=>k.adadelta(1,.95,ji()),Adam:()=>k.adam(.001,.9,.999,ji()),Adamax:()=>k.adamax(.002,.9,.999,ji(),0),RMSProp:()=>k.rmsprop(.001,.9,0,ji()),SGD:()=>k.sgd(.01)};if(e.adagrad=e.Adagrad,e.adadelta=e.Adadelta,e.adam=e.Adam,e.adamax=e.Adamax,e.rmsprop=e.RMSProp,e.sgd=e.SGD,t in e)return e[t]();throw new Gi(`Unknown Optimizer ${t}`)}(t.optimizer),this.isOptimizerOwned=!0;else{if(!(t.optimizer instanceof C))throw new Gi("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=t.optimizer,this.isOptimizerOwned=!1}let e=[];if(Array.isArray(t.loss)||"string"==typeof t.loss||"function"==typeof t.loss)if(Array.isArray(t.loss)){if(t.loss.length!==this.outputs.length)throw new Gi(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${t.loss}.`);const n=t.loss;e=n.map((t=>wo(t)))}else{const n=wo(t.loss);this.outputs.forEach((t=>{e.push(n)}))}else{t.loss=t.loss;for(const e in t.loss)if(-1===this.outputNames.indexOf(e))throw new Gi(`Unknown entry in loss dictionary: "${e}". Only expected the following keys: ${this.outputNames}`);for(const n of this.outputNames)null==t.loss[n]&&console.warn(`Output "${n}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${n} during training`),e.push(wo(t.loss[n]))}this.lossFunctions=e,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let t=0;t<this.outputs.length;++t){const e=this.internalOutputShapes[t],n=this.outputNames[t];this.feedOutputNames.push(n),this.feedOutputShapes.push(e),this.feedLossFns.push(this.lossFunctions[t])}const n=[];this.metrics=t.metrics,this.metricsNames=["loss"],this.metricsTensors=[],Rr("loss",(()=>{for(let t=0;t<this.outputs.length;++t){if(-1!==n.indexOf(t))continue;const e=this.lossFunctions[t];this.outputs.length>1&&(this.metricsTensors.push([e,t]),this.metricsNames.push(this.outputNames[t]+"_loss"))}}));const s=function(t,e){if(null==t||Array.isArray(t)&&0===t.length)return e.map((t=>[]));let n;if("string"==typeof t||"function"==typeof t)n=[t];else{if(!Array.isArray(t)&&"object"!=typeof t)throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${t}`);n=t}if(Array.isArray(n))return e.map((t=>n));{const t=[];for(const s of e){let e=n.hasOwnProperty(s)?n[s]:[];Array.isArray(e)||(e=[e]),t.push(e)}return t}}(t.metrics,this.outputNames),i=(t,e,n)=>{this.outputNames.length>1&&(e=this.outputNames[t]+"_"+e),this.metricsNames.push(e),this.metricsTensors.push([n,t])};Rr("metric",(()=>{for(let t=0;t<this.outputs.length;++t){if(-1!==n.indexOf(t))continue;(e=>{let n,s,r;for(const a of e){if("string"==typeof a&&-1!==["accuracy","acc","crossentropy","ce"].indexOf(a)){const e=this.internalOutputShapes[t];let i;1===e[e.length-1]||this.lossFunctions[t]===mo?-1!==["accuracy","acc"].indexOf(a)?s=ko:-1!==["crossentropy","ce"].indexOf(a)&&(s=Io):this.lossFunctions[t]===go?-1!==["accuracy","acc"].indexOf(a)?s=Ao:-1!==["crossentropy","ce"].indexOf(a)&&(s=To):-1!==["accuracy","acc"].indexOf(a)?s=vo:-1!==["crossentropy","ce"].indexOf(a)&&(s=Co),-1!==["accuracy","acc"].indexOf(a)?i="acc":-1!==["crossentropy","ce"].indexOf(a)&&(i="ce"),r=s,n=""+i}else{const t=Eo(a);r=t,n=""+$o(a)}let e;Rr(n,(()=>{e=r})),i(t,n,e)}})(s[t])}})),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){null!=this.collectedTrainableWeights&&this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?")}evaluate(t,e,n={}){const s=null==n.batchSize?32:n.batchSize;sl(s);const i=this.standardizeUserDataXY(t,e,!0,s);try{const r=i[0].concat(i[1]);this.makeTestFunction();const a=this.testFunction;return Qi(this.testLoop(a,r,s,n.verbose,n.steps))}finally{ul(i[0],t),ul(i[1],e)}}async evaluateDataset(e,n){return this.makeTestFunction(),async function(e,n,s){const i=null!=(s=s||{}).batches,r=e.testFunction;let a=[];if(s.verbose>0)throw new Hi("Verbose mode is not implemented yet.");t.util.assert(!i||s.batches>0&&Number.isInteger(s.batches),(()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(s.batches)}`));const o="function"==typeof n.next?n:await n.iterator();let l=0,h=0;for(;!i||h<s.batches;){const n=await o.next();if(a=t.tidy((()=>{if(n.value){const{xs:s,ys:i}=Qo(e,n.value),o=s.concat(i),c=t.tidy((()=>r(o)));if(t.dispose(o),0===h)for(let t=0;t<c.length;++t)a.push(u(0));const p=o[0].shape[0];for(let e=0;e<c.length;++e){const n=c[e],s=a[e];a[e]=t.tidy((()=>t.add(a[e],t.mul(p,n)))),h>0&&t.dispose(s)}t.dispose(c),l+=p,++h}return a})),n.done){i&&console.warn(`Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least \`batches\` batches (in this case, ${s.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let e=0;e<a.length;++e){const n=a[e];a[e]=t.div(a[e],l),t.dispose(n)}return Qi(a)}(this,e,n)}checkNumSamples(t,e,n,s="steps"){let i;if(null!=n){if(i=null,null!=e)throw new Gi(`If ${s} is set, batchSize must be null or undefined.Got batchSize = ${e}`)}else{if(null==t)throw new Gi(`Either the input data should have a defined shape, or ${s} shoud be specified.`);i=Array.isArray(t)?t[0].shape[0]:t.shape[0]}return i}execute(t,e){if(Array.isArray(e)&&0===e.length)throw new Gi("`outputs` is an empty Array, which is not allowed.");const n=Array.isArray(e),s=n?e:[e],i=this.retrieveSymbolicTensors(s),r=new Wo;if(t instanceof A&&(t=[t]),Array.isArray(t)){if(t.length!==this.inputs.length)throw new Gi(`The number of inputs provided (${t.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let e=0;e<this.inputs.length;++e)r.add(this.inputs[e],t[e])}else for(const e of this.inputs){const n=t[e.name];if(null==n)throw new Gi(`No value is provided for the model's input ${e.name}`);r.add(e,n)}const a=qo(i,r);return n?a:a[0]}retrieveSymbolicTensors(t){const e=Ji(null,t.length);let n=t.length;for(const s of this.layers){const i=Array.isArray(s.output)?s.output:[s.output],r=i.map((t=>t.name));for(let s=0;s<t.length;++s){const a=r.indexOf(t[s]);if(-1!==a&&(e[s]=i[a],n--),0===n)break}if(0===n)break}if(n>0){const n=[];throw e.forEach(((e,s)=>{null==e&&n.push(t[s])})),new Gi(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(n)}`)}return e}predictLoop(e,n=32,s=!1){return t.tidy((()=>{const i=this.checkNumSamples(e);if(s)throw new Hi("Verbose predictLoop() is not implemented yet.");const r=al(i,n),a=this.outputs.map((t=>[]));for(let n=0;n<r.length;++n){t.tidy((()=>{const t=r[n][0],s=r[n][1],i=il(e,t,s),a=[];if(Array.isArray(i))for(let t=0;t<i.length;++t)a.push({key:this.inputs[t],value:i[t]});else a.push({key:this.inputs[0],value:i});const o=new Wo(a);return qo(this.outputs,o)})).forEach(((t,e)=>a[e].push(t)))}return Qi(a.map((e=>t.concat(e,0))))}))}predict(t,e={}){const n=ll(t);dl(n,this.inputNames,this.feedInputShapes,!1);try{const s=null==e.batchSize?32:e.batchSize;return sl(s),this.predictLoop(n,s)}finally{ul(n,t)}}predictOnBatch(t){dl(t,this.inputNames,this.feedInputShapes,!0);const e=(Array.isArray(t)?t[0]:t).shape[0];return this.predictLoop(t,e)}standardizeUserDataXY(t,e,s=!0,i){if(null==this.optimizer_)throw new Ki("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");const r=[];for(let t=0;t<this.feedOutputShapes.length;++t){const e=this.feedOutputShapes[t];this.feedLossFns[t]===go?r.push(e.slice(0,e.length-1).concat([1])):r.push(e)}if(function(t,e,s){const i=lr(t.map((t=>t.shape[0])));i.sort();const r=lr(e.map((t=>t.shape[0])));if(r.sort(),i.length>1)throw new Gi(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map((t=>t.shape)))}`);if(r.length>1)throw new Gi(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map((t=>t.shape)))}`);if(i.length>0&&r.length>0&&!n.arraysEqual(i,r))throw new Gi(`Input Tensors should have the same number of samples as target Tensors. Found ${i[0]} input sample(s) and ${r[0]} target sample(s).`)}(t=pl(t,this.feedInputNames,this.feedInputShapes,!1,"input"),e=pl(e,this.feedOutputNames,r,!1,"target")),function(t,e,n){const s=[ho,mo,fo];for(let i=0;i<t.length;++i){const r=t[i],a=e[i],o=n[i];if(null!=a){if(a===fo&&1===r.shape[r.shape.length-1])throw new Gi(`You are passing a target array of shape ${r.shape} while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].`);if(-1!==s.indexOf(a)){const t=r.shape.slice(1),e=o.slice(1);for(let n=0;n<t.length;++n){const s=t[n],i=e[n];if(null!=i&&s!==i)throw new Gi(`A target Tensor with shape ${r.shape} was passed for an output of shape ${o}, while using a loss function that expects targets to have the same shape as the output.`)}}}}}(e,this.feedLossFns,this.feedOutputShapes),this.stateful&&null!=i&&i>0&&t[0].shape[0]%i!=0)throw new Gi(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${i}. Found: ${t[0].shape[0]} sample(s).`);return[t,e]}async standardizeUserData(t,e,n,s,i=!0,r){const[a,o]=this.standardizeUserDataXY(t,e,i,r);if(null!=n)throw new Error("sample weight is not supported yet.");let l=null;if(null!=s){const t=Jo(s,this.outputNames);l=[];for(let e=0;e<t.length;++e)l.push(await Yo(o[e],null,t[e]))}return[a,o,l]}testLoop(e,n,s,i=0,a){return t.tidy((()=>{const o=this.checkNumSamples(n,s,a,"steps"),l=[];if(i>0)throw new Hi("Verbose mode is not implemented yet.");if(null!=a)throw new Hi("steps mode in testLoop() is not implemented yet");{const i=al(o,s),a=r(jr(0,o));for(let s=0;s<i.length;++s){const r=i[s][0],o=i[s][1],h=Gr(a,r,o-r),c=rl(n,h),p=e(c);if(0===s)for(let t=0;t<p.length;++t)l.push(u(0));for(let e=0;e<p.length;++e){const n=p[e];l[e]=t.add(l[e],t.mul(o-r,n))}}for(let e=0;e<l.length;++e)l[e]=t.div(l[e],o)}return l}))}getDedupedMetricsNames(){const t=this.metricsNames,e=[];for(let n=0;n<t.length;++n){const s=t[n];let i=s;if(Xi(t,s)>1){i+=`_${Xi(t.slice(0,n),s)}`}e.push(i)}return e}makeTrainFunction(){return e=>{const n=[],s=e.slice(0,this.inputs.length),i=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),r=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+2*this.outputs.length),a=[],o=this.collectedTrainableWeights.map((t=>t.read()));return[this.optimizer_.minimize((()=>{const e=[];for(let t=0;t<this.inputs.length;++t)e.push({key:this.inputs[t],value:s[t]});const o=new Wo(e),l=qo(this.outputs,o,{training:!0});let u;for(let e=0;e<this.lossFunctions.length;++e){let s=(0,this.lossFunctions[e])(i[e],l[e]);null!=r[e]&&(s=Xo(s,r[e]));const a=t.mean(s);n.push(a),u=0===e?s:t.add(u,s)}for(let e=0;e<this.metricsTensors.length;++e){let s;if(this.outputs.length>1&&e<this.outputs.length)s=n[e];else{const n=this.metricsTensors[e][0],r=this.metricsTensors[e][1];s=t.mean(n(i[r],l[r]))}t.keep(s),a.push(s)}return u=t.mean(u),this.calculateLosses().forEach((e=>{u=t.add(u,e)})),u}),!0,o)].concat(a)}}makeTestFunction(){this.testFunction=e=>t.tidy((()=>{const n=[];let s;const i=e.slice(0,this.inputs.length),r=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),a=[];for(let t=0;t<this.inputs.length;++t)a.push({key:this.inputs[t],value:i[t]});const o=new Wo(a),l=qo(this.outputs,o);for(let e=0;e<this.lossFunctions.length;++e){const i=this.lossFunctions[e],a=t.mean(i(r[e],l[e]));s=0===e?a:t.add(s,a),n.push(s)}for(let e=0;e<this.metricsTensors.length;++e){const s=this.metricsTensors[e][0],i=this.metricsTensors[e][1],a=t.mean(s(r[i],l[i]));n.push(a)}return n}))}async fit(t,e,n={}){return ol(this,t,e,n)}async fitDataset(t,e){return el(this,t,e)}async trainOnBatch(e,n){const s=await this.standardizeUserData(e,n),i=s[0],r=s[1],a=this.makeTrainFunction()(i.concat(r)),o=[];for(const t of a){const e=await t.data();o.push(e[0])}return t.dispose(a),ul(s[0],e),ul(s[1],n),Qi(o)}getNamedWeights(t){const e=[],n=null!=t&&t.trainableOnly,s=n?this.trainableWeights:this.weights,i=this.getWeights(n);for(let t=0;t<s.length;++t)n&&!s[t].trainable||e.push({name:s[t].originalName,tensor:i[t]});return e}set stopTraining(t){this.stopTraining_=t}get stopTraining(){return this.stopTraining_}get optimizer(){return this.optimizer_}set optimizer(t){this.optimizer_!==t&&(this.optimizer_=t,this.isOptimizerOwned=!1)}dispose(){const e=super.dispose();if(0===e.refCountAfterDispose&&null!=this.optimizer&&this.isOptimizerOwned){const n=t.memory().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=n-t.memory().numTensors}return e}getLossIdentifiers(){let t;if("string"==typeof this.loss)t=er(this.loss);else if(Array.isArray(this.loss)){for(const t of this.loss)if("string"!=typeof t)throw new Error("Serialization of non-string loss is not supported.");t=this.loss.map((t=>er(t)))}else{const e=Object.keys(this.loss);t={};const n=this.loss;for(const s of e){if("string"!=typeof n[s])throw new Error("Serialization of non-string loss is not supported.");t[s]=er(n[s])}}return t}getMetricIdentifiers(){if("string"==typeof this.metrics||"function"==typeof this.metrics)return[er($o(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map((t=>er($o(t))));{const t={};for(const e in this.metrics)t[e]=er($o(this.metrics[e]));return t}}getTrainingConfig(){return{loss:this.getLossIdentifiers(),metrics:this.getMetricIdentifiers(),optimizer_config:{class_name:this.optimizer.getClassName(),config:this.optimizer.getConfig()}}}loadTrainingConfig(t){if(null!=t.weighted_metrics)throw new Error("Loading weight_metrics is not supported yet.");if(null!=t.loss_weights)throw new Error("Loading loss_weights is not supported yet.");if(null!=t.sample_weight_mode)throw new Error("Loading sample_weight_mode is not supported yet.");const e=lo(Bo(t.optimizer_config));let n,s;if("string"==typeof t.loss)n=nr(t.loss);else if(Array.isArray(t.loss))n=t.loss.map((t=>nr(t)));else if(null!=t.loss){n={};for(const e in t.loss)n[e]=nr(t.loss[e])}if(Array.isArray(t.metrics))s=t.metrics.map((t=>nr(t)));else if(null!=t.metrics){s={};for(const e in t.metrics)s[e]=nr(t.metrics[e])}this.compile({loss:n,metrics:s,optimizer:e})}async save(t,e){if("string"==typeof t){const e=T.getSaveHandlers(t);if(0===e.length)throw new Gi(`Cannot find any save handlers for URL '${t}'`);if(e.length>1)throw new Gi(`Found more than one (${e.length}) save handlers for URL '${t}'`);t=e[0]}if(null==t.save)throw new Gi("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");const n=await T.encodeWeights(this.getNamedWeights(e)),s={modelTopology:this.toJSON(null,!1),format:"layers-model",generatedBy:"TensorFlow.js tfjs-layers v3.14.0",convertedBy:null};if(null!=e&&e.includeOptimizer&&null!=this.optimizer){s.trainingConfig=this.getTrainingConfig();const t="optimizer",{data:e,specs:i}=await T.encodeWeights(await this.optimizer.getWeights(),t);n.specs.push(...i),n.data=T.concatenateArrayBuffers([n.data,e])}if(null!=this.userDefinedMetadata){const t=!0;Fo(this.userDefinedMetadata,this.name,t),s.userDefinedMetadata=this.userDefinedMetadata}return s.weightData=n.data,s.weightSpecs=n.specs,t.save(s)}setUserDefinedMetadata(t){Fo(t,this.name),this.userDefinedMetadata=t}getUserDefinedMetadata(){return this.userDefinedMetadata}}fl.className="Model",s.registerClass(fl);class gl extends fl{}async function ml(t,e){if(null==e&&(e={}),"string"==typeof t){const n=T.getLoadHandlers(t,e);if(0===n.length)n.push(T.browserHTTPRequest(t,e));else if(n.length>1)throw new Gi(`Found more than one (${n.length}) load handlers for URL '${t}'`);t=n[0]}return async function(t,e,n){null==n&&(n={});if(null==t.load)throw new Gi("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");const s=await t.load();let i=s.modelTopology;null!=i.model_config&&(i=i.model_config);const r=null==n.strict||n.strict,a=null!=s.weightData&&null!=s.weightSpecs&&r,o=lo(Bo(i),e,a),l=s.trainingConfig;null!=l&&o.loadTrainingConfig(l);null!=s.userDefinedMetadata&&o.setUserDefinedMetadata(s.userDefinedMetadata);if(null!=s.weightData){if(null==s.weightSpecs)throw new Gi("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");const{modelWeights:t,optimizerWeights:e}=function(t,e){const n=T.decodeWeights(t,e),s={},i=[];return e.forEach((t=>{"optimizer"===t.group?i.push({name:t.name,tensor:n[t.name]}):s[t.name]=n[t.name]})),{modelWeights:s,optimizerWeights:i}}(s.weightData,s.weightSpecs);o.loadWeights(t,r),null!=o.optimizer&&e.length>0&&await o.optimizer.setWeights(e),g(t),g(e.map((t=>t.tensor)))}return o}(t,void 0,e)}gl.className="Functional",s.registerClass(gl);class yl extends fl{constructor(t){if(super({inputs:[],outputs:[]}),t=t||{},this.trainable=!0,this.built=!1,this.name=null!=t.name?t.name:Da("sequential_"),null!=t.layers)for(const e of t.layers)this.add(e)}checkShape(t){if(t.inboundNodes[0].outputTensors[0].shape.some((t=>t<0)))throw new Gi(`Negative dimension size caused by adding layer ${t.name} with input shape [${t.inboundNodes[0].inputTensors[0].shape}]`)}add(t){const e=t instanceof yl||t instanceof fl;let n;if(e){if(n=t,1!==n.outputs.length)throw new Gi("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(1!==n.inputs.length)throw new Gi("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(0===this.outputs.length){if(0===t.inboundNodes.length){if(null==t.batchInputShape)throw new Gi("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");const e=Ja({batchShape:t.batchInputShape,dtype:t.dtype,name:t.name+"_input"});t.apply(e)}if(e)this.outputs=n.outputs,this.inputs=n.inputs;else{if(1!==t.inboundNodes.length)throw new Gi(`A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer ${t.name} which has ${t.inboundNodes.length} pre-existing inbound connections.`);if(1!==t.inboundNodes[0].outputTensors.length)throw new Gi("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(t),this.outputs=[t.inboundNodes[0].outputTensors[0]],this.inputs=Ha(this.outputs[0])}this.inboundNodes=[],new qa({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:Ji(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map((t=>t.shape)),outputShapes:this.outputs[0].shape})}else{const e=t.apply(this.outputs[0]);if(Array.isArray(e))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(t),this.outputs=[e],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(t),this.built=!1}pop(){if(0===this.layers.length)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),0===this.layers.length)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{const t=this.layers.length-1;this.layers[t].outboundNodes=[],this.outputs=[this.layers[t].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(t,e){return null==this.model&&this.build(),this.model.call(t,e)}build(t){if(Ma(t),0===this.inputs.length||0===this.outputs.length)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new fl({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0}countParams(){return this.built||this.build(),super.countParams()}summary(t,e,n=console.log){this.built||this.build(),super.summary(t,e,n)}setWeights(t){null==this.model&&this.build(),this.model.setWeights(t)}evaluate(t,e,n={}){if(!this.built)throw new Ki("The model needs to be compiled before being used.");return this.model.evaluate(t,e,n)}async evaluateDataset(t,e){if(!this.built)throw new Ki("The model needs to be compiled before being used.");return this.model.evaluateDataset(t,e)}predict(t,e={}){return null==this.model&&this.build(),this.model.predict(t,e)}predictOnBatch(t){return null==this.model&&this.build(),this.model.predictOnBatch(t)}compile(t){this.build(),this.model.compile(t),this.optimizer_=this.model.optimizer,this.isOptimizerOwned=this.model.isOptimizerOwned,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames}get optimizer(){return null==this.model?void 0:this.model.optimizer}set optimizer(t){this.model.optimizer=t}async fit(t,e,n={}){if(!this.built)throw new Ki("The model needs to be compiled before being used.");return this.model.fit(t,e,n)}async fitDataset(t,e){if(!this.built)throw new Ki("The model needs to be compiled before being used.");return this.model.fitDataset(t,e)}async trainOnBatch(t,e){return this.model.trainOnBatch(t,e)}static fromConfig(t,e,s={},i=!1){let r,a={};if(e instanceof Array){if(null==e[0].className||"Merge"===e[0].className)throw new Gi("Legacy serialization format not supported yet.");r=e}else n.assert(null!=e.layers,(()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field.")),r=e.layers,delete e.layers,a=e;const o=new t(a);if(!(o instanceof yl))throw new Hi(`Sequential.fromConfig called on non-Sequential input: ${o}`);for(const t of r){const e=lo(t,void 0,i);i&&e.setFastWeightInitDuringBuild(!0),o.add(e)}return o}set stopTraining(t){if(null==this.model)throw new Gi("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=t}get stopTraining(){if(null==this.model)throw new Gi("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){const t=[];for(const e of this.layers){const n={};n.className=e.getClassName(),n.config=e.getConfig(),t.push(n)}return{name:this.name,layers:t}}}function bl(t){return new fl(t)}function wl(t){return new yl(t)}function kl(t,e){return null==e&&(e={}),ml(t,e)}function vl(t){return Ja(t)}function Sl(t,e){ao.registerCallbackConstructor(t,e)}yl.className="Sequential",s.registerClass(yl);class xl extends s.Serializable{getConfig(){return{}}}class Nl extends xl{apply(e,n=1){return function(e,n=1){if(1!==n)throw new Hi(`Support for alpha values other than 1 (${n}) is not implemented yet.`);return t.elu(e)}(e,n)}}Nl.className="elu",s.registerClass(Nl);class Il extends xl{apply(e){return t.selu(e)}}Il.className="selu",s.registerClass(Il);class Al extends xl{apply(e){return t.relu(e)}}Al.className="relu",s.registerClass(Al);class Cl extends xl{apply(e){return i((()=>t.minimum(6,t.relu(e))))}}Cl.className="relu6",s.registerClass(Cl);class Tl extends xl{apply(t){return t}}Tl.className="linear",s.registerClass(Tl);class zl extends xl{apply(e){return t.sigmoid(e)}}zl.className="sigmoid",s.registerClass(zl);class El extends xl{apply(e){return function(e){return i((()=>{const n=t.add(.5,t.mul(.2,e));return t.clipByValue(n,0,1)}))}(e)}}El.className="hardSigmoid",s.registerClass(El);class $l extends xl{apply(e){return t.softplus(e)}}$l.className="softplus",s.registerClass($l);class Fl extends xl{apply(e){return function(e){return i((()=>t.div(e,t.add(t.abs(e),1))))}(e)}}Fl.className="softsign",s.registerClass(Fl);class Dl extends xl{apply(e){return t.tanh(e)}}Dl.className="tanh",s.registerClass(Dl);class Ll extends xl{apply(e,n=-1){return t.softmax(e,n)}}Ll.className="softmax",s.registerClass(Ll);class _l extends xl{apply(e,n=-1){return t.logSoftmax(e,n)}}_l.className="logSoftmax",s.registerClass(_l);class Rl extends xl{apply(e,n=1){return i((()=>t.mul(t.sigmoid(t.mul(e,n)),e)))}}Rl.className="swish",s.registerClass(Rl);class Ml extends xl{apply(e){return i((()=>t.mul(e,t.tanh(t.softplus(e)))))}}function Ol(t){return t.getClassName()}function Bl(t,e={}){return ar(t,s.SerializationMap.getMap().classNameMap,e,"activation")}function Pl(t){if(null==t){const t={className:"linear",config:{}};return Bl(t)}if("string"==typeof t){const e={};return e.className=t,e.config={},Bl(e)}return t instanceof xl?t:Bl(t)}function Ul(t){if(null!=t&&"object"!=typeof t)throw new Error(`Argument to L1L2 regularizer's constructor is expected to be an object, but received: ${t}`)}Ml.className="mish",s.registerClass(Ml);class Wl extends s.Serializable{}class Vl extends Wl{constructor(t){super(),Ul(t),this.l1=null==t||null==t.l1?.01:t.l1,this.l2=null==t||null==t.l2?.01:t.l2,this.hasL1=0!==this.l1,this.hasL2=0!==this.l2}apply(e){return i((()=>{let n=a([1]);return this.hasL1&&(n=y(n,z(t.mul(this.l1,E(e))))),this.hasL2&&(n=y(n,z(t.mul(this.l2,na(e))))),t.reshape(n,[])}))}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(t,e){return new t({l1:e.l1,l2:e.l2})}}Vl.className="L1L2",s.registerClass(Vl);const jl={l1l2:"L1L2"};function ql(t){return ir(t)}function Kl(t,e={}){return ar(t,s.SerializationMap.getMap().classNameMap,e,"regularizer")}function Gl(t){if(null==t)return null;if("string"==typeof t){return Kl({className:t in jl?jl[t]:t,config:{}})}return t instanceof Wl?t:Kl(t)}class Hl extends Ga{constructor(t){super(null==t?{}:t),this.supportsMasking=!0,null!=t&&(this.maxValue=t.maxValue)}call(t,e){t=Ra(t);let n=$(t);return null!=this.maxValue&&(n=F(n,0,this.maxValue)),n}computeOutputShape(t){return t}getConfig(){const t={maxValue:this.maxValue},e=super.getConfig();return Object.assign(t,e),t}}Hl.className="ReLU",s.registerClass(Hl);class Zl extends Ga{constructor(t){super(null==t?{}:t),this.DEFAULT_ALPHA=.3,null==t&&(t={}),this.alpha=null==t.alpha?this.DEFAULT_ALPHA:t.alpha}call(t,e){const n=Ra(t);return D(n,this.alpha)}computeOutputShape(t){return t}getConfig(){const t={alpha:this.alpha},e=super.getConfig();return Object.assign(t,e),t}}Zl.className="LeakyReLU",s.registerClass(Zl);class Jl extends Ga{constructor(t){if(super(null==t?{}:t),this.DEFAULT_ALPHA_INITIALIZER="zeros",null==t&&(t={}),this.supportsMasking=!0,this.alphaInitializer=Ta(t.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=Gl(t.alphaRegularizer),this.alphaConstraint=Nr(t.alphaConstraint),null==t.sharedAxes)this.sharedAxes=null;else if(Array.isArray(t.sharedAxes))this.sharedAxes=t.sharedAxes;else{if("number"!=typeof t.sharedAxes)throw new Gi(`Expected sharedAxes to be a number or an array of numbers, but got ${t.sharedAxes}`);this.sharedAxes=[t.sharedAxes]}}build(t){const e=(t=Ma(t)).slice(1);if(null!=this.sharedAxes)for(const t of this.sharedAxes)e[t-1]=1;this.alpha=this.addWeight("alpha",e,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);const n={};if(null!=this.sharedAxes)for(let e=1;e<t.length;++e)n[e]=t[e];this.inputSpec=[new Wa({ndim:t.length,axes:n})],this.built=!0}call(t,e){return t=Ra(t),L(t,this.alpha.read())}getConfig(){const t={alphaInitializer:Ca(this.alphaInitializer),alphaRegularizer:ql(this.alphaRegularizer),alphaConstraint:Sr(this.alphaConstraint),sharedAxes:this.sharedAxes},e=super.getConfig();return Object.assign(t,e),t}}Jl.className="PReLU",s.registerClass(Jl);class Yl extends Ga{constructor(t){if(super(null==t?{}:t),this.DEFAULT_ALPHA=1,null==t&&(t={}),null!=t.alpha&&t.alpha!==this.DEFAULT_ALPHA)throw new Hi(`Non-default alpha value (${t.alpha}) is not supported by the ELU layer yet.`);this.alpha=null==t.alpha?this.DEFAULT_ALPHA:t.alpha}call(t,e){const n=Ra(t);return _(n)}computeOutputShape(t){return t}getConfig(){const t={alpha:this.alpha},e=super.getConfig();return Object.assign(t,e),t}}Yl.className="ELU",s.registerClass(Yl);class Xl extends Ga{constructor(t){super(null==t?{}:t),this.DEFAULT_THETA=1,null==t&&(t={}),this.theta=null==t.theta?this.DEFAULT_THETA:t.theta}call(t,e){const n=Ra(t);return l(n,S(R(n,this.theta),"float32"))}computeOutputShape(t){return t}getConfig(){const t={theta:this.theta},e=super.getConfig();return Object.assign(t,e),t}}Xl.className="ThresholdedReLU",s.registerClass(Xl);class Ql extends Ga{constructor(t){super(null==t?{}:t),this.DEFAULT_AXIS=1,null==t&&(t={}),this.softmax=(new Ll).apply,this.axis=null==t.axis?this.DEFAULT_AXIS:t.axis}call(t,e){const n=Ra(t);return this.softmax(n,this.axis)}computeOutputShape(t){return t}getConfig(){const t={axis:this.axis},e=super.getConfig();return Object.assign(t,e),t}}function tu(t,e,n){if("number"==typeof t)return Ji(t,e);if(t.length!==e)throw new Gi(`The ${n} argument must be an integer or tuple of ${e} integers. Received: ${t.length} elements.`);for(let i=0;i<e;++i){const r=t[i];if((s=r)!==parseInt(s.toString(),10))throw new Gi(`The ${n} argument must be an integer or tuple of ${e} integers. Received: ${JSON.stringify(t)} including a non-integer number ${r}`)}return t;var s}function eu(t,e,n,s,i=1){if(null==t)return t;let r;return r="same"===n?t:t-(e+(e-1)*(i-1))+1,Math.floor((r+s-1)/s)}function nu(t,e,n,s){if(null==t)return null;if("valid"===s)t=t*e+Vr([n-e,0]);else{if("same"!==s)throw new Gi(`Unsupport padding mode: ${s}.`);t*=e}return t}function su(e,n){return i((()=>(Fr(n),"channelsFirst"===n?t.transpose(e,[0,2,3,1]):e)))}function iu(e,n){return i((()=>(Fr(n),"channelsFirst"===n?t.transpose(e,[0,2,3,4,1]):e)))}function ru(e,n,s,r=[1,1],a="valid",o,l,u=null){return i((()=>{if(null==o&&(o="channelsLast"),Fr(o),3!==e.rank&&4!==e.rank)throw new Gi(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(3!==n.rank&&4!==n.rank)throw new Gi(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let i=su(e,o);if("causal"===a)throw new Hi("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return i=t.fused.conv2d({x:i,filter:n,strides:r,pad:"same"===a?"same":"valid",dilations:l,dataFormat:"NHWC",bias:s,activation:u}),"channelsFirst"===o&&(i=t.transpose(i,[0,3,1,2])),i}))}Ql.className="Softmax",s.registerClass(Ql);class au extends Ga{constructor(t,e){if(super(e),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",au.verifyArgs(e),this.rank=t,pr(this.rank,"rank"),1!==this.rank&&2!==this.rank&&3!==this.rank)throw new Hi(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=tu(e.kernelSize,t,"kernelSize"),this.strides=tu(null==e.strides?1:e.strides,t,"strides"),this.padding=null==e.padding?"valid":e.padding,Dr(this.padding),this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,Fr(this.dataFormat),this.activation=Pl(e.activation),this.useBias=null==e.useBias||e.useBias,this.biasInitializer=Ta(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=Nr(e.biasConstraint),this.biasRegularizer=Gl(e.biasRegularizer),this.activityRegularizer=Gl(e.activityRegularizer),this.dilationRate=tu(null==e.dilationRate?1:e.dilationRate,t,"dilationRate"),1===this.rank&&Array.isArray(this.dilationRate)&&1!==this.dilationRate.length)throw new Gi(`dilationRate must be a number or an array of a single number for 1D convolution, but received ${JSON.stringify(this.dilationRate)}`);if(2===this.rank){if("number"==typeof this.dilationRate)this.dilationRate=[this.dilationRate,this.dilationRate];else if(2!==this.dilationRate.length)throw new Gi(`dilationRate must be a number or array of two numbers for 2D convolution, but received ${JSON.stringify(this.dilationRate)}`)}else if(3===this.rank)if("number"==typeof this.dilationRate)this.dilationRate=[this.dilationRate,this.dilationRate,this.dilationRate];else if(3!==this.dilationRate.length)throw new Gi(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}static verifyArgs(t){if(Yi("kernelSize"in t,"required key 'kernelSize' not in config"),"number"!=typeof t.kernelSize&&!cr(t.kernelSize,"number",1,3))throw new Gi(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(t.kernelSize)}.`)}getConfig(){const t={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:Ol(this.activation),useBias:this.useBias,biasInitializer:Ca(this.biasInitializer),biasRegularizer:ql(this.biasRegularizer),activityRegularizer:ql(this.activityRegularizer),biasConstraint:Sr(this.biasConstraint)},e=super.getConfig();return Object.assign(t,e),t}}class ou extends au{constructor(t,e){super(t,e),this.kernel=null,ou.verifyArgs(e),this.filters=e.filters,pr(this.filters,"filters"),this.kernelInitializer=Ta(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=Nr(e.kernelConstraint),this.kernelRegularizer=Gl(e.kernelRegularizer)}build(t){t=Ma(t);const e="channelsFirst"===this.dataFormat?1:t.length-1;if(null==t[e])throw new Gi(`The channel dimension of the input should be defined. Found ${t[e]}`);const n=t[e],s=this.kernelSize.concat([n,this.filters]);this.kernel=this.addWeight("kernel",s,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:{[e]:n}}],this.built=!0}call(e,n){return i((()=>{let n;e=Ra(e);const s=null==this.bias?null:this.bias.read(),r=fr(this.activation.getClassName());if(null!=r&&2===this.rank)n=ru(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate,r);else{if(1===this.rank)n=function(e,n,s,r=1,a="valid",o,l=1){return i((()=>{if(null==o&&(o="channelsLast"),Fr(o),3!==e.shape.length)throw new Gi(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(3!==n.shape.length)throw new Gi(`The kernel for a conv1dWithBias operation should be 3, but is ${n.shape.length} instead`);if(null!=s&&1!==s.shape.length)throw new Gi(`The bias for a conv1dWithBias operation should be 1, but is ${n.shape.length} instead`);if("channelsFirst"===o&&(e=t.transpose(e,[0,2,1])),"causal"===a)throw new Hi("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let i=t.conv1d(e,n,r,"same"===a?"same":"valid","NWC",l);return null!=s&&(i=ia(i,s)),i}))}(e,this.kernel.read(),s,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(2===this.rank)n=ru(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate);else{if(3!==this.rank)throw new Hi("convolutions greater than 3D are not implemented yet.");n=function(e,n,s,r=[1,1,1],a="valid",o,l){return i((()=>{if(null==o&&(o="channelsLast"),Fr(o),4!==e.rank&&5!==e.rank)throw new Gi(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(4!==n.rank&&5!==n.rank)throw new Gi(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let i=iu(e,o);if("causal"===a)throw new Hi("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return i=t.conv3d(i,n,r,"same"===a?"same":"valid","NDHWC",l),null!=s&&(i=ia(i,s)),"channelsFirst"===o&&(i=t.transpose(i,[0,4,1,2,3])),i}))}(e,this.kernel.read(),s,this.strides,this.padding,this.dataFormat,this.dilationRate)}null!=this.activation&&(n=this.activation.apply(n))}return n}))}computeOutputShape(t){t=Ma(t);const e=[],n="channelsLast"===this.dataFormat?t.slice(1,t.length-1):t.slice(2);for(let t=0;t<n.length;++t){const s=eu(n[t],this.kernelSize[t],this.padding,this.strides[t],"number"==typeof this.dilationRate?this.dilationRate:this.dilationRate[t]);e.push(s)}let s=[t[0]];return"channelsLast"===this.dataFormat?(s=s.concat(e),s.push(this.filters)):(s.push(this.filters),s=s.concat(e)),s}getConfig(){const t={filters:this.filters,kernelInitializer:Ca(this.kernelInitializer),kernelRegularizer:ql(this.kernelRegularizer),kernelConstraint:Sr(this.kernelConstraint)},e=super.getConfig();return Object.assign(t,e),t}static verifyArgs(t){if(!("filters"in t)||"number"!=typeof t.filters||t.filters<1)throw new Gi(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(t.filters)}`)}}class lu extends ou{constructor(t){super(2,t),lu.verifyArgs(t)}getConfig(){const t=super.getConfig();return delete t.rank,t}static verifyArgs(t){if("number"!=typeof t.kernelSize&&!cr(t.kernelSize,"number",1,2))throw new Gi(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(t.kernelSize)}.`)}}lu.className="Conv2D",s.registerClass(lu);class uu extends ou{constructor(t){super(3,t),uu.verifyArgs(t)}getConfig(){const t=super.getConfig();return delete t.rank,t}static verifyArgs(t){if("number"!=typeof t.kernelSize&&(!Array.isArray(t.kernelSize)||1!==t.kernelSize.length&&3!==t.kernelSize.length))throw new Gi(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(t.kernelSize)}.`)}}uu.className="Conv3D",s.registerClass(uu);class hu extends lu{constructor(t){if(super(t),this.inputSpec=[new Wa({ndim:4})],"same"!==this.padding&&"valid"!==this.padding)throw new Gi(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(t){if(4!==(t=Ma(t)).length)throw new Gi("Input should have rank 4; Received input shape: "+JSON.stringify(t));const e="channelsFirst"===this.dataFormat?1:t.length-1;if(null==t[e])throw new Gi("The channel dimension of the inputs should be defined. Found `None`.");const n=t[e],s=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",s,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Wa({ndim:4,axes:{[e]:n}})],this.built=!0}call(e,n){return t.tidy((()=>{let n=Ra(e);if(4!==n.shape.length)throw new Gi(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);const s=n.shape,i=s[0];let r,a;"channelsFirst"===this.dataFormat?(r=2,a=3):(r=1,a=2);const o=s[r],l=s[a],u=this.kernelSize[0],h=this.kernelSize[1],c=this.strides[0],p=this.strides[1],d=[i,nu(o,c,u,this.padding),nu(l,p,h,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(n=t.transpose(n,[0,2,3,1]));let f=t.conv2dTranspose(n,this.kernel.read(),d,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(f=t.transpose(f,[0,3,1,2])),null!=this.bias&&(f=ia(f,this.bias.read(),this.dataFormat)),null!=this.activation&&(f=this.activation.apply(f)),f}))}computeOutputShape(t){const e=(t=Ma(t)).slice();let n,s,i;"channelsFirst"===this.dataFormat?(n=1,s=2,i=3):(n=3,s=1,i=2);const r=this.kernelSize[0],a=this.kernelSize[1],o=this.strides[0],l=this.strides[1];return e[n]=this.filters,e[s]=nu(e[s],o,r,this.padding),e[i]=nu(e[i],l,a,this.padding),e}getConfig(){const t=super.getConfig();return delete t.dilationRate,t}}hu.className="Conv2DTranspose",s.registerClass(hu);class cu extends uu{constructor(t){if(super(t),this.inputSpec=[new Wa({ndim:5})],"same"!==this.padding&&"valid"!==this.padding)throw new Gi(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(t){if(5!==(t=Ma(t)).length)throw new Gi("Input should have rank 5; Received input shape: "+JSON.stringify(t));const e="channelsFirst"===this.dataFormat?1:t.length-1;if(null==t[e])throw new Gi("The channel dimension of the inputs should be defined. Found `None`.");const n=t[e],s=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",s,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new Wa({ndim:5,axes:{[e]:n}})],this.built=!0}call(e,n){return t.tidy((()=>{let n=Ra(e);if(5!==n.shape.length)throw new Gi(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);const s=n.shape,i=s[0];let r,a,o;"channelsFirst"===this.dataFormat?(o=2,r=3,a=4):(o=1,r=2,a=3);const l=s[o],u=s[r],h=s[a],c=this.kernelSize[0],p=this.kernelSize[1],d=this.kernelSize[2],f=this.strides[0],g=this.strides[1],m=this.strides[2],y=[i,nu(l,f,c,this.padding),nu(u,g,p,this.padding),nu(h,m,d,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(n=t.transpose(n,[0,2,3,4,1]));let b=t.conv3dTranspose(n,this.kernel.read(),y,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(b=t.transpose(b,[0,4,1,2,3])),null!==this.bias&&(b=ia(b,this.bias.read(),this.dataFormat)),null!==this.activation&&(b=this.activation.apply(b)),b}))}computeOutputShape(t){const e=(t=Ma(t)).slice();let n,s,i,r;"channelsFirst"===this.dataFormat?(n=1,s=2,i=3,r=4):(n=4,s=1,i=2,r=3);const a=this.kernelSize[0],o=this.kernelSize[1],l=this.kernelSize[2],u=this.strides[0],h=this.strides[1],c=this.strides[2];return e[n]=this.filters,e[s]=nu(e[s],u,a,this.padding),e[i]=nu(e[i],h,o,this.padding),e[r]=nu(e[r],c,l,this.padding),e}getConfig(){const t=super.getConfig();return delete t.dilationRate,t}}cu.className="Conv3DTranspose",s.registerClass(cu);class pu extends ou{constructor(t,e){if(super(t,e),this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,null==e.filters)throw new Gi("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=e.kernelInitializer||null!=e.kernelRegularizer||null!=e.kernelConstraint)throw new Gi("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(null!=e.padding&&"same"!==e.padding&&"valid"!==e.padding)throw new Gi(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(e.padding)}`);this.depthMultiplier=null==e.depthMultiplier?1:e.depthMultiplier,this.depthwiseInitializer=Ta(e.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=Gl(e.depthwiseRegularizer),this.depthwiseConstraint=Nr(e.depthwiseConstraint),this.pointwiseInitializer=Ta(e.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=Gl(e.pointwiseRegularizer),this.pointwiseConstraint=Nr(e.pointwiseConstraint)}build(t){if((t=Ma(t)).length<this.rank+2)throw new Gi(`Inputs to SeparableConv${this.rank}D should have rank ${this.rank+2}, but received input shape: ${JSON.stringify(t)}`);const e="channelsFirst"===this.dataFormat?1:t.length-1;if(null==t[e]||t[e]<0)throw new Gi(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(t[e])}`);const n=t[e],s=this.kernelSize.concat([n,this.depthMultiplier]),i=[];for(let t=0;t<this.rank;++t)i.push(1);i.push(n*this.depthMultiplier,this.filters);const r=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",s,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,r,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",i,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,r,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,r,this.biasConstraint):this.bias=null,this.inputSpec=[new Wa({ndim:this.rank+2,axes:{[e]:n}})],this.built=!0}call(e,n){return i((()=>{let n;if(e=Ra(e),1===this.rank)throw new Hi("1D separable convolution is not implemented yet.");return 2===this.rank&&("channelsFirst"===this.dataFormat&&(e=t.transpose(e,[0,2,3,1])),n=t.separableConv2d(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(n=ia(n,this.bias.read(),this.dataFormat)),null!=this.activation&&(n=this.activation.apply(n)),"channelsFirst"===this.dataFormat&&(n=t.transpose(n,[0,3,1,2])),n}))}getConfig(){const t=super.getConfig();return delete t.rank,delete t.kernelInitializer,delete t.kernelRegularizer,delete t.kernelConstraint,t.depthwiseInitializer=Ca(this.depthwiseInitializer),t.pointwiseInitializer=Ca(this.pointwiseInitializer),t.depthwiseRegularizer=ql(this.depthwiseRegularizer),t.pointwiseRegularizer=ql(this.pointwiseRegularizer),t.depthwiseConstraint=Sr(this.depthwiseConstraint),t.pointwiseConstraint=Sr(this.pointwiseConstraint),t}}pu.className="SeparableConv";class du extends pu{constructor(t){super(2,t)}}du.className="SeparableConv2D",s.registerClass(du);class fu extends ou{constructor(t){super(1,t),fu.verifyArgs(t),this.inputSpec=[{ndim:3}]}getConfig(){const t=super.getConfig();return delete t.rank,delete t.dataFormat,t}static verifyArgs(t){if("number"!=typeof t.kernelSize&&!cr(t.kernelSize,"number",1,1))throw new Gi(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(t.kernelSize)}.`)}}fu.className="Conv1D",s.registerClass(fu);class gu extends Ga{constructor(t){super(t),"number"==typeof t.cropping?this.cropping=[[t.cropping,t.cropping],[t.cropping,t.cropping]]:"number"==typeof t.cropping[0]?this.cropping=[[t.cropping[0],t.cropping[0]],[t.cropping[1],t.cropping[1]]]:this.cropping=t.cropping,this.dataFormat=void 0===t.dataFormat?"channelsLast":t.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(t){return"channelsFirst"===this.dataFormat?[t[0],t[1],t[2]-this.cropping[0][0]-this.cropping[0][1],t[3]-this.cropping[1][0]-this.cropping[1][1]]:[t[0],t[1]-this.cropping[0][0]-this.cropping[0][1],t[2]-this.cropping[1][0]-this.cropping[1][1],t[3]]}call(t,e){return i((()=>{if(t=Ra(t),"channelsLast"===this.dataFormat){const e=Zr(t,this.cropping[0][0],t.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Zr(e,this.cropping[1][0],t.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}{const e=Zr(t,this.cropping[0][0],t.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Zr(e,this.cropping[1][0],t.shape[3]-this.cropping[1][1]-this.cropping[1][0],4)}}))}getConfig(){const t={cropping:this.cropping,dataFormat:this.dataFormat},e=super.getConfig();return Object.assign(t,e),t}}gu.className="Cropping2D",s.registerClass(gu);class mu extends Ga{constructor(t){var e;super(t),this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=null==t.size?this.DEFAULT_SIZE:t.size,this.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,Fr(this.dataFormat),this.interpolation=null==t.interpolation?"nearest":t.interpolation,e=this.interpolation,hr(Cr,"InterpolationFormat",e)}computeOutputShape(t){if("channelsFirst"===this.dataFormat){const e=null==t[2]?null:this.size[0]*t[2],n=null==t[3]?null:this.size[1]*t[3];return[t[0],t[1],e,n]}{const e=null==t[1]?null:this.size[0]*t[1],n=null==t[2]?null:this.size[1]*t[2];return[t[0],e,n,t[3]]}}call(e,n){return t.tidy((()=>{let n=Ra(e);const s=n.shape;if("channelsFirst"===this.dataFormat){n=t.transpose(n,[0,2,3,1]);const e=this.size[0]*s[2],i=this.size[1]*s[3],r="nearest"===this.interpolation?t.image.resizeNearestNeighbor(n,[e,i]):t.image.resizeBilinear(n,[e,i]);return t.transpose(r,[0,3,1,2])}{const e=this.size[0]*s[1],i=this.size[1]*s[2];return"nearest"===this.interpolation?t.image.resizeNearestNeighbor(n,[e,i]):t.image.resizeBilinear(n,[e,i])}}))}getConfig(){const t={size:this.size,dataFormat:this.dataFormat},e=super.getConfig();return Object.assign(t,e),t}}mu.className="UpSampling2D",s.registerClass(mu);class yu extends au{constructor(t){super(2,t),this.depthwiseKernel=null,this.depthMultiplier=null==t.depthMultiplier?1:t.depthMultiplier,this.depthwiseInitializer=Ta(t.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=Nr(t.depthwiseConstraint),this.depthwiseRegularizer=Gl(t.depthwiseRegularizer)}build(t){if((t=Ma(t)).length<4)throw new Gi(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(t)}.`);const e="channelsFirst"===this.dataFormat?1:3;if(null==t[e]||t[e]<0)throw new Gi(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${t[e]}).`);const n=t[e],s=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",s,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[n*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,n){return i((()=>{let n=function(e,n,s=[1,1],r="valid",a,o){return i((()=>{null==a&&(a="channelsLast"),Fr(a);let i=su(e,a);if(4!==e.rank)throw new Gi(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(4!==n.rank)throw new Gi(`depthwiseKernel is required to be 4-D, but is instead ${n.rank}-D`);return i=t.depthwiseConv2d(i,n,s,"same"===r?"same":"valid","NHWC",o),"channelsFirst"===a&&(i=t.transpose(i,[0,3,1,2])),i}))}(e=Ra(e),this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(n=ia(n,this.bias.read(),this.dataFormat)),null!=this.activation&&(n=this.activation.apply(n)),n}))}computeOutputShape(t){t=Ma(t);const e="channelsFirst"===this.dataFormat?t[2]:t[1],n="channelsFirst"===this.dataFormat?t[3]:t[2],s="channelsFirst"===this.dataFormat?t[1]*this.depthMultiplier:t[3]*this.depthMultiplier,i=eu(e,this.kernelSize[0],this.padding,this.strides[0]),r=eu(n,this.kernelSize[1],this.padding,this.strides[1]);return"channelsFirst"===this.dataFormat?[t[0],s,i,r]:[t[0],i,r,s]}getConfig(){const t=super.getConfig();return t.depthMultiplier=this.depthMultiplier,t.depthwiseInitializer=Ca(this.depthwiseInitializer),t.depthwiseRegularizer=ql(this.depthwiseRegularizer),t.depthwiseConstraint=Sr(this.depthwiseRegularizer),t}}function bu(t,e,n,s){if(Array.isArray(t)){if(null!=e||null!=n)throw new Gi("When inputs is an array, neither initialState or constants should be provided");null!=s&&(n=t.slice(t.length-s,t.length),t=t.slice(0,t.length-s)),t.length>1&&(e=t.slice(1,t.length)),t=t[0]}function i(t){return null==t||Array.isArray(t)?t:[t]}return{inputs:t,initialState:e=i(e),constants:n=i(n)}}function wu(e,n,s,i=!1,r,a,o=!1,l=!1){return t.tidy((()=>{const u=n.shape.length;if(u<3)throw new Gi(`Input should be at least 3D, but is ${u}D.`);const h=[1,0].concat(jr(2,u));if(n=t.transpose(n,h),null!=a)throw new Hi("The rnn() functoin of the deeplearn.js backend does not support constants yet.");o&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),null!=r&&((r=t.cast(t.cast(r,"bool"),"float32")).rank===u-1&&(r=t.expandDims(r,-1)),r=t.transpose(r,h)),i&&(n=t.reverse(n,0),null!=r&&(r=t.reverse(r,0)));const c=[];let p,d=s;const f=n.shape[0],g=t.unstack(n);let m,y;null!=r&&(m=t.unstack(r));for(let n=0;n<f;++n){const s=g[n],i=t.tidy((()=>e(s,d)));if(null==r)p=i[0],d=i[1];else{const e=t.tidy((()=>{const e=m[n],s=t.sub(t.onesLike(e),e);return{output:t.add(t.mul(i[0],e),t.mul(d[0],s)),newStates:d.map(((n,r)=>t.add(t.mul(i[1][r],e),t.mul(n,s))))}}));p=e.output,d=e.newStates}l&&c.push(p)}if(l){const e=1;y=t.stack(c,e)}return[p,y,d]}))}yu.className="DepthwiseConv2D",s.registerClass(yu);class ku extends Ga{constructor(t){let e;if(super(t),null==t.cell)throw new Gi("cell property is missing for the constructor of RNN.");if(e=Array.isArray(t.cell)?new Tu({cells:t.cell}):t.cell,null==e.stateSize)throw new Gi("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=e,this.returnSequences=null!=t.returnSequences&&t.returnSequences,this.returnState=null!=t.returnState&&t.returnState,this.goBackwards=null!=t.goBackwards&&t.goBackwards,this._stateful=null!=t.stateful&&t.stateful,this.unroll=null!=t.unroll&&t.unroll,this.supportsMasking=!0,this.inputSpec=[new Wa({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(null==this.states_){return jr(0,Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1).map((t=>null))}return this.states_}setStates(t){this.states_=t}computeOutputShape(t){La(t)&&(t=t[0]),t=t;let e=this.cell.stateSize;Array.isArray(e)||(e=[e]);const n=e[0];let s;if(s=this.returnSequences?[t[0],t[1],n]:[t[0],n],this.returnState){const n=[];for(const s of e)n.push([t[0],s]);return[s].concat(n)}return s}computeMask(e,n){return t.tidy((()=>{Array.isArray(n)&&(n=n[0]);const t=this.returnSequences?n:null;if(this.returnState){const e=this.states.map((t=>null));return[t].concat(e)}return t}))}get states(){if(null==this.states_){const t=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,e=[];for(let n=0;n<t;++n)e.push(null);return e}return this.states_}set states(t){this.states_=t}build(t){if(null!=this.numConstants)throw new Hi("Constants support is not implemented in RNN yet.");La(t)&&(t=t[0]),t=t;const e=this.stateful?t[0]:null,s=t.slice(2);this.inputSpec[0]=new Wa({shape:[e,null,...s]});const i=[t[0]].concat(t.slice(2));let r;if(this.cell.build(i),r=Array.isArray(this.cell.stateSize)?this.cell.stateSize:[this.cell.stateSize],null!=this.stateSpec){if(!n.arraysEqual(this.stateSpec.map((t=>t.shape[t.shape.length-1])),r))throw new Gi(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`)}else this.stateSpec=r.map((t=>new Wa({shape:[null,t]})));this.stateful&&this.resetStates()}resetStates(e,s=!1){i((()=>{if(!this.stateful)throw new qi("Cannot call resetStates() on an RNN Layer that is not stateful.");const i=this.inputSpec[0].shape[0];if(null==i)throw new Gi("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(null==this.states_)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((e=>t.zeros([i,e]))):this.states_=[t.zeros([i,this.cell.stateSize])];else if(null==e)t.dispose(this.states_),null!=this.keptStates&&(t.dispose(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((e=>t.zeros([i,e]))):this.states_[0]=t.zeros([i,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new Gi(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);!0===s?this.keptStates.push(this.states_.slice()):t.dispose(this.states_);for(let t=0;t<this.states_.length;++t){const s=e[t],r=Array.isArray(this.cell.stateSize)?this.cell.stateSize[t]:this.cell.stateSize,a=[i,r];if(!n.arraysEqual(s.shape,a))throw new Gi(`State ${t} is incompatible with layer ${this.name}: expected shape=${a}, received shape=${s.shape}`);this.states_[t]=s}}this.states_=this.states_.map((e=>t.keep(e.clone())))}))}apply(t,e){let n=null==e?null:e.initialState,s=null==e?null:e.constants;null==e&&(e={});const i=bu(t,n,s,this.numConstants);t=i.inputs,n=i.initialState,s=i.constants;let r=[],a=[];if(null!=n){e.initialState=n,r=r.concat(n),this.stateSpec=[];for(const t of n)this.stateSpec.push(new Wa({shape:t.shape}));a=a.concat(this.stateSpec)}null!=s&&(e.constants=s,r=r.concat(s),this.numConstants=s.length);if(r[0]instanceof Va){const n=[t].concat(r),s=this.inputSpec.concat(a),i=this.inputSpec;this.inputSpec=s;const o=super.apply(n,e);return this.inputSpec=i,o}return super.apply(t,e)}call(t,e){return i((()=>{const n=null==e?null:e.mask,s=null==e?null:e.training;let i=null==e?null:e.initialState;t=Ra(t),null==i&&(i=this.stateful?this.states_:this.getInitialState(t));const r=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(i.length!==r)throw new Gi(`RNN Layer has ${r} state(s) but was passed ${i.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");const a={training:s},o=wu(((t,e)=>{const n=this.cell.call([t].concat(e),a);return[n[0],n.slice(1)]}),t,i,this.goBackwards,n,null,this.unroll,this.returnSequences),l=o[0],u=o[1],h=o[2];this.stateful&&this.resetStates(h,s);const c=this.returnSequences?u:l;return this.returnState?[c].concat(h):c}))}getInitialState(e){return i((()=>{let n=t.zeros(e.shape);return n=t.sum(n,[1,2]),n=Kr(n),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map((t=>t>1?Xr(n,[1,t]):n)):this.cell.stateSize>1?[Xr(n,[1,this.cell.stateSize])]:[n]}))}get trainableWeights(){return this.trainable?this.cell.trainableWeights:[]}get nonTrainableWeights(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights}setFastWeightInitDuringBuild(t){super.setFastWeightInitDuringBuild(t),null!=this.cell&&this.cell.setFastWeightInitDuringBuild(t)}getConfig(){const t=super.getConfig(),e={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};null!=this.numConstants&&(e.numConstants=this.numConstants);const n=this.cell.getConfig();return this.getClassName()===ku.className&&(e.cell={className:this.cell.getClassName(),config:n}),Object.assign({},n,t,e)}static fromConfig(t,e,n={}){const s=lo(e.cell,n);return new t(Object.assign(e,{cell:s}))}}ku.className="RNN",s.registerClass(ku);class vu extends Ga{}class Su extends vu{constructor(t){super(t),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=t.units,pr(this.units,"units"),this.activation=Pl(null==t.activation?this.DEFAULT_ACTIVATION:t.activation),this.useBias=null==t.useBias||t.useBias,this.kernelInitializer=Ta(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Ta(t.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Ta(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Gl(t.kernelRegularizer),this.recurrentRegularizer=Gl(t.recurrentRegularizer),this.biasRegularizer=Gl(t.biasRegularizer),this.kernelConstraint=Nr(t.kernelConstraint),this.recurrentConstraint=Nr(t.recurrentConstraint),this.biasConstraint=Nr(t.biasConstraint),this.dropout=Wr([1,Vr([0,null==t.dropout?0:t.dropout])]),this.recurrentDropout=Wr([1,Vr([0,null==t.recurrentDropout?0:t.recurrentDropout])]),this.dropoutFunc=t.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(t){t=Ma(t),this.kernel=this.addWeight("kernel",[t[t.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,n){return i((()=>{if(2!==(e=e).length)throw new Gi(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let s=e[1];e=e[0];const i=null!=n.training&&n.training;let r;0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=zu({ones:()=>t.onesLike(e),rate:this.dropout,training:i,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=zu({ones:()=>t.onesLike(s),rate:this.recurrentDropout,training:i,dropoutFunc:this.dropoutFunc}));const a=this.dropoutMask,o=this.recurrentDropoutMask;r=ta(null!=a?t.mul(e,a):e,this.kernel.read()),null!=this.bias&&(r=ia(r,this.bias.read())),null!=o&&(s=t.mul(s,o));let l=t.add(r,ta(s,this.recurrentKernel.read()));return null!=this.activation&&(l=this.activation.apply(l)),[l,l]}))}getConfig(){const t=super.getConfig(),e={units:this.units,activation:Ol(this.activation),useBias:this.useBias,kernelInitializer:Ca(this.kernelInitializer),recurrentInitializer:Ca(this.recurrentInitializer),biasInitializer:Ca(this.biasInitializer),kernelRegularizer:ql(this.kernelRegularizer),recurrentRegularizer:ql(this.recurrentRegularizer),biasRegularizer:ql(this.biasRegularizer),activityRegularizer:ql(this.activityRegularizer),kernelConstraint:Sr(this.kernelConstraint),recurrentConstraint:Sr(this.recurrentConstraint),biasConstraint:Sr(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign({},t,e)}}Su.className="SimpleRNNCell",s.registerClass(Su);class xu extends ku{constructor(t){t.cell=new Su(t),super(t)}call(e,n){return i((()=>{null!=this.cell.dropoutMask&&(t.dispose(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(t.dispose(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const s=null==n?null:n.mask,i=null==n?null:n.training,r=null==n?null:n.initialState;return super.call(e,{mask:s,training:i,initialState:r})}))}static fromConfig(t,e){return new t(e)}}xu.className="SimpleRNN",s.registerClass(xu);class Nu extends vu{constructor(t){if(super(t),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",t.resetAfter)throw new Gi("GRUCell does not support reset_after parameter set to true.");this.units=t.units,pr(this.units,"units"),this.activation=Pl(void 0===t.activation?this.DEFAULT_ACTIVATION:t.activation),this.recurrentActivation=Pl(void 0===t.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:t.recurrentActivation),this.useBias=null==t.useBias||t.useBias,this.kernelInitializer=Ta(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Ta(t.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Ta(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Gl(t.kernelRegularizer),this.recurrentRegularizer=Gl(t.recurrentRegularizer),this.biasRegularizer=Gl(t.biasRegularizer),this.kernelConstraint=Nr(t.kernelConstraint),this.recurrentConstraint=Nr(t.recurrentConstraint),this.biasConstraint=Nr(t.biasConstraint),this.dropout=Wr([1,Vr([0,null==t.dropout?0:t.dropout])]),this.recurrentDropout=Wr([1,Vr([0,null==t.recurrentDropout?0:t.recurrentDropout])]),this.dropoutFunc=t.dropoutFunc,this.implementation=t.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(t){const e=(t=Ma(t))[t.length-1];this.kernel=this.addWeight("kernel",[e,3*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,3*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[3*this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,n){return i((()=>{if(2!==(e=e).length)throw new Gi(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);const s=null!=n.training&&n.training;let i=e[1];e=e[0],0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=zu({ones:()=>t.onesLike(e),rate:this.dropout,training:s,count:3,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=zu({ones:()=>t.onesLike(i),rate:this.recurrentDropout,training:s,count:3,dropoutFunc:this.dropoutFunc}));const r=this.dropoutMask,a=this.recurrentDropoutMask;let o,l,u;0<this.dropout&&this.dropout<1&&(e=t.mul(e,r[0]));let h=ta(e,this.kernel.read());this.useBias&&(h=ia(h,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(i=t.mul(i,a[0]));const c=this.recurrentKernel.read(),[p,d]=t.split(c,[2*this.units,this.units],c.rank-1),f=ta(i,p),[g,m,y]=t.split(h,3,h.rank-1),[b,w]=t.split(f,2,f.rank-1);o=this.recurrentActivation.apply(t.add(g,b)),l=this.recurrentActivation.apply(t.add(m,w));const k=ta(t.mul(l,i),d);u=this.activation.apply(t.add(y,k));const v=t.add(t.mul(o,i),t.mul(t.add(1,t.neg(o)),u));return[v,v]}))}getConfig(){const t=super.getConfig(),e={units:this.units,activation:Ol(this.activation),recurrentActivation:Ol(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Ca(this.kernelInitializer),recurrentInitializer:Ca(this.recurrentInitializer),biasInitializer:Ca(this.biasInitializer),kernelRegularizer:ql(this.kernelRegularizer),recurrentRegularizer:ql(this.recurrentRegularizer),biasRegularizer:ql(this.biasRegularizer),activityRegularizer:ql(this.activityRegularizer),kernelConstraint:Sr(this.kernelConstraint),recurrentConstraint:Sr(this.recurrentConstraint),biasConstraint:Sr(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign({},t,e)}}Nu.className="GRUCell",s.registerClass(Nu);class Iu extends ku{constructor(t){0===t.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),t.cell=new Nu(t),super(t)}call(e,n){return i((()=>{null!=this.cell.dropoutMask&&(t.dispose(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(t.dispose(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const s=null==n?null:n.mask,i=null==n?null:n.training,r=null==n?null:n.initialState;return super.call(e,{mask:s,training:i,initialState:r})}))}static fromConfig(t,e){return 0===e.implmentation&&(e.implementation=1),new t(e)}}Iu.className="GRU",s.registerClass(Iu);class Au extends vu{constructor(t){super(t),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=t.units,pr(this.units,"units"),this.activation=Pl(void 0===t.activation?this.DEFAULT_ACTIVATION:t.activation),this.recurrentActivation=Pl(void 0===t.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:t.recurrentActivation),this.useBias=null==t.useBias||t.useBias,this.kernelInitializer=Ta(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Ta(t.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Ta(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=t.unitForgetBias,this.kernelRegularizer=Gl(t.kernelRegularizer),this.recurrentRegularizer=Gl(t.recurrentRegularizer),this.biasRegularizer=Gl(t.biasRegularizer),this.kernelConstraint=Nr(t.kernelConstraint),this.recurrentConstraint=Nr(t.recurrentConstraint),this.biasConstraint=Nr(t.biasConstraint),this.dropout=Wr([1,Vr([0,null==t.dropout?0:t.dropout])]),this.recurrentDropout=Wr([1,Vr([0,null==t.recurrentDropout?0:t.recurrentDropout])]),this.dropoutFunc=t.dropoutFunc,this.implementation=t.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(t){var e;const n=(t=Ma(t))[t.length-1];let s;if(this.kernel=this.addWeight("kernel",[n,4*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,4*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){if(this.unitForgetBias){const t=this.biasInitializer,n=this.units;s=new((e=class extends ua{apply(e,s){const i=t.apply([n]),r=(new ca).apply([n]),a=t.apply([2*n]);return Yr(Yr(i,r),a)}}).className="CustomInit",e)}else s=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.units],null,s,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,n){return i((()=>{const s=null!=n.training&&n.training;if(3!==(e=e).length)throw new Gi(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let i=e[1];const r=e[2];e=e[0],0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=zu({ones:()=>t.onesLike(e),rate:this.dropout,training:s,count:4,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=zu({ones:()=>t.onesLike(i),rate:this.recurrentDropout,training:s,count:4,dropoutFunc:this.dropoutFunc}));const a=this.dropoutMask,o=this.recurrentDropoutMask;let l,u,h,c;0<this.dropout&&this.dropout<1&&(e=t.mul(e,a[0]));let p=ta(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(i=t.mul(i,o[0])),p=t.add(p,ta(i,this.recurrentKernel.read())),this.useBias&&(p=ia(p,this.bias.read()));const[d,f,g,m]=t.split(p,4,p.rank-1);l=this.recurrentActivation.apply(d),u=this.recurrentActivation.apply(f),h=t.add(t.mul(u,r),t.mul(l,this.activation.apply(g))),c=this.recurrentActivation.apply(m);const y=t.mul(c,this.activation.apply(h));return[y,y,h]}))}getConfig(){const t=super.getConfig(),e={units:this.units,activation:Ol(this.activation),recurrentActivation:Ol(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Ca(this.kernelInitializer),recurrentInitializer:Ca(this.recurrentInitializer),biasInitializer:Ca(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:ql(this.kernelRegularizer),recurrentRegularizer:ql(this.recurrentRegularizer),biasRegularizer:ql(this.biasRegularizer),activityRegularizer:ql(this.activityRegularizer),kernelConstraint:Sr(this.kernelConstraint),recurrentConstraint:Sr(this.recurrentConstraint),biasConstraint:Sr(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign({},t,e)}}Au.className="LSTMCell",s.registerClass(Au);class Cu extends ku{constructor(t){0===t.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),t.cell=new Au(t),super(t)}call(e,n){return i((()=>{null!=this.cell.dropoutMask&&(t.dispose(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(t.dispose(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const s=null==n?null:n.mask,i=null==n?null:n.training,r=null==n?null:n.initialState;return super.call(e,{mask:s,training:i,initialState:r})}))}static fromConfig(t,e){return 0===e.implmentation&&(e.implementation=1),new t(e)}}Cu.className="LSTM",s.registerClass(Cu);class Tu extends vu{constructor(t){super(t),this.cells=t.cells}get stateSize(){const t=[];for(const e of this.cells.slice().reverse())Array.isArray(e.stateSize)?t.push(...e.stateSize):t.push(e.stateSize);return t}call(t,e){return i((()=>{let n=(t=t).slice(1);const s=[];for(const t of this.cells.slice().reverse())Array.isArray(t.stateSize)?s.push(n.splice(0,t.stateSize.length)):s.push(n.splice(0,1));s.reverse();const i=[];let r;for(let a=0;a<this.cells.length;++a){const o=this.cells[a];n=s[a],r=0===a?[t[0]].concat(n):[r[0]].concat(n),r=o.call(r,e),i.push(r.slice(1))}n=[];for(const t of i.slice().reverse())n.push(...t);return[r[0]].concat(n)}))}build(t){let e;La(t)&&(t=t[0]),t=t,this.cells.forEach(((n,s)=>{Rr(`RNNCell_${s}`,(()=>{n.build(t),e=Array.isArray(n.stateSize)?n.stateSize[0]:n.stateSize,t=[t[0],e]}))})),this.built=!0}getConfig(){const t=super.getConfig(),e={cells:this.cells.map((t=>({className:t.getClassName(),config:t.getConfig()})))};return Object.assign({},t,e)}static fromConfig(t,e,n={}){const s=[];for(const t of e.cells)s.push(lo(t,n));return new t({cells:s})}get trainableWeights(){if(!this.trainable)return[];const t=[];for(const e of this.cells)t.push(...e.trainableWeights);return t}get nonTrainableWeights(){const t=[];for(const e of this.cells)t.push(...e.nonTrainableWeights);if(!this.trainable){const e=[];for(const t of this.cells)e.push(...t.trainableWeights);return e.concat(t)}return t}getWeights(){const t=[];for(const e of this.cells)t.push(...e.weights);return Pa(t)}setWeights(t){const e=[];for(const n of this.cells){const s=n.weights.length,i=t.splice(s);for(let t=0;t<n.weights.length;++t)e.push([n.weights[t],i[t]])}Ua(e)}}function zu(e){const{ones:n,rate:s,training:i=!1,count:r=1,dropoutFunc:a}=e,o=()=>null!=a?a(n(),s):ra(n(),s),l=()=>aa(o,n,i);if(!r||r<=1)return t.keep(l().clone());return Array(r).fill(void 0).map(l).map((e=>t.keep(e.clone())))}Tu.className="StackedRNNCells",s.registerClass(Tu);var Eu=function(t,e){var n={};for(var s in t)Object.prototype.hasOwnProperty.call(t,s)&&e.indexOf(s)<0&&(n[s]=t[s]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(s=Object.getOwnPropertySymbols(t);i<s.length;i++)e.indexOf(s[i])<0&&Object.prototype.propertyIsEnumerable.call(t,s[i])&&(n[s[i]]=t[s[i]])}return n};class $u extends ku{constructor(t){if(t.unroll)throw new Hi("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(t.cell))throw new Hi("It is not possible at the moment to stack convolutional cells.");super(t),this.inputSpec=[new Wa({ndim:5})]}call(e,n){return t.tidy((()=>{if(null!=this.cell.dropoutMask&&(t.dispose(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(t.dispose(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),n&&n.constants)throw new Gi("ConvRNN2D cell does not support constants");const s=null==n?null:n.mask,i=null==n?null:n.training,r=null==n?null:n.initialState;return super.call(e,{mask:s,training:i,initialState:r})}))}computeOutputShape(t){let e=this.computeSingleOutputShape(t);return this.returnSequences||(e=[e[0],...e.slice(2)]),this.returnState&&(e=[e,...Array(2).fill([t[0],...e.slice(-3)])]),e}getInitialState(e){return t.tidy((()=>{const{stateSize:n}=this.cell,s=e.shape,i=this.computeSingleOutputShape(s),r=[i[0],...i.slice(2)],a=t.zeros(r);return Array.isArray(n)?Array(n.length).fill(a):[a]}))}resetStates(e,s=!1){t.tidy((()=>{if(!this.stateful)throw new qi("Cannot call resetStates() on an RNN Layer that is not stateful.");const i=this.inputSpec[0].shape,r=this.computeSingleOutputShape(i),a=[r[0],...r.slice(2)];if(null==i[0])throw new Gi("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(null==this.getStates())Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((()=>t.zeros(a))):this.states_=[t.zeros(a)];else if(null==e)t.dispose(this.states_),null!=this.keptStates&&(t.dispose(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((()=>t.zeros(a))):this.states_[0]=t.zeros(a);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new Gi(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);s?this.keptStates.push(this.states_.slice()):t.dispose(this.states_);for(let t=0;t<this.states_.length;++t){const s=e[t],i=a;if(!n.arraysEqual(s.shape,i))throw new Gi(`State ${t} is incompatible with layer ${this.name}: expected shape=${i}, received shape=${s.shape}`);this.states_[t]=s}}this.states_=this.states_.map((e=>t.keep(e.clone())))}))}computeSingleOutputShape(t){const{dataFormat:e,filters:n,kernelSize:s,padding:i,strides:r,dilationRate:a}=this.cell,o="channelsFirst"===e,l=t[o?3:2],u=t[o?4:3],h=eu(l,s[0],i,r[0],a[0]),c=eu(u,s[1],i,r[1],a[1]);return[...t.slice(0,2),...o?[n,h,c]:[h,c,n]]}}$u.className="ConvRNN2D";class Fu extends Au{constructor(t){const{filters:e,kernelSize:n,strides:s,padding:i,dataFormat:r,dilationRate:a}=t;super(Object.assign({},t,{units:e})),this.filters=e,pr(this.filters,"filters"),this.kernelSize=tu(n,2,"kernelSize"),this.kernelSize.forEach((t=>pr(t,"kernelSize"))),this.strides=tu(s||1,2,"strides"),this.strides.forEach((t=>pr(t,"strides"))),this.padding=i||"valid",Dr(this.padding),this.dataFormat=r||"channelsLast",Fr(this.dataFormat),this.dilationRate=tu(a||1,2,"dilationRate"),this.dilationRate.forEach((t=>pr(t,"dilationRate")))}build(e){var n;e=Ma(e);const s="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[s])throw new Gi(`The channel dimension of the input should be defined. Found ${e[s]}`);const i=e[s],r=this.kernelSize.concat([i,4*this.filters]);this.kernel=this.addWeight("kernel",r,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);const a=this.kernelSize.concat([this.filters,4*this.filters]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",a,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let e;if(this.unitForgetBias){const s=this.biasInitializer,i=this.filters;e=new((n=class extends ua{apply(e,n){return Jr([s.apply([i]),t.ones([i]),s.apply([2*i])])}}).className="CustomInit",n)}else e=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.filters],null,e,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,n){return t.tidy((()=>{if(3!==e.length)throw new Gi(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);const s=n.training||!1,i=e[0],r=e[1],a=e[2];0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=zu({ones:()=>t.onesLike(i),rate:this.dropout,training:s,count:4,dropoutFunc:this.dropoutFunc}));const o=this.dropoutMask,l=(e,n,s)=>n&&n[s]?t.mul(n[s],e):e;let u=l(i,o,0),h=l(i,o,1),c=l(i,o,2),p=l(i,o,3);0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=zu({ones:()=>t.onesLike(r),rate:this.recurrentDropout,training:s,count:4,dropoutFunc:this.dropoutFunc}));const d=this.recurrentDropoutMask;let f=l(r,d,0),g=l(r,d,1),m=l(r,d,2),y=l(r,d,3);const[b,w,k,v]=t.split(this.kernel.read(),4,3),[S,x,N,I]=this.useBias?t.split(this.bias.read(),4):[null,null,null,null];u=this.inputConv(u,b,S,this.padding),h=this.inputConv(h,w,x,this.padding),c=this.inputConv(c,k,N,this.padding),p=this.inputConv(p,v,I,this.padding);const[A,C,T,z]=t.split(this.recurrentKernel.read(),4,3);f=this.recurrentConv(f,A),g=this.recurrentConv(g,C),m=this.recurrentConv(m,T),y=this.recurrentConv(y,z);const E=this.recurrentActivation.apply(t.add(u,f)),$=this.recurrentActivation.apply(t.add(h,g)),F=t.add(t.mul($,a),t.mul(E,this.activation.apply(t.add(c,m)))),D=t.mul(this.recurrentActivation.apply(t.add(p,y)),this.activation.apply(F));return[D,D,F]}))}getConfig(){const t=super.getConfig(),e=Eu(t,["units"]),n={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return Object.assign({},e,n)}inputConv(e,n,s,i){const r=t.conv2d(e,n,this.strides,i||"valid","channelsFirst"===this.dataFormat?"NCHW":"NHWC",this.dilationRate);return s?ia(r,s,this.dataFormat):r}recurrentConv(e,n){return t.conv2d(e,n,1,"same","channelsFirst"===this.dataFormat?"NCHW":"NHWC")}}Fu.className="ConvLSTM2DCell",t.serialization.registerClass(Fu);class Du extends $u{constructor(t){const e=new Fu(t);super(Object.assign({},t,{cell:e}))}static fromConfig(t,e){return new t(e)}}Du.className="ConvLSTM2D",t.serialization.registerClass(Du);class Lu extends Ga{constructor(t){super(t),this.rate=Math.max(Math.min(t.rate,1),0),this.noiseShape=t.noiseShape,this.seed=t.seed,this.supportsMasking=!0}getNoiseShape(t){if(null==this.noiseShape)return this.noiseShape;const e=t.shape,n=[];for(let t=0;t<this.noiseShape.length;++t)n.push(null==this.noiseShape[t]?e[t]:this.noiseShape[t]);return n}call(t,e){return i((()=>{this.invokeCallHook(t,e);const n=Ra(t);if(0<this.rate&&this.rate<1){const t=null!=e.training&&e.training,s=this.getNoiseShape(n);return aa((()=>ra(n,this.rate,s,this.seed)),(()=>n),t)}return t}))}getConfig(){const t={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},e=super.getConfig();return Object.assign(t,e),t}dispose(){return super.dispose()}}Lu.className="Dropout",s.registerClass(Lu);class _u extends Lu{constructor(t){super(t),this.inputSpec=[{ndim:3}]}getNoiseShape(t){const e=t.shape;return[e[0],1,e[2]]}}_u.className="SpatialDropout1D",s.registerClass(_u);class Ru extends Ga{constructor(t){if(super(t),this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",null==t.batchInputShape&&null==t.inputShape&&null!=t.inputDim){let e=null;null!=t.batchSize&&(e=t.batchSize),this.batchInputShape=[e,t.inputDim]}this.units=t.units,pr(this.units,"units"),this.activation=Pl(t.activation),null!=t.useBias&&(this.useBias=t.useBias),this.kernelInitializer=Ta(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=Ta(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=Nr(t.kernelConstraint),this.biasConstraint=Nr(t.biasConstraint),this.kernelRegularizer=Gl(t.kernelRegularizer),this.biasRegularizer=Gl(t.biasRegularizer),this.activityRegularizer=Gl(t.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(t){const e=(t=Ma(t))[t.length-1];null==this.kernel&&(this.kernel=this.addWeight("kernel",[e,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:{[-1]:e}}],this.built=!0}computeOutputShape(t){const e=(t=Ma(t)).slice();return e[e.length-1]=this.units,e}call(t,e){return i((()=>{this.invokeCallHook(t,e);const n=Ra(t),s=fr(this.activation.getClassName());let i;return null!=s?i=ta(n,this.kernel.read(),s,this.bias?this.bias.read():null):(i=ta(n,this.kernel.read()),null!=this.bias&&(i=ia(i,this.bias.read())),null!=this.activation&&(i=this.activation.apply(i))),i}))}getConfig(){const t={units:this.units,activation:Ol(this.activation),useBias:this.useBias,kernelInitializer:Ca(this.kernelInitializer),biasInitializer:Ca(this.biasInitializer),kernelRegularizer:ql(this.kernelRegularizer),biasRegularizer:ql(this.biasRegularizer),activityRegularizer:ql(this.activityRegularizer),kernelConstraint:Sr(this.kernelConstraint),biasConstraint:Sr(this.biasConstraint)},e=super.getConfig();return Object.assign(t,e),t}}Ru.className="Dense",s.registerClass(Ru);class Mu extends Ga{constructor(t){super(t=t||{}),this.inputSpec=[{minNDim:3}],this.dataFormat=t.dataFormat}computeOutputShape(t){t=Ma(t);for(const e of t.slice(1))if(null==e)throw new Gi(`The shape of the input to "Flatten" is not fully defined (got ${t.slice(1)}). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.`);return[t[0],Ur(t,1)]}call(e,n){return i((()=>{this.invokeCallHook(e,n);let s=Ra(e);if("channelsFirst"===this.dataFormat&&s.rank>1){const t=[0];for(let e=2;e<s.rank;++e)t.push(e);t.push(1),s=f(s,t)}return function(e){if(e.rank<=1)throw new Gi(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);const n=[e.shape[0],Ur(e.shape,1)];return t.reshape(e,n)}(s)}))}getConfig(){const t={};null!=this.dataFormat&&(t.dataFormat=this.dataFormat);const e=super.getConfig();return Object.assign(t,e),t}}Mu.className="Flatten",s.registerClass(Mu);class Ou extends Ga{constructor(t){super(t),this.supportsMasking=!0,this.activation=Pl(t.activation)}call(t,e){return i((()=>{this.invokeCallHook(t,e);const n=Ra(t);return this.activation.apply(n)}))}getConfig(){const t={activation:Ol(this.activation)},e=super.getConfig();return Object.assign(t,e),t}}Ou.className="Activation",s.registerClass(Ou);class Bu extends Ga{constructor(t){super(t),this.n=t.n,this.inputSpec=[{ndim:2}]}computeOutputShape(t){return[t[0],this.n,t[1]]}call(t,e){return i((()=>{return t=Ra(t),e=t,n=this.n,i((()=>{if(2!==e.shape.length)throw new Gi(`repeat() expects a rank-2 tensor, but received a rank-${e.shape.length} tensor.`);return Xr(Kr(e,1),[1,n,1])}));var e,n}))}getConfig(){const t={n:this.n},e=super.getConfig();return Object.assign(t,e),t}}Bu.className="RepeatVector",s.registerClass(Bu);class Pu extends Ga{constructor(t){super(t),this.targetShape=t.targetShape;for(let t=0;t<this.targetShape.length;++t)this.isUnknown(this.targetShape[t])&&(this.targetShape[t]=null)}isUnknown(t){return t<0||null==t}fixUnknownDimension(t,e){const n="Total size of new array must be unchanged.",s=e.slice();let i=1,r=null;for(let t=0;t<s.length;++t){const e=s[t];if(this.isUnknown(e)){if(null!==r)throw new Gi("Can only specifiy one unknown dimension.");r=t}else i*=e}const a=Ur(t);if(null!==r){if(0===i||a%i!=0)throw new Gi(n);s[r]=a/i}else if(a!==i)throw new Gi(n);return s}computeOutputShape(t){let e=!1;for(let n=0;n<t.length;++n)if(this.isUnknown(t[n])){e=!0;break}return e?t.slice(0,1).concat(this.targetShape):t.slice(0,1).concat(this.fixUnknownDimension(t.slice(1),this.targetShape))}call(t,e){return i((()=>{this.invokeCallHook(t,e);const n=Ra(t),s=n.shape,i=s.slice(0,1).concat(this.fixUnknownDimension(s.slice(1),this.targetShape));return I(n,i)}))}getConfig(){const t={targetShape:this.targetShape},e=super.getConfig();return Object.assign(t,e),t}}Pu.className="Reshape",s.registerClass(Pu);class Uu extends Ga{constructor(t){if(super(t),null==t.dims)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(t.dims))throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${t.dims} instead.`);const e=jr(1,t.dims.length+1);if(!n.arraysEqual(t.dims.slice().sort(),e))throw new Error("Invalid permutation `dims`: "+JSON.stringify(t.dims)+" `dims` must contain consecutive integers starting from 1.");this.dims=t.dims,this.dimsIncludingBatch=[0].concat(this.dims),this.inputSpec=[new Wa({ndim:this.dims.length+1})]}computeOutputShape(t){const e=(t=Ma(t)).slice();return this.dims.forEach(((n,s)=>{e[s+1]=t[n]})),e}call(t,e){return f(Ra(t),this.dimsIncludingBatch)}getConfig(){const t={dims:this.dims},e=super.getConfig();return Object.assign(t,e),t}}Uu.className="Permute",s.registerClass(Uu);class Wu extends Ga{constructor(t){super(null==t?{}:t),this.supportsMasking=!0,this.maskValue=null!=t?null==t.maskValue?0:t.maskValue:0}computeOutputShape(t){return t}getConfig(){const t=super.getConfig(),e={maskValue:this.maskValue};return Object.assign(e,t),e}computeMask(t,e){const n=Ra(t);return M(O(n,this.maskValue),-1)}call(t,e){return i((()=>{this.invokeCallHook(t,e);const n=Ra(t),s=M(O(n,this.maskValue),-1,!0);return l(n,S(s,n.dtype))}))}}Wu.className="Masking",s.registerClass(Wu);class Vu extends Ga{constructor(t){if(super(t),this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",null==t.batchInputShape&&null==t.inputShape){let e=null;null!=t.batchSize&&(e=t.batchSize),null==t.inputLength?this.batchInputShape=[e,null]:this.batchInputShape=[e].concat(tr(t.inputLength))}this.inputDim=t.inputDim,pr(this.inputDim,"inputDim"),this.outputDim=t.outputDim,pr(this.outputDim,"outputDim"),this.embeddingsInitializer=Ta(t.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=Gl(t.embeddingsRegularizer),this.activityRegularizer=Gl(t.activityRegularizer),this.embeddingsConstraint=Nr(t.embeddingsConstraint),this.maskZero=t.maskZero,this.supportsMasking=t.maskZero,this.inputLength=t.inputLength}build(t){this.embeddings=this.addWeight("embeddings",[this.inputDim,this.outputDim],this.dtype,this.embeddingsInitializer,this.embeddingsRegularizer,!0,this.embeddingsConstraint),this.built=!0}warnOnIncompatibleInputShape(t){}computeMask(t,e){return i((()=>this.maskZero?(t=Ra(t),O(t,B(t))):null))}computeOutputShape(t){if(t=Ma(t),null==this.inputLength)return[...t,this.outputDim];const e=tr(this.inputLength);if(e.length!==t.length-1)throw new Gi(`"inputLength" is ${this.inputLength}, but received input shape has shape ${t}`);{let n=0;for(let s=0;s<e.length;++s){const i=e[s],r=t[s+1];if(null!=i&&null!=r&&i!==r)throw new Gi(`"inputLength" is ${this.inputLength}, but received input shape has shape ${t}`);null==i&&(e[n]=r),n++}}return[t[0],...e,this.outputDim]}call(t,e){return i((()=>{this.invokeCallHook(t,e);let n=Ra(t);"int32"!==n.dtype&&(n=qr(n,"int32"));const s=ea(this.embeddings.read(),I(n,[n.size]));return I(s,Ma(this.computeOutputShape(n.shape)))}))}getConfig(){const t={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:Ca(this.embeddingsInitializer),embeddingsRegularizer:ql(this.embeddingsRegularizer),activityRegularizer:ql(this.activityRegularizer),embeddingsConstraint:Sr(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},e=super.getConfig();return Object.assign(t,e),t}}Vu.className="Embedding",s.registerClass(Vu);class ju extends Ga{constructor(t){super(t||{}),this.supportsMasking=!0}mergeFunction(t){throw new Hi}computeElementwiseOpOutputShape(t,e){if(null==t||null==e)return null;if(t.length<e.length)return this.computeElementwiseOpOutputShape(e,t);if(0===e.length)return t;const n=t.slice(0,t.length-e.length);for(let s=0;s<e.length;++s){const i=t[t.length-e.length+s],r=e[s];if(null==i||null==r||i<0||r<0)n.push(null);else if(1===i)n.push(r);else if(1===r)n.push(i);else{if(i!==r)throw new Gi("Operands could not be broadcast together with shapes "+JSON.stringify(t)+" "+JSON.stringify(e));n.push(i)}}return n}build(t){if(Array.isArray(t)&&!Array.isArray(t[0])&&(t=[Ma(t)]),(t=t).length<2)throw new Gi(`A merge layer should be called on an Array of at least 2 inputs. Got ${t.length} input(s).`);let e=[];for(const n of t)null!=n&&null!==n[0]&&e.push(n[0]);if(e=lr(e),e.length>1)throw new Gi(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(t)}.`);let n=null==t[0]?null:t[0].slice(1);for(let e=1;e<t.length;++e){const s=null==t[e]?null:t[e].slice(1);n=this.computeElementwiseOpOutputShape(n,s)}const s=t.map((t=>t.length));-1===t.indexOf(null)&&1===lr(s).length?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,n){return i((()=>{if(e=e,this.reshapeRequired){const n=[],s=e.map((t=>t.rank));if(-1===s.indexOf(null)){const t=Vr(s);for(let s of e){const e=s.rank;for(let n=0;n<t-e;++n)s=Kr(s,1);n.push(s)}return this.mergeFunction(n)}{let s=!1;for(const i of e){const e=i.rank;if(null==e){const e=i.shape,r=e[0],a=e.slice(1).concat([r]);let o=t.reshape(i,[r].concat(Ur(e.slice(1))));o=t.transpose(o,[1,0]),o=t.reshape(o,a),n.push(o),s=!0}else if(e>1){const r=jr(1,e).concat([0]);n.push(t.transpose(i,r)),s=!0}else n.push(i)}let i=this.mergeFunction(n);const r=i.rank;if(s)if(null==r){const e=i.shape,n=e[e.length-1],s=[n].concat(e.slice(0,e.length-1));i=t.reshape(t.transpose(t.reshape(i,[-1,n]),[1,0]),s)}else if(r>1){const e=[r-1].concat(jr(0,r-1));i=t.transpose(i,e)}return i}}return this.mergeFunction(e)}))}computeOutputShape(t){let e;e=null==(t=t)[0]?null:t[0].slice(1);for(let n=1;n<t.length;++n){const s=null==t[n]?null:t[n].slice(1);e=this.computeElementwiseOpOutputShape(e,s)}let n=[];for(const e of t)null!=e&&null!==e[0]&&n.push(e[0]);return n=lr(n),e=1===n.length?n.concat(e):[null].concat(e),e}computeMask(e,n){return t.tidy((()=>{if(null==n)return null;if(!Array.isArray(n))throw new Gi("`mask` should be an Array");if(!Array.isArray(e))throw new Gi("`inputs` should be an Array");if(n.length!==e.length)throw new Gi(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${n.length})`);if(n.every((t=>null==t)))return null;let s=(n=n.map((e=>null==e?e:t.expandDims(e,0))))[0];for(let e=1;e<n.length-1;++e)s=t.logicalAnd(s,n[e]);return s}))}}class qu extends ju{constructor(t){super(t)}mergeFunction(e){return i((()=>{let n=e[0].clone();for(let s=1;s<e.length;++s)n=t.add(n,e[s]);return n}))}}qu.className="Add",s.registerClass(qu);class Ku extends ju{constructor(t){super(t)}mergeFunction(e){return i((()=>{let n=e[0].clone();for(let s=1;s<e.length;++s)n=t.mul(n,e[s]);return n}))}}Ku.className="Multiply",s.registerClass(Ku);class Gu extends ju{constructor(t){super(t)}mergeFunction(e){return i((()=>{let n=e[0].clone();for(let s=1;s<e.length;++s)n=t.add(n,e[s]);return t.mul(1/e.length,n)}))}}Gu.className="Average",s.registerClass(Gu);class Hu extends ju{constructor(t){super(t)}mergeFunction(e){return i((()=>{let n=e[0];for(let s=1;s<e.length;++s)n=t.maximum(n,e[s]);return n}))}}Hu.className="Maximum",s.registerClass(Hu);class Zu extends ju{constructor(t){super(t)}mergeFunction(e){return i((()=>{let n=e[0];for(let s=1;s<e.length;++s)n=t.minimum(n,e[s]);return n}))}}Zu.className="Minimum",s.registerClass(Zu);class Ju extends ju{constructor(t){super(t),this.DEFAULT_AXIS=-1,null==t&&(t={}),this.axis=null==t.axis?this.DEFAULT_AXIS:t.axis,this.supportsMasking=!0,this.reshapeRequired=!1}build(t){if(!Array.isArray(t)||!Array.isArray(t[0])||1===t.length)throw new Gi("A `Concatenate` layer should be called on a list of at least 2 inputs");t=t;let e=!0;for(const n of t)if(null!=n){e=!1;break}if(e)return;const s=[];for(let e=0;e<t.length;++e){const i=t[e].slice();i.splice(this.axis,1);let r=!1;for(const t of s)if(n.arraysEqual(t,i)){r=!0;break}r||s.push(i)}if(s.length>1)throw new Gi("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(t))}mergeFunction(t){return i((()=>Jr(t,this.axis)))}computeOutputShape(t){if(!Array.isArray(t)||!Array.isArray(t[0]))throw new Gi("A `Concatenate` layer should be called on a list of inputs.");const e=t,n=e[0].slice(),s=this.axis<0?n.length+this.axis:this.axis;for(const t of e.slice(1)){if(null==n[s]||null==t[s]){n[s]=null;break}n[s]+=t[s]}return n}computeMask(e,n){if(null==n)return null;if(!Array.isArray(n))throw new Gi("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new Gi("`inputs` should be an array for Concatenate");if(n.length!==e.length)throw new Gi(`Mismatch in the length of mask (${n.length}) and the legnth of inputs (${e.length})`);return t.tidy((()=>{let s=!0;if(n.forEach((t=>{null==t||(s=!1)})),s)return null;const i=[];for(let s=0;s<e.length;++s)null==n[s]?i.push(t.cast(t.onesLike(e[s]),"bool")):n[s].rank<e[s].rank?i.push(t.expandDims(n[s],-1)):i.push(n[s]);const r=t.concat(i,this.axis);return t.all(r,-1,!1)}))}getConfig(){const t={axis:this.axis},e=super.getConfig();return Object.assign(t,e),t}}function Yu(t,e){for(;t<0;)t+=e;return t}Ju.className="Concatenate",s.registerClass(Ju);class Xu extends ju{constructor(t){super(t),this.axes=t.axes,this.normalize=null!=t.normalize&&t.normalize,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){t.util.assert(Array.isArray(e)&&2===e.length&&Array.isArray(e[0])&&Array.isArray(e[1]),(()=>"A `Dot` layer should be called on a list of exactly 2 inputs."));const n=e[0],s=e[1];if(n.length>3||s.length>3)throw new Hi("Dot layer does not support tensors of 4D or higher rank yet.");const i=this.interpretAxes(n,s);if(n[i[0]]!==s[i[1]])throw new Gi(`Dimension incompatibility: ${n[i[0]]} !== ${s[i[1]]}`)}mergeFunction(e){if(2!==e.length)throw new Gi(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let n,s=e[0],i=e[1];return n=Array.isArray(this.axes)?this.axes.map(((t,n)=>Yu(t,e[n].shape.length))):[Yu(this.axes,s.shape.length),Yu(this.axes,i.shape.length)],this.normalize&&(s=uo(s,n[0]),i=uo(i,n[1])),function(e,n,s){if(e.shape.length>3||n.shape.length>3)throw new Hi("batchDot is not implemented for tensors of 4D or higher rank yet");if(t.util.assert(e.shape.length>=2,(()=>`batchDot requires the rank of x to be >= 2, but got ${e.shape.length}`)),t.util.assert(e.shape.length>=2,(()=>`batchDot requires the rank of y to be >= 2, but got ${n.shape.length}`)),"number"==typeof s&&(s=[s,s]),"complex64"===e.dtype||"complex64"===n.dtype)throw new Hi("batchDot is not implemented for complex64-type Tensors yet.");const i=e.shape.length,r=n.shape.length;null==s&&(s=[i-1,r-2]);const a=s;return t.tidy((()=>{let s,o;if(i>r){s=i-r;const e=[];for(let t=0;t<s;++t)e.push(1);n=t.reshape(n,n.shape.concat(e))}else if(r>i){s=r-i;const n=[];for(let t=0;t<s;++t)n.push(1);e=t.reshape(e,e.shape.concat(n))}else s=0;if(2===e.shape.length&&2===n.shape.length)o=a[0]===a[1]?t.sum(t.mul(e,n),a[0]):t.sum(t.mul(t.transpose(e,[1,0]),n),a[1]);else{const s=a[0]!==e.shape.length-1,i=a[1]===n.shape.length-1;o=t.matMul(e,n,s,i)}if(s>0){let e;e=i>r?i+r-3:i-1;const n=[];for(let t=e;t<e+s;++t)n.push(t);o=t.squeeze(o,n)}return 1===o.shape.length&&(o=t.expandDims(o,1)),o}))}(s,i,n)}interpretAxes(t,e){let n;return n=Array.isArray(this.axes)?this.axes:[Yu(this.axes,t.length),Yu(this.axes,e.length)],n}computeOutputShape(e){t.util.assert(Array.isArray(e)&&2===e.length&&Array.isArray(e[0])&&Array.isArray(e[1]),(()=>"A `Dot` layer should be called on a list of exactly 2 inputs."));const n=e[0].slice(),s=e[1].slice();if(n.length>3||s.length>3)throw new Hi("Dot layer does not support tensors of 4D or higher rank yet.");const i=this.interpretAxes(n,s);n.splice(i[0],1),s.splice(i[1],1),s.splice(0,1);const r=n.concat(s);return 1===r.length&&r.push(1),r}computeMask(t,e){return null}getConfig(){const t={axes:this.axes,normalize:this.normalize},e=super.getConfig();return Object.assign(t,e),t}}Xu.className="Dot",s.registerClass(Xu);class Qu extends Ga{constructor(t){super(t),this.supportsMasking=!0,this.stddev=t.stddev}computeOutputShape(t){return t}getConfig(){const t=super.getConfig(),e={stddev:this.stddev};return Object.assign(e,t),e}call(t,e){return i((()=>{this.invokeCallHook(t,e);const n=Ra(t);return aa((()=>y(Qr(n.shape,0,this.stddev),n)),(()=>n),e.training||!1)}))}}Qu.className="GaussianNoise",s.registerClass(Qu);class th extends Ga{constructor(t){super(t),this.supportsMasking=!0,this.rate=t.rate}computeOutputShape(t){return t}getConfig(){const t=super.getConfig(),e={rate:this.rate};return Object.assign(e,t),e}call(t,e){return i((()=>{this.invokeCallHook(t,e);const n=Ra(t);if(this.rate>0&&this.rate<1){return aa((()=>{const t=Math.sqrt(this.rate/(1-this.rate));return l(n,Qr(n.shape,1,t))}),(()=>n),e.training||!1)}return n}))}}th.className="GaussianDropout",s.registerClass(th);class eh extends Ga{constructor(t){super(t),this.supportsMasking=!0,this.rate=t.rate,this.noiseShape=t.noiseShape}_getNoiseShape(t){return this.noiseShape||Ra(t).shape}computeOutputShape(t){return t}getConfig(){const t=super.getConfig(),e={rate:this.rate};return Object.assign(e,t),e}call(t,e){return i((()=>{if(this.rate<1&&this.rate>0){const n=this._getNoiseShape(t);return aa((()=>{const e=Ra(t),s=-1.7580993408473766;let i=P(h(n),this.rate);i=qr(i,"float32");const r=((1-this.rate)*(1+this.rate*s**2))**-.5,a=-r*s*this.rate,o=y(l(e,i),l(y(i,-1),s));return y(l(o,r),a)}),(()=>Ra(t)),e.training||!1)}return t}))}}function nh(e,n,s,i,r,a=.001){let o;if(2===e.rank)o=t.batchNorm2d(e,n,s,i,r,a);else if(3===e.rank)o=t.batchNorm3d(e,n,s,i,r,a);else{if(4!==e.rank)throw new Hi(`batchNormalization is not implemented for array of rank ${e.rank} yet`);o=t.batchNorm4d(e,n,s,i,r,a)}return o}function sh(e,s,r,a,o=.001){return n.arraysEqual(a.slice().sort(),jr(0,e.rank-1))?function(e,n,s,r,a=.001){return i((()=>{const i=t.moments(e,r),o=i.mean,l=i.variance;return[nh(e,o,l,s,n,a),o,l]}))}(e,s,r,a,o):function(e,n,s,r,a=.001){return i((()=>{const i=t.moments(e,r),o=i.mean,l=i.variance,u=[];for(const t of jr(0,e.rank))-1!==r.indexOf(t)?u.push(1):u.push(e.shape[t]);const h=I(o,u),c=I(l,u),p=null==n?null:I(n,u),d=null==s?null:I(s,u);return[nh(e,h,c,d,p,a),o,l]}))}(e,s,r,a,o)}eh.className="AlphaDropout",s.registerClass(eh);class ih extends Ga{constructor(t){null==t&&(t={}),super(t),this.supportsMasking=!0,this.axis=null==t.axis?-1:t.axis,this.momentum=null==t.momentum?.99:t.momentum,this.epsilon=null==t.epsilon?.001:t.epsilon,this.center=null==t.center||t.center,this.scale=null==t.scale||t.scale,this.betaInitializer=Ta(t.betaInitializer||"zeros"),this.gammaInitializer=Ta(t.gammaInitializer||"ones"),this.movingMeanInitializer=Ta(t.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=Ta(t.movingVarianceInitializer||"ones"),this.betaConstraint=Nr(t.betaConstraint),this.gammaConstraint=Nr(t.gammaConstraint),this.betaRegularizer=Gl(t.betaRegularizer),this.gammaRegularizer=Gl(t.gammaRegularizer)}build(t){t=Ma(t);const e=this.axis>=0?this.axis:this.axis+t.length,n=t[e];if(null==n)throw new Gi(`Axis ${e} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(t)}.`);this.inputSpec=[new Wa({ndim:t.length,axes:{[e]:n}})];const s=[n];this.scale&&(this.gamma=this.addWeight("gamma",s,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",s,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",s,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",s,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,s){return i((()=>{const i=null!=s.training&&s.training,r=Ra(e),a=r.shape,o=a.length,l=jr(0,o),u=this.axis>=0?this.axis:this.axis+o;l.splice(u,1);const h=Ji(1,o);h[u]=a[u];const c=l.slice();c.sort();const p=!n.arraysEqual(c,jr(0,o).slice(0,o-1));if(!i)return(()=>{if(p){const t=I(this.movingMean.read(),h),e=I(this.movingVariance.read(),h),n=this.center?I(this.beta.read(),h):null,s=this.scale?I(this.gamma.read(),h):null;return nh(r,t,e,n,s,this.epsilon)}return nh(r,this.movingMean.read(),this.movingVariance.read(),null==this.beta?null:this.beta.read(),null==this.gamma?null:this.gamma.read(),this.epsilon)})();const[d,f,g]=sh(r,this.gamma.read(),this.beta.read(),l,this.epsilon),m=(e,n,s)=>{t.tidy((()=>{const i=1-s,r=e.read(),a=t.mul(t.sub(r,n),i);e.write(t.sub(r,a))}))};return(()=>{m(this.movingMean,f,this.momentum),m(this.movingVariance,g,this.momentum)})(),d}))}getConfig(){const t={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Ca(this.betaInitializer),gammaInitializer:Ca(this.gammaInitializer),movingMeanInitializer:Ca(this.movingMeanInitializer),movingVarianceInitializer:Ca(this.movingVarianceInitializer),betaRegularizer:ql(this.betaRegularizer),gammaRegularizer:ql(this.gammaRegularizer),betaConstraint:Sr(this.betaConstraint),gammaConstraint:Sr(this.gammaConstraint)},e=super.getConfig();return Object.assign(t,e),t}}ih.className="BatchNormalization",s.registerClass(ih);class rh extends Ga{constructor(t){if(null==t&&(t={}),super(t),this.axis=null==t.axis?-1:t.axis,"number"==typeof this.axis){if(!Number.isInteger(this.axis))throw new Error(`Expected axis to be an integer, but received ${this.axis}`)}else{if(!Array.isArray(this.axis))throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);for(const t of this.axis)if(!Number.isInteger(t))throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`)}this.epsilon=null==t.epsilon?.001:t.epsilon,this.center=null==t.center||t.center,this.scale=null==t.scale||t.scale,this.betaInitializer=Ta(t.betaInitializer||"zeros"),this.gammaInitializer=Ta(t.gammaInitializer||"ones"),this.betaRegularizer=Gl(t.betaRegularizer),this.gammaRegularizer=Gl(t.gammaRegularizer),this.supportsMasking=!0}build(t){const e=(t=Ma(t)).length;"number"==typeof this.axis&&(this.axis=[this.axis]);for(let t=0;t<this.axis.length;++t)this.axis[t]<0&&(this.axis[t]+=e);for(const t of this.axis)if(t<0||t>=e)throw new Error(`Invalid axis: ${t}`);if(this.axis.length!==lr(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);const n=this.axis.map((e=>t[e]));this.scale?this.gamma=this.addWeight("gamma",n,"float32",this.gammaInitializer,this.gammaRegularizer,true):this.gamma=null,this.center?this.beta=this.addWeight("beta",n,"float32",this.betaInitializer,this.betaRegularizer,true):this.beta=null,this.built=!0}call(e,n){const s=Ra(e),r=s.shape,a=r.length;return i((()=>{let{mean:e,variance:n}=U(s,this.axis,!0);const i=Ji(1,a);for(const t of this.axis)i[t]=r[t];const o=e=>null!=e&&e.shape.length!==a?t.reshape(e,i):e;let l=o(this.gamma.read()),u=o(this.beta.read());const h=[],c=[];for(let t=0;t<a;++t)-1!==this.axis.indexOf(t)?(h.push(r[t]),c.push(1)):(h.push(1),c.push(r[t]));return e=t.tile(e,h),n=t.tile(n,h),l=t.tile(l,c),u=t.tile(u,c),nh(s,e,n,u,l,this.epsilon)}))}getConfig(){const t={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Ca(this.betaInitializer),gammaInitializer:Ca(this.gammaInitializer),betaRegularizer:ql(this.betaRegularizer),gammaRegularizer:ql(this.gammaRegularizer)},e=super.getConfig();return Object.assign(t,e),t}}rh.className="LayerNormalization",s.registerClass(rh);class ah extends Ga{constructor(t){if(null==t&&(t={}),super(t),this.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,null==t.padding)this.padding=[[1,1],[1,1]];else if("number"==typeof t.padding)this.padding=[[t.padding,t.padding],[t.padding,t.padding]];else{if(t.padding=t.padding,2!==t.padding.length)throw new Gi(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${t.padding.length} array.`);let e,n;if("number"==typeof t.padding[0])e=[t.padding[0],t.padding[0]],n=[t.padding[1],t.padding[1]];else{if(t.padding=t.padding,2!==t.padding[0].length)throw new Gi(`ZeroPadding2D expects height padding to be a length-2 array, but received a length-${t.padding[0].length} array.`);if(e=t.padding[0],2!==t.padding[1].length)throw new Gi(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${t.padding[1].length} array.`);n=t.padding[1]}this.padding=[e,n]}this.inputSpec=[new Wa({ndim:4})]}computeOutputShape(t){let e,n;return t=Ma(t),"channelsFirst"===this.dataFormat?(e=null!=t[2]&&t[2]>=0?t[2]+this.padding[0][0]+this.padding[0][1]:null,n=null!=t[3]&&t[3]>=0?t[3]+this.padding[1][0]+this.padding[1][1]:null,[t[0],t[1],e,n]):(e=null!=t[1]&&t[1]>=0?t[1]+this.padding[0][0]+this.padding[0][1]:null,n=null!=t[2]&&t[2]>=0?t[2]+this.padding[1][0]+this.padding[1][1]:null,[t[0],e,n,t[3]])}call(e,n){return i((()=>{return n=Ra(e),s=this.padding,r=this.dataFormat,i((()=>{if(4!==n.rank)throw new Gi(`temporalPadding expects input tensor to be 4-D, but received a ${n.rank}-D tensor.`);if(null==s&&(s=[[1,1],[1,1]]),2!==s.length||2!==s[0].length||2!==s[1].length)throw new Gi("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(null==r&&(r="channelsLast"),"channelsLast"!==r&&"channelsFirst"!==r)throw new Gi(`Unknown data format: ${r}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let e;return e="channelsFirst"===r?[[0,0],[0,0],s[0],s[1]]:[[0,0],s[0],s[1],[0,0]],t.pad(n,e)}));var n,s,r}))}getConfig(){const t={padding:this.padding,dataFormat:this.dataFormat},e=super.getConfig();return Object.assign(t,e),t}}function oh(e,n,s,r,a,o){return i((()=>{let i;Fr(a),Lr(o),Dr(r),null==s&&(s=[1,1]),null==r&&(r="valid"),null==a&&(a="channelsLast"),null==o&&(o="max"),e=su(e,a);const l="same"===r?"same":"valid";return i="max"===o?t.maxPool(e,n,s,l):t.avgPool(e,n,s,l),"channelsFirst"===a&&(i=t.transpose(i,[0,3,1,2])),i}))}function lh(e,n,s,r,a,o){return i((()=>{let i;Fr(a),Lr(o),Dr(r),null==s&&(s=[1,1,1]),null==r&&(r="valid"),null==a&&(a="channelsLast"),null==o&&(o="max"),e=iu(e,a);const l="same"===r?"same":"valid";return i="max"===o?t.maxPool3d(e,n,s,l):t.avgPool3d(e,n,s,l),"channelsFirst"===a&&(i=t.transpose(i,[0,4,1,2,3])),i}))}ah.className="ZeroPadding2D",s.registerClass(ah);class uh extends Ga{constructor(t){if(null==t.poolSize&&(t.poolSize=2),super(t),"number"==typeof t.poolSize)this.poolSize=[t.poolSize];else{if(!Array.isArray(t.poolSize)||1!==t.poolSize.length||"number"!=typeof t.poolSize[0])throw new Gi(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(t.poolSize)}`);this.poolSize=t.poolSize}if(pr(this.poolSize,"poolSize"),null==t.strides)this.strides=this.poolSize;else if("number"==typeof t.strides)this.strides=[t.strides];else{if(!Array.isArray(t.strides)||1!==t.strides.length||"number"!=typeof t.strides[0])throw new Gi(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(t.strides)}`);this.strides=t.strides}pr(this.strides,"strides"),this.padding=null==t.padding?"valid":t.padding,Dr(this.padding),this.inputSpec=[new Wa({ndim:3})]}computeOutputShape(t){const e=eu((t=Ma(t))[1],this.poolSize[0],this.padding,this.strides[0]);return[t[0],e,t[2]]}call(e,n){return i((()=>{this.invokeCallHook(e,n),e=Kr(Ra(e),2);const s=this.poolingFunction(Ra(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return t.squeeze(s,[2])}))}getConfig(){const t={poolSize:this.poolSize,padding:this.padding,strides:this.strides},e=super.getConfig();return Object.assign(t,e),t}}class hh extends uh{constructor(t){super(t)}poolingFunction(t,e,n,s,i){return Fr(i),Dr(s),oh(t,e,n,s,i,"max")}}hh.className="MaxPooling1D",s.registerClass(hh);class ch extends uh{constructor(t){super(t)}poolingFunction(t,e,n,s,i){return Fr(i),Dr(s),oh(t,e,n,s,i,"avg")}}ch.className="AveragePooling1D",s.registerClass(ch);class ph extends Ga{constructor(t){if(null==t.poolSize&&(t.poolSize=[2,2]),super(t),this.poolSize=Array.isArray(t.poolSize)?t.poolSize:[t.poolSize,t.poolSize],null==t.strides)this.strides=this.poolSize;else if(Array.isArray(t.strides)){if(2!==t.strides.length)throw new Gi(`If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length ${t.strides.length}.`);this.strides=t.strides}else this.strides=[t.strides,t.strides];pr(this.poolSize,"poolSize"),pr(this.strides,"strides"),this.padding=null==t.padding?"valid":t.padding,this.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,Fr(this.dataFormat),Dr(this.padding),this.inputSpec=[new Wa({ndim:4})]}computeOutputShape(t){t=Ma(t);let e="channelsFirst"===this.dataFormat?t[2]:t[1],n="channelsFirst"===this.dataFormat?t[3]:t[2];return e=eu(e,this.poolSize[0],this.padding,this.strides[0]),n=eu(n,this.poolSize[1],this.padding,this.strides[1]),"channelsFirst"===this.dataFormat?[t[0],t[1],e,n]:[t[0],e,n,t[3]]}call(t,e){return i((()=>(this.invokeCallHook(t,e),this.poolingFunction(Ra(t),this.poolSize,this.strides,this.padding,this.dataFormat))))}getConfig(){const t={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},e=super.getConfig();return Object.assign(t,e),t}}class dh extends ph{constructor(t){super(t)}poolingFunction(t,e,n,s,i){return Fr(i),Dr(s),oh(t,e,n,s,i,"max")}}dh.className="MaxPooling2D",s.registerClass(dh);class fh extends ph{constructor(t){super(t)}poolingFunction(t,e,n,s,i){return Fr(i),Dr(s),oh(t,e,n,s,i,"avg")}}fh.className="AveragePooling2D",s.registerClass(fh);class gh extends Ga{constructor(t){if(null==t.poolSize&&(t.poolSize=[2,2,2]),super(t),this.poolSize=Array.isArray(t.poolSize)?t.poolSize:[t.poolSize,t.poolSize,t.poolSize],null==t.strides)this.strides=this.poolSize;else if(Array.isArray(t.strides)){if(3!==t.strides.length)throw new Gi(`If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length ${t.strides.length}.`);this.strides=t.strides}else this.strides=[t.strides,t.strides,t.strides];pr(this.poolSize,"poolSize"),pr(this.strides,"strides"),this.padding=null==t.padding?"valid":t.padding,this.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,Fr(this.dataFormat),Dr(this.padding),this.inputSpec=[new Wa({ndim:5})]}computeOutputShape(t){t=Ma(t);let e="channelsFirst"===this.dataFormat?t[2]:t[1],n="channelsFirst"===this.dataFormat?t[3]:t[2],s="channelsFirst"===this.dataFormat?t[4]:t[3];return e=eu(e,this.poolSize[0],this.padding,this.strides[0]),n=eu(n,this.poolSize[1],this.padding,this.strides[1]),s=eu(s,this.poolSize[2],this.padding,this.strides[2]),"channelsFirst"===this.dataFormat?[t[0],t[1],e,n,s]:[t[0],e,n,s,t[4]]}call(t,e){return i((()=>(this.invokeCallHook(t,e),this.poolingFunction(Ra(t),this.poolSize,this.strides,this.padding,this.dataFormat))))}getConfig(){const t={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},e=super.getConfig();return Object.assign(t,e),t}}class mh extends gh{constructor(t){super(t)}poolingFunction(t,e,n,s,i){return Fr(i),Dr(s),lh(t,e,n,s,i,"max")}}mh.className="MaxPooling3D",s.registerClass(mh);class yh extends gh{constructor(t){super(t)}poolingFunction(t,e,n,s,i){return Fr(i),Dr(s),lh(t,e,n,s,i,"avg")}}yh.className="AveragePooling3D",s.registerClass(yh);class bh extends Ga{constructor(t){super(t),this.inputSpec=[new Wa({ndim:3})]}computeOutputShape(t){return[t[0],t[2]]}call(t,e){throw new Hi}}class wh extends bh{constructor(t){super(t||{})}call(e,n){return i((()=>{const n=Ra(e);return t.mean(n,1)}))}}wh.className="GlobalAveragePooling1D",s.registerClass(wh);class kh extends bh{constructor(t){super(t||{})}call(e,n){return i((()=>{const n=Ra(e);return t.max(n,1)}))}}kh.className="GlobalMaxPooling1D",s.registerClass(kh);class vh extends Ga{constructor(t){super(t),this.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,Fr(this.dataFormat),this.inputSpec=[new Wa({ndim:4})]}computeOutputShape(t){return t=t,"channelsLast"===this.dataFormat?[t[0],t[3]]:[t[0],t[1]]}call(t,e){throw new Hi}getConfig(){const t={dataFormat:this.dataFormat},e=super.getConfig();return Object.assign(t,e),t}}class Sh extends vh{call(e,n){return i((()=>{const n=Ra(e);return"channelsLast"===this.dataFormat?t.mean(n,[1,2]):t.mean(n,[2,3])}))}}Sh.className="GlobalAveragePooling2D",s.registerClass(Sh);class xh extends vh{call(e,n){return i((()=>{const n=Ra(e);return"channelsLast"===this.dataFormat?t.max(n,[1,2]):t.max(n,[2,3])}))}}xh.className="GlobalMaxPooling2D",s.registerClass(xh);class Nh extends Ga{constructor(t){super(t),this.layer=t.layer}build(t){this.built=!0}get trainable(){return null!=this.layer&&this.layer.trainable}set trainable(t){null!=this.layer&&(this.layer.trainable=t)}get trainableWeights(){return this.layer.trainableWeights}get nonTrainableWeights(){return this.layer.nonTrainableWeights}get updates(){return this.layer._updates}get losses(){return this.layer.losses}getWeights(){return this.layer.getWeights()}setWeights(t){this.layer.setWeights(t)}getConfig(){const t={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},e=super.getConfig();return Object.assign(t,e),t}setFastWeightInitDuringBuild(t){super.setFastWeightInitDuringBuild(t),null!=this.layer&&this.layer.setFastWeightInitDuringBuild(t)}static fromConfig(t,e,n={}){const s=lo(e.layer,n);delete e.layer;const i={layer:s};return Object.assign(i,e),new t(i)}}class Ih extends Nh{constructor(t){super(t),this.supportsMasking=!0}build(t){if((t=Ma(t)).length<3)throw new Gi(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(t)}`);this.inputSpec=[{shape:t}];const e=[t[0]].concat(t.slice(2));this.layer.built||(this.layer.build(e),this.layer.built=!0),super.build(t)}computeOutputShape(t){const e=[(t=Ma(t))[0]].concat(t.slice(2)),n=this.layer.computeOutputShape(e),s=t[1];return[n[0],s].concat(n.slice(1))}call(t,e){return i((()=>wu(((t,n)=>[Ra(this.layer.call(t,e)),[]]),t=Ra(t),[],!1,null,null,!1,!0)[1]))}}Ih.className="TimeDistributed",s.registerClass(Ih);class Ah extends Nh{constructor(t){super(t);const e=t.layer.getConfig(),n={};n.className=t.layer.getClassName(),n.config=e,this.forwardLayer=lo(n),e.goBackwards=!0!==e.goBackwards;const s={};var i;if(s.className=t.layer.getClassName(),s.config=e,this.backwardLayer=lo(s),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=void 0===t.mergeMode?"concat":t.mergeMode,i=this.mergeMode,hr(Er,"BidirectionalMergeMode",i),t.weights)throw new Hi("weights support is not implemented for Bidirectional layer yet.");this._stateful=t.layer.stateful,this.returnSequences=t.layer.returnSequences,this.returnState=t.layer.returnState,this.supportsMasking=!0,this._trainable=!0,this.inputSpec=t.layer.inputSpec,this.numConstants=null}get trainable(){return this._trainable}set trainable(t){this._trainable=t,null!=this.forwardLayer&&(this.forwardLayer.trainable=t),null!=this.backwardLayer&&(this.backwardLayer.trainable=t)}getWeights(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())}setWeights(t){const e=t.length,n=Math.floor(e/2);this.forwardLayer.setWeights(t.slice(0,n)),this.backwardLayer.setWeights(t.slice(n))}computeOutputShape(t){let e,n,s,i=this.forwardLayer.computeOutputShape(t);return Array.isArray(i)&&Array.isArray(i[0])||(i=[i]),i=i,this.returnState?(s=i.slice(1),e=i[0]):e=i[0],e=e,"concat"===this.mergeMode?(e[e.length-1]*=2,n=[e]):n=null==this.mergeMode?[e,e.slice()]:[e],this.returnState?null==this.mergeMode?n.concat(s).concat(s.slice()):[e].concat(s).concat(s.slice()):Qi(n)}apply(t,e){let n=null==e?null:e.initialState,s=null==e?null:e.constants;null==e&&(e={});const i=bu(t,n,s,this.numConstants);if(t=i.inputs,n=i.initialState,s=i.constants,Array.isArray(t)&&(n=t.slice(1),t=t[0]),(null==n||0===n.length)&&null==s)return super.apply(t,e);const r=[],a=[];if(null!=n){const t=n.length;if(t%2>0)throw new Gi("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");e.initialState=n,r.push(...n);const s=n.map((t=>new Wa({shape:t.shape})));this.forwardLayer.stateSpec=s.slice(0,t/2),this.backwardLayer.stateSpec=s.slice(t/2),a.push(...s)}if(null!=s)throw new Hi("Support for constants in Bidirectional layers is not implemented yet.");const o=r[0]instanceof Va;for(const t of r)if(t instanceof Va!==o)throw new Gi("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(o){const n=[t].concat(r),s=this.inputSpec.concat(a),i=this.inputSpec;this.inputSpec=s;const o=super.apply(n,e);return this.inputSpec=i,o}return super.apply(t,e)}call(e,n){return i((()=>{const s=n.initialState;let i,r,a,o;if(null==s)i=this.forwardLayer.call(e,n),r=this.backwardLayer.call(e,n);else{const t=s.slice(0,s.length/2),a=s.slice(s.length/2);i=this.forwardLayer.call(e,Object.assign(n,{initialState:t})),r=this.backwardLayer.call(e,Object.assign(n,{initialState:a}))}return this.returnState&&(Array.isArray(i)&&(a=i.slice(1).concat(r.slice(1))),i=i[0],r=r[0]),this.returnSequences&&(r=t.reverse(r,1)),"concat"===this.mergeMode?o=Jr([i,r]):"sum"===this.mergeMode?o=t.add(i,r):"ave"===this.mergeMode?o=t.mul(.5,t.add(i,r)):"mul"===this.mergeMode?o=t.mul(i,r):null==this.mergeMode&&(o=[i,r]),this.returnState?null==this.mergeMode?o.concat(a):[o].concat(a):o}))}resetStates(t){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(t){Rr(this.forwardLayer.name,(()=>{this.forwardLayer.build(t)})),Rr(this.backwardLayer.name,(()=>{this.backwardLayer.build(t)})),this.built=!0}computeMask(t,e){let n;if(Array.isArray(e)&&(e=e[0]),n=this.returnSequences?null==this.mergeMode?[e,e]:e:null==this.mergeMode?[null,null]:null,this.returnState){const t=this.forwardLayer.states.map((t=>null));return Array.isArray(n)?n.concat(t).concat(t):[n].concat(t).concat(t)}return n}get trainableWeights(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)}get nonTrainableWeights(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)}setFastWeightInitDuringBuild(t){super.setFastWeightInitDuringBuild(t),null!=this.forwardLayer&&this.forwardLayer.setFastWeightInitDuringBuild(t),null!=this.backwardLayer&&this.backwardLayer.setFastWeightInitDuringBuild(t)}getConfig(){const t={mergeMode:this.mergeMode},e=super.getConfig();return Object.assign(t,e),t}static fromConfig(t,e){const n=lo(e.layer);if(delete e.layer,null!=e.numConstants)throw new Hi("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");const s=e;return s.layer=n,new t(s)}}function Ch(t){return new ch(t)}function Th(t){return new fh(t)}function zh(t){return new yh(t)}function Eh(t){return new kh(t)}function $h(t){return new xh(t)}function Fh(t){return new hh(t)}function Dh(t){return new dh(t)}Ah.className="Bidirectional",s.registerClass(Ah);var Lh={__proto__:null,inputLayer:function(t){return new Za(t)},elu:function(t){return new Yl(t)},reLU:function(t){return new Hl(t)},leakyReLU:function(t){return new Zl(t)},prelu:function(t){return new Jl(t)},softmax:function(t){return new Ql(t)},thresholdedReLU:function(t){return new Xl(t)},conv1d:function(t){return new fu(t)},conv2d:function(t){return new lu(t)},conv2dTranspose:function(t){return new hu(t)},conv3d:function(t){return new uu(t)},conv3dTranspose:function(t){return new cu(t)},separableConv2d:function(t){return new du(t)},cropping2D:function(t){return new gu(t)},upSampling2d:function(t){return new mu(t)},depthwiseConv2d:function(t){return new yu(t)},activation:function(t){return new Ou(t)},dense:function(t){return new Ru(t)},dropout:function(t){return new Lu(t)},spatialDropout1d:function(t){return new _u(t)},flatten:function(t){return new Mu(t)},repeatVector:function(t){return new Bu(t)},reshape:function(t){return new Pu(t)},permute:function(t){return new Uu(t)},embedding:function(t){return new Vu(t)},add:function(t){return new qu(t)},average:function(t){return new Gu(t)},concatenate:function(t){return new Ju(t)},maximum:function(t){return new Hu(t)},minimum:function(t){return new Zu(t)},multiply:function(t){return new Ku(t)},dot:function(t){return new Xu(t)},batchNormalization:function(t){return new ih(t)},layerNormalization:function(t){return new rh(t)},zeroPadding2d:function(t){return new ah(t)},averagePooling1d:Ch,avgPool1d:function(t){return Ch(t)},avgPooling1d:function(t){return Ch(t)},averagePooling2d:Th,avgPool2d:function(t){return Th(t)},avgPooling2d:function(t){return Th(t)},averagePooling3d:zh,avgPool3d:function(t){return zh(t)},avgPooling3d:function(t){return zh(t)},globalAveragePooling1d:function(t){return new wh(t)},globalAveragePooling2d:function(t){return new Sh(t)},globalMaxPooling1d:Eh,globalMaxPooling2d:$h,maxPooling1d:Fh,maxPooling2d:Dh,maxPooling3d:function(t){return new mh(t)},gru:function(t){return new Iu(t)},gruCell:function(t){return new Nu(t)},lstm:function(t){return new Cu(t)},lstmCell:function(t){return new Au(t)},simpleRNN:function(t){return new xu(t)},simpleRNNCell:function(t){return new Su(t)},convLstm2d:function(t){return new Du(t)},convLstm2dCell:function(t){return new Fu(t)},rnn:function(t){return new ku(t)},stackedRNNCells:function(t){return new Tu(t)},bidirectional:function(t){return new Ah(t)},timeDistributed:function(t){return new Ih(t)},globalMaxPool1d:Eh,globalMaxPool2d:$h,maxPool1d:Fh,maxPool2d:Dh,Layer:Ga,RNN:ku,RNNCell:vu,input:vl,gaussianNoise:function(t){return new Qu(t)},gaussianDropout:function(t){return new th(t)},alphaDropout:function(t){return new eh(t)},masking:function(t){return new Wu(t)}};var _h={__proto__:null,binaryAccuracy:function(t,e){return ko(t,e)},binaryCrossentropy:function(t,e){return Io(t,e)},sparseCategoricalAccuracy:function(t,e){return Ao(t,e)},categoricalAccuracy:function(t,e){return vo(t,e)},categoricalCrossentropy:function(t,e){return Co(t,e)},precision:function(t,e){return xo(t,e)},recall:function(t,e){return No(t,e)},cosineProximity:function(t,e){return yo(t,e)},meanAbsoluteError:function(t,e){return co(t,e)},meanAbsolutePercentageError:function(t,e){return po(t,e)},MAPE:function(t,e){return po(t,e)},mape:function(t,e){return po(t,e)},meanSquaredError:function(t,e){return ho(t,e)},MSE:function(t,e){return ho(t,e)},mse:function(t,e){return ho(t,e)}},Rh={__proto__:null,modelFromJSON:async function(t,e){"modelTopology"in t||(t={modelTopology:t});let n=(t=t).modelTopology;null!=n.model_config&&(n=n.model_config);const s=lo(Bo(n),e);if(null!=t.weightsManifest){const e=await T.loadWeights(t.weightsManifest,t.pathPrefix,s.weights.map((t=>t.originalName))),n={};for(const t of s.weights)n[t.originalName]=e[t.originalName];s.loadWeights(n),g(e)}return s}};var Mh={__proto__:null,l1l2:function(t){return new Vl(t)},l1:function(t){return Ul(e=t),new Vl({l1:null!=e?e.l1:null,l2:0});var e},l2:function(t){return Ul(e=t),new Vl({l2:null!=e?e.l2:null,l1:0});var e}};class Oh extends to{constructor(){super(...arguments),this.model=null}setModel(t){if(!(t instanceof fl))throw new Error("model must be a LayersModel, not some other Container");this.model=t}}function Bh(t,e){return t<e}function Ph(t,e){return t>e}class Uh extends Oh{constructor(t){if(super(),null==t&&(t={}),t.restoreBestWeights)throw new Hi("restoreBestWeights = True is not implemented in EarlyStopping yet.");this.monitor=t.monitor||"val_loss",this.minDelta=Math.abs(t.minDelta||0),this.patience=t.patience||0,this.verbose=t.verbose||0,this.mode=t.mode||"auto",this.baseline=t.baseline,-1===["auto","min","max"].indexOf(this.mode)&&(console.warn(`EarlyStopping mode '${this.mode}' is invalid. Falling back to mode 'auto'.`),this.mode="auto"),"min"===this.mode?this.monitorFunc=Bh:"max"===this.mode||-1!==this.monitor.indexOf("acc")?this.monitorFunc=Ph:this.monitorFunc=Bh,this.monitorFunc===Bh&&(this.minDelta*=-1)}async onTrainBegin(t){this.wait=0,this.stoppedEpoch=0,null!=this.baseline?this.best=this.baseline:this.best=this.monitorFunc===Bh?1/0:-1/0}async onEpochEnd(t,e){await Ya(e);const n=this.getMonitorValue(e);null!=n&&(this.monitorFunc(n-this.minDelta,this.best)?(this.best=n,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=t,this.model.stopTraining=!0)))}async onTrainEnd(t){this.stoppedEpoch>0&&this.verbose&&console.log(`Epoch ${this.stoppedEpoch}: early stopping.`)}getMonitorValue(t){null==t&&(t={});const e=t[this.monitor];return null==e&&console.warn(`Metric for EarlyStopping ${this.monitor} is not available. Available metrics are: ${Object.keys(t)}`),e}}const Wh={earlyStopping:function(t){return new Uh(t)}};export{Oh as Callback,eo as CallbackList,io as CustomCallback,Uh as EarlyStopping,so as History,Wa as InputSpec,Ba as LayerVariable,fl as LayersModel,ku as RNN,yl as Sequential,Va as SymbolicTensor,Wh as callbacks,Ir as constraints,za as initializers,vl as input,Lh as layers,kl as loadLayersModel,_h as metrics,bl as model,Rh as models,Sl as registerCallbackConstructor,Mh as regularizers,wl as sequential,Uo as version_layers};
18//# sourceMappingURL=tf-layers.fesm.min.js.map