gx
chenyc
2025-02-12 ea42ff3ebee1eeb3fb29423aa848a249441db81c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
 * @license
 * Copyright 2023 Google LLC. All Rights Reserved.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * =============================================================================
 */
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).tf=e.tf||{})}(this,(function(e){"use strict";function t(e,t){return t.forEach((function(t){t&&"string"!=typeof t&&!Array.isArray(t)&&Object.keys(t).forEach((function(n){if("default"!==n&&!(n in e)){var s=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,s.get?s:{enumerable:!0,get:function(){return t[n]}})}}))})),Object.freeze(e)}class n{constructor(e,t){this.backend=e,this.dataMover=t,this.data=new WeakMap,this.dataIdsCount=0}get(e){return this.data.has(e)||this.dataMover.moveData(this.backend,e),this.data.get(e)}set(e,t){this.dataIdsCount++,this.data.set(e,t)}has(e){return this.data.has(e)}delete(e){return this.dataIdsCount--,this.data.delete(e)}numDataIds(){return this.dataIdsCount}}class s{refCount(e){return r("refCount")}incRef(e){return r("incRef")}timerAvailable(){return!0}time(e){return r("time")}read(e){return r("read")}readSync(e){return r("readSync")}readToGPU(e,t){return r("readToGPU")}numDataIds(){return r("numDataIds")}disposeData(e,t){return r("disposeData")}write(e,t,n){return r("write")}move(e,t,n,s,a){return r("move")}createTensorFromGPUData(e,t,n){return r("createTensorFromGPUData")}memory(){return r("memory")}floatPrecision(){return r("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return r("dispose")}}function r(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function a(e){let t=e.length,n=0;for(;t>0;)n=Math.random()*t|0,t--,l(e,t,n)}function i(e,t,n){return Math.max(e,Math.min(t,n))}function o(e){return e%2==0?e:e+1}function l(e,t,n){const s=e[t];e[t]=e[n],e[n]=s}function u(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}function c(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function h(e,t,n=""){c(m(e,t),(()=>n+` Shapes ${e} and ${t} must match`))}function p(e){c(null!=e,(()=>"The input to the tensor constructor must be a non-null value."))}function d(e){if(0===e.length)return 1;let t=e[0];for(let n=1;n<e.length;n++)t*=e[n];return t}function f(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(null!==e[n]&&null!==t[n]&&e[n]!==t[n])return!1;return!0}function m(e,t){if(e===t)return!0;if(null==e||null==t)return!1;if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function g(e){return e%1==0}function y(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function b(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function x(e,t=(e=>0),n,s){return new Promise(((r,a)=>{let i=0;const o=()=>{if(e())return void r();i++;const l=t(i);null!=n&&i>=n?a():null!=s?s(o,l):setTimeout(o,l)};o()}))}function w(e,t){let n=1,s=-1;for(let t=0;t<e.length;++t)if(e[t]>=0)n*=e[t];else if(-1===e[t]){if(-1!==s)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${s} and dim ${t}`);s=t}else if(e[t]<0)throw Error(`Shapes can not be < 0. Found ${e[t]} at dim ${t}`);if(-1===s){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(0===n)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%n!=0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${n}`);const r=e.slice();return r[s]=t/n,r}function v(e,t){const n=t.length;return c((e=null==e?t.map(((e,t)=>t)):[].concat(e)).every((e=>e>=-n&&e<n)),(()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`)),c(e.every((e=>g(e))),(()=>`All values in axis param must be integers but got axis ${e}`)),e.map((e=>e<0?n+e:e))}function k(e,t){const n=[],s=[],r=null!=t&&Array.isArray(t)&&0===t.length,a=null==t||r?null:v(t,e).sort();let i=0;for(let t=0;t<e.length;++t){if(null!=a){if(a[i]===t&&1!==e[t])throw new Error(`Can't squeeze axis ${t} since its dim '${e[t]}' is not 1`);(null==a[i]||a[i]>t)&&1===e[t]&&(n.push(e[t]),s.push(t)),a[i]<=t&&i++}1!==e[t]&&(n.push(e[t]),s.push(t))}return{newShape:n,keptDims:s}}function N(e,t){return I(e,t)}function I(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else if("bool"===e)n=new Uint8Array(t);else{if("string"!==e)throw new Error(`Unknown data type ${e}`);n=new Array(t)}return n}function S(e,t){for(let n=0;n<e.length;n++){const s=e[n];if(isNaN(s)||!isFinite(s))throw Error(`A tensor of type ${t} being uploaded contains ${s}.`)}}function T(e){return"bool"===e||"complex64"===e||"float32"===e||"int32"===e||"string"===e}function C(e,t){return"complex64"!==t&&(("float32"!==t||"complex64"===e)&&(("int32"!==t||"float32"===e||"complex64"===e)&&("bool"!==t||"bool"!==e)))}function $(e){if("float32"===e||"int32"===e)return 4;if("complex64"===e)return 8;if("bool"===e)return 1;throw new Error(`Unknown dtype ${e}`)}function E(e){if(null==e)return 0;let t=0;return e.forEach((e=>t+=e.length)),t}function A(e){return"string"==typeof e||e instanceof String}function R(e){return"boolean"==typeof e}function _(e){return"number"==typeof e}function F(e){return Array.isArray(e)?F(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":_(e)?"float32":A(e)?"string":R(e)?"bool":"float32"}function D(e){return!!(e&&e.constructor&&e.call&&e.apply)}function O(e,t){for(let n=t;n<e;++n)if(e%n==0)return n;return e}function M(e){const t=e.length;if(t<2)return[];const n=new Array(t-1);n[t-2]=e[t-1];for(let s=t-3;s>=0;--s)n[s]=n[s+1]*e[s+1];return n}function L(e,t,n,s=!1){const r=new Array;if(1===t.length){const a=t[0]*(s?2:1);for(let t=0;t<a;t++)r[t]=n[e+t]}else{const a=t[0],i=t.slice(1),o=i.reduce(((e,t)=>e*t))*(s?2:1);for(let t=0;t<a;t++)r[t]=L(e+t*o,i,n,s)}return r}function z(e,t,n=!1){if(0===e.length)return t[0];const s=e.reduce(((e,t)=>e*t))*(n?2:1);if(0===s)return[];if(s!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return L(0,e,t,n)}function P(e,t){if(Array.isArray(e))return e;if("float32"===t)return e instanceof Float32Array?e:new Float32Array(e);if("int32"===t)return e instanceof Int32Array?e:new Int32Array(e);if("bool"===t||"string"===t)return Uint8Array.from(new Int32Array(e));throw new Error(`Unknown dtype ${t}`)}function B(e,t){const n=W(e,t);for(let e=0;e<n.length;e++)n[e]=1;return n}function W(e,t){if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t)return new Uint8Array(e);throw new Error(`Unknown data type ${t}`)}function V(e,t){const n=e.reduce(((e,t)=>e*t),1);if(null==t||"float32"===t)return z(e,new Float32Array(n));if("int32"===t)return z(e,new Int32Array(n));if("bool"===t)return z(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function U(e){e.forEach((t=>{c(Number.isInteger(t)&&t>=0,(()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`))}))}function G(e,t,n){if(0===t)return 0;if(1===t)return e[0];let s=e[e.length-1];for(let t=0;t<e.length-1;++t)s+=n[t]*e[t];return s}function H(e,t,n){if(0===t)return[];if(1===t)return[e];const s=new Array(t);for(let t=0;t<s.length-1;++t)s[t]=Math.floor(e/n[t]),e-=s[t]*n[t];return s[s.length-1]=e,s}function j(e){return e&&e.then&&"function"==typeof e.then}const q="tfjsflags";class K{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=X,this.populateURLFlags()}setPlatform(e,t){null!=this.platform&&(Y().getBool("IS_TEST")||Y().getBool("PROD")||console.warn(`Platform ${this.platformName} has already been set. Overwriting the platform with ${e}.`)),this.platformName=e,this.platform=t}registerFlag(e,t,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},null!=this.urlFlags[e]){const t=this.urlFlags[e];Y().getBool("IS_TEST")||Y().getBool("PROD")||console.warn(`Setting feature override from URL ${e}: ${t}.`),this.set(e,t)}}async getAsync(e){return e in this.flags||(this.flags[e]=await this.evaluateFlag(e)),this.flags[e]}get(e){if(e in this.flags)return this.flags[e];const t=this.evaluateFlag(e);if(j(t))throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getString(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(null==this.flagRegistry[e])throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,null!=this.flagRegistry[e].setHook&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(null==this.flagRegistry[e])throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(void 0===this.global||void 0===this.global.location||void 0===this.global.location.search)return;const e=this.getQueryParams(this.global.location.search);if(q in e){e.tfjsflags.split(",").forEach((e=>{const[t,n]=e.split(":");this.urlFlags[t]=function(e,t){const n=t.toLowerCase();return"true"===n||"false"===n?"true"===n:""+ +n===n?+n:t}(0,n)}))}}}function X(e){const t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,((e,...n)=>(function(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}(t,n[0],n[1]),n.join("=")))),t}function Y(){return e.ENV}let Z;function J(){if(null==Z){let e;if("undefined"!=typeof window)e=window;else if("undefined"!=typeof global)e=global;else if("undefined"!=typeof process)e=process;else{if("undefined"==typeof self)throw new Error("Could not find a global object");e=self}Z=e}return Z}function Q(e,t){const n=function(){const e=J();return null==e._tfGlobals&&(e._tfGlobals=new Map),e._tfGlobals}();if(n.has(e))return n.get(e);{const s=t();return n.set(e,s),n.get(e)}}e.ENV=null;const ee="Abs",te="Acos",ne="Acosh",se="Add",re="AddN",ae="All",ie="Any",oe="ArgMax",le="ArgMin",ue="Asin",ce="Asinh",he="Atan",pe="Atanh",de="Atan2",fe="AvgPool",me="AvgPoolGrad",ge="AvgPool3D",ye="AvgPool3DGrad",be="BatchMatMul",xe="BatchToSpaceND",we="Bincount",ve="BitwiseAnd",ke="BroadcastTo",Ne="BroadcastArgs",Ie="Cast",Se="Ceil",Te="ClipByValue",Ce="Complex",$e="ComplexAbs",Ee="Concat",Ae="Conv2D",Re="Conv2DBackpropFilter",_e="Conv2DBackpropInput",Fe="Conv3D",De="Conv3DBackpropFilterV2",Oe="Conv3DBackpropInputV2",Me="Cos",Le="Cosh",ze="Cumprod",Pe="Cumsum",Be="CropAndResize",We="DenseBincount",Ve="DepthToSpace",Ue="DepthwiseConv2dNative",Ge="DepthwiseConv2dNativeBackpropFilter",He="DepthwiseConv2dNativeBackpropInput",je="Diag",qe="Dilation2D",Ke="Dilation2DBackpropInput",Xe="Dilation2DBackpropFilter",Ye="Draw",Ze="RealDiv",Je="Einsum",Qe="Elu",et="EluGrad",tt="Erf",nt="Equal",st="Exp",rt="ExpandDims",at="Expm1",it="FFT",ot="Fill",lt="FlipLeftRight",ut="Floor",ct="FloorDiv",ht="FusedBatchNorm",pt="GatherV2",dt="GatherNd",ft="Greater",mt="GreaterEqual",gt="Identity",yt="IFFT",bt="Imag",xt="IsFinite",wt="IsInf",vt="IsNan",kt="LeakyRelu",Nt="Less",It="LessEqual",St="LinSpace",Tt="Log",Ct="Log1p",$t="LogicalAnd",Et="LogicalNot",At="LogicalOr",Rt="LogSoftmax",_t="LRN",Ft="LRNGrad",Dt="Max",Ot="Maximum",Mt="MaxPool",Lt="MaxPoolGrad",zt="MaxPool3D",Pt="MaxPool3DGrad",Bt="MaxPoolWithArgmax",Wt="Mean",Vt="Min",Ut="Minimum",Gt="MirrorPad",Ht="Mod",jt="Multinomial",qt="Multiply",Kt="Neg",Xt="NotEqual",Yt="NonMaxSuppressionV3",Zt="NonMaxSuppressionV4",Jt="NonMaxSuppressionV5",Qt="OnesLike",en="OneHot",tn="Pack",nn="PadV2",sn="Pow",rn="Prelu",an="Prod",on="RaggedGather",ln="RaggedRange",un="RaggedTensorToTensor",cn="Range",hn="Real",pn="Reciprocal",dn="Relu",fn="Reshape",mn="ResizeNearestNeighbor",gn="ResizeNearestNeighborGrad",yn="ResizeBilinear",bn="ResizeBilinearGrad",xn="Relu6",wn="Reverse",vn="Round",kn="Rsqrt",Nn="ScatterNd",In="TensorScatterUpdate",Sn="SearchSorted",Tn="Select",Cn="Selu",$n="Slice",En="Sin",An="Sinh",Rn="Sign",_n="Sigmoid",Fn="Softplus",Dn="Sqrt",On="Sum",Mn="SpaceToBatchND",Ln="SplitV",zn="Softmax",Pn="SparseFillEmptyRows",Bn="SparseReshape",Wn="SparseSegmentMean",Vn="SparseSegmentSum",Un="SparseToDense",Gn="SquaredDifference",Hn="Square",jn="StaticRegexReplace",qn="StridedSlice",Kn="StringNGrams",Xn="StringSplit",Yn="StringToHashBucketFast",Zn="Sub",Jn="Tan",Qn="Tanh",es="Tile",ts="TopK",ns="Transform",ss="Transpose",rs="Unique",as="Unpack",is="UnsortedSegmentSum",os="ZerosLike",ls="Step",us="FromPixels",cs="RotateWithOffset",hs="_FusedMatMul",ps="FusedConv2D",ds="FusedDepthwiseConv2D";function fs(...e){Y().getBool("IS_TEST")||Y().getBool("PROD")||console.warn(...e)}const ms=Q("kernelRegistry",(()=>new Map)),gs=Q("gradRegistry",(()=>new Map));function ys(e,t){const n=ks(e,t);return ms.get(n)}function bs(e){return gs.get(e)}function xs(e){const t=ms.entries(),n=[];for(;;){const{done:s,value:r}=t.next();if(s)break;const[a,i]=r,[o]=a.split("_");o===e&&n.push(i)}return n}function ws(e){const{kernelName:t,backendName:n}=e,s=ks(t,n);ms.has(s)&&fs(`The kernel '${t}' for backend '${n}' is already registered`),ms.set(s,e)}function vs(e){const{kernelName:t}=e;gs.has(t)&&Y().getBool("DEBUG")&&fs(`Overriding the gradient for '${t}'`),gs.set(t,e)}function ks(e,t){return`${t}_${e}`}function Ns(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}var Is="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Ss(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var Ts=$s,Cs=null;try{Cs=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(e){}function $s(e,t,n){this.low=0|e,this.high=0|t,this.unsigned=!!n}function Es(e){return!0===(e&&e.__isLong__)}$s.prototype.__isLong__,Object.defineProperty($s.prototype,"__isLong__",{value:!0}),$s.isLong=Es;var As={},Rs={};function _s(e,t){var n,s,r;return t?(r=0<=(e>>>=0)&&e<256)&&(s=Rs[e])?s:(n=Ds(e,(0|e)<0?-1:0,!0),r&&(Rs[e]=n),n):(r=-128<=(e|=0)&&e<128)&&(s=As[e])?s:(n=Ds(e,e<0?-1:0,!1),r&&(As[e]=n),n)}function Fs(e,t){if(isNaN(e))return t?Us:Vs;if(t){if(e<0)return Us;if(e>=Ps)return Ks}else{if(e<=-Bs)return Xs;if(e+1>=Bs)return qs}return e<0?Fs(-e,t).neg():Ds(e%zs|0,e/zs|0,t)}function Ds(e,t,n){return new $s(e,t,n)}$s.fromInt=_s,$s.fromNumber=Fs,$s.fromBits=Ds;var Os=Math.pow;function Ms(e,t,n){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return Vs;if("number"==typeof t?(n=t,t=!1):t=!!t,(n=n||10)<2||36<n)throw RangeError("radix");var s;if((s=e.indexOf("-"))>0)throw Error("interior hyphen");if(0===s)return Ms(e.substring(1),t,n).neg();for(var r=Fs(Os(n,8)),a=Vs,i=0;i<e.length;i+=8){var o=Math.min(8,e.length-i),l=parseInt(e.substring(i,i+o),n);if(o<8){var u=Fs(Os(n,o));a=a.mul(u).add(Fs(l))}else a=(a=a.mul(r)).add(Fs(l))}return a.unsigned=t,a}function Ls(e,t){return"number"==typeof e?Fs(e,t):"string"==typeof e?Ms(e,t):Ds(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}$s.fromString=Ms,$s.fromValue=Ls;var zs=4294967296,Ps=zs*zs,Bs=Ps/2,Ws=_s(1<<24),Vs=_s(0);$s.ZERO=Vs;var Us=_s(0,!0);$s.UZERO=Us;var Gs=_s(1);$s.ONE=Gs;var Hs=_s(1,!0);$s.UONE=Hs;var js=_s(-1);$s.NEG_ONE=js;var qs=Ds(-1,2147483647,!1);$s.MAX_VALUE=qs;var Ks=Ds(-1,-1,!0);$s.MAX_UNSIGNED_VALUE=Ks;var Xs=Ds(0,-2147483648,!1);$s.MIN_VALUE=Xs;var Ys=$s.prototype;Ys.toInt=function(){return this.unsigned?this.low>>>0:this.low},Ys.toNumber=function(){return this.unsigned?(this.high>>>0)*zs+(this.low>>>0):this.high*zs+(this.low>>>0)},Ys.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(Xs)){var t=Fs(e),n=this.div(t),s=n.mul(t).sub(this);return n.toString(e)+s.toInt().toString(e)}return"-"+this.neg().toString(e)}for(var r=Fs(Os(e,6),this.unsigned),a=this,i="";;){var o=a.div(r),l=(a.sub(o.mul(r)).toInt()>>>0).toString(e);if((a=o).isZero())return l+i;for(;l.length<6;)l="0"+l;i=""+l+i}},Ys.getHighBits=function(){return this.high},Ys.getHighBitsUnsigned=function(){return this.high>>>0},Ys.getLowBits=function(){return this.low},Ys.getLowBitsUnsigned=function(){return this.low>>>0},Ys.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Xs)?64:this.neg().getNumBitsAbs();for(var e=0!=this.high?this.high:this.low,t=31;t>0&&0==(e&1<<t);t--);return 0!=this.high?t+33:t+1},Ys.isZero=function(){return 0===this.high&&0===this.low},Ys.eqz=Ys.isZero,Ys.isNegative=function(){return!this.unsigned&&this.high<0},Ys.isPositive=function(){return this.unsigned||this.high>=0},Ys.isOdd=function(){return 1==(1&this.low)},Ys.isEven=function(){return 0==(1&this.low)},Ys.equals=function(e){return Es(e)||(e=Ls(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},Ys.eq=Ys.equals,Ys.notEquals=function(e){return!this.eq(e)},Ys.neq=Ys.notEquals,Ys.ne=Ys.notEquals,Ys.lessThan=function(e){return this.comp(e)<0},Ys.lt=Ys.lessThan,Ys.lessThanOrEqual=function(e){return this.comp(e)<=0},Ys.lte=Ys.lessThanOrEqual,Ys.le=Ys.lessThanOrEqual,Ys.greaterThan=function(e){return this.comp(e)>0},Ys.gt=Ys.greaterThan,Ys.greaterThanOrEqual=function(e){return this.comp(e)>=0},Ys.gte=Ys.greaterThanOrEqual,Ys.ge=Ys.greaterThanOrEqual,Ys.compare=function(e){if(Es(e)||(e=Ls(e)),this.eq(e))return 0;var t=this.isNegative(),n=e.isNegative();return t&&!n?-1:!t&&n?1:this.unsigned?e.high>>>0>this.high>>>0||e.high===this.high&&e.low>>>0>this.low>>>0?-1:1:this.sub(e).isNegative()?-1:1},Ys.comp=Ys.compare,Ys.negate=function(){return!this.unsigned&&this.eq(Xs)?Xs:this.not().add(Gs)},Ys.neg=Ys.negate,Ys.add=function(e){Es(e)||(e=Ls(e));var t=this.high>>>16,n=65535&this.high,s=this.low>>>16,r=65535&this.low,a=e.high>>>16,i=65535&e.high,o=e.low>>>16,l=0,u=0,c=0,h=0;return c+=(h+=r+(65535&e.low))>>>16,u+=(c+=s+o)>>>16,l+=(u+=n+i)>>>16,l+=t+a,Ds((c&=65535)<<16|(h&=65535),(l&=65535)<<16|(u&=65535),this.unsigned)},Ys.subtract=function(e){return Es(e)||(e=Ls(e)),this.add(e.neg())},Ys.sub=Ys.subtract,Ys.multiply=function(e){if(this.isZero())return Vs;if(Es(e)||(e=Ls(e)),Cs)return Ds(Cs.mul(this.low,this.high,e.low,e.high),Cs.get_high(),this.unsigned);if(e.isZero())return Vs;if(this.eq(Xs))return e.isOdd()?Xs:Vs;if(e.eq(Xs))return this.isOdd()?Xs:Vs;if(this.isNegative())return e.isNegative()?this.neg().mul(e.neg()):this.neg().mul(e).neg();if(e.isNegative())return this.mul(e.neg()).neg();if(this.lt(Ws)&&e.lt(Ws))return Fs(this.toNumber()*e.toNumber(),this.unsigned);var t=this.high>>>16,n=65535&this.high,s=this.low>>>16,r=65535&this.low,a=e.high>>>16,i=65535&e.high,o=e.low>>>16,l=65535&e.low,u=0,c=0,h=0,p=0;return h+=(p+=r*l)>>>16,c+=(h+=s*l)>>>16,h&=65535,c+=(h+=r*o)>>>16,u+=(c+=n*l)>>>16,c&=65535,u+=(c+=s*o)>>>16,c&=65535,u+=(c+=r*i)>>>16,u+=t*l+n*o+s*i+r*a,Ds((h&=65535)<<16|(p&=65535),(u&=65535)<<16|(c&=65535),this.unsigned)},Ys.mul=Ys.multiply,Ys.divide=function(e){if(Es(e)||(e=Ls(e)),e.isZero())throw Error("division by zero");var t,n,s;if(Cs)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?Ds((this.unsigned?Cs.div_u:Cs.div_s)(this.low,this.high,e.low,e.high),Cs.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?Us:Vs;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Us;if(e.gt(this.shru(1)))return Hs;s=Us}else{if(this.eq(Xs))return e.eq(Gs)||e.eq(js)?Xs:e.eq(Xs)?Gs:(t=this.shr(1).div(e).shl(1)).eq(Vs)?e.isNegative()?Gs:js:(n=this.sub(e.mul(t)),s=t.add(n.div(e)));if(e.eq(Xs))return this.unsigned?Us:Vs;if(this.isNegative())return e.isNegative()?this.neg().div(e.neg()):this.neg().div(e).neg();if(e.isNegative())return this.div(e.neg()).neg();s=Vs}for(n=this;n.gte(e);){t=Math.max(1,Math.floor(n.toNumber()/e.toNumber()));for(var r=Math.ceil(Math.log(t)/Math.LN2),a=r<=48?1:Os(2,r-48),i=Fs(t),o=i.mul(e);o.isNegative()||o.gt(n);)o=(i=Fs(t-=a,this.unsigned)).mul(e);i.isZero()&&(i=Gs),s=s.add(i),n=n.sub(o)}return s},Ys.div=Ys.divide,Ys.modulo=function(e){return Es(e)||(e=Ls(e)),Cs?Ds((this.unsigned?Cs.rem_u:Cs.rem_s)(this.low,this.high,e.low,e.high),Cs.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},Ys.mod=Ys.modulo,Ys.rem=Ys.modulo,Ys.not=function(){return Ds(~this.low,~this.high,this.unsigned)},Ys.and=function(e){return Es(e)||(e=Ls(e)),Ds(this.low&e.low,this.high&e.high,this.unsigned)},Ys.or=function(e){return Es(e)||(e=Ls(e)),Ds(this.low|e.low,this.high|e.high,this.unsigned)},Ys.xor=function(e){return Es(e)||(e=Ls(e)),Ds(this.low^e.low,this.high^e.high,this.unsigned)},Ys.shiftLeft=function(e){return Es(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?Ds(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):Ds(0,this.low<<e-32,this.unsigned)},Ys.shl=Ys.shiftLeft,Ys.shiftRight=function(e){return Es(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?Ds(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):Ds(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},Ys.shr=Ys.shiftRight,Ys.shiftRightUnsigned=function(e){if(Es(e)&&(e=e.toInt()),0===(e&=63))return this;var t=this.high;return e<32?Ds(this.low>>>e|t<<32-e,t>>>e,this.unsigned):Ds(32===e?t:t>>>e-32,0,this.unsigned)},Ys.shru=Ys.shiftRightUnsigned,Ys.shr_u=Ys.shiftRightUnsigned,Ys.toSigned=function(){return this.unsigned?Ds(this.low,this.high,!1):this},Ys.toUnsigned=function(){return this.unsigned?this:Ds(this.low,this.high,!0)},Ys.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},Ys.toBytesLE=function(){var e=this.high,t=this.low;return[255&t,t>>>8&255,t>>>16&255,t>>>24,255&e,e>>>8&255,e>>>16&255,e>>>24]},Ys.toBytesBE=function(){var e=this.high,t=this.low;return[e>>>24,e>>>16&255,e>>>8&255,255&e,t>>>24,t>>>16&255,t>>>8&255,255&t]},$s.fromBytes=function(e,t,n){return n?$s.fromBytesLE(e,t):$s.fromBytesBE(e,t)},$s.fromBytesLE=function(e,t){return new $s(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},$s.fromBytesBE=function(e,t){return new $s(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};var Zs=Ss(Ts);const Js=Zs||t({__proto__:null,default:Zs},[Ts]);function Qs(e){return Js.fromString(e,!0,16)}const er=Qs("c3a5c85c97cb3127"),tr=Qs("b492b66fbe98f273"),nr=Qs("9ae16a3b2f90404f");function sr(e){return e.xor(e.shru(47))}function rr(e,t,n){const s=e.slice(t,t+n);return Js.fromBytes(Array.from(s),!0,!0)}function ar(e,t){return rr(e,t,8)}function ir(e,t){return rr(e,t,4)}function or(e,t){return 0===t?e:e.shru(t).or(e.shl(64-t))}function lr(e,t,n=Qs("9ddfea08eb382d69")){let s=e.xor(t).mul(n);s=s.xor(s.shru(47));let r=t.xor(s).mul(n);return r=r.xor(r.shru(47)),r=r.mul(n),r}function ur(e,t,n,s){return function(e,t,n,s,r,a){r=r.add(e),a=or(a.add(r).add(s),21);const i=r;return r=(r=r.add(t)).add(n),a=a.add(or(r,44)),[r.add(s),a.add(i)]}(ar(e,t),ar(e,t+8),ar(e,t+16),ar(e,t+24),n,s)}function cr(e,t=e.length){const n=Js.fromNumber(81,!0);if(t<=32)return t<=16?function(e,t=e.length){if(t>=8){const n=nr.add(2*t),s=ar(e,0).add(nr),r=ar(e,t-8);return lr(or(r,37).mul(n).add(s),or(s,25).add(r).mul(n),n)}if(t>=4){const n=nr.add(2*t);return lr(ir(e,0).shl(3).add(t),ir(e,t-4),n)}if(t>0){const n=e[0]+(e[t>>1]<<8),s=t+(e[t-1]<<2);return sr(nr.mul(n).xor(er.mul(s))).mul(nr)}return nr}(e,t):function(e,t=e.length){const n=nr.add(2*t),s=ar(e,0).mul(tr),r=ar(e,8),a=ar(e,t-8).mul(n),i=ar(e,t-16).mul(nr);return lr(or(s.add(r),43).add(or(a,30)).add(i),s.add(or(r.add(nr),18)).add(a),n)}(e,t);if(t<=64)return function(e,t=e.length){const n=nr.add(2*t),s=ar(e,0).mul(nr),r=ar(e,8),a=ar(e,t-8).mul(n),i=ar(e,t-16).mul(nr),o=or(s.add(r),43).add(or(a,30)).add(i),l=lr(o,s.add(or(r.add(nr),18)).add(a),n),u=ar(e,16).mul(n),c=ar(e,24),h=o.add(ar(e,t-32)).mul(n),p=l.add(ar(e,t-24)).mul(n);return lr(or(u.add(c),43).add(or(h,30)).add(p),u.add(or(c.add(s),18)).add(h),n)}(e,t);let s=n,r=n.mul(tr).add(113),a=sr(r.mul(nr).add(113)).mul(nr),i=[Js.UZERO,Js.UZERO],o=[Js.UZERO,Js.UZERO];s=s.mul(nr).add(ar(e,0));let l=0;const u=64*(t-1>>6),c=u+(t-1&63)-63;do{s=or(s.add(r).add(i[0]).add(ar(e,l+8)),37).mul(tr),r=or(r.add(i[1]).add(ar(e,l+48)),42).mul(tr),s=s.xor(o[1]),r=r.add(i[0]).add(ar(e,l+40)),a=or(a.add(o[0]),33).mul(tr),i=ur(e,l,i[1].mul(tr),s.add(o[0])),o=ur(e,l+32,a.add(o[1]),r.add(ar(e,l+16))),[a,s]=[s,a],l+=64}while(l!==u);const h=tr.add(a.and(255).shl(1));return l=c,o[0]=o[0].add(t-1&63),i[0]=i[0].add(o[0]),o[0]=o[0].add(i[0]),s=or(s.add(r).add(i[0]).add(ar(e,l+8)),37).mul(h),r=or(r.add(i[1]).add(ar(e,l+48)),42).mul(h),s=s.xor(o[1].mul(9)),r=r.add(i[0].mul(9).add(ar(e,l+40))),a=or(a.add(o[0]),33).mul(h),i=ur(e,l,i[1].mul(h),s.add(o[0])),o=ur(e,l+32,a.add(o[1]),r.add(ar(e,l+16))),[a,s]=[s,a],lr(lr(i[0],o[0],h).add(sr(r).mul(er)).add(a),lr(i[1],o[1],h).add(s),h)}function hr(e,t){return"string"===t?mr(e):pr([e],t)}function pr(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=br(e)),Y().getBool("DEBUG")&&S(e,t),function(e,t){return e instanceof Float32Array&&"float32"===t||e instanceof Int32Array&&"int32"===t||e instanceof Uint8Array&&"bool"===t}(e,t))return e;if(null==t||"float32"===t||"complex64"===t)return new Float32Array(e);if("int32"===t)return new Int32Array(e);if("bool"===t){const t=new Uint8Array(e.length);for(let n=0;n<t.length;++n)0!==Math.round(e[n])&&(t[n]=1);return t}throw new Error(`Unknown data type ${t}`)}function dr(){return Y().platform.now()}function fr(e,t){return Y().platform.fetch(e,t)}function mr(e,t="utf-8"){return t=t||"utf-8",Y().platform.encode(e,t)}function gr(e,t="utf-8"){return t=t||"utf-8",Y().platform.decode(e,t)}function yr(e){return null!=Y().platform.isTypedArray?Y().platform.isTypedArray(e):Ns(e)}function br(e,t=[],n=!1){if(null==t&&(t=[]),"boolean"==typeof e||"number"==typeof e||"string"==typeof e||j(e)||null==e||yr(e)&&n)t.push(e);else if(Array.isArray(e)||yr(e))for(let s=0;s<e.length;++s)br(e[s],t,n);else{let s=-1;for(const t of Object.keys(e))/^([1-9]+[0-9]*|0)$/.test(t)&&(s=Math.max(s,Number(t)));for(let r=0;r<=s;r++)br(e[r],t,n)}return t}var xr=Object.freeze({__proto__:null,arraysEqual:m,arraysEqualWithNull:f,assert:c,assertNonNegativeIntegerDimensions:U,assertNonNull:p,assertShapesMatch:h,bytesFromStringArray:E,bytesPerElement:$,checkConversionForErrors:S,clamp:i,computeStrides:M,convertBackendValuesAndArrayBuffer:P,createScalarValue:hr,createShuffledIndices:function(e){const t=new Uint32Array(e);for(let n=0;n<e;++n)t[n]=n;return a(t),t},decodeString:gr,distSquared:function(e,t){let n=0;for(let s=0;s<e.length;s++){const r=Number(e[s])-Number(t[s]);n+=r*r}return n},encodeString:mr,fetch:fr,fingerPrint64:cr,flatten:br,getArrayFromDType:I,getTypedArrayFromDType:N,hasEncodingLoss:C,hexToLong:Qs,indexToLoc:H,inferDtype:F,inferFromImplicitShape:w,isBoolean:R,isFunction:D,isInt:g,isNumber:_,isPromise:j,isScalarShape:function(e){return 0===e.length},isString:A,isTypedArray:yr,isValidDtype:T,locToIndex:G,makeOnesTypedArray:B,makeZerosNestedTypedArray:V,makeZerosTypedArray:W,nearestDivisor:O,nearestLargerEven:o,now:dr,parseAxisParam:v,randUniform:function(e,t){const n=Math.random();return t*n+(1-n)*e},repeatedTry:x,rightPad:b,shuffle:a,shuffleCombo:function(e,t){if(e.length!==t.length)throw new Error(`Array sizes must match to be shuffled together First array length was ${e.length}Second array length was ${t.length}`);let n=e.length,s=0;for(;n>0;)s=Math.random()*n|0,n--,l(e,n,s),l(t,n,s)},sizeFromShape:d,sizeToSquarishShape:y,squeezeShape:k,sum:u,swap:l,tanh:function(e){if(null!=Math.tanh)return Math.tanh(e);if(e===1/0)return 1;if(e===-1/0)return-1;{const t=Math.exp(2*e);return(t-1)/(t+1)}},toNestedArray:z,toTypedArray:pr});class wr{constructor(e,t){this.backendTimer=e,this.logger=t,null==t&&(this.logger=new kr)}profileKernel(e,t,n){let s;const r=()=>{s=n()};let a;const i=dr();if(this.backendTimer.timerAvailable())a=this.backendTimer.time(r);else{r();for(const e of s)e.dataSync();a=Promise.resolve({kernelMs:dr()-i})}if(Y().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let t=0;t<s.length;t++){const n=s[t];n.data().then((t=>{vr(t,n.dtype,e)}))}return{kernelName:e,outputs:s,inputs:t,timeMs:a.then((e=>e.kernelMs)),extraInfo:a.then((e=>null!=e.getExtraProfileInfo?e.getExtraProfileInfo():""))}}logKernelProfile(e){const{kernelName:t,outputs:n,timeMs:s,inputs:r,extraInfo:a}=e;n.forEach((e=>{Promise.all([e.data(),s,a]).then((n=>{this.logger.logKernelProfile(t,e,n[0],n[1],r,n[2])}))}))}}function vr(e,t,n){if("float32"!==t)return!1;for(let t=0;t<e.length;t++){const s=e[t];if(isNaN(s)||!isFinite(s))return console.warn(`Found ${s} in the result of '${n}'`),!0}return!1}class kr{logKernelProfile(e,t,n,s,r,a){const i="number"==typeof s?b(`${s}ms`,9):s.error,o=b(e,25),l=t.rank,u=t.size,c=b(t.shape.toString(),14);let h="";for(const e in r){const n=r[e];if(null!=n){const s=n.shape||t.shape,r=s.length;h+=`${e}: ${r}D ${r>0?s:""} `}}console.log(`%c${o}\t%c${i}\t%c${l}D ${c}\t%c${u}\t%c${h}\t%c${a}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}}function Nr(e,t,n,s){const r=M(t),a=function(e,t,n,s){const r=d(t),a=s[s.length-1],i=new Array(a).fill(0),o=t.length,l="complex64"===n?Cr(e):e;if(o>1)for(let e=0;e<r/a;e++){const t=e*a;for(let e=0;e<a;e++)i[e]=Math.max(i[e],Ir(l[t+e],0,n).length)}return i}(e,t,n,r),i=t.length,o=Tr(e,t,n,r,a),l=["Tensor"];return s&&(l.push(`  dtype: ${n}`),l.push(`  rank: ${i}`),l.push(`  shape: [${t}]`),l.push("  values:")),l.push(o.map((e=>"    "+e)).join("\n")),l.join("\n")}function Ir(e,t,n){let s;return s=Array.isArray(e)?`${parseFloat(e[0].toFixed(7))} + ${parseFloat(e[1].toFixed(7))}j`:A(e)?`'${e}'`:"bool"===n?Sr(e):parseFloat(e.toFixed(7)).toString(),b(s,t)}function Sr(e){return 0===e?"false":"true"}function Tr(e,t,n,s,r,a=!0){const i="complex64"===n?2:1,o=t[0],l=t.length;if(0===l){if("complex64"===n){return[Ir(Cr(e)[0],0,n)]}return"bool"===n?[Sr(e[0])]:[e[0].toString()]}if(1===l){if(o>20){const t=3*i;let s=Array.from(e.slice(0,t)),a=Array.from(e.slice((o-3)*i,o*i));return"complex64"===n&&(s=Cr(s),a=Cr(a)),["["+s.map(((e,t)=>Ir(e,r[t],n))).join(", ")+", ..., "+a.map(((e,t)=>Ir(e,r[o-3+t],n))).join(", ")+"]"]}return["["+("complex64"===n?Cr(e):Array.from(e)).map(((e,t)=>Ir(e,r[t],n))).join(", ")+"]"]}const u=t.slice(1),c=s.slice(1),h=s[0]*i,p=[];if(o>20){for(let t=0;t<3;t++){const s=t*h,a=s+h;p.push(...Tr(e.slice(s,a),u,n,c,r,!1))}p.push("...");for(let t=o-3;t<o;t++){const s=t*h,a=s+h;p.push(...Tr(e.slice(s,a),u,n,c,r,t===o-1))}}else for(let t=0;t<o;t++){const s=t*h,a=s+h;p.push(...Tr(e.slice(s,a),u,n,c,r,t===o-1))}const d=2===l?",":"";p[0]="["+(o>0?p[0]+d:"");for(let e=1;e<p.length-1;e++)p[e]=" "+p[e]+d;let f=",\n";for(let e=2;e<l;e++)f+="\n";return p[p.length-1]=" "+p[p.length-1]+"]"+(a?"":f),p}function Cr(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}class $r{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=d(e),null!=n){const e=n.length;c(e===this.size,(()=>`Length of values '${e}' does not match the size inferred by the shape '${this.size}'.`))}if("complex64"===t)throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||I(t,this.size),this.strides=M(e)}set(e,...t){0===t.length&&(t=[0]),c(t.length===this.rank,(()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`));const n=this.locToIndex(t);this.values[n]=e}get(...e){0===e.length&&(e=[0]);let t=0;for(const n of e){if(n<0||n>=this.shape[t]){const t=`Requested out of range element at ${e}.   Buffer shape=${this.shape}`;throw new Error(t)}t++}let n=e[e.length-1];for(let t=0;t<e.length-1;++t)n+=this.strides[t]*e[t];return this.values[n]}locToIndex(e){if(0===this.rank)return 0;if(1===this.rank)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(0===this.rank)return[];if(1===this.rank)return[e];const t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return Er().makeTensor(this.values,this.shape,this.dtype)}}let Er=null,Ar=null,Rr=null;class _r{constructor(e,t,n,s){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=d(e),this.strides=M(e),this.dataId=n,this.id=s,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){const e=await this.data();return Ar.buffer(this.shape,this.dtype,e)}bufferSync(){return Ar.buffer(this.shape,this.dtype,this.dataSync())}async array(){const e=await this.data();return z(this.shape,e,"complex64"===this.dtype)}arraySync(){return z(this.shape,this.dataSync(),"complex64"===this.dtype)}async data(){this.throwIfDisposed();const e=Er().read(this.dataId);if("string"===this.dtype){const t=await e;try{return t.map((e=>gr(e)))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataToGPU(e){return this.throwIfDisposed(),Er().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=Er().readSync(this.dataId);if("string"===this.dtype)try{return e.map((e=>gr(e)))}catch(e){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}return e}async bytes(){this.throwIfDisposed();const e=await Er().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(this.kerasMask&&this.kerasMask.dispose(),Er().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Ar.print(this,e)}clone(){return this.throwIfDisposed(),Ar.clone(this)}toString(e=!1){return Nr(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Ar.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Er().makeVariable(this,e,t,n)}}function Fr(){return Q("Tensor",(()=>_r))}Object.defineProperty(_r,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),Fr();class Dr extends _r{constructor(e,t,n,s){super(e.shape,e.dtype,e.dataId,s),this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!m(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Er().disposeTensor(this),this.dataId=e.dataId,Er().incRef(this,null)}dispose(){Er().disposeVariable(this),this.isDisposedInternal=!0}}var Or,Mr,Lr,zr,Pr;Object.defineProperty(Dr,Symbol.hasInstance,{value:e=>e instanceof _r&&null!=e.assign&&e.assign instanceof Function}),e.Rank=void 0,(Or=e.Rank||(e.Rank={})).R0="R0",Or.R1="R1",Or.R2="R2",Or.R3="R3",Or.R4="R4",Or.R5="R5",Or.R6="R6",function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"}(Mr||(Mr={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"}(Lr||(Lr={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"}(zr||(zr={})),function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"}(Pr||(Pr={}));const Br={float32:zr,int32:Mr,bool:Lr,complex64:Pr};function Wr(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return Br[e][t]}function Vr(e){return Wr(e,"int32")}function Ur(e){return null!=e&&"object"==typeof e&&"texture"in e&&e.texture instanceof WebGLTexture}function Gr(e){return"undefined"!=typeof GPUBuffer&&null!=e&&"object"==typeof e&&"buffer"in e&&e.buffer instanceof GPUBuffer}function Hr(e,t){if(e.dtype===t.dtype)return[e,t];const n=Wr(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function jr(e,t){c(e.dtype===t.dtype,(()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`))}function qr(e,t){return t.some((t=>t.id===e.id))}function Kr(e){const t=[];return Xr(e,t,new Set),t}function Xr(e,t,n){if(null==e)return;if(e instanceof _r)return void t.push(e);if(s=e,!Array.isArray(s)&&"object"!=typeof s)return;var s;const r=e;for(const e in r){const s=r[e];n.has(s)||(n.add(s),Xr(s,t,n))}}var Yr=Object.freeze({__proto__:null,assertTypesMatch:jr,getTensorsInContainer:Kr,isTensorInList:qr,makeTypesMatch:Hr});function Zr(e){return null!=e.kernelName}class Jr{constructor(){this.registeredVariables={},this.nextTapeNodeId=0,this.numBytes=0,this.numTensors=0,this.numStringTensors=0,this.numDataBuffers=0,this.gradientDepth=0,this.kernelDepth=0,this.scopeStack=[],this.numDataMovesStack=[],this.nextScopeId=0,this.tensorInfo=new WeakMap,this.profiling=!1,this.activeProfile={newBytes:0,newTensors:0,peakBytes:0,kernels:[],result:null,get kernelNames(){return Array.from(new Set(this.kernels.map((e=>e.name))))}}}dispose(){for(const e in this.registeredVariables)this.registeredVariables[e].dispose()}}class Qr{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Jr}async ready(){if(null!=this.pendingBackendInit)return this.pendingBackendInit.then((()=>{}));if(null!=this.backendInstance)return;const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t];if(await this.initializeBackend(n).success)return void await this.setBackend(n)}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(null!=this.pendingBackendInit)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(null==this.backendInstance){const{name:e,asyncInit:t}=this.initializeBackendsAndReturnBest();if(t)throw new Error(`The highest priority backend '${e}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(e)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(e){if(!(e in this.registry)){if(!(e in this.registryFactory))return null;{const{asyncInit:t}=this.initializeBackend(e);if(t)return null}}return this.registry[e]}findBackendFactory(e){return e in this.registryFactory?this.registryFactory[e].factory:null}registerBackend(e,t,n=1){return e in this.registryFactory?(fs(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:n},!0)}async setBackend(e){if(null==this.registryFactory[e])throw new Error(`Backend name '${e}' not found in registry`);if(this.backendName=e,null==this.registry[e]){this.backendInstance=null;const{success:t,asyncInit:n}=this.initializeBackend(e);if(!(n?await t:t))return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new wr(this.backendInstance),!0}setupRegisteredKernels(){xs(this.backendName).forEach((e=>{null!=e.setupFunc&&e.setupFunc(this.backendInstance)}))}disposeRegisteredKernels(e){xs(e).forEach((t=>{null!=t.disposeFunc&&t.disposeFunc(this.registry[e])}))}initializeBackend(e){const t=this.registryFactory[e];if(null==t)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{const n=t.factory();if(!n||n instanceof s||"function"!=typeof n.then)return this.registry[e]=n,{success:!0,asyncInit:!1};{const t=++this.pendingBackendInitId,s=n.then((n=>!(t<this.pendingBackendInitId)&&(this.registry[e]=n,this.pendingBackendInit=null,!0))).catch((n=>(t<this.pendingBackendInitId||(this.pendingBackendInit=null,fs(`Initialization of backend ${e} failed`),fs(n.stack||n.message)),!1)));return this.pendingBackendInit=s,{success:s,asyncInit:!0}}}catch(t){return fs(`Initialization of backend ${e} failed`),fs(t.stack||t.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(`${e} backend not found in registry`);this.backendName===e&&null!=this.pendingBackendInit&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(0===Object.keys(this.registryFactory).length)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort(((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority))}initializeBackendsAndReturnBest(){const e=this.getSortedBackends();for(let t=0;t<e.length;t++){const n=e[t],{success:s,asyncInit:r}=this.initializeBackend(n);if(r||s)return{name:n,asyncInit:r}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){const n=this.state.tensorInfo.get(t),s=n.backend,r=this.readSync(t),a=s.refCount(t);s.disposeData(t,!0),n.backend=e,e.move(t,r,n.shape,n.dtype,a),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let n,s=null;if(null==t){if("function"!=typeof e)throw new Error("Please provide a function to tidy()");t=e}else{if("string"!=typeof e&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if("function"!=typeof t)throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");s=e}return this.scopedRun((()=>this.startScope(s)),(()=>this.endScope(n)),(()=>(n=t(),n instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n)))}scopedRun(e,t,n){e();try{const e=n();return t(),e}catch(e){throw t(),e}}nextTensorId(){return Qr.nextTensorId++}nextVariableId(){return Qr.nextVariableId++}clone(e){const t=ta.runKernel(gt,{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],(e=>({x:()=>{const t={x:e},n={dtype:"float32"};return ta.runKernel(Ie,t,n)}})),[],{}),t}runKernel(e,t,n){null==this.backendName&&this.backend;if(!(null!=ys(e,this.backendName)))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){const s=this.backend.numDataIds();let r=0;n.forEach((e=>{r+="complex64"===e.dtype?3:1}));const a=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],i=s-t-r-a;if(i>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${i} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[];const s=this.isTapeOn(),r=this.state.numBytes,a=this.state.numTensors;let i,o;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0),null==this.backendName&&this.backend;const l=Zr(e)?e.kernelName:null!=this.state.activeScope?this.state.activeScope.name:"";if(Zr(e)){const{kernelName:t,inputs:r,attrs:a}=e;null==this.backendName&&this.backend;const l=ys(t,this.backendName);c(null!=l,(()=>`Cannot find registered kernel '${t}' for backend '${this.backendName}'`)),i=()=>{const e=this.backend.numDataIds();o=l.kernelFunc({inputs:r,attrs:a,backend:this.backend});const i=Array.isArray(o)?o:[o];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(t,e,i);const u=i.map((e=>null!=e.rank?e:this.makeTensorFromTensorInfo(e)));if(s){const e=this.getTensorsForGradient(t,r,u);n=this.saveTensorsForBackwardMode(e)}return u}}else{const{forwardFunc:t}=e,r=e=>{s&&(n=e.map((e=>this.keep(this.clone(e)))))};i=()=>{const e=this.backend.numDataIds();o=this.tidy((()=>t(this.backend,r)));const n=Array.isArray(o)?o:[o];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,e,n),n}}const{inputs:u,attrs:h}=e,p=Zr(e)?null:e.backwardsFunc;let d;return this.scopedRun((()=>this.state.kernelDepth++),(()=>this.state.kernelDepth--),(()=>{this.ENV.getBool("DEBUG")||this.state.profiling?(d=this.profiler.profileKernel(l,u,(()=>i())),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(d),t=d.outputs):t=i()})),s&&this.addTapeNode(l,u,t,p,n,h),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-r,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-a,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(u).map((e=>null!=u[e]?u[e].shape:null)),outputShapes:t.map((e=>e.shape)),kernelTimeMs:d.timeMs,extraInfo:d.extraInfo}),Array.isArray(o)?t:t[0]}saveTensorsForBackwardMode(e){const t=e.map((e=>this.keep(this.clone(e))));return t}getTensorsForGradient(e,t,n){const s=bs(e);if(null!=s){const e=s.inputsToSave||[],r=s.outputsToSave||[];let a;s.saveAllInputs?(c(Array.isArray(t),(()=>"saveAllInputs is true, expected inputs to be an array.")),a=Object.keys(t).map((e=>t[e]))):a=e.map((e=>t[e]));const i=n.filter(((e,t)=>r[t]));return a.concat(i)}return[]}makeTensor(e,t,n,s){if(null==e)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",s=s||this.backend;let r=e;"string"===n&&A(e[0])&&(r=e.map((e=>mr(e))));const a=s.write(r,t,n),i=new _r(t,n,a,this.nextTensorId());if(this.trackTensor(i,s),"string"===n){const e=this.state.tensorInfo.get(a),t=E(r);this.state.numBytes+=t-e.bytes,e.bytes=t}return i}makeTensorFromDataId(e,t,n,s){const r={dataId:e,shape:t,dtype:n=n||"float32"};return this.makeTensorFromTensorInfo(r,s)}makeTensorFromTensorInfo(e,t){const{dataId:n,shape:s,dtype:r}=e,a=new _r(s,r,n,this.nextTensorId());return this.trackTensor(a,t),a}makeVariable(e,t=!0,n,s){n=n||this.nextVariableId().toString(),null!=s&&s!==e.dtype&&(e=e.cast(s));const r=new Dr(e,t,n,this.nextTensorId());if(null!=this.state.registeredVariables[r.name])throw new Error(`Variable with name ${r.name} was already registered`);return this.state.registeredVariables[r.name]=r,this.incRef(r,this.backend),r}trackTensor(e,t){this.state.numTensors++,"string"===e.dtype&&this.state.numStringTensors++;let n=0;"complex64"!==e.dtype&&"string"!==e.dtype&&(n=e.size*$(e.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n})),e instanceof Dr||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;const t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,"string"===e.dtype&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),"complex64"!==e.dtype&&"string"!==e.dtype){const t=e.size*$(e.dtype);this.state.numBytes-=t}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(const e in this.state.registeredVariables){const t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),null!=this.state.registeredVariables[e.name]&&delete this.state.registeredVariables[e.name]}memory(){const e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,null==e.reasons&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;const t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map((e=>e.totalBytesSnapshot))),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(const e of this.state.activeProfile.kernels)e.kernelTimeMs=await e.kernelTimeMs,e.extraInfo=await e.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&0===this.state.kernelDepth}addTapeNode(e,t,n,s,r,a){const i={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:r},o=bs(e);null!=o&&(s=o.gradFunc),null!=s&&(i.gradient=e=>(e=e.map(((e,t)=>{if(null==e){const e=n[t],s=W(e.size,e.dtype);return this.makeTensor(s,e.shape,e.dtype)}return e})),s(e.length>1?e:e[0],r,a))),this.state.activeTape.push(i)}keep(e){return e.kept=!0,e}startTape(){0===this.state.gradientDepth&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){const t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){const t=Kr(e),n=new Set(t.map((e=>e.id)));for(let e=0;e<this.state.activeScope.track.length;e++){const t=this.state.activeScope.track[e];t.kept||n.has(t.id)||t.dispose()}const s=this.state.scopeStack.pop();this.state.activeScope=0===this.state.scopeStack.length?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach((e=>{e.kept||e.scopeId!==s.id||this.track(e)}))}gradients(e,t,n,s=!1){if(c(t.length>0,(()=>"gradients() received an empty list of xs.")),null!=n&&"float32"!==n.dtype)throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);const r=this.scopedRun((()=>this.startTape()),(()=>this.endTape()),(()=>this.tidy("forward",e)));c(r instanceof _r,(()=>"The result y returned by f() must be a tensor."));const a=function(e,t,n){const s={},r={};for(let e=0;e<t.length;e++)s[t[e].id]=!0;for(let n=0;n<e.length;n++){const a=e[n],i=a.inputs;for(const e in i){const n=i[e];let o=!1;for(let e=0;e<t.length;e++)if(s[n.id]){a.outputs.forEach((e=>s[e.id]=!0)),o=!0,r[a.id]=!0;break}if(o)break}}const a={};a[n.id]=!0;const i={};for(let t=e.length-1;t>=0;t--){const n=e[t],s=n.inputs;for(let e=0;e<n.outputs.length;e++)if(a[n.outputs[e].id]){for(const e in s)a[s[e].id]=!0,i[n.id]=!0;break}}const o=[];for(let t=0;t<e.length;t++){const n=e[t];if(r[n.id]&&i[n.id]){const e={};for(const t in n.inputs){const r=n.inputs[t];s[r.id]&&(e[t]=r)}const t=Object.assign({},n);t.inputs=e,t.outputs=n.outputs,o.push(t)}}return o}(this.state.activeTape,t,r);if(!s&&0===a.length&&t.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",(()=>{const e={};e[r.id]=null==n?function(e){const t=B(d(e),"float32");return ta.makeTensor(t,e,"float32")}(r.shape):n,function(e,t,n,s){for(let r=t.length-1;r>=0;r--){const a=t[r],i=[];if(a.outputs.forEach((t=>{const n=e[t.id];null!=n?i.push(n):i.push(null)})),null==a.gradient)throw new Error(`Cannot compute gradient: gradient function not found for ${a.kernelName}.`);const o=a.gradient(i);for(const t in a.inputs){if(!(t in o))throw new Error(`Cannot backprop through input ${t}. Available gradients found: ${Object.keys(o)}.`);const r=n((()=>o[t]()));if("float32"!==r.dtype)throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input ${t} must have 'float32' dtype, but has '${r.dtype}'`);const i=a.inputs[t];if(!m(r.shape,i.shape))throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input '${t}' has shape '${r.shape}', which does not match the shape of the input '${i.shape}'`);if(null==e[i.id])e[i.id]=r;else{const t=e[i.id];e[i.id]=s(t,r),t.dispose()}}}}(e,a,(e=>this.tidy(e)),na);const s=t.map((t=>e[t.id]));return 0===this.state.gradientDepth&&(this.state.activeTape.forEach((e=>{for(const t of e.saved)t.dispose()})),this.state.activeTape=null),{value:r,grads:s}}))}customGrad(e){return c(D(e),(()=>"The f passed in customGrad(f) must be a function.")),(...t)=>{let n;c(t.every((e=>e instanceof _r)),(()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors"));const s={};t.forEach(((e,t)=>{s[t]=e}));return this.runKernelFunc({forwardFunc:(s,r)=>(n=e(...t,r),c(n.value instanceof _r,(()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor")),c(D(n.gradFunc),(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function.")),n.value),backwardsFunc:(e,s)=>{const r=n.gradFunc(e,s),a=Array.isArray(r)?r:[r];c(a.length===t.length,(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...).")),c(a.every((e=>e instanceof _r)),(()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors."));const i={};return a.forEach(((e,t)=>{i[t]=()=>e})),i},inputs:s})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}readToGPU(e,t){return this.state.tensorInfo.get(e).backend.readToGPU(e,t)}async time(e){const t=dr(),n=await this.backend.time(e);return n.wallMs=dr()-t,n}track(e){return null!=this.state.activeScope&&(e.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(e)),e}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new Jr;for(const e in this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}}function ea(){const t=J();if(null==t._tfengine){const e=new K(t);t._tfengine=new Qr(e)}var n;return n=t._tfengine.ENV,e.ENV=n,Er=()=>t._tfengine,t._tfengine}Qr.nextTensorId=0,Qr.nextVariableId=0;const ta=ea();function na(e,t){const n={a:e,b:t};return ta.runKernel(se,n)}let sa;function ra(e){if(void 0!==sa)return sa;if(e||"undefined"!=typeof navigator&&null!=navigator){if(e||(e=navigator),"ReactNative"===e.product)return!0;const t=e.userAgent||e.vendor||("undefined"!=typeof window?window.opera:"");if(!t){const t=e;return t.userAgentData&&t.userAgentData.mobile}return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4))}return!1}function aa(){return"undefined"!=typeof window&&null!=window.document||"undefined"!=typeof WorkerGlobalScope}var ia=Object.freeze({__proto__:null,isBrowser:aa,isMobile:ra,mockIsMobile:function(e){sa=e}});const oa=Y();function la(e,t){let n=e;if(yr(e))return"string"===t?[]:[e.length];if(Ur(e)){const t=e.channels||"RGBA";return[e.height,e.width*t.length]}if(Gr(e))return[e.buffer.size/(null==t?4:$(t))];if(!Array.isArray(e))return[];const s=[];for(;Array.isArray(n)||yr(n)&&"string"!==t;)s.push(n.length),n=n[0];return Array.isArray(e)&&Y().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&ua(e,s,[]),s}function ua(e,t,n){if(n=n||[],!Array.isArray(e)&&!yr(e))return void c(0===t.length,(()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`));c(t.length>0,(()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`)),c(e.length===t[0],(()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`));const s=t.slice(1);for(let t=0;t<e.length;++t)ua(e[t],s,n.concat(t))}function ca(e,t,n,s){if("string_or_numeric"!==e){if(null==e)throw new Error("Expected dtype cannot be null.");if("numeric"!==e&&e!==t||"numeric"===e&&"string"===t)throw new Error(`Argument '${n}' passed to '${s}' must be ${e} tensor, but got ${t} tensor`)}}function ha(e,t,n,s="numeric"){if(e instanceof Fr())return ca(s,e.dtype,t,n),e;let r=F(e);if("string"!==r&&["bool","int32","float32"].indexOf(s)>=0&&(r=s),ca(s,r,t,n),null==e||!yr(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e){const s=null==e?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${s}'`)}const a=la(e,r);yr(e)||Array.isArray(e)||(e=[e]);const i="string"!==r?pr(e,r):br(e,[],!0);return ta.makeTensor(i,a,r)}function pa(e,t,n,s="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map(((e,r)=>ha(e,`${t}[${r}]`,n,s)))}oa.registerFlag("DEBUG",(()=>!1),(e=>{e&&console.warn("Debugging mode is ON. The output of every math call will be downloaded to CPU and checked for NaNs. This significantly impacts performance.")})),oa.registerFlag("IS_BROWSER",(()=>aa())),oa.registerFlag("IS_NODE",(()=>"undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node)),oa.registerFlag("IS_CHROME",(()=>"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor))),oa.registerFlag("IS_SAFARI",(()=>"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Safari/.test(navigator.userAgent)&&/Apple/.test(navigator.vendor))),oa.registerFlag("PROD",(()=>!1)),oa.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",(()=>oa.getBool("DEBUG"))),oa.registerFlag("DEPRECATION_WARNINGS_ENABLED",(()=>!0)),oa.registerFlag("IS_TEST",(()=>!1)),oa.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",(()=>oa.getBool("DEBUG"))),oa.registerFlag("WRAP_TO_IMAGEBITMAP",(()=>!1)),oa.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",(()=>!1)),oa.registerFlag("USE_SETTIMEOUTCUSTOM",(()=>!1));const da="__op";function fa(e){const t=Object.keys(e);if(1!==t.length)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);let n=t[0];const s=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n+=da;const r=(...e)=>{ta.startScope(n);try{const t=s(...e);return j(t)&&console.error("Cannot return a Promise inside of tidy."),ta.endScope(t),t}catch(e){throw ta.endScope(null),e}};return Object.defineProperty(r,"name",{value:n,configurable:!0}),r}const ma=fa({complex_:function(e,t){const n=ha(e,"real","complex"),s=ha(t,"imag","complex");h(n.shape,s.shape,`real and imag shapes, ${n.shape} and ${s.shape}, must match in call to tf.complex().`);const r={real:n,imag:s};return ta.runKernel(Ce,r)}});function ga(e,t,n,s){if(null==s)s=F(e);else if("complex64"===s)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(Gr(e)||Ur(e)){if("float32"!==s&&"int32"!==s)throw new Error(`Creating tensor from GPU data only supports 'float32'|'int32' dtype, while the dtype is ${s}.`);return ta.backend.createTensorFromGPUData(e,t||n,s)}if(!yr(e)&&!Array.isArray(e)&&"number"!=typeof e&&"boolean"!=typeof e&&"string"!=typeof e)throw new Error("values passed to tensor(values) must be a number/boolean/string or an array of numbers/booleans/strings, or a TypedArray");if(null!=t){U(t);const e=d(t),s=d(n);c(e===s,(()=>`Based on the provided shape, [${t}], the tensor should have ${e} values but has ${s}`));for(let e=0;e<n.length;++e){const s=n[e],r=e!==n.length-1||s!==d(t.slice(e));c(n[e]===t[e]||!r,(()=>`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `))}}return yr(e)||Array.isArray(e)||(e=[e]),t=t||n,e="string"!==s?pr(e,s):br(e,[],!0),ta.makeTensor(e,t,s)}function ya(e,t,n){return ga(e,t,la(e,n),n)}const ba={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};class xa{static join(e){return new xa(e).slice()}constructor(e){if(this.shards=[],this.previousShardIndex=0,null==e)return;if(e instanceof Array||(e=[e]),0===(e=e.map((e=>yr(e)?e.buffer:e))).length)return;this.bufferUniformSize=e[0].byteLength;let t=0;for(let n=0;n<e.length;n++){const s=e[n];n!==e.length-1&&s.byteLength!==this.bufferUniformSize&&(this.bufferUniformSize=void 0);const r=t+s.byteLength;this.shards.push({buffer:s,start:t,end:r}),t=r}0===this.shards.length&&(this.byteLength=0),this.byteLength=this.shards[this.shards.length-1].end}slice(e=0,t=this.byteLength){if(0===this.shards.length)return new ArrayBuffer(0);if(e=isNaN(Number(e))?0:e,t=isNaN(Number(t))?0:t,e=Math.max(0,e),(t=Math.min(this.byteLength,t))<=e)return new ArrayBuffer(0);const n=this.findShardForByte(e);if(-1===n)throw new Error(`Could not find start shard for byte ${e}`);const s=new ArrayBuffer(t-e),r=new Uint8Array(s);let a=0;for(let s=n;s<this.shards.length;s++){const n=this.shards[s],i=e+a-n.start,o=a,l=Math.min(t,n.end)-n.start,u=new Uint8Array(n.buffer,i,l-i);if(r.set(u,o),a+=u.length,t<n.end)break}return s}findShardForByte(e){if(0===this.shards.length||e<0||e>=this.byteLength)return-1;if(null!=this.bufferUniformSize)return this.previousShardIndex=Math.floor(e/this.bufferUniformSize),this.previousShardIndex;function t(t){return e<t.start?-1:e>=t.end?1:0}if(0===t(this.shards[this.previousShardIndex]))return this.previousShardIndex;const n=function(e,t){let n=0,s=e.length;for(;n<=s;){const r=Math.floor((s-n)/2)+n,a=t(e[r]);if(0===a)return r;a<0?s=r:n=r+1}return-1}(this.shards,t);return-1===n?-1:(this.previousShardIndex=n,this.previousShardIndex)}}function wa(e){Y().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function va(){return ta}function ka(){return ta.memory()}function Na(e,t){return ta.tidy(e,t)}function Ia(e){Kr(e).forEach((e=>e.dispose()))}function Sa(e){return ta.keep(e)}function Ta(e){return ta.setBackend(e)}function Ca(){return ta.backendName}function $a(e,t,n=1){return ta.registerBackend(e,t,n)}function Ea(){return ta.backend}Rr=wa;async function Aa(e,t){const n=[],s=[],r=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);for(let a=0;a<r.length;++a){const i=r[a],o=Array.isArray(e)?e[a].tensor:e[i];if("float32"!==o.dtype&&"int32"!==o.dtype&&"bool"!==o.dtype&&"string"!==o.dtype&&"complex64"!==o.dtype)throw new Error(`Unsupported dtype in weight '${i}': ${o.dtype}`);const l={name:i,shape:o.shape,dtype:o.dtype};if("string"===o.dtype){const e=new Promise((async e=>{const t=await o.bytes(),n=t.reduce(((e,t)=>e+t.length),0)+4*t.length,s=new Uint8Array(n);let r=0;for(let e=0;e<t.length;e++){const n=t[e],a=new Uint8Array(new Uint32Array([n.length]).buffer);s.set(a,r),r+=4,s.set(n,r),r+=n.length}e(s)}));s.push(e)}else s.push(o.data());null!=t&&(l.group=t),n.push(l)}return{data:La(await Promise.all(s)),specs:n}}function Ra(e,t){const n=new xa(e),s={};let r=0;for(const e of t){const t=_a(e,((e,t)=>n.slice(r+e,r+t)));s[e.name]=Da(e,n.slice(r,r+t)),r+=t}return s}function _a(e,t){const n=d(e.shape);let s;if("quantization"in e){const t=e.quantization;s=ba[t.dtype]}else{if("string"===e.dtype){let e=0;for(let s=0;s<n;s++)e+=4+new Uint32Array(t(e,e+4))[0];return e}s=ba[e.dtype]}return n*s}async function Fa(e,t){const n=d(e.shape);let s;if("quantization"in e){const t=e.quantization;s=ba[t.dtype]}else{if("string"===e.dtype){let e=0;for(let s=0;s<n;s++)e+=4+new Uint32Array(await t(e,e+4))[0];return e}s=ba[e.dtype]}return n*s}function Da(e,t){const n=e.name,s=e.dtype,r=e.shape,a=d(r);let i,o=0;if("quantization"in e){const r=e.quantization;if("uint8"===r.dtype||"uint16"===r.dtype){if(!("min"in r)||!("scale"in r))throw new Error(`Weight ${e.name} with quantization ${r.dtype} doesn't have corresponding metadata min and scale.`)}else{if("float16"!==r.dtype)throw new Error(`Weight ${e.name} has unknown quantization dtype ${r.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);if("float32"!==s)throw new Error(`Weight ${e.name} is quantized with ${r.dtype} which only supports weights of type float32 not ${s}.`)}const l=ba[r.dtype],u="uint8"===r.dtype?new Uint8Array(t):new Uint16Array(t);if("float32"===s)if("uint8"===r.dtype||"uint16"===r.dtype){i=new Float32Array(u.length);for(let e=0;e<u.length;e++){const t=u[e];i[e]=t*r.scale+r.min}}else{if("float16"!==r.dtype)throw new Error(`Unsupported quantization type ${r.dtype} for weight type float32.`);{const e=function(){const e=function(){const e=e=>{let t=e<<13,n=0;for(;0==(8388608&t);)n-=8388608,t<<=1;return t&=-8388609,n+=947912704,t|n},t=new Uint32Array(2048);t[0]=0;for(let n=1;n<1024;n++)t[n]=e(n);for(let e=1024;e<2048;e++)t[e]=939524096+(e-1024<<13);return t}(),t=function(){const e=new Uint32Array(64);e[0]=0,e[31]=1199570944,e[32]=2147483648,e[63]=3347054592;for(let t=1;t<31;t++)e[t]=t<<23;for(let t=33;t<63;t++)e[t]=2147483648+(t-32<<23);return e}(),n=function(){const e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}();return s=>{const r=new ArrayBuffer(4*s.length),a=new Uint32Array(r);for(let r=0;r<s.length;r++){const i=s[r],o=e[n[i>>10]+(1023&i)]+t[i>>10];a[r]=o}return new Float32Array(r)}}();i=e(u)}}else{if("int32"!==s)throw new Error(`Unsupported dtype in weight '${n}': ${s}`);if("uint8"!==r.dtype&&"uint16"!==r.dtype)throw new Error(`Unsupported quantization type ${r.dtype} for weight type int32.`);i=new Int32Array(u.length);for(let e=0;e<u.length;e++){const t=u[e];i[e]=Math.round(t*r.scale+r.min)}}o+=a*l}else if("string"===s){const n=d(e.shape);i=[];for(let e=0;e<n;e++){const e=new Uint32Array(t.slice(o,o+4))[0];o+=4;const n=new Uint8Array(t.slice(o,o+e));i.push(n),o+=e}}else{const e=ba[s];if("float32"===s)i=new Float32Array(t);else if("int32"===s)i=new Int32Array(t);else{if("bool"!==s){if("complex64"===s){i=new Float32Array(t);const e=new Float32Array(i.length/2),n=new Float32Array(i.length/2);for(let t=0;t<e.length;t++)e[t]=i[2*t],n[t]=i[2*t+1];const s=ya(e,r,"float32"),a=ya(n,r,"float32"),o=ma(s,a);return s.dispose(),a.dispose(),o}throw new Error(`Unsupported dtype in weight '${n}': ${s}`)}i=new Uint8Array(t)}o+=a*e}return ya(i,r,s)}async function Oa(e,t,n){let s=new Uint8Array(t);for(;s.byteLength<n;){const{done:t,value:r}=await e.read();if(t&&null==r){const e=n-s.byteLength;throw new Error(`Reader is done but ${e} bytes are still expected`)}const a=new Uint8Array(s.length+r.byteLength);a.set(s,0),a.set(new Uint8Array(r),s.length),s=a}return s.buffer}async function Ma(e,t){const n={},s=e.getReader();let r=new ArrayBuffer(0);for(const e of t){const t=await Fa(e,(async(e,t)=>(r=await Oa(s,r,t),r.slice(e,t))));r=await Oa(s,r,t);const a=r.slice(0,t);r=r.slice(t);const i=Da(e,a);if(n[e.name]=i,"webgpu"===Ca()){const e=Ea();"uploadToGPU"in e&&d(i.shape)>=Y().get("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD")&&e.uploadToGPU(i.dataId)}}return n}function La(e){if(null===e)throw new Error(`Invalid input value: ${JSON.stringify(e)}`);let t=0;const n=[];e.forEach((e=>{if(t+=e.byteLength,n.push(e.byteLength===e.buffer.byteLength?e:new e.constructor(e)),!(e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${e.constructor.name}`)}));const s=new Uint8Array(t);let r=0;return n.forEach((e=>{s.set(new Uint8Array(e.buffer),r),r+=e.byteLength})),s.buffer}const za="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function Pa(e){return za?Buffer.byteLength(e,"utf8"):new Blob([e]).size}function Ba(e){return xa.join(e)}function Wa(e){for(e=e.trim();e.endsWith("/");)e=e.slice(0,e.length-1);const t=e.split("/");return t[t.length-1]}function Va(e,t){const n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:t};return null!=e.signature&&(n.signature=e.signature),null!=e.userDefinedMetadata&&(n.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(n.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(n.initializerSignature=e.initializerSignature),null!=e.trainingConfig&&(n.trainingConfig=e.trainingConfig),n}function Ua(e,t,n){const s={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(null!=e.trainingConfig&&(s.trainingConfig=e.trainingConfig),null!=e.weightsManifest){if(!t)throw new Error("modelJSON has weightsManifest but weightSpecs is null");if(!n)throw new Error("modelJSON has weightsManifest but weightData is null");s.weightSpecs=t,s.weightData=n}return null!=e.signature&&(s.signature=e.signature),null!=e.userDefinedMetadata&&(s.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(s.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(s.initializerSignature=e.initializerSignature),s}async function Ga(e,t){let n,s;return null!=e.weightsManifest&&([n,s]=await t(e.weightsManifest)),Ua(e,n,s)}function Ha(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("Expected JSON model topology, received ArrayBuffer.");return{dateSaved:new Date,modelTopologyType:"JSON",modelTopologyBytes:null==e.modelTopology?0:Pa(JSON.stringify(e.modelTopology)),weightSpecsBytes:null==e.weightSpecs?0:Pa(JSON.stringify(e.weightSpecs)),weightDataBytes:null==e.weightData?0:new xa(e.weightData).byteLength}}function ja(e){const t=[];for(const n of e)t.push(...n.weights);return t}class qa{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return null==qa.instance&&(qa.instance=new qa),qa.instance}static registerSaveRouter(e){qa.getInstance().saveRouters.push(e)}static registerLoadRouter(e){qa.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return qa.getHandlers(e,"save")}static getLoadHandlers(e,t){return qa.getHandlers(e,"load",t)}static getHandlers(e,t,n){const s=[];return("load"===t?qa.getInstance().loadRouters:qa.getInstance().saveRouters).forEach((t=>{const r=t(e,n);null!==r&&s.push(r)})),s}}const Ka=e=>qa.getSaveHandlers(e),Xa=(e,t)=>qa.getLoadHandlers(e,t),Ya="tensorflowjs",Za="models_store",Ja="model_info_store";function Qa(){if(!Y().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");const e="undefined"==typeof window?self:window,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(null==t)throw new Error("The current browser does not appear to support IndexedDB.");return t}function ei(e){const t=e.result;t.createObjectStore(Za,{keyPath:"modelPath"}),t.createObjectStore(Ja,{keyPath:"modelPath"})}class ti{constructor(e){if(this.indexedDB=Qa(),null==e||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,e)}async load(){return this.databaseAction(this.modelPath)}databaseAction(e,t){return new Promise(((e,n)=>{const s=this.indexedDB.open(Ya,1);s.onupgradeneeded=()=>ei(s),s.onsuccess=()=>{const r=s.result;if(null==t){const t=r.transaction(Za,"readonly"),s=t.objectStore(Za).get(this.modelPath);s.onsuccess=()=>{if(null==s.result)return r.close(),n(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));e(s.result.modelArtifacts)},s.onerror=e=>(r.close(),n(s.error)),t.oncomplete=()=>r.close()}else{t.weightData=xa.join(t.weightData);const s=Ha(t),a=r.transaction(Ja,"readwrite");let i,o,l=a.objectStore(Ja);try{i=l.put({modelPath:this.modelPath,modelArtifactsInfo:s})}catch(e){return n(e)}i.onsuccess=()=>{o=r.transaction(Za,"readwrite");const i=o.objectStore(Za);let u;try{u=i.put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:s})}catch(e){return n(e)}u.onsuccess=()=>e({modelArtifactsInfo:s}),u.onerror=e=>{l=a.objectStore(Ja);const t=l.delete(this.modelPath);t.onsuccess=()=>(r.close(),n(u.error)),t.onerror=e=>(r.close(),n(u.error))}},i.onerror=e=>(r.close(),n(i.error)),a.oncomplete=()=>{null==o?r.close():o.oncomplete=()=>r.close()}}},s.onerror=e=>n(s.error)}))}}ti.URL_SCHEME="indexeddb://";const ni=e=>{return Y().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(ti.URL_SCHEME)?(t=e.slice(ti.URL_SCHEME.length),new ti(t)):null;var t};qa.registerSaveRouter(ni),qa.registerLoadRouter(ni);class si{constructor(){this.indexedDB=Qa()}async listModels(){return new Promise(((e,t)=>{const n=this.indexedDB.open(Ya,1);n.onupgradeneeded=()=>ei(n),n.onsuccess=()=>{const s=n.result,r=s.transaction(Ja,"readonly"),a=r.objectStore(Ja).getAll();a.onsuccess=()=>{const t={};for(const e of a.result)t[e.modelPath]=e.modelArtifactsInfo;e(t)},a.onerror=e=>(s.close(),t(a.error)),r.oncomplete=()=>s.close()},n.onerror=e=>t(n.error)}))}async removeModel(e){var t;return e=(t=e).startsWith(ti.URL_SCHEME)?t.slice(ti.URL_SCHEME.length):t,new Promise(((t,n)=>{const s=this.indexedDB.open(Ya,1);s.onupgradeneeded=()=>ei(s),s.onsuccess=()=>{const r=s.result,a=r.transaction(Ja,"readwrite"),i=a.objectStore(Ja),o=i.get(e);let l;o.onsuccess=()=>{if(null==o.result)return r.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{const s=i.delete(e),a=()=>{l=r.transaction(Za,"readwrite");const s=l.objectStore(Za).delete(e);s.onsuccess=()=>t(o.result.modelArtifactsInfo),s.onerror=e=>n(o.error)};s.onsuccess=a,s.onerror=e=>(a(),r.close(),n(o.error))}},o.onerror=e=>(r.close(),n(o.error)),a.oncomplete=()=>{null==l?r.close():l.oncomplete=()=>r.close()}},s.onerror=e=>n(s.error)}))}}const ri="/",ai="tensorflowjs_models",ii="info",oi="model_topology",li="weight_specs",ui="weight_data",ci="model_metadata";function hi(e){return{info:[ai,e,ii].join(ri),topology:[ai,e,oi].join(ri),weightSpecs:[ai,e,li].join(ri),weightData:[ai,e,ui].join(ri),modelMetadata:[ai,e,ci].join(ri)}}function pi(e){for(const t of Object.values(e))window.localStorage.removeItem(t)}function di(e){const t=e.split(ri);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(ri)}class fi{constructor(e){if(!Y().getBool("IS_BROWSER")||"undefined"==typeof window||void 0===window.localStorage)throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,null==e||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=hi(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{const t=JSON.stringify(e.modelTopology),n=JSON.stringify(e.weightSpecs),s=Ha(e),r=xa.join(e.weightData);try{this.LS.setItem(this.keys.info,JSON.stringify(s)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,function(e){if(za)return Buffer.from(e).toString("base64");const t=new Uint8Array(e);let n="";for(let e=0,s=t.length;e<s;e++)n+=String.fromCharCode(t[e]);return btoa(n)}(r));const a={format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,signature:null!=e.signature?e.signature:void 0,userDefinedMetadata:null!=e.userDefinedMetadata?e.userDefinedMetadata:void 0,modelInitializer:null!=e.modelInitializer?e.modelInitializer:void 0,initializerSignature:null!=e.initializerSignature?e.initializerSignature:void 0,trainingConfig:null!=e.trainingConfig?e.trainingConfig:void 0};return this.LS.setItem(this.keys.modelMetadata,JSON.stringify(a)),{modelArtifactsInfo:s}}catch(e){throw pi(this.keys),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${s.modelTopologyBytes}, weightSpecsBytes=${s.weightSpecsBytes}, weightDataBytes=${s.weightDataBytes}.`)}}}async load(){const e=JSON.parse(this.LS.getItem(this.keys.info));if(null==e)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if("JSON"!==e.modelTopologyType)throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");const t={},n=JSON.parse(this.LS.getItem(this.keys.topology));if(null==n)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);t.modelTopology=n;const s=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(null==s)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=s;const r=this.LS.getItem(this.keys.modelMetadata);if(null!=r){const e=JSON.parse(r);t.format=e.format,t.generatedBy=e.generatedBy,t.convertedBy=e.convertedBy,null!=e.signature&&(t.signature=e.signature),null!=e.userDefinedMetadata&&(t.userDefinedMetadata=e.userDefinedMetadata),null!=e.modelInitializer&&(t.modelInitializer=e.modelInitializer),null!=e.initializerSignature&&(t.initializerSignature=e.initializerSignature),null!=e.trainingConfig&&(t.trainingConfig=e.trainingConfig)}const a=this.LS.getItem(this.keys.weightData);if(null==a)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=function(e){if(za){const t=Buffer.from(e,"base64");return t.buffer.slice(t.byteOffset,t.byteOffset+t.byteLength)}const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n.set([t.charCodeAt(e)],e);return n.buffer}(a),t}}fi.URL_SCHEME="localstorage://";const mi=e=>{return Y().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(fi.URL_SCHEME)?(t=e.slice(fi.URL_SCHEME.length),new fi(t)):null;var t};qa.registerSaveRouter(mi),qa.registerLoadRouter(mi);class gi{constructor(){c(Y().getBool("IS_BROWSER"),(()=>"Current environment is not a web browser")),c("undefined"==typeof window||void 0!==window.localStorage,(()=>"Current browser does not appear to support localStorage")),this.LS=window.localStorage}async listModels(){const e={},t=ai+ri,n=ri+ii;for(let s=0;s<this.LS.length;++s){const r=this.LS.key(s);if(r.startsWith(t)&&r.endsWith(n)){e[di(r)]=JSON.parse(this.LS.getItem(r))}}return e}async removeModel(e){var t;const n=hi(e=(t=e).startsWith(fi.URL_SCHEME)?t.slice(fi.URL_SCHEME.length):t);if(null==this.LS.getItem(n.info))throw new Error(`Cannot find model at path '${e}'`);const s=JSON.parse(this.LS.getItem(n.info));return pi(n),s}}const yi="://";class bi{constructor(){this.managers={}}static getInstance(){return null==bi.instance&&(bi.instance=new bi),bi.instance}static registerManager(e,t){c(null!=e,(()=>"scheme must not be undefined or null.")),e.endsWith(yi)&&(e=e.slice(0,e.indexOf(yi))),c(e.length>0,(()=>"scheme must not be an empty string."));const n=bi.getInstance();c(null==n.managers[e],(()=>`A model store manager is already registered for scheme '${e}'.`)),n.managers[e]=t}static getManager(e){const t=bi.getInstance().managers[e];if(null==t)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(bi.getInstance().managers)}}function xi(e){if(-1===e.indexOf(yi))throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${bi.getSchemes().join(",")}`);return{scheme:e.split(yi)[0],path:e.split(yi)[1]}}async function wi(e,t,n=!1){c(e!==t,(()=>`Old path and new path are the same: '${e}'`));const s=qa.getLoadHandlers(e);c(s.length>0,(()=>`Copying failed because no load handler is found for source URL ${e}.`)),c(s.length<2,(()=>`Copying failed because more than one (${s.length}) load handlers for source URL ${e}.`));const r=s[0],a=qa.getSaveHandlers(t);c(a.length>0,(()=>`Copying failed because no save handler is found for destination URL ${t}.`)),c(a.length<2,(()=>`Copying failed because more than one (${s.length}) save handlers for destination URL ${t}.`));const i=a[0],o=xi(e).scheme,l=xi(e).path,u=o===xi(e).scheme,h=await r.load();n&&u&&await bi.getManager(o).removeModel(l);const p=await i.save(h);return n&&!u&&await bi.getManager(o).removeModel(l),p.modelArtifactsInfo}class vi{constructor(){this.messageName="setTimeoutCustom",this.functionRefs=[],this.handledMessageCount=0,this.hasEventListener=!1}fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error(`Browser's encoder only supports utf-8, but got ${t}`);return null==this.textEncoder&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}setTimeoutCustom(e,t){"undefined"!=typeof window&&Y().getBool("USE_SETTIMEOUTCUSTOM")?(this.functionRefs.push(e),setTimeout((()=>{window.postMessage({name:this.messageName,index:this.functionRefs.length-1},"*")}),t),this.hasEventListener||(this.hasEventListener=!0,window.addEventListener("message",(e=>{if(e.source===window&&e.data.name===this.messageName){e.stopPropagation();(0,this.functionRefs[e.data.index])(),this.handledMessageCount++,this.handledMessageCount===this.functionRefs.length&&(this.functionRefs=[],this.handledMessageCount=0)}}),!0))):setTimeout(e,t)}isTypedArray(e){return Ns(e)}}if(Y().get("IS_BROWSER")){Y().setPlatform("browser",new vi);try{bi.registerManager(fi.URL_SCHEME,new gi)}catch(e){}try{bi.registerManager(ti.URL_SCHEME,new si)}catch(e){}}const ki=()=>require("node-fetch");let Ni;class Ii{constructor(){this.util=require("util"),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return null!=Y().global.fetch?Y().global.fetch(e,t):(null==Ni&&(Ni=ki()),Ni(e,t))}now(){const e=process.hrtime();return 1e3*e[0]+e[1]/1e6}encode(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error(`Node built-in encoder only supports utf-8, but got ${t}`);return this.textEncoder.encode(e)}decode(e,t){return 0===e.length?"":new this.util.TextDecoder(t).decode(e)}isTypedArray(e){return this.util.types.isFloat32Array(e)||this.util.types.isInt32Array(e)||this.util.types.isUint8Array(e)||this.util.types.isUint8ClampedArray(e)}}function Si(e,t="float32",n){return t=t||"float32",U(e),new $r(e,t,n)}Y().get("IS_NODE")&&!Y().get("IS_BROWSER")&&Y().setPlatform("node",new Ii);const Ti=fa({cast_:function(e,t){const n=ha(e,"x","cast");if(!T(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if("string"===t&&"string"!==n.dtype||"string"!==t&&"string"===n.dtype)throw new Error("Only strings can be casted to strings");const s={x:n},r={dtype:t};return ta.runKernel(Ie,s,r)}});const Ci=fa({clone_:function(e){const t={x:ha(e,"x","clone","string_or_numeric")};return ta.runKernel(gt,t)}});function $i(e,t=!1){console.log(e.toString(t))}ea();Ar={buffer:Si,cast:Ti,clone:Ci,print:$i};const Ei=fa({add_:function(e,t){let n=ha(e,"a","add"),s=ha(t,"b","add");[n,s]=Hr(n,s);const r={a:n,b:s};return ta.runKernel(se,r)}});const Ai=fa({floorDiv_:function(e,t){let n=ha(e,"a","floorDiv"),s=ha(t,"b","floorDiv");[n,s]=Hr(n,s);const r={a:n,b:s};return ta.runKernel(ct,r)}});const Ri=fa({div_:function(e,t){let n=ha(e,"a","div"),s=ha(t,"b","div");if([n,s]=Hr(n,s),"int32"===n.dtype&&"int32"===s.dtype)return Ai(n,s);const r={a:n,b:s};return ta.runKernel(Ze,r,{})}});const _i=fa({mul_:function(e,t){let n=ha(e,"a","mul"),s=ha(t,"b","mul");[n,s]=Hr(n,s);const r={a:n,b:s};return ta.runKernel(qt,r)}});const Fi=fa({abs_:function(e){const t=ha(e,"x","abs");if("complex64"===t.dtype){const e={x:t};return ta.runKernel($e,e)}{const e={x:t};return ta.runKernel(ee,e)}}});const Di=fa({acos_:function(e){const t={x:ha(e,"x","acos")};return ta.runKernel(te,t)}});const Oi=fa({acosh_:function(e){const t={x:ha(e,"x","acosh")};return ta.runKernel(ne,t)}});const Mi=fa({addN_:function(e){c(Array.isArray(e),(()=>"The argument passed to tf.addN() must be a list of tensors")),c(e.length>=1,(()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`));const t=e.map(((e,t)=>ha(e,`tensors${t}`,"addN"))),n=t[0];t.forEach((e=>{if(e.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")})),t.forEach((e=>{if(!m(e.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")}));const s=t;return ta.runKernel(re,s)}});const Li=fa({all_:function(e,t=null,n=!1){const s={x:ha(e,"x","all","bool")},r={axis:t,keepDims:n};return ta.runKernel(ae,s,r)}});const zi=fa({any_:function(e,t=null,n=!1){const s={x:ha(e,"x","any","bool")},r={axis:t,keepDims:n};return ta.runKernel(ie,s,r)}});const Pi=fa({argMax_:function(e,t=0){const n={x:ha(e,"x","argMax")},s={axis:t};return ta.runKernel(oe,n,s)}});const Bi=fa({argMin_:function(e,t=0){const n={x:ha(e,"x","argMin")},s={axis:t};return ta.runKernel(le,n,s)}});const Wi=fa({asin_:function(e){const t={x:ha(e,"x","asin")};return ta.runKernel(ue,t)}});const Vi=fa({asinh_:function(e){const t={x:ha(e,"x","asinh")};return ta.runKernel(ce,t)}});const Ui=fa({atan_:function(e){const t={x:ha(e,"x","atan")};return ta.runKernel(he,t)}});const Gi=fa({atan2_:function(e,t){let n=ha(e,"a","atan2"),s=ha(t,"b","atan2");[n,s]=Hr(n,s);const r={a:n,b:s};return ta.runKernel(de,r)}});const Hi=fa({atanh_:function(e){const t={x:ha(e,"x","atanh")};return ta.runKernel(pe,t)}});function ji(e,t,n,s,r="NHWC",a){return Xi(e,[...t,e[3]],n,a,s,null,null,ao(r))}function qi(e,t,n,s,r,a,i="channelsLast"){const[o,l]=Ji(t);let u;if("channelsLast"===i)u=[o,l,e[3],e[3]];else{if("channelsFirst"!==i)throw new Error(`Unknown dataFormat ${i}`);u=[o,l,e[1],e[1]]}return Xi(e,u,n,s,r,a,!1,i)}function Ki(e,t,n,s,r,a,i="NDHWC"){const[o,l,u]=Qi(t);let c,h;if("NDHWC"===i)h="channelsLast",c=[o,l,u,e[4],e[4]];else{if("NCDHW"!==i)throw new Error(`Unknown dataFormat ${i}`);h="channelsFirst",c=[o,l,u,e[1],e[1]]}return Yi(e,c,n,s,r,!1,h,a)}function Xi(e,t,n,s,r,a,i=!1,o="channelsLast"){let[l,u,c,h]=[-1,-1,-1,-1];if("channelsLast"===o)[l,u,c,h]=e;else{if("channelsFirst"!==o)throw new Error(`Unknown dataFormat ${o}`);[l,h,u,c]=e}const[p,d,,f]=t,[m,g]=Ji(n),[y,b]=Ji(s),x=eo(p,y),w=eo(d,b),{padInfo:v,outHeight:k,outWidth:N}=function(e,t,n,s,r,a,i,o,l){let u,c,h;if("number"==typeof e){u={top:e,bottom:e,left:e,right:e,type:0===e?"VALID":"NUMBER"};const r=function(e,t,n,s,r){null==s&&(s=Zi(e,t,n));const a=e[0],i=e[1],o=to((a-t+2*s)/n+1,r),l=to((i-t+2*s)/n+1,r);return[o,l]}([t,n],a,s,e,o);c=r[0],h=r[1]}else if("same"===e){c=Math.ceil(t/s),h=Math.ceil(n/r);const e=Math.max(0,(c-1)*s+a-t),o=Math.max(0,(h-1)*r+i-n),l=Math.floor(e/2),p=e-l,d=Math.floor(o/2);u={top:l,bottom:p,left:d,right:o-d,type:"SAME"}}else if("valid"===e)u={top:0,bottom:0,left:0,right:0,type:"VALID"},c=Math.ceil((t-a+1)/s),h=Math.ceil((n-i+1)/r);else{if("object"!=typeof e)throw Error(`Unknown padding parameter: ${e}`);{const p="channelsLast"===l?e[1][0]:e[2][0],d="channelsLast"===l?e[1][1]:e[2][1],f="channelsLast"===l?e[2][0]:e[3][0],m="channelsLast"===l?e[2][1]:e[3][1];u={top:p,bottom:d,left:f,right:m,type:0===p&&0===d&&0===f&&0===m?"VALID":"EXPLICIT"},c=to((t-a+p+d)/s+1,o),h=to((n-i+f+m)/r+1,o)}}return{padInfo:u,outHeight:c,outWidth:h}}(r,u,c,m,g,x,w,a,o),I=i?f*h:f;let S;return"channelsFirst"===o?S=[l,I,k,N]:"channelsLast"===o&&(S=[l,k,N,I]),{batchSize:l,dataFormat:o,inHeight:u,inWidth:c,inChannels:h,outHeight:k,outWidth:N,outChannels:I,padInfo:v,strideHeight:m,strideWidth:g,filterHeight:p,filterWidth:d,effectiveFilterHeight:x,effectiveFilterWidth:w,dilationHeight:y,dilationWidth:b,inShape:e,outShape:S,filterShape:t}}function Yi(e,t,n,s,r,a=!1,i="channelsLast",o){let[l,u,c,h,p]=[-1,-1,-1,-1,-1];if("channelsLast"===i)[l,u,c,h,p]=e;else{if("channelsFirst"!==i)throw new Error(`Unknown dataFormat ${i}`);[l,p,u,c,h]=e}const[d,f,m,,g]=t,[y,b,x]=Qi(n),[w,v,k]=Qi(s),N=eo(d,w),I=eo(f,v),S=eo(m,k),{padInfo:T,outDepth:C,outHeight:$,outWidth:E}=function(e,t,n,s,r,a,i,o,l,u,c){let h,p,d,f;"valid"===e&&(e=0);if("number"==typeof e){h={top:e,bottom:e,left:e,right:e,front:e,back:e,type:0===e?"VALID":"NUMBER"};const m=function(e,t,n,s,r,a){null==r&&(r=Zi(e,t[0],s[0]));const i=[0,0,0,n];for(let n=0;n<3;n++)e[n]+2*r>=t[n]&&(i[n]=to((e[n]-t[n]+2*r)/s[n]+1,a));return i}([t,n,s,1],[o,l,u],1,[r,a,i],e,c);p=m[0],d=m[1],f=m[2]}else{if("same"!==e)throw Error(`Unknown padding parameter: ${e}`);{p=Math.ceil(t/r),d=Math.ceil(n/a),f=Math.ceil(s/i);const e=(p-1)*r+o-t,c=(d-1)*a+l-n,m=(f-1)*i+u-s,g=Math.floor(e/2),y=e-g,b=Math.floor(c/2),x=c-b,w=Math.floor(m/2);h={top:b,bottom:x,left:w,right:m-w,front:g,back:y,type:"SAME"}}}return{padInfo:h,outDepth:p,outHeight:d,outWidth:f}}(r,u,c,h,y,b,x,N,I,S,o),A=a?g*p:g;let R;return"channelsFirst"===i?R=[l,A,C,$,E]:"channelsLast"===i&&(R=[l,C,$,E,A]),{batchSize:l,dataFormat:i,inDepth:u,inHeight:c,inWidth:h,inChannels:p,outDepth:C,outHeight:$,outWidth:E,outChannels:A,padInfo:T,strideDepth:y,strideHeight:b,strideWidth:x,filterDepth:d,filterHeight:f,filterWidth:m,effectiveFilterDepth:N,effectiveFilterHeight:I,effectiveFilterWidth:S,dilationDepth:w,dilationHeight:v,dilationWidth:k,inShape:e,outShape:R,filterShape:t}}function Zi(e,t,n,s=1){const r=eo(t,s);return Math.floor((e[0]*(n-1)-n+r)/2)}function Ji(e){return"number"==typeof e?[e,e,e]:2===e.length?[e[0],e[1],1]:e}function Qi(e){return"number"==typeof e?[e,e,e]:e}function eo(e,t){return t<=1?e:e+(e-1)*(t-1)}function to(e,t){if(!t)return Math.trunc(e);switch(t){case"round":return Math.round(e);case"ceil":return Math.ceil(e);case"floor":return Math.floor(e);default:throw new Error(`Unknown roundingMode ${t}`)}}function no(e){const[t,n,s]=Ji(e);return 1===t&&1===n&&1===s}function so(e,t){return no(e)||no(t)}function ro(e){return Ji(e).every((e=>e>0))}function ao(e){if("NHWC"===e)return"channelsLast";if("NCHW"===e)return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function io(e,t,n){if(null!=n){if("string"==typeof t)throw Error(`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`);if("number"==typeof t)c(g(t),(()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`));else{if("object"!=typeof t)throw Error(`Error in ${e}: Unknown padding parameter: ${t}`);t.forEach((t=>{t.forEach((t=>{c(g(t),(()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`))}))}))}}}const oo=fa({reshape_:function(e,t){const n={x:ha(e,"x","reshape","string_or_numeric")},s={shape:t};return ta.runKernel(fn,n,s)}});const lo=fa({avgPool_:function(e,t,n,s,r){const a=ha(e,"x","avgPool","float32");c(so(n,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`));let i=a,o=!1;3===a.rank&&(o=!0,i=oo(a,[1,a.shape[0],a.shape[1],a.shape[2]])),c(4===i.rank,(()=>`Error in avgPool: x must be rank 4 but got rank ${i.rank}.`)),io("avgPool",s,r);const l={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:r};let h=ta.runKernel(fe,l,u);return h=Ti(h,a.dtype),o?oo(h,[h.shape[1],h.shape[2],h.shape[3]]):h}});const uo=fa({avgPool3d_:function(e,t,n,s,r,a="NDHWC"){const i=ha(e,"x","avgPool3d","float32");let o=i,l=!1;4===i.rank&&(l=!0,o=oo(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),c(5===o.rank,(()=>`Error in avgPool3d: x must be rank 5 but got rank ${o.rank}.`)),c("NDHWC"===a,(()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`)),c("number"==typeof n&&n>0||Array.isArray(n)&&n[0]>0&&n[1]>0&&n[2]>0,(()=>`Error in avgPool3d: Stride must be > 0, but got '${n}'`)),io("avgPool3d",s,r);const u={x:o},h={filterSize:t,strides:n,pad:s,dimRoundingMode:r,dataFormat:a};let p=ta.runKernel(ge,u,h);return p=Ti(p,o.dtype),l?oo(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}});const co=fa({concat_:function(e,t=0){c(e.length>=1,(()=>"Pass at least one tensor to concat"));const n=pa(e,"tensors","concat","string_or_numeric");if("complex64"===n[0].dtype&&n.forEach((e=>{if("complex64"!==e.dtype)throw new Error(`Cannot concatenate complex64 tensors with a tensor\n          with dtype ${e.dtype}. `)})),1===n.length)return Ci(n[0]);const s=n,r={axis:t};return ta.runKernel(Ee,s,r)}});const ho=fa({matMul_:function(e,t,n=!1,s=!1){let r=ha(e,"a","matMul"),a=ha(t,"b","matMul");[r,a]=Hr(r,a);const i={a:r,b:a},o={transposeA:n,transposeB:s};return ta.runKernel(be,i,o)}});const po=fa({sigmoid_:function(e){const t={x:ha(e,"x","sigmoid","float32")};return ta.runKernel(_n,t)}});const fo=fa({slice_:function(e,t,n){const s=ha(e,"x","slice","string_or_numeric");if(0===s.rank)throw new Error("Slicing scalar is not possible");const r={x:s},a={begin:t,size:n};return ta.runKernel($n,r,a)}});const mo=fa({tanh_:function(e){const t={x:ha(e,"x","tanh","float32")};return ta.runKernel(Qn,t)}});const go=fa({basicLSTMCell_:function(e,t,n,s,r,a){const i=ha(e,"forgetBias","basicLSTMCell"),o=ha(t,"lstmKernel","basicLSTMCell"),l=ha(n,"lstmBias","basicLSTMCell"),u=ha(s,"data","basicLSTMCell"),c=ha(r,"c","basicLSTMCell"),h=ha(a,"h","basicLSTMCell"),p=co([u,h],1),d=ho(p,o),f=Ei(d,l),m=f.shape[0],g=f.shape[1]/4,y=[m,g],b=fo(f,[0,0],y),x=fo(f,[0,g],y),w=fo(f,[0,2*g],y),v=fo(f,[0,3*g],y),k=Ei(_i(po(b),mo(x)),_i(c,po(Ei(i,w))));return[k,_i(mo(k),po(v))]}});const yo=fa({batchToSpaceND_:function(e,t,n){const s=ha(e,"x","batchToSpaceND"),r=t.reduce(((e,t)=>e*t));c(s.rank>=1+t.length,(()=>`input rank is ${s.rank} but should be > than blockShape.length ${t.length}`)),c(n.length===t.length,(()=>`crops.length is ${n.length} but should be equal to blockShape.length  ${t.length}`)),c(s.shape[0]%r==0,(()=>`input tensor batch is ${s.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${r}`));const a={x:s},i={blockShape:t,crops:n};return ta.runKernel(xe,a,i)}});const bo=fa({batchNorm_:function(e,t,n,s,r,a){null==a&&(a=.001);const i=ha(e,"x","batchNorm"),o=ha(t,"mean","batchNorm"),l=ha(n,"variance","batchNorm");let u,h;null!=r&&(u=ha(r,"scale","batchNorm")),null!=s&&(h=ha(s,"offset","batchNorm")),c(o.rank===l.rank,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),c(null==h||o.rank===h.rank,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),c(null==u||o.rank===u.rank,(()=>"Batch normalization gradient requires mean and scale to have equal ranks."));const p=function(e){let t;return t=0===e.rank||1===e.rank?oo(e,[1,1,1,e.size]):2===e.rank?oo(e,[1,1,e.shape[0],e.shape[1]]):3===e.rank?oo(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e,t}(i),d={x:p,scale:u,offset:h,mean:o,variance:l},f={varianceEpsilon:a},m=ta.runKernel(ht,d,f);return oo(m,i.shape)}});const xo=fa({batchNorm2d_:function(e,t,n,s,r,a){const i=ha(e,"x","batchNorm"),o=ha(t,"mean","batchNorm"),l=ha(n,"variance","batchNorm");let u,h;return null!=r&&(u=ha(r,"scale","batchNorm")),null!=s&&(h=ha(s,"offset","batchNorm")),c(2===i.rank,(()=>`Error in batchNorm2D: x must be rank 2 but got rank ${i.rank}.`)),c(2===o.rank||1===o.rank,(()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${o.rank}.`)),c(2===l.rank||1===l.rank,(()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`)),null!=u&&c(2===u.rank||1===u.rank,(()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${u.rank}.`)),null!=h&&c(2===h.rank||1===h.rank,(()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${h.rank}.`)),bo(i,o,l,h,u,a)}});const wo=fa({batchNorm3d_:function(e,t,n,s,r,a){const i=ha(e,"x","batchNorm"),o=ha(t,"mean","batchNorm"),l=ha(n,"variance","batchNorm");let u,h;return null!=r&&(u=ha(r,"scale","batchNorm")),null!=s&&(h=ha(s,"offset","batchNorm")),c(3===i.rank,(()=>`Error in batchNorm3D: x must be rank 3 but got rank ${i.rank}.`)),c(3===o.rank||1===o.rank,(()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${o.rank}.`)),c(3===l.rank||1===l.rank,(()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`)),null!=u&&c(3===u.rank||1===u.rank,(()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${u.rank}.`)),null!=h&&c(3===h.rank||1===h.rank,(()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${h.rank}.`)),bo(i,o,l,h,u,a)}});const vo=fa({batchNorm4d_:function(e,t,n,s,r,a){const i=ha(e,"x","batchNorm"),o=ha(t,"mean","batchNorm"),l=ha(n,"variance","batchNorm");let u,h;return null!=r&&(u=ha(r,"scale","batchNorm")),null!=s&&(h=ha(s,"offset","batchNorm")),c(4===i.rank,(()=>`Error in batchNorm4D: x must be rank 4 but got rank ${i.rank}.`)),c(4===o.rank||1===o.rank,(()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${o.rank}.`)),c(4===l.rank||1===l.rank,(()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`)),null!=u&&c(4===u.rank||1===u.rank,(()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${u.rank}.`)),null!=h&&c(4===h.rank||1===h.rank,(()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${h.rank}.`)),bo(i,o,l,h,u,a)}});const ko=fa({bincount_:function(e,t,n){const s=ha(e,"x","bincount"),r=ha(t,"weights","bincount");c("int32"===s.dtype,(()=>`Error in bincount: input dtype must be int32, but got ${s.dtype}`)),c(n>=0,(()=>`size must be non-negative, but got ${n}.`)),c(r.size===s.size||0===r.size,(()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${s.shape}, weights shape: ${r.shape}.`));const a={x:s,weights:r},i={size:n};return ta.runKernel(we,a,i)}});const No=fa({bitwiseAnd_:function(e,t){const n=ha(e,"x","bitwiseAnd"),s=ha(t,"y","bitwiseAnd");if(!m(n.shape,s.shape))throw new Error(`BitwiseAnd: Tensors must have the same shape. x: ${n.shape}, y: ${s.shape}`);if("int32"!==n.dtype||"int32"!==s.dtype)throw new Error(`BitwiseAnd: Only supports 'int32' values in tensor, found type of x: ${n.dtype} and type of y: ${s.dtype}`);const r={a:n,b:s};return ta.runKernel(ve,r)}});const Io=fa({broadcastArgs_:function(e,t){const n=ha(e,"s0","broadcastArgs","int32"),s=ha(t,"s1","broadcastArgs","int32");if(1!==n.rank)throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${n.rank}`);if(1!==s.rank)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${s.rank}`);const r={s0:n,s1:s};return ta.runKernel(Ne,r)}});const So=fa({broadcastTo_:function(e,t){let n=ha(e,"broadcastTo","x");const s=n.shape;if(U(t),t.length<n.rank)throw new Error(`broadcastTo(): shape.length=${t.length} < input.rank=${n.rank}.`);if(t.length>n.rank){const e=n.shape.slice();for(;e.length<t.length;)e.unshift(1);n=oo(n,e)}const r=n.shape,a=Array.from(t);for(let e=t.length-1;e>=0;e--)if(r[e]===t[e])a[e]=1;else if(1!==n.shape[e])throw new Error(`broadcastTo(): [${s}] cannot be broadcast to [${t}].`);if(0===a.map(((e,t)=>e>1?t:-1)).filter((e=>e>=0)).length)return Ci(n);const i={x:n},o={reps:a};return ta.runKernel(es,i,o)}});const To=fa({ceil_:function(e){const t={x:ha(e,"x","ceil","float32")};return ta.runKernel(Se,t)}});function Co(e,t,n){U(e);const s={shape:e,value:t,dtype:n=n||F(t)};return ta.runKernel(ot,{},s)}const $o=fa({clipByValue_:function(e,t,n){const s=ha(e,"x","clipByValue");if(c(t<=n,(()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`)),t===n)return Co(s.shape,t,s.dtype);const r={x:s},a={clipValueMin:t,clipValueMax:n};return ta.runKernel(Te,r,a)}});const Eo=fa({concat1d_:function(e){return co(e,0)}});const Ao=fa({concat2d_:function(e,t){return co(e,t)}});const Ro=fa({concat3d_:function(e,t){return co(e,t)}});const _o=fa({concat4d_:function(e,t){return co(e,t)}});const Fo=fa({conv2d_:function(e,t,n,s,r="NHWC",a=[1,1],i){const o=ha(e,"x","conv2d","float32"),l=ha(t,"filter","conv2d","float32");let u=o,h=!1;3===o.rank&&(h=!0,u=oo(o,[1,o.shape[0],o.shape[1],o.shape[2]])),c(4===u.rank,(()=>`Error in conv2d: input must be rank 4, but got rank ${u.rank}.`)),c(4===l.rank,(()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`)),io("conv2d",s,i);const p="NHWC"===r?u.shape[3]:u.shape[1];c(p===l.shape[2],(()=>`Error in conv2d: depth of input (${p}) must match input depth for filter ${l.shape[2]}.`)),c(so(n,a),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`)),c(ro(a),(()=>"Error in conv2D: Dilated rates should be larger than 0.")),c(ro(n),(()=>"Error in conv2D: Strides should be larger than 0."));const d={x:u,filter:l},f={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:i},m=ta.runKernel(Ae,d,f);return h?oo(m,[m.shape[1],m.shape[2],m.shape[3]]):m}});const Do=fa({conv1d_:function(e,t,n,s,r="NWC",a=1,i){const o=ha(e,"x","conv1d"),l=ha(t,"filter","conv1d");let u=o,h=!1;2===o.rank&&(h=!0,u=oo(o,[1,o.shape[0],o.shape[1]])),c(3===u.rank,(()=>`Error in conv1d: input must be rank 3, but got rank ${u.rank}.`)),c(3===l.rank,(()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`)),io("conv1d",s,i),c(u.shape[2]===l.shape[1],(()=>`Error in conv1d: depth of input (${u.shape[2]}) must match input depth for filter ${l.shape[1]}.`)),c(so(n,a),(()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${a}'`)),c(ro(a),(()=>"Error in conv1D: Dilated rates should be larger than 0.")),c(ro(n),(()=>"Error in conv1D: Stride should be larger than 0.")),c("NWC"===r,(()=>`Error in conv1d: got dataFormat of ${r} but only NWC is currently supported.`));const p=oo(l,[1,l.shape[0],l.shape[1],l.shape[2]]),d=oo(u,[u.shape[0],1,u.shape[1],u.shape[2]]),f=Fo(d,p,[1,n],s,"NHWC",[1,a],i);return oo(f,h?[f.shape[2],f.shape[3]]:[f.shape[0],f.shape[2],f.shape[3]])}});const Oo=fa({conv2DBackpropInput_:function(e,t,n,s,r,a="NHWC",i){c(e.length===t.rank,(()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`));let o=e,l=t,u=!1;3===t.rank&&(u=!0,l=oo(t,[1,t.shape[0],t.shape[1],t.shape[2]]),o=[1,e[0],e[1],e[2]]),c(4===o.length,(()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${o.length}.`)),c(4===l.rank,(()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`)),c(4===n.rank,(()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`));const h="NHWC"===a?o[3]:o[1],p="NHWC"===a?l.shape[3]:l.shape[1];c(h===n.shape[2],(()=>`Error in conv2dDerInput: depth of input (${h}) must match input depth for filter ${n.shape[2]}.`)),c(p===n.shape[3],(()=>`Error in conv2dDerInput: depth of output (${p}) must match output depth for filter ${n.shape[3]}.`)),io("conv2dDerInput",r,i);const d={dy:l,filter:n},f={strides:s,pad:r,dataFormat:a,dimRoundingMode:i,inputShape:o},m=ta.runKernel(_e,d,f);return u?oo(m,[m.shape[1],m.shape[2],m.shape[3]]):m}});const Mo=fa({conv2dTranspose_:function(e,t,n,s,r,a){const i=ha(e,"x","conv2dTranspose"),o=ha(t,"filter","conv2dTranspose");return Oo(n,i,o,s,r,"NHWC",a)}});const Lo=fa({conv3d_:function(e,t,n,s,r="NDHWC",a=[1,1,1]){const i=ha(e,"x","conv3d"),o=ha(t,"filter","conv3d");let l=i,u=!1;4===i.rank&&(u=!0,l=oo(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),c(5===l.rank,(()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`)),c(5===o.rank,(()=>`Error in conv3d: filter must be rank 5, but got rank ${o.rank}.`)),c(l.shape[4]===o.shape[3],(()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${o.shape[3]}.`)),c(so(n,a),(()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`)),c("NDHWC"===r,(()=>`Error in conv3d: got dataFormat of ${r} but only NDHWC is currently supported.`)),c(ro(a),(()=>"Error in conv3D: Dilated rates should be larger than 0.")),c(ro(n),(()=>"Error in conv3D: Strides should be larger than 0."));const h={x:l,filter:o},p={strides:n,pad:s,dataFormat:r,dilations:a},d=ta.runKernel(Fe,h,p);return u?oo(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}});const zo=fa({conv3DBackpropInput_:function(e,t,n,s,r){c(e.length===t.rank,(()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`));let a=e,i=t,o=!1;4===t.rank&&(o=!0,i=oo(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),a=[1,e[0],e[1],e[2],e[3]]);const l=a[4],u=i.shape[4];c(5===a.length,(()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${a.length}.`)),c(5===i.rank,(()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${i.rank}`)),c(5===n.rank,(()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`)),c(l===n.shape[3],(()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[3]}.`)),c(u===n.shape[4],(()=>`Error in conv3dDerInput: depth of output (${u}) must match output depth for filter ${n.shape[4]}.`));const h={dy:i,filter:n},p={pad:r,strides:s,inputShape:a},d=ta.runKernel(Oe,h,p);return o?oo(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}});const Po=fa({conv3dTranspose_:function(e,t,n,s,r){const a=ha(e,"x","conv3dTranspose"),i=ha(t,"filter","conv3dTranspose");return zo(n,a,i,s,r)}});const Bo=fa({cos_:function(e){const t={x:ha(e,"x","cos","float32")};return ta.runKernel(Me,t)}});const Wo=fa({cosh_:function(e){const t={x:ha(e,"x","cosh","float32")};return ta.runKernel(Le,t)}});const Vo=fa({cumprod_:function(e,t=0,n=!1,s=!1){const r={x:ha(e,"x","cumprod")},a={axis:t,exclusive:n,reverse:s};return ta.runKernel(ze,r,a)}});const Uo=fa({cumsum_:function(e,t=0,n=!1,s=!1){const r={x:ha(e,"x","cumsum")},a={axis:t,exclusive:n,reverse:s};return ta.runKernel(Pe,r,a)}});const Go=fa({denseBincount_:function(e,t,n,s=!1){const r=ha(e,"x","denseBincount"),a=ha(t,"weights","denseBincount");c("int32"===r.dtype,(()=>`Error in denseBincount: input dtype must be int32, but got ${r.dtype}`)),c(r.rank<=2,(()=>`Error in denseBincount: input must be at most rank 2, but got rank ${r.rank}.`)),c(n>=0,(()=>`size must be non-negative, but got ${n}.`)),c(a.size===r.size||0===a.size,(()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${r.shape}, weights shape: ${a.shape}.`));const i={x:r,weights:a},o={size:n,binaryOutput:s};return ta.runKernel(We,i,o)}});const Ho=fa({depthToSpace_:function(e,t,n="NHWC"){const s=ha(e,"x","depthToSpace","float32"),r="NHWC"===n?s.shape[1]:s.shape[2],a="NHWC"===n?s.shape[2]:s.shape[3],i="NHWC"===n?s.shape[3]:s.shape[1];c(t>1,(()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`)),c(r*t>=0,(()=>`Negative dimension size caused by overflow when multiplying\n    ${r} and ${t}  for depthToSpace with input shape\n    ${s.shape}`)),c(a*t>=0,(()=>`Negative dimension size caused by overflow when multiplying\n    ${a} and ${t} for depthToSpace with input shape\n        ${s.shape}`)),c(i%(t*t)==0,(()=>`Dimension size must be evenly divisible by ${t*t} but is ${i} for depthToSpace with input shape ${s.shape}`));const o={x:s},l={blockSize:t,dataFormat:n};return ta.runKernel(Ve,o,l)}});const jo=fa({depthwiseConv2d_:function(e,t,n,s,r="NHWC",a=[1,1],i){const o=ha(e,"x","depthwiseConv2d","float32"),l=ha(t,"filter","depthwiseConv2d","float32");let u=o,h=!1;3===o.rank&&(h=!0,u=oo(o,[1,o.shape[0],o.shape[1],o.shape[2]])),c(4===u.rank,(()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${u.rank}.`)),c(4===l.rank,(()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`));const p="NHWC"===r?u.shape[3]:u.shape[1];c(p===l.shape[2],(()=>`Error in depthwiseConv2d: number of input channels (${p}) must match the inChannels dimension in filter ${l.shape[2]}.`)),io("depthwiseConv2d",s,i);const d={x:u,filter:l},f={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:i},m=ta.runKernel(Ue,d,f);return h?oo(m,[m.shape[1],m.shape[2],m.shape[3]]):m}});const qo=fa({diag_:function(e){const t={x:ha(e,"x","diag")};return ta.runKernel(je,t)}});const Ko=fa({dilation2d_:function(e,t,n,s,r=[1,1],a="NHWC"){const i=ha(e,"x","dilation2d"),o=ha(t,"filter","dilation2d");c(3===i.rank||4===i.rank,(()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${i.rank}.`)),c(3===o.rank,(()=>`Error in dilation2d: filter must be rank 3, but got rank ${o.rank}.`)),c("NHWC"===a,(()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${a}`));let l=i,u=!1;3===i.rank&&(l=oo(i,[1,i.shape[0],i.shape[1],i.shape[2]]),u=!0),c(l.shape[3]===o.shape[2],(()=>`Error in dilation2d:  input and filter must have the same depth: ${l.shape[3]} vs ${o.shape[2]}`));const h={x:l,filter:o},p={strides:n,pad:s,dilations:r},d=ta.runKernel(qe,h,p);return u?oo(d,[d.shape[1],d.shape[2],d.shape[3]]):d}});function Xo(e,t){const n=e.length,s=[];for(let r=0;r<n;r++){const a=n-1-r,i=e[a]||1;(t[t.length-1-r]||1)>1&&1===i&&s.unshift(a)}return s}function Yo(e,t){const n=[];for(let s=0;s<t.length;s++){const r=e[e.length-s-1],a=t.length-s-1,i=t[a];(null==r||1===r&&i>1)&&n.unshift(a)}return n}function Zo(e,t){const n=Math.max(e.length,t.length),s=new Array(n);for(let r=0;r<n;r++){let a=e[e.length-r-1];null==a&&(a=1);let i=t[t.length-r-1];if(null==i&&(i=1),1===a)s[n-r-1]=i;else if(1===i)s[n-r-1]=a;else{if(a!==i){throw Error(`Operands could not be broadcast together with shapes ${e} and ${t}.`)}s[n-r-1]=a}}return s}var Jo=Object.freeze({__proto__:null,assertAndGetBroadcastShape:Zo,getBroadcastDims:Xo,getReductionAxes:Yo});const Qo=fa({equal_:function(e,t){let n=ha(e,"a","equal","string_or_numeric"),s=ha(t,"b","equal","string_or_numeric");[n,s]=Hr(n,s),Zo(n.shape,s.shape);const r={a:n,b:s};return ta.runKernel(nt,r)}});const el=fa({where_:function(e,t,n){const s=ha(t,"a","where"),r=ha(n,"b","where"),a=ha(e,"condition","where","bool"),i=Zo(Zo(a.shape,s.shape),r.shape),o={condition:So(a,i),t:So(s,i),e:So(r,i)};return ta.runKernel(Tn,o)}});const tl=fa({zerosLike_:function(e){const t={x:ha(e,"x","zerosLike")};return ta.runKernel(os,t)}});const nl=fa({divNoNan_:function(e,t){let n=ha(e,"a","div"),s=ha(t,"b","div");[n,s]=Hr(n,s);const r=Ri(n,s),a=tl(r),i=Qo(s,a);return el(i,a,r)}});const sl=fa({dot_:function(e,t){const n=ha(e,"t1","dot"),s=ha(t,"t2","dot");c(!(1!==n.rank&&2!==n.rank||1!==s.rank&&2!==s.rank),(()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${s.rank}.`));const r=1===n.rank?n.size:n.shape[1],a=1===s.rank?s.size:s.shape[0];if(c(r===a,(()=>`Error in dot: inner dimensions of inputs must match, but got ${r} and ${a}.`)),1===n.rank&&1===s.rank){const e=oo(n,[1,-1]),t=oo(s,[-1,1]),r=ho(e,t);return oo(r,[])}if(1===n.rank&&2===s.rank){const e=oo(n,[1,-1]),t=oo(s,[s.shape[0],s.shape[1]]),r=ho(e,t);return oo(r,[r.size])}if(2===n.rank&&1===s.rank){const e=oo(s,[-1,1]),t=ho(n,e);return oo(t,[t.size])}{const e=oo(s,[s.shape[0],s.shape[1]]);return ho(n,e)}}});const rl=fa({einsum_:function(e,...t){const n=t.map(((e,t)=>ha(e,`tensors${t}`,"einsum"))),s={equation:e};return ta.runKernel(Je,n,s)}});const al=fa({elu_:function(e){const t={x:ha(e,"x","elu","float32")};return ta.runKernel(Qe,t)}});const il=fa({ensureShape_:function(e,t){const n=ha(e,"x","ensureShape","string_or_numeric");if(!f(n.shape,t))throw new Error(`EnsureShape: Shape of tensor ${n.shape} is not compatible with expected shape ${t}`);return e}});const ol=fa({erf_:function(e){let t=ha(e,"x","erf");c("int32"===t.dtype||"float32"===t.dtype,(()=>"Input dtype must be `int32` or `float32`.")),"int32"===t.dtype&&(t=Ti(t,"float32"));const n={x:t};return ta.runKernel(tt,n)}});function ll(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function ul(e,t,n){const s=e.length+t.length,r=[];let a=0,i=0;for(let o=0;o<s;o++)-1===n.indexOf(o)?r.push(e[a++]):r.push(t[i++]);return r}function cl(e,t){const n=[],s=e.length;for(let r=0;r<s;r++)-1===t.indexOf(r)&&n.push(e[r]);return[n,t.map((t=>e[t]))]}function hl(e,t){return ul(e,t.map((e=>1)),t)}function pl(e,t,n){c(ll(t,n),(()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`))}function dl(e,t){if(ll(e,t))return null;const n=[];for(let s=0;s<t;++s)-1===e.indexOf(s)&&n.push(s);return e.forEach((e=>n.push(e))),n}function fl(e){return e.map(((e,t)=>[t,e])).sort(((e,t)=>e[1]-t[1])).map((e=>e[0]))}function ml(e,t){const n=[];for(let s=t-e;s<t;++s)n.push(s);return n}const gl=fa({max_:function(e,t=null,n=!1){const s={x:ha(e,"x","max")},r={reductionIndices:t,keepDims:n};return ta.runKernel(Dt,s,r)}});const yl=fa({min_:function(e,t=null,n=!1){const s={x:ha(e,"x","min")},r={axis:t,keepDims:n};return ta.runKernel(Vt,s,r)}});const bl=fa({pow_:function(e,t){let n=ha(e,"base","pow"),s=ha(t,"exp","pow");[n,s]=Hr(n,s);const r={a:n,b:s};return ta.runKernel(sn,r)}});function xl(e,t){if((yr(e)&&"string"!==t||Array.isArray(e))&&"complex64"!==t)throw new Error("Error creating a new Scalar: value must be a primitive (number|boolean|string)");if("string"===t&&yr(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return ga(e,[],[],t)}const wl=fa({sqrt_:function(e){const t={x:ha(e,"x","sqrt","float32")};return ta.runKernel(Dn,t)}});const vl=fa({square_:function(e){const t=ha(e,"x","square");return ta.runKernel("Square",{x:t},{})}});const kl=fa({sum_:function(e,t=null,n=!1){let s=ha(e,"x","sum");"bool"===s.dtype&&(s=Ti(s,"int32"));const r={x:s},a={axis:t,keepDims:n};return ta.runKernel(On,r,a)}});function Nl(e,t,n=null){if(0===e.rank)return Fi(e);if(1!==e.rank&&null===n)return Nl(oo(e,[-1]),t,n);if(1===e.rank||"number"==typeof n||Array.isArray(n)&&1===n.length){if(1===t)return kl(Fi(e),n);if(t===1/0)return gl(Fi(e),n);if(t===-1/0)return yl(Fi(e),n);if("euclidean"===t||2===t)return wl(kl(bl(Fi(e),xl(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&2===n.length){if(1===t)return gl(kl(Fi(e),n[0]),n[1]-1);if(t===1/0)return gl(kl(Fi(e),n[1]),n[0]);if(t===-1/0)return yl(kl(Fi(e),n[1]),n[0]);if("fro"===t||"euclidean"===t)return wl(kl(vl(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}const Il=fa({norm_:function(e,t="euclidean",n=null,s=!1){const r=Nl(e=ha(e,"x","norm"),t,n);let a=r.shape;if(s){const t=v(n,e.shape);a=hl(r.shape,t)}return oo(r,a)}});const Sl=fa({euclideanNorm_:function(e,t=null,n=!1){return Il(e,"euclidean",t,n)}});const Tl=fa({exp_:function(e){const t={x:ha(e,"x","exp")};return ta.runKernel(st,t)}});const Cl=fa({expandDims_:function(e,t=0){const n=ha(e,"x","expandDims","string_or_numeric");c(t<=n.rank,(()=>"Axis must be <= rank of the tensor"));const s={input:n},r={dim:t};return ta.runKernel(rt,s,r)}});const $l=fa({expm1_:function(e){const t={x:ha(e,"x","expm1")};return ta.runKernel(at,t)}});const El=fa({tile_:function(e,t){const n=ha(e,"x","tile","string_or_numeric");c(n.rank===t.length,(()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`));const s={x:n},r={reps:t};return ta.runKernel(es,s,r)}});const Al=fa({eye_:function(e,t,n,s="float32"){null==t&&(t=e);const r=Si([e,t],s),a=e<=t?e:t;for(let e=0;e<a;++e)r.set(1,e,e);const i=oo(r.toTensor(),[e,t]);if(null==n)return i;if(1===n.length)return El(Cl(i,0),[n[0],1,1]);if(2===n.length)return El(Cl(Cl(i,0),0),[n[0],n[1],1,1]);if(3===n.length)return El(Cl(Cl(Cl(i,0),0),0),[n[0],n[1],n[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${n.length}D.`)}});const Rl=fa({floor_:function(e){const t={x:ha(e,"x","floor","float32")};return ta.runKernel(ut,t)}});const _l=fa({gather_:function(e,t,n=0,s=0){const r={x:ha(e,"x","gather"),indices:ha(t,"indices","gather","int32")},a={axis:n,batchDims:s};return ta.runKernel(pt,r,a)}});const Fl=fa({greater_:function(e,t){let n=ha(e,"a","greater","string_or_numeric"),s=ha(t,"b","greater","string_or_numeric");[n,s]=Hr(n,s),Zo(n.shape,s.shape);const r={a:n,b:s};return ta.runKernel(ft,r)}});const Dl=fa({greaterEqual_:function(e,t){let n=ha(e,"a","greaterEqual","string_or_numeric"),s=ha(t,"b","greaterEqual","string_or_numeric");[n,s]=Hr(n,s),Zo(n.shape,s.shape);const r={a:n,b:s};return ta.runKernel(mt,r)}});const Ol=fa({imag_:function(e){const t={input:ha(e,"input","imag")};return ta.runKernel(bt,t)}});const Ml=fa({isFinite_:function(e){const t={x:ha(e,"x","isFinite")};return ta.runKernel(xt,t)}});const Ll=fa({isInf_:function(e){const t={x:ha(e,"x","isInf")};return ta.runKernel(wt,t)}});const zl=fa({isNaN_:function(e){const t={x:ha(e,"x","isNaN")};return ta.runKernel(vt,t)}});const Pl=fa({leakyRelu_:function(e,t=.2){const n={x:ha(e,"x","leakyRelu")},s={alpha:t};return ta.runKernel(kt,n,s)}});const Bl=fa({less_:function(e,t){let n=ha(e,"a","less","string_or_numeric"),s=ha(t,"b","less","string_or_numeric");[n,s]=Hr(n,s),Zo(n.shape,s.shape);const r={a:n,b:s};return ta.runKernel(Nt,r)}});const Wl=fa({lessEqual_:function(e,t){let n=ha(e,"a","lessEqual","string_or_numeric"),s=ha(t,"b","lessEqual","string_or_numeric");[n,s]=Hr(n,s),Zo(n.shape,s.shape);const r={a:n,b:s};return ta.runKernel(It,r)}});function Vl(e,t,n){if(n<=0)throw new Error("The number of values should be positive.");const s={start:e,stop:t,num:n};return ta.runKernel(St,{},s)}const Ul=fa({localResponseNormalization_:function(e,t=5,n=1,s=1,r=.5){const a=ha(e,"x","localResponseNormalization");c(4===a.rank||3===a.rank,(()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got\n               rank ${a.rank}.`)),c(g(t),(()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`));let i=a,o=!1;3===a.rank&&(o=!0,i=oo(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const l={x:i},u={depthRadius:t,bias:n,alpha:s,beta:r},h=ta.runKernel(_t,l,u);return o?oo(h,[h.shape[1],h.shape[2],h.shape[3]]):h}});const Gl=fa({log_:function(e){const t={x:ha(e,"x","log","float32")};return ta.runKernel(Tt,t)}});const Hl=fa({log1p_:function(e){const t={x:ha(e,"x","log1p")};return ta.runKernel(Ct,t)}});function jl(e,t){c(D(e),(()=>"The f passed in variableGrads(f) must be a function")),c(null==t||Array.isArray(t)&&t.every((e=>e instanceof Dr)),(()=>"The varList passed in variableGrads(f, varList) must be an array of variables"));const n=null!=t;if(!n){t=[];for(const e in ta.registeredVariables)t.push(ta.registeredVariables[e])}const s=n?t.filter((e=>!e.trainable)):null,r=t.length;t=t.filter((e=>e.trainable)),c(t.length>0,(()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${r} variables is trainable.`));const{value:a,grads:i}=ta.gradients(e,t,null,!0);c(i.some((e=>null!=e)),(()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize().")),c(0===a.rank,(()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${a.rank} tensor`));const o={};return t.forEach(((e,t)=>{null!=i[t]&&(o[e.name]=i[t])})),null!=s&&s.forEach((e=>o[e.name]=null)),{value:a,grads:o}}function ql(e){return ta.customGrad(e)}function Kl(e){if(e.filter((e=>null==e)).length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that\n    the f you passed encloses all operations that lead from x to y.")}const Xl=fa({neg_:function(e){const t={x:ha(e,"x","neg")};return ta.runKernel(Kt,t)}});const Yl=fa({softplus_:function(e){const t={x:ha(e,"x","softplus")};return ta.runKernel(Fn,t)}});const Zl=fa({logSigmoid_:function(e){const t=ha(e,"x","logSigmoid"),n=ql((e=>({value:Xl(Yl(Xl(e))),gradFunc:t=>_i(t,po(Xl(e)))})));return n(t)}});const Jl=fa({sub_:function(e,t){let n=ha(e,"a","sub"),s=ha(t,"b","sub");[n,s]=Hr(n,s);const r={a:n,b:s};return ta.runKernel(Zn,r)}});const Ql=fa({logSoftmax_:function(e,t=-1){const n=ha(e,"logits","logSoftmax");if(-1===t&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);const s=ql(((e,n)=>{const s=gl(e,t,!0),r=Jl(e,s),a=Jl(Ti(r,"float32"),Gl(kl(Tl(r),t,!0)));n([a]);return{value:a,gradFunc:(e,n)=>{const[s]=n,r=Tl(s);return Jl(e,_i(kl(e,t,!0),r))}}}));return s(n)}});const eu=fa({logSumExp_:function(e,t=null,n=!1){const s=ha(e,"x","logSumExp"),r=v(t,s.shape),a=gl(s,r,!0),i=Jl(s,a),o=Tl(i),l=kl(o,r),u=Gl(l),c=Ei(oo(a,u.shape),u);if(n){const e=hl(c.shape,r);return oo(c,e)}return c}});const tu=fa({logicalAnd_:function(e,t){const n=ha(e,"a","logicalAnd","bool"),s=ha(t,"b","logicalAnd","bool");Zo(n.shape,s.shape);const r={a:n,b:s};return ta.runKernel($t,r)}});const nu=fa({logicalNot_:function(e){const t={x:ha(e,"x","logicalNot","bool")};return ta.runKernel(Et,t)}});const su=fa({logicalOr_:function(e,t){const n=ha(e,"a","logicalOr","bool"),s=ha(t,"b","logicalOr","bool");Zo(n.shape,s.shape);const r={a:n,b:s};return ta.runKernel(At,r)}});const ru=fa({logicalXor_:function(e,t){const n=ha(e,"a","logicalXor","bool"),s=ha(t,"b","logicalXor","bool");return Zo(n.shape,s.shape),tu(su(e,t),nu(tu(e,t)))}}),au=2147483648;const iu=fa({searchSorted_:function(e,t,n="left"){const s=ha(e,"sortedSequence","searchSorted"),r=ha(t,"values","searchSorted"),a=s.shape[s.shape.length-1],i=r.shape[r.shape.length-1],o=oo(s,[-1,a]),l=oo(r,[-1,i]);if(o.rank<2)throw new Error("Sorted input argument must be at least 2-dimensional");if(o.shape[0]!==l.shape[0])throw new Error("Leading dimension of 'sortedSequence' and 'values' must match.");if(d(l.shape)>=au)throw new Error("values tensor size must less than 2147483648");if(o.shape[1]>=au)throw new Error(`trailing dim_size must less than 2147483648 for int32 output type, was ${o.shape[1]}`);const u={sortedSequence:o,values:l},c={side:n};return ta.runKernel(Sn,u,c)}});function ou(e,t){return iu(e,t,"left")}const lu=fa({maxPool_:function(e,t,n,s,r){const a=ha(e,"x","maxPool");let i=a,o=!1;3===a.rank&&(o=!0,i=oo(a,[1,a.shape[0],a.shape[1],a.shape[2]])),c(4===i.rank,(()=>`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`)),c(so(n,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`)),io("maxPool",s,r);const l={x:i},u={filterSize:t,strides:n,pad:s,dimRoundingMode:r},h=ta.runKernel(Mt,l,u);return o?oo(h,[h.shape[1],h.shape[2],h.shape[3]]):h}});const uu=fa({maxPool3d_:function(e,t=[1,1,1],n,s,r,a="NDHWC"){const i=ha(e,"x","maxPool3d");let o=i,l=!1;4===i.rank&&(l=!0,o=oo(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),c(5===o.rank,(()=>`Error in maxPool3d: x must be rank 5 but got rank ${o.rank}.`)),c("NDHWC"===a,(()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`)),io("maxPool3d",s,r);const u={x:o},h={filterSize:t,strides:n,pad:s,dimRoundingMode:r,dataFormat:a},p=ta.runKernel(zt,u,h);return l?oo(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}});const cu=fa({maxPoolWithArgmax_:function(e,t,n,s,r=!1){const a={x:ha(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:s,includeBatchInIndex:r},o=ta.runKernel(Bt,a,i);return{result:o[0],indexes:o[1]}}});const hu=fa({maximum_:function(e,t){let n=ha(e,"a","maximum"),s=ha(t,"b","maximum");[n,s]=Hr(n,s),"bool"===n.dtype&&(n=Ti(n,"int32"),s=Ti(s,"int32")),Zo(n.shape,s.shape);const r={a:n,b:s};return ta.runKernel(Ot,r)}});const pu=fa({mean_:function(e,t=null,n=!1){const s={x:ha(e,"x","mean")},r={axis:t,keepDims:n};return ta.runKernel(Wt,s,r)}});function du(e,t="float32"){if(U(e),"complex64"===t){const t=du(e,"float32"),n=du(e,"float32");return ma(t,n)}const n=W(d(e),t);return ta.makeTensor(n,e,t)}function fu(e,t="float32"){if(U(e),"complex64"===t){const t=fu(e,"float32"),n=du(e,"float32");return ma(t,n)}const n=B(d(e),t);return ta.makeTensor(n,e,t)}function mu(e,t,{indexing:n="xy"}={}){if("xy"!==n&&"ij"!==n)throw new TypeError(`${n} is not a valid third argument to meshgrid`);if(void 0===e)return[];let s=ha(e,"x","meshgrid",e instanceof _r?e.dtype:"float32");if(void 0===t)return[s];let r=ha(t,"y","meshgrid",t instanceof _r?t.dtype:"float32");const a=d(s.shape),i=d(r.shape);return"xy"===n?(s=oo(s,[1,-1]),r=oo(r,[-1,1]),[ho(fu([i,1],s.dtype),s),ho(r,fu([1,a],r.dtype))]):(s=oo(s,[-1,1]),r=oo(r,[1,-1]),[ho(s,fu([1,i],s.dtype)),ho(fu([a,1],r.dtype),r)])}const gu=fa({minimum_:function(e,t){let n=ha(e,"a","minimum"),s=ha(t,"b","minimum");[n,s]=Hr(n,s),"bool"===n.dtype&&(n=Ti(n,"int32"),s=Ti(s,"int32")),Zo(n.shape,s.shape);const r={a:n,b:s};return ta.runKernel(Ut,r)}});const yu=fa({mirrorPad_:function(e,t,n){c("reflect"===n||"symmetric"===n,(()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`));const s=ha(e,"x","mirrorPad");if(0===s.rank)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");c(t.length===s.rank,(()=>`Padding doesn't match input. Must be ${s.rank}. Got ${t.length}.`));const r="reflect"===n?1:0;for(let e=0;e<s.rank;e++)c(2===t[e].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),c(t[e][0]>=0&&t[e][0]<=s.shape[e]-r&&t[e][1]>=0&&t[e][1]<=s.shape[e]-r,(()=>`Padding in dimension ${e} cannot be greater than or equal to ${s.shape[e]-r} or less than 0 for input of shape ${s.shape}`));const a={paddings:t,mode:n},i={x:s};return ta.runKernel(Gt,i,a)}});const bu=fa({mod_:function(e,t){let n=ha(e,"a","mod"),s=ha(t,"b","mod");[n,s]=Hr(n,s);const r={a:n,b:s};return ta.runKernel(Ht,r)}});const xu=fa({moments_:function(e,t=null,n=!1){const s=v(t,(e=ha(e,"x","moments")).shape),r=pu(e,s,n);let a=r.shape;n||(a=hl(r.shape,s));const i=vl(Jl(Ti(e,"float32"),oo(r,a)));return{mean:r,variance:pu(i,s,n)}}});const wu=fa({multiRNNCell_:function(e,t,n,s){const r=ha(t,"data","multiRNNCell"),a=pa(n,"c","multiRNNCell"),i=pa(s,"h","multiRNNCell");let o=r;const l=[];for(let t=0;t<e.length;t++){const n=e[t](o,a[t],i[t]);l.push(n[0]),l.push(n[1]),o=n[1]}const u=[],c=[];for(let e=0;e<l.length;e+=2)u.push(l[e]),c.push(l[e+1]);return[u,c]}});const vu=fa({multinomial_:function(e,t,n,s=!1){const r=ha(e,"logits","multinomial"),a=r.size,i=r.rank;if(a<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${a}.`);if(i>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${i}`);n=n||Math.random();const o={logits:1===i?oo(r,[1,-1]):r},l={numSamples:t,seed:n,normalized:s},u=ta.runKernel(jt,o,l);return 1===i?oo(u,[u.size]):u}});const ku=fa({notEqual_:function(e,t){let n=ha(e,"a","notEqual","string_or_numeric"),s=ha(t,"b","notEqual","string_or_numeric");[n,s]=Hr(n,s),Zo(n.shape,s.shape);const r={a:n,b:s};return ta.runKernel(Xt,r)}});const Nu=fa({oneHot_:function(e,t,n=1,s=0,r="int32"){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);const a={indices:ha(e,"indices","oneHot","int32")},i={dtype:r,depth:t,onValue:n,offValue:s};return ta.runKernel(en,a,i)}});const Iu=fa({onesLike_:function(e){const t={x:ha(e,"x","onesLike")};return ta.runKernel(Qt,t)}});const Su=fa({outerProduct_:function(e,t){const n=ha(e,"v1","outerProduct"),s=ha(t,"v2","outerProduct");c(1===n.rank&&1===s.rank,(()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${s.rank}.`));const r=oo(n,[-1,1]),a=oo(s,[1,-1]);return ho(r,a)}});const Tu=fa({pad_:function(e,t,n=0){const s=ha(e,"x","pad");if(0===s.rank)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");const r={paddings:t,constantValue:n},a={x:s};return ta.runKernel(nn,a,r)}});const Cu=fa({pad1d_:function(e,t,n=0){return c(2===t.length,(()=>"Invalid number of paddings. Must be length of 2.")),Tu(e,[t],n)}});const $u=fa({pad2d_:function(e,t,n=0){return c(2===t.length&&2===t[0].length&&2===t[1].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),Tu(e,t,n)}});const Eu=fa({pad3d_:function(e,t,n=0){return c(3===t.length&&2===t[0].length&&2===t[1].length&&2===t[2].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),Tu(e,t,n)}});const Au=fa({pad4d_:function(e,t,n=0){return c(4===t.length&&2===t[0].length&&2===t[1].length&&2===t[2].length&&2===t[3].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),Tu(e,t,n)}});const Ru=fa({spaceToBatchND_:function(e,t,n){const s=ha(e,"x","spaceToBatchND");c(s.rank>=1+t.length,(()=>`input rank ${s.rank} should be > than [blockShape] ${t.length}`)),c(n.length===t.length,(()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`)),c(s.shape.reduce(((e,s,r)=>r>0&&r<=t.length?e&&(s+n[r-1][0]+n[r-1][1])%t[r-1]==0:e),!0),(()=>`input spatial dimensions ${s.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`));const r={x:s},a={blockShape:t,paddings:n};return ta.runKernel(Mn,r,a)}});const _u=fa({pool_:function(e,t,n,s,r,a,i){null==r&&(r=[1,1]),null==a&&(a=1),0===s&&(s="valid");const o=ha(e,"x","maxPool");let l=o,u=!1;3===o.rank&&(u=!0,l=oo(o,[1,o.shape[0],o.shape[1],o.shape[2]])),c(so(a,r),(()=>`Error in pool: Either strides or dilations must be 1. Got strides ${a} and dilations '${r}'`));const h=qi(l.shape,t,a,r,s),p=[h.dilationHeight,h.dilationWidth];let d;d="same"===s?function(e,t){const n=e.map(((e,n)=>e+(e-1)*(t[n]-1))).map((e=>e-1)),s=n.map((e=>Math.floor(e/2))),r=n.map(((e,t)=>e-s[t]));return n.map(((e,t)=>[s[t],r[t]]))}([h.filterHeight,h.filterWidth],p):[[0,0],[0,0]];const f=1===p[0]&&1===p[1],[m,g]=function(e,t,n){const s=n.map((e=>e[0])),r=n.map((e=>e[1])),a=e.concat(s,r),i=t.map(((e,t)=>(e-a[t]%e)%e)),o=r.map(((e,t)=>e+i[t])),l=t.map(((e,t)=>[s[t],o[t]])),u=t.map(((e,t)=>[0,i[t]]));return[l,u]}([h.inHeight,h.inWidth],p,d),y=f?s:"valid",b=f?l:Ru(l,p,m),x=("avg"===n?()=>lo(b,t,a,y,i):()=>lu(b,t,a,y,i))(),w=f?x:yo(x,p,g);return u?oo(w,[w.shape[1],w.shape[2],w.shape[3]]):w}});const Fu=fa({prelu_:function(e,t){const n={x:ha(e,"x","prelu"),alpha:ha(t,"alpha","prelu")};return ta.runKernel(rn,n)}});const Du=fa({prod_:function(e,t=null,n=!1){let s=ha(e,"x","prod");"bool"===s.dtype&&(s=Ti(s,"int32"));const r={x:s},a={axis:t,keepDims:n};return ta.runKernel(an,r,a)}});const Ou=fa({raggedGather_:function(e,t,n,s){const r={paramsNestedSplits:e.map(((e,t)=>ha(e,`tensors${t}`,"raggedGather","int32"))),paramsDenseValues:ha(t,"paramsDenseValues","raggedGather"),indices:ha(n,"indices","raggedGather","int32")},a={outputRaggedRank:s},i=ta.runKernel(on,r,a);return{outputNestedSplits:i.slice(0,i.length-1),outputDenseValues:i[i.length-1]}}});const Mu=fa({raggedRange_:function(e,t,n){const s=ha(e,"starts","raggedRange"),r={starts:s,limits:ha(t,"limits","raggedRange",s.dtype),deltas:ha(n,"deltas","raggedRange",s.dtype)},a=ta.runKernel(ln,r);return{rtNestedSplits:a[0],rtDenseValues:a[1]}}});const Lu=fa({raggedTensorToTensor_:function(e,t,n,s,r){const a=ha(e,"shape","raggedTensorToTensor","int32"),i=ha(t,"values","raggedTensorToTensor"),o={shape:a,values:i,defaultValue:ha(n,"defaultValue","raggedTensorToTensor",i.dtype),rowPartitionTensors:s.map(((e,t)=>ha(e,`tensors${t}`,"raggedTensorToTensor","int32")))},l={rowPartitionTypes:r};return ta.runKernel(un,o,l)}});const zu=fa({rand_:function(e,t,n){U(e);const s=d(e);let r=null;if(null==n||"float32"===n)r=new Float32Array(s);else if("int32"===n)r=new Int32Array(s);else{if("bool"!==n)throw new Error(`Unknown data type ${n}`);r=new Uint8Array(s)}for(let e=0;e<s;e++)r[e]=t();return ta.makeTensor(r,e,n)}});var Pu={exports:{}};!function(e){!function(e,t,n){function s(e){var t,n=this,s=(t=4022871197,function(e){e=String(e);for(var n=0;n<e.length;n++){var s=.02519603282416938*(t+=e.charCodeAt(n));s-=t=s>>>0,t=(s*=t)>>>0,t+=4294967296*(s-=t)}return 2.3283064365386963e-10*(t>>>0)});n.next=function(){var e=2091639*n.s0+2.3283064365386963e-10*n.c;return n.s0=n.s1,n.s1=n.s2,n.s2=e-(n.c=0|e)},n.c=1,n.s0=s(" "),n.s1=s(" "),n.s2=s(" "),n.s0-=s(e),n.s0<0&&(n.s0+=1),n.s1-=s(e),n.s1<0&&(n.s1+=1),n.s2-=s(e),n.s2<0&&(n.s2+=1),s=null}function r(e,t){return t.c=e.c,t.s0=e.s0,t.s1=e.s1,t.s2=e.s2,t}function a(e,t){var n=new s(e),a=t&&t.state,i=n.next;return i.int32=function(){return 4294967296*n.next()|0},i.double=function(){return i()+11102230246251565e-32*(2097152*i()|0)},i.quick=i,a&&("object"==typeof a&&r(a,n),i.state=function(){return r(n,{})}),i}t&&t.exports?t.exports=a:n&&n.amd?n((function(){return a})):this.alea=a}(0,e,!1)}(Pu);var Bu=Pu.exports,Wu={exports:{}};!function(e){!function(e,t,n){function s(e){var t=this,n="";t.x=0,t.y=0,t.z=0,t.w=0,t.next=function(){var e=t.x^t.x<<11;return t.x=t.y,t.y=t.z,t.z=t.w,t.w^=t.w>>>19^e^e>>>8},e===(0|e)?t.x=e:n+=e;for(var s=0;s<n.length+64;s++)t.x^=0|n.charCodeAt(s),t.next()}function r(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t}function a(e,t){var n=new s(e),a=t&&t.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&r(a,n),i.state=function(){return r(n,{})}),i}t&&t.exports?t.exports=a:n&&n.amd?n((function(){return a})):this.xor128=a}(0,e,!1)}(Wu);var Vu=Wu.exports,Uu={exports:{}};!function(e){!function(e,t,n){function s(e){var t=this,n="";t.next=function(){var e=t.x^t.x>>>2;return t.x=t.y,t.y=t.z,t.z=t.w,t.w=t.v,(t.d=t.d+362437|0)+(t.v=t.v^t.v<<4^e^e<<1)|0},t.x=0,t.y=0,t.z=0,t.w=0,t.v=0,e===(0|e)?t.x=e:n+=e;for(var s=0;s<n.length+64;s++)t.x^=0|n.charCodeAt(s),s==n.length&&(t.d=t.x<<10^t.x>>>4),t.next()}function r(e,t){return t.x=e.x,t.y=e.y,t.z=e.z,t.w=e.w,t.v=e.v,t.d=e.d,t}function a(e,t){var n=new s(e),a=t&&t.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&r(a,n),i.state=function(){return r(n,{})}),i}t&&t.exports?t.exports=a:n&&n.amd?n((function(){return a})):this.xorwow=a}(0,e,!1)}(Uu);var Gu=Uu.exports,Hu={exports:{}};!function(e){!function(e,t,n){function s(e){var t=this;t.next=function(){var e,n,s=t.x,r=t.i;return e=s[r],n=(e^=e>>>7)^e<<24,n^=(e=s[r+1&7])^e>>>10,n^=(e=s[r+3&7])^e>>>3,n^=(e=s[r+4&7])^e<<7,e=s[r+7&7],n^=(e^=e<<13)^e<<9,s[r]=n,t.i=r+1&7,n},function(e,t){var n,s=[];if(t===(0|t))s[0]=t;else for(t=""+t,n=0;n<t.length;++n)s[7&n]=s[7&n]<<15^t.charCodeAt(n)+s[n+1&7]<<13;for(;s.length<8;)s.push(0);for(n=0;n<8&&0===s[n];++n);for(8==n?s[7]=-1:s[n],e.x=s,e.i=0,n=256;n>0;--n)e.next()}(t,e)}function r(e,t){return t.x=e.x.slice(),t.i=e.i,t}function a(e,t){null==e&&(e=+new Date);var n=new s(e),a=t&&t.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},i.int32=n.next,i.quick=i,a&&(a.x&&r(a,n),i.state=function(){return r(n,{})}),i}t&&t.exports?t.exports=a:n&&n.amd?n((function(){return a})):this.xorshift7=a}(0,e,!1)}(Hu);var ju=Hu.exports,qu={exports:{}};!function(e){!function(e,t,n){function s(e){var t=this;t.next=function(){var e,n,s=t.w,r=t.X,a=t.i;return t.w=s=s+1640531527|0,n=r[a+34&127],e=r[a=a+1&127],n^=n<<13,e^=e<<17,n^=n>>>15,e^=e>>>12,n=r[a]=n^e,t.i=a,n+(s^s>>>16)|0},function(e,t){var n,s,r,a,i,o=[],l=128;for(t===(0|t)?(s=t,t=null):(t+="\0",s=0,l=Math.max(l,t.length)),r=0,a=-32;a<l;++a)t&&(s^=t.charCodeAt((a+32)%t.length)),0===a&&(i=s),s^=s<<10,s^=s>>>15,s^=s<<4,s^=s>>>13,a>=0&&(i=i+1640531527|0,r=0==(n=o[127&a]^=s+i)?r+1:0);for(r>=128&&(o[127&(t&&t.length||0)]=-1),r=127,a=512;a>0;--a)s=o[r+34&127],n=o[r=r+1&127],s^=s<<13,n^=n<<17,s^=s>>>15,n^=n>>>12,o[r]=s^n;e.w=i,e.X=o,e.i=r}(t,e)}function r(e,t){return t.i=e.i,t.w=e.w,t.X=e.X.slice(),t}function a(e,t){null==e&&(e=+new Date);var n=new s(e),a=t&&t.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},i.int32=n.next,i.quick=i,a&&(a.X&&r(a,n),i.state=function(){return r(n,{})}),i}t&&t.exports?t.exports=a:n&&n.amd?n((function(){return a})):this.xor4096=a}(0,e,!1)}(qu);var Ku=qu.exports,Xu={exports:{}};!function(e){!function(e,t,n){function s(e){var t=this,n="";t.next=function(){var e=t.b,n=t.c,s=t.d,r=t.a;return e=e<<25^e>>>7^n,n=n-s|0,s=s<<24^s>>>8^r,r=r-e|0,t.b=e=e<<20^e>>>12^n,t.c=n=n-s|0,t.d=s<<16^n>>>16^r,t.a=r-e|0},t.a=0,t.b=0,t.c=-1640531527,t.d=1367130551,e===Math.floor(e)?(t.a=e/4294967296|0,t.b=0|e):n+=e;for(var s=0;s<n.length+20;s++)t.b^=0|n.charCodeAt(s),t.next()}function r(e,t){return t.a=e.a,t.b=e.b,t.c=e.c,t.d=e.d,t}function a(e,t){var n=new s(e),a=t&&t.state,i=function(){return(n.next()>>>0)/4294967296};return i.double=function(){do{var e=((n.next()>>>11)+(n.next()>>>0)/4294967296)/(1<<21)}while(0===e);return e},i.int32=n.next,i.quick=i,a&&("object"==typeof a&&r(a,n),i.state=function(){return r(n,{})}),i}t&&t.exports?t.exports=a:n&&n.amd?n((function(){return a})):this.tychei=a}(0,e,!1)}(Xu);var Yu=Xu.exports,Zu={exports:{}};!function(e){!function(t,n,s){var r,a=256,i=s.pow(a,6),o=s.pow(2,52),l=2*o,u=255;function c(e,u,c){var g=[],y=f(d((u=1==u?{entropy:!0}:u||{}).entropy?[e,m(n)]:null==e?function(){try{var e;return r&&(e=r.randomBytes)?e=e(a):(e=new Uint8Array(a),(t.crypto||t.msCrypto).getRandomValues(e)),m(e)}catch(e){var s=t.navigator,i=s&&s.plugins;return[+new Date,t,i,t.screen,m(n)]}}():e,3),g),b=new h(g),x=function(){for(var e=b.g(6),t=i,n=0;e<o;)e=(e+n)*a,t*=a,n=b.g(1);for(;e>=l;)e/=2,t/=2,n>>>=1;return(e+n)/t};return x.int32=function(){return 0|b.g(4)},x.quick=function(){return b.g(4)/4294967296},x.double=x,f(m(b.S),n),(u.pass||c||function(e,t,n,r){return r&&(r.S&&p(r,b),e.state=function(){return p(b,{})}),n?(s.random=e,t):e})(x,y,"global"in u?u.global:this==s,u.state)}function h(e){var t,n=e.length,s=this,r=0,i=s.i=s.j=0,o=s.S=[];for(n||(e=[n++]);r<a;)o[r]=r++;for(r=0;r<a;r++)o[r]=o[i=u&i+e[r%n]+(t=o[r])],o[i]=t;(s.g=function(e){for(var t,n=0,r=s.i,i=s.j,o=s.S;e--;)t=o[r=u&r+1],n=n*a+o[u&(o[r]=o[i=u&i+t])+(o[i]=t)];return s.i=r,s.j=i,n})(a)}function p(e,t){return t.i=e.i,t.j=e.j,t.S=e.S.slice(),t}function d(e,t){var n,s=[],r=typeof e;if(t&&"object"==r)for(n in e)try{s.push(d(e[n],t-1))}catch(e){}return s.length?s:"string"==r?e:e+"\0"}function f(e,t){for(var n,s=e+"",r=0;r<s.length;)t[u&r]=u&(n^=19*t[u&r])+s.charCodeAt(r++);return m(t)}function m(e){return String.fromCharCode.apply(0,e)}if(f(s.random(),n),e.exports){e.exports=c;try{r=require("crypto")}catch(e){}}else s.seedrandom=c}("undefined"!=typeof self?self:Is,[],Math)}(Zu);var Ju=Zu.exports,Qu=Bu,ec=Vu,tc=Gu,nc=ju,sc=Ku,rc=Yu,ac=Ju;ac.alea=Qu,ac.xor128=ec,ac.xorwow=tc,ac.xorshift7=nc,ac.xor4096=sc,ac.tychei=rc;var ic=ac;function oc(){return 32===ta.backend.floatPrecision()?.001:.1}function lc(e,t,n){let s=!0;if((yr(e)||yr(t))&&(s=!1),yr(e)&&yr(t)&&(s=!0),s){const n=e.constructor.name,s=t.constructor.name;if(n!==s)throw new Error(`Arrays are of different type. Actual: ${n}. Expected: ${s}`)}if(Array.isArray(e)&&Array.isArray(t)){const n=la(e),s=la(t);if(!m(n,s))throw new Error(`Arrays have different shapes. Actual: [${n}]. Expected: [${s}]`)}const r=yr(e)?e:br(e),a=yr(t)?t:br(t);if(r.length!==a.length)throw new Error(`Arrays have different lengths actual: ${r.length} vs expected: ${a.length}.\nActual:   ${r}.\nExpected: ${a}.`);for(let e=0;e<a.length;++e){const t=r[e],s=a[e];if(!n(t,s))throw new Error(`Arrays differ: actual[${e}] = ${t}, expected[${e}] = ${s}.\nActual:   ${r}.\nExpected: ${a}.`)}"undefined"!=typeof expect&&expect().nothing()}function uc(e,t,n){if(null==n&&(n=oc()),!cc(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`);"undefined"!=typeof expect&&expect().nothing()}function cc(e,t,n){return!isFinite(e)&&!isFinite(t)||!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}var hc=Object.freeze({__proto__:null,TEST_EPSILON_FLOAT16:.1,createVideoElement:function(e){const t=document.createElement("video");return"playsInline"in t&&(t.playsInline=!0),t.muted=!0,t.loop=!0,t.style.position="fixed",t.style.left="0px",t.style.top="0px",t.preload="auto",t.appendChild(e),new Promise((e=>{t.addEventListener("loadeddata",(n=>e(t))),t.load()}))},encodeStrings:function e(t){for(let n=0;n<t.length;n++){const s=t[n];Array.isArray(s)?e(s):t[n]=mr(s)}return t},expectArrayBuffersEqual:function(e,t){const n=new Float32Array(e),s=new Float32Array(t);if(n.length!==s.length)throw new Error(`Expected ArrayBuffer to be of length ${s.length}, but it was ${n.length}`);for(let e=0;e<s.length;e++)if(n[e]!==s[e])throw new Error(`Expected ArrayBuffer value at ${e} to be ${s[e]} but got ${n[e]} instead`)},expectArraysClose:function(e,t,n){return null==n&&(n=oc()),lc(e,t,((e,t)=>cc(e,t,n)))},expectArraysEqual:function(e,t){const n="string"==typeof t||"number"==typeof t||"boolean"==typeof t?[t]:t;return A(e)||A(e[0])||A(t)||A(t[0])?lc(e,n,((e,t)=>e==t)):lc(e,t,((e,t)=>cc(e,t,0)))},expectNumbersClose:uc,expectPromiseToFail:function(e,t){e().then((()=>t.fail()),(()=>t())),"undefined"!=typeof expect&&expect().nothing()},expectValuesInRange:function(e,t,n){for(let s=0;s<e.length;s++)if(e[s]<t||e[s]>n)throw new Error(`Value out of range:${e[s]} low: ${t}, high: ${n}`)},play:async function(e){await e.play(),"requestVideoFrameCallback"in e&&await new Promise((t=>{e.requestVideoFrameCallback(t)}))},testEpsilon:oc});class pc{constructor(e,t,n,s,r){this.mean=e,this.stdDev=t,this.dtype=n,this.nextVal=NaN,this.truncated=s,this.truncated&&(this.upper=this.mean+2*this.stdDev,this.lower=this.mean-2*this.stdDev);const a=r||Math.random();this.random=ic.alea(a.toString())}nextValue(){if(!isNaN(this.nextVal)){const e=this.nextVal;return this.nextVal=NaN,e}let e,t,n=!1;for(;!n;){let s,r,a;do{s=2*this.random()-1,r=2*this.random()-1,a=s*s+r*r}while(a>=1||0===a);const i=Math.sqrt(-2*Math.log(a)/a);e=this.mean+this.stdDev*s*i,t=this.mean+this.stdDev*r*i,this.truncated&&!this.isValidTruncated(e)||(n=!0)}return this.truncated&&!this.isValidTruncated(t)||(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return null==this.dtype||"float32"===this.dtype?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}}class dc{constructor(e,t,n,s){this.alpha=e,this.beta=1/t,this.dtype=n;const r=s||Math.random();this.randu=ic.alea(r.toString()),this.randn=new pc(0,1,n,!1,this.randu()),this.d=e<1?e+2/3:e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,n,s,r,a;for(;;){do{s=this.randn.nextValue(),a=1+this.c*s}while(a<=0);if(a*=a*a,e=s*s,t=1-.331*e*e,n=.5*e+this.d*(1-a+Math.log(a)),r=this.randu(),r<t||Math.log(r)<n)break}return a=1/this.beta*this.d*a,this.alpha<1&&(a*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(a)}convertValue(e){return"float32"===this.dtype?e:Math.round(e)}}class fc{constructor(e=0,t=1,n,s){if(this.canReturnFloat=()=>null==this.dtype||"float32"===this.dtype,this.min=e,this.range=t-e,this.dtype=n,null==s&&(s=Math.random()),"number"==typeof s&&(s=s.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=ic.alea(s)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}const mc=fa({randomGamma_:function(e,t,n=1,s="float32",r){if(U(e),null==n&&(n=1),null==s&&(s="float32"),"float32"!==s&&"int32"!==s)throw new Error(`Unsupported data type ${s}`);const a=new dc(t,n,s,r),i=Si(e,s);for(let e=0;e<i.values.length;e++)i.values[e]=a.nextValue();return i.toTensor()}});const gc=fa({randomNormal_:function(e,t=0,n=1,s,r){if(U(e),null!=s&&"bool"===s)throw new Error(`Unsupported data type ${s}`);const a=new pc(t,n,s,!1,r),i=Si(e,s);for(let e=0;e<i.values.length;e++)i.values[e]=a.nextValue();return i.toTensor()}});const yc=fa({randomStandardNormal_:function(e,t,n){if(null!=t&&"bool"===t)throw new Error(`Unsupported data type ${t}`);return gc(e,0,1,t,n)}});const bc=fa({randomUniform_:function(e,t=0,n=1,s="float32",r){U(e);const a=Si(e,s),i=new fc(t,n,null,r);for(let e=0;e<a.values.length;e++)a.values[e]=i.nextValue();return a.toTensor()}});const xc=fa({randomUniformInt_:function(e,t,n,s){return bc(e,t,n,"int32",s)}});function wc(e,t,n=1,s="float32"){if(0===n)throw new Error("Cannot have a step of zero");const r={start:e,stop:t,step:n,dtype:s};return ta.runKernel(cn,{},r)}const vc=fa({real_:function(e){const t={input:ha(e,"input","real")};return ta.runKernel(hn,t)}});const kc=fa({reciprocal_:function(e){const t={x:ha(e,"x","reciprocal")};return ta.runKernel(pn,t)}});const Nc=fa({relu_:function(e){const t={x:ha(e,"x","relu")};return ta.runKernel(dn,t)}});const Ic=fa({relu6_:function(e){const t={x:ha(e,"x","relu6")};return ta.runKernel(xn,t)}});const Sc=fa({reverse_:function(e,t){const n={x:ha(e,"x","reverse")},s={dims:t};return ta.runKernel(wn,n,s)}});const Tc=fa({reverse1d_:function(e){const t=ha(e,"x","reverse");return c(1===t.rank,(()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`)),Sc(t,0)}});const Cc=fa({reverse2d_:function(e,t){const n=ha(e,"x","reverse");return c(2===n.rank,(()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`)),Sc(n,t)}});const $c=fa({reverse3d_:function(e,t){const n=ha(e,"x","reverse");return c(3===n.rank,(()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`)),Sc(n,t)}});const Ec=fa({reverse4d_:function(e,t){const n=ha(e,"x","reverse");return c(4===n.rank,(()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`)),Sc(n,t)}});const Ac=fa({round_:function(e){const t={x:ha(e,"x","round")};return ta.runKernel(vn,t)}});const Rc=fa({rsqrt_:function(e){const t={x:ha(e,"x","rsqrt","float32")};return ta.runKernel(kn,t)}});const _c=fa({selu_:function(e){const t={x:ha(e,"x","selu")};return ta.runKernel(Cn,t)}});const Fc=fa({separableConv2d_:function(e,t,n,s,r,a=[1,1],i="NHWC"){const o=ha(e,"x","separableConv2d"),l=ha(t,"depthwiseFilter","separableConv2d"),u=ha(n,"pointwiseFilter","separableConv2d");let h=o,p=!1;if(3===o.rank&&(p=!0,h=oo(o,[1,o.shape[0],o.shape[1],o.shape[2]])),"NCHW"===i)throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");c(4===h.rank,(()=>`Error in separableConv2d: input must be rank 4, but got rank ${h.rank}.`)),c(4===l.rank,(()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`)),c(4===u.rank,(()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`)),c(1===u.shape[0],(()=>`Error in separableConv2d: the first dimension of pointwise filter  must be 1, but got ${u.shape[0]}.`)),c(1===u.shape[1],(()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${u.shape[1]}.`));const d=l.shape[2],f=l.shape[3];c(u.shape[2]===d*f,(()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${d*f}, but got ${u.shape[2]}.`));const m=jo(h,l,s,r,i,a),g=Fo(m,u,1,"valid",i);return p?oo(g,[g.shape[1],g.shape[2],g.shape[3]]):g}});const Dc=async function(e,t){const n=ha(e,"x","setdiff1d"),s=ha(t,"y","setdiff1d");c(n.dtype===s.dtype,(()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${s.dtype}).`)),c(1===n.rank,(()=>`x should be 1D tensor, but got x (${n.shape}).`)),c(1===s.rank,(()=>`y should be 1D tensor, but got y (${s.shape}).`));const r=await n.data(),a=await s.data(),i=new Set(a);let o=0;for(let e=0;e<r.length;e++)i.has(r[e])||o++;const l=new $r([o],n.dtype),u=new $r([o],"int32");for(let e=0,t=0;e<r.length;e++)i.has(r[e])||(l.values[t]=r[e],u.values[t]=e,t++);return[l.toTensor(),u.toTensor()]};const Oc=fa({sign_:function(e){const t={x:ha(e,"x","sign")};return ta.runKernel(Rn,t)}});const Mc=fa({sin_:function(e){const t={x:ha(e,"x","sin","float32")};return ta.runKernel(En,t)}});const Lc=fa({sinh_:function(e){const t={x:ha(e,"x","sinh")};return ta.runKernel(An,t)}});const zc=fa({slice1d_:function(e,t,n){const s=ha(e,"x","slice1d");return c(1===s.rank,(()=>`slice1d expects a rank-1 tensor, but got a rank-${s.rank} tensor`)),fo(s,[t],[n])}});const Pc=fa({slice2d_:function(e,t,n){const s=ha(e,"x","slice2d");return c(2===s.rank,(()=>`slice2d expects a rank-2 tensor, but got a rank-${s.rank} tensor`)),fo(s,t,n)}});const Bc=fa({slice3d_:function(e,t,n){const s=ha(e,"x","slice3d");return c(3===s.rank,(()=>`slice3d expects a rank-3 tensor, but got a rank-${s.rank} tensor`)),fo(s,t,n)}});const Wc=fa({slice4d_:function(e,t,n){const s=ha(e,"x","slice4d");return c(4===s.rank,(()=>`slice4d expects a rank-4 tensor, but got a rank-${s.rank} tensor`)),fo(s,t,n)}});const Vc=fa({softmax_:function(e,t=-1){const n=ha(e,"logits","softmax","float32");if(-1===t&&(t=n.rank-1),t!==n.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and dim was ${t}`);const s={logits:n},r={dim:t};return ta.runKernel(zn,s,r)}});const Uc=fa({fft_:function(e){c("complex64"===e.dtype,(()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`));const t={input:e};return ta.runKernel(it,t)}});const Gc=fa({ifft_:function(e){c("complex64"===e.dtype,(()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`));const t={input:e};return ta.runKernel(yt,t)}});const Hc=fa({irfft_:function(e){const t=e.shape[e.shape.length-1],n=e.size/t;let s;if(t<=2){const r=oo(e,[n,t]);s=Gc(r)}else{const r=[n,2*(t-1)],a=oo(vc(e),[n,t]),i=oo(Ol(e),[n,t]),o=Sc(fo(a,[0,1],[n,t-2]),1),l=_i(Sc(fo(i,[0,1],[n,t-2]),1),xl(-1)),u=co([a,o],1),c=co([i,l],1),h=oo(ma(u,c),[r[0],r[1]]);s=Gc(h)}if(s=vc(s),3===e.rank&&0!==e.shape[0]){const t=s,n=e.shape[0];s=oo(s,[n,s.shape[0]/n,s.shape[1]]),t.dispose()}return s}});const jc=fa({split_:function(e,t,n=0){const s={x:ha(e,"x","split")},r={numOrSizeSplits:t,axis:n};return ta.runKernel(Ln,s,r)}});const qc=fa({rfft_:function(e,t){c("float32"===e.dtype,(()=>`The dtype for rfft() must be real value but got ${e.dtype}`));let n=e.shape[e.shape.length-1];const s=e.size/n;let r;if(null!=t&&t<n){const s=e.shape.map((e=>0)),a=e.shape.map((e=>e));a[e.shape.length-1]=t,r=fo(e,s,a),n=t}else if(null!=t&&t>n){const s=e.shape.map((e=>e));s[e.shape.length-1]=t-n,r=co([e,du(s)],e.shape.length-1),n=t}else r=e;const a=tl(r),i=oo(ma(r,a),[s,n]),o=Uc(i),l=Math.floor(n/2)+1,u=vc(o),h=Ol(o),p=jc(u,[l,n-l],u.shape.length-1),d=jc(h,[l,n-l],h.shape.length-1),f=r.shape.slice();return f[r.shape.length-1]=l,oo(ma(p[0],d[0]),f)}});const Kc=fa({squaredDifference_:function(e,t){let n=ha(e,"a","squaredDifference"),s=ha(t,"b","squaredDifference");[n,s]=Hr(n,s),Zo(n.shape,s.shape);const r={a:n,b:s};return ta.runKernel(Gn,r,{})}});const Xc=fa({squeeze_:function(e,t){const n=ha(e,"x","squeeze","string_or_numeric");return oo(n,k(n.shape,t).newShape)}});const Yc=fa({stack_:function(e,t=0){const n=pa(e,"tensors","stack","string_or_numeric");c(n.length>=1,(()=>"Pass at least one tensor to tf.stack")),n.length>0&&c(t<=n[0].rank,(()=>"Axis must be <= rank of the tensor"));const s=n,r={axis:t};return ta.runKernel(tn,s,r)}});const Zc=fa({step_:function(e,t=0){const n={x:ha(e,"x","step")},s={alpha:t};return ta.runKernel(ls,n,s)}});const Jc=fa({stridedSlice_:function(e,t,n,s,r=0,a=0,i=0,o=0,l=0){const u={x:ha(e,"x","stridedSlice","string_or_numeric")},c={begin:t,end:n,strides:s,beginMask:r,endMask:a,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};return ta.runKernel(qn,u,c)}});const Qc=fa({tan_:function(e){const t={x:ha(e,"x","tan","float32")};return ta.runKernel(Jn,t)}});function eh(e,t){p(e);const n=la(e,t);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return ga(e,null,n,t)}function th(e,t,n){if(p(e),null!=t&&2!==t.length)throw new Error("tensor2d() requires shape to have two numbers");const s=la(e,n);if(2!==s.length&&1!==s.length)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(1===s.length&&null==t)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return ga(e,t,s,n)}function nh(e,t,n){if(p(e),null!=t&&3!==t.length)throw new Error("tensor3d() requires shape to have three numbers");const s=la(e,n);if(3!==s.length&&1!==s.length)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(1===s.length&&null==t)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return ga(e,t,s,n)}function sh(e,t,n){if(p(e),null!=t&&4!==t.length)throw new Error("tensor4d() requires shape to have four numbers");const s=la(e,n);if(4!==s.length&&1!==s.length)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(1===s.length&&null==t)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return ga(e,t,s,n)}function rh(e,t,n){if(p(e),null!=t&&5!==t.length)throw new Error("tensor5d() requires shape to have five numbers");const s=la(e,n);if(5!==s.length&&1!==s.length)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(1===s.length&&null==t)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return ga(e,t,s,n)}function ah(e,t,n){if(p(e),null!=t&&6!==t.length)throw new Error("tensor6d() requires shape to have six numbers");const s=la(e,n);if(6!==s.length&&1!==s.length)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(1===s.length&&null==t)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return ga(e,t=t||s,s,n)}function ih(e,t,n){const s=t.rank>1?t.shape[t.rank-1]:1,r=t.rank>1?t.rank-1:1,a=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${n.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${s}, and batchDim: ${r}.`;if(n.rank<r)throw new Error(a+` update.rank < ${r}. `);if(e.length<s+(n.rank-r))throw new Error(a+` Output shape length < ${s+(n.rank-r)}`);if(n.rank!==r+e.length-s)throw new Error(a+" update.rank != "+(r+e.length-s));for(let e=0;e<r;++e)if(n.shape[e]!==t.shape[e])throw new Error(a+` updates.shape[${e}] (${n.shape[e]}) != indices.shape[${e}] (${t.shape[e]}).`);for(let t=0;t<n.rank-r;++t)if(n.shape[t+r]!==e[t+s])throw new Error(a+` updates.shape[${t+r}] (${n.shape[t+r]}) != shape[${t+r}] (${e[t+r]})`)}function oh(e,t,n){if(t.rank<1)throw new Error(`tf.scatterND() expects the indices to be rank 1 or higher, but the rank was ${t.rank}.`);if(e.rank<1)throw new Error(`tf.scatterND() expects the updates to be rank 1 or higher, but the rank was ${e.rank}.`);if("int32"!==t.dtype)throw new Error(`The dtype of 'indices' should be int32, but got dtype: ${t.dtype}`);if(n.length<1)throw new Error(`Output rank must be greater or equal to 1, but got shape: ${n}`);if(0===n.length){if(0===t.size)throw new Error(`Indices specified for empty output. indices shape: ${t.shape}`);if(0===e.size)throw new Error(`Updates specified for empty output. updates shape: ${e.shape}`)}ih(n,t,e)}function lh(e,t,n){const s=t.shape.length,r=s>1?t.shape[s-1]:1,a=n.length;let i=1;for(let e=r;e<a;++e)i*=n[e];const o=r<1?1:r;return{sliceRank:r,numUpdates:d(t.shape)/o,sliceSize:i,strides:[...M(n.slice(0,r)),1],outputSize:d(n)}}var uh=Object.freeze({__proto__:null,calculateShapes:lh,validateInput:oh,validateUpdateShape:ih});const ch=fa({tensorScatterUpdate_:function(e,t,n){const s=ha(e,"tensor","tensorScatterupdate"),r=ha(t,"indices","tensorScatterupdate","int32"),a=ha(n,"updates","tensorScatterupdate");if(oh(a,r,s.shape),s.dtype!==a.dtype)throw new Error(`tensor and updates must have the same dtype, instead they are ${s.dtype} and ${a.dtype}.`);const i={tensor:s,indices:r,updates:a};return ta.runKernel(In,i,{})}});const hh=fa({topk_:function(e,t=1,n=!0){const s=ha(e,"x","topk");if(0===s.rank)throw new Error("topk() expects the input to be of rank 1 or higher");const r=s.shape[s.shape.length-1];if(t<0)throw new Error(`'k' passed to topk() must be >= 0 but got ${t}`);if(t>r)throw new Error(`'k' passed to topk() must be <= the last dimension (${r}) but got ${t}`);const a={x:s},i={k:t,sorted:n},[o,l]=ta.runKernel(ts,a,i);return{values:o,indices:l}}});const ph=fa({truncatedNormal_:function(e,t=0,n=1,s,r){if(U(e),null!=s&&"bool"===s)throw new Error("Unsupported data type $ { dtype }");const a=new pc(t,n,s,!0,r),i=Si(e,s);for(let e=0;e<i.values.length;e++)i.values[e]=a.nextValue();return i.toTensor()}});const dh=fa({unique_:function(e,t=0){const n=ha(e,"x","unique","string_or_numeric");c(n.rank>0,(()=>"The input tensor must be at least 1D"));const s={x:n},r={axis:t},[a,i]=ta.runKernel(rs,s,r);return{values:a,indices:i}}});const fh=fa({unsortedSegmentSum_:function(e,t,n){const s=ha(e,"x","unsortedSegmentSum"),r=ha(t,"segmentIds","unsortedSegmentSum","int32");c(g(n),(()=>"numSegments must be of dtype int"));const a={x:s,segmentIds:r},i={numSegments:n};return ta.runKernel(is,a,i)}});const mh=fa({unstack_:function(e,t=0){const n=ha(e,"x","unstack","string_or_numeric");c(t>=-n.shape.length&&t<n.shape.length,(()=>`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`));const s={value:n},r={axis:t};return ta.runKernel(as,s,r)}});function gh(e,t){return iu(e,t,"right")}function yh(e,t=!0,n,s){return ta.makeVariable(e,t,n,s)}function bh(e,t){const n=[];for(let e=0;e<t.length;e++)t[e]&&n.push(e);const s=Si(e,"int32"),r=Si([n.length,e.length],"int32");for(let t=0;t<n.length;t++){const a=s.indexToLoc(n[t]),i=t*e.length;r.values.set(a,i)}return r.toTensor()}const xh=async function(e){const t=ha(e,"condition","whereAsync","bool"),n=await t.data(),s=bh(t.shape,n);return e!==t&&t.dispose(),s};const wh=async function(e,t,n){const s=ha(e,"tensor","boolMask"),r=ha(t,"mask","boolMask","bool"),a=null==n?0:n,i=r.rank,o=s.shape;c(i>0,(()=>"mask cannot be scalar")),h(o.slice(a,a+i),r.shape,"mask's shape must match the first K dimensions of tensor's shape,");let l=1;for(let e=a;e<a+i;e++)l*=o[e];const u=o.slice(0,a).concat([l],o.slice(a+i)),p=oo(s,u),d=oo(r,[-1]),f=await xh(d),m=Xc(f,[1]),g=_l(p,m,a);return e!==s&&s.dispose(),t!==r&&r.dispose(),m.dispose(),p.dispose(),d.dispose(),f.dispose(),g};const vh=fa({transpose_:function(e,t,n){const s=ha(e,"x","transpose");if(null==t&&(t=s.shape.map(((e,t)=>t)).reverse()),c(s.rank===t.length,(()=>`Error in transpose: rank of input ${s.rank} must match length of perm ${t}.`)),t.forEach((e=>{c(e>=0&&e<s.rank,(()=>"All entries in 'perm' must be between 0 and "+(s.rank-1)+` but got ${t}`))})),s.rank<=1)return s.clone();const r={x:s},a={perm:t};return"complex64"===s.dtype?Na((()=>{let e=vc(s),t=Ol(s);return e=ta.runKernel(ss,{x:e},a),t=ta.runKernel(ss,{x:t},a),n&&(t=Xl(t)),ma(e,t)})):ta.runKernel(ss,r,a)}});const kh=fa({movingAverage_:function(e,t,n,s,r=!0){const a=ha(e,"v","movingAverage"),i=ha(t,"x","movingAverage"),o=ha(n,"decay","movingAverage");jr(a,i),c(m(a.shape,i.shape),(()=>"Shape mismatch in v and x"));const l=xl(1),u=Jl(l,o);let h=_i(Jl(i,a),u);if(r){c(null!=s,(()=>"When using zeroDebias: true, step is required."));const e=ha(s,"step","movingAverage");h=Ri(h,Jl(l,bl(o,e)))}return Ei(a,h)}});const Nh=fa({scatterND_:function(e,t,n){U(n);const s=ha(e,"indices","scatterND","int32"),r=ha(t,"updates","scatterND");oh(r,s,n);const a={indices:s,updates:r},i={shape:n};return ta.runKernel(Nn,a,i)}});const Ih=fa({sparseToDense_:function(e,t,n,s=0){U(n);const r=ha(e,"sparseIndices","sparseToDense","int32"),a=ha(t,"sparseValues","sparseToDense","string_or_numeric"),i=ha(s,"defaultValue","sparseToDense",a.dtype);!function(e,t,n,s){if("int32"!==e.dtype)throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${e.shape}.`);const r=e.rank>0?e.shape[0]:1,a=e.rank>1?e.shape[1]:1;if(n.length!==a)throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${a}.`);const i=t.size;if(0!==t.rank&&(1!==t.rank||i!==r))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${r}]`);if(t.dtype!==s.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}(r,a,n,i);const o={sparseIndices:r,sparseValues:a,defaultValue:i},l={outputShape:n};return ta.runKernel(Un,o,l)}});const Sh=fa({gatherND_:function(e,t){const n=ha(t,"indices","gatherND","int32"),s={params:ha(e,"x","gatherND","string_or_numeric"),indices:n};return ta.runKernel(dt,s)}});const Th=fa({dropout_:function(e,t,n,s){const r=ha(e,"x","dropout");if(c("float32"===r.dtype,(()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${r.dtype} tensor instead.`)),c(t>=0&&t<1,(()=>`rate must be a float in the range [0, 1), but got ${t}.`)),0===t)return e instanceof _r?r.clone():r;const a=function(e,t){if(null==t)return e.shape.slice();if(m(e.shape,t))return t;if(e.shape.length===t.length){const n=[];for(let s=0;s<e.shape.length;s++)null==t[s]&&null!=e.shape[s]?n.push(e.shape[s]):n.push(t[s]);return n}return t}(r,n),i=1-t,o=Ri(Rl(Ei(bc(a,0,1,"float32",s),i)),i);return _i(r,o)}});function Ch(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function $h(e,t,n){const s=1-e%2,r=new Float32Array(e);for(let a=0;a<e;++a){const i=2*Math.PI*a/(e+s-1);r[a]=t-n*Math.cos(i)}return eh(r,"float32")}const Eh=async function(e,t,n=1){const s=ha(e,"predictions","inTopK"),r=ha(t,"targets","inTopK");c(s.rank>1,(()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${s.rank}`)),c(s.rank-1===r.rank,(()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${s.rank} and targets rank ${r.rank}`)),h(s.shape.slice(0,s.shape.length-1),r.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");const a=s.shape[s.shape.length-1];c(n>0&&n<=a,(()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${a}), but got ${n}`));const i=await s.data(),o=await r.data(),[l,u]=[i.length/a,a],p=N("bool",l);for(let e=0;e<l;e++){const t=e*u,s=i.subarray(t,t+u),r=[];for(let e=0;e<s.length;e++)r.push({value:s[e],index:e});r.sort(((e,t)=>t.value-e.value)),p[e]=0;for(let t=0;t<n;t++)if(r[t].index===o[e]){p[e]=1;break}}return e!==s&&s.dispose(),t!==r&&r.dispose(),ya(p,r.shape,"bool")};const Ah=fa({conv2DBackpropFilter_:function(e,t,n,s,r,a="NHWC",i){let o=e;3===e.rank&&(o=oo(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;3===l.rank&&(l=oo(t,[1,t.shape[0],t.shape[1],t.shape[2]])),c(4===o.rank,(()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${o.shape}.`)),c(4===l.rank,(()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`)),c(4===n.length,(()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`));const u="NHWC"===a?o.shape[3]:o.shape[1],h="NHWC"===a?l.shape[3]:l.shape[1];c(u===n[2],(()=>`Error in conv2dDerFilter: depth of input ${u}) must match input depth in filter (${n[2]}.`)),c(h===n[3],(()=>`Error in conv2dDerFilter: depth of dy (${h}) must match output depth for filter (${n[3]}).`)),io("conv2dDerFilter",r,i);const p={x:o,dy:l},d={strides:s,pad:r,dataFormat:a,dimRoundingMode:i,filterShape:n};return ta.runKernel(Re,p,d)}});function Rh(e,t,n){if(null==n||"linear"===n)return e;if("relu"===n)return _i(e,Zc(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function _h(e,t){let n=t;const s=Yo(e.shape,t.shape);return s.length>0&&(n=kl(n,s)),oo(n,e.shape)}function Fh(e,t,n,s){if("linear"===t)return e;if("relu"===t)return Nc(e);if("elu"===t)return al(e);if("relu6"===t)return Ic(e);if("prelu"===t)return Fu(e,n);if("leakyrelu"===t)return Pl(e,s);if("sigmoid"===t)return po(e);throw new Error(`Unknown fused activation ${t}.`)}const Dh=(e,t)=>!(e>0)||"linear"===t;const Oh=fa({fusedConv2d_:function({x:e,filter:t,strides:n,pad:s,dataFormat:r="NHWC",dilations:a=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:h}){if(l=l||"linear",!1===Dh(ta.state.gradientDepth,l)){c("NHWC"===r,(()=>`Error in fused conv2d: got dataFormat of ${r} but only NHWC is currently supported for the case of gradient depth is 0 and the activation is not linear.`));let p=Fo(e,t,n,s,r,a,i);return null!=o&&(p=Ei(p,o)),Fh(p,l,u,h)}const p=ha(e,"x","conv2d","float32"),d=ha(t,"filter","conv2d","float32");let f=p,m=!1;3===p.rank&&(m=!0,f=oo(p,[1,p.shape[0],p.shape[1],p.shape[2]])),c(4===f.rank,(()=>`Error in fused conv2d: input must be rank 4, but got rank ${f.rank}.`)),c(4===d.rank,(()=>`Error in fused conv2d: filter must be rank 4, but got rank ${d.rank}.`)),io("fused conv2d",s,i);const g="NHWC"===r?f.shape[3]:f.shape[1];c(d.shape[2]===g,(()=>`Error in conv2d: depth of input (${g}) must match input depth for filter ${d.shape[2]}.`)),c(so(n,a),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`));const y=Xi(f.shape,d.shape,n,a,s,i);let b,x;if(null!=o&&(b=ha(o,"bias","fused conv2d"),[b]=Hr(b,p),"NHWC"===r?Zo(y.outShape,b.shape):(c(b.shape.length<=1,(()=>`Error in fused conv2d: only supports scalar or 1-D Tensor bias for NCHW format but got the bias of rank-${b.shape.length}.`)),c(0===b.shape.length||b.shape[0]===y.outChannels||1===b.shape[0],(()=>`Error in fused conv2d: bias shape (${b.shape}) is not compatible with the number of output channels (${y.outChannels})`)))),null!=u){const e=u.shape;if(c(e.length<=1||3===e.length,(()=>`Error in fused conv2d: only supports scalar, 1-D Tensor or 3-D Tensor PReLU activation weights but got a tensor of rank-${e.length}.`)),1===e.length)c(1===e[0]||e[0]===y.outChannels,(()=>`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the number of output channels (${y.outChannels}).`));else if(3===e.length)try{Zo(e,y.outShape)}catch(t){const n=`Error in fused conv2d: PReLU activation weights (${e}) is not compatible with the output shape of the conv2d (${y.outShape}).`;throw Error(n)}x=ha(u,"prelu weights","fused conv2d")}const w=(e,t)=>{c("NHWC"===r,(()=>`Error in gradient of fused conv2D: got dataFormat of ${r} but only NHWC is currently supported.`));const[i,o,u,h]=t,p=Rh(e,u,l);c(no(a),(()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`));const d=[Oo(o.shape,p,i,n,s),Ah(o,p,i.shape,n,s)];if(null!=h){const e=_h(h,p);d.push(e)}return d},v={x:f,filter:d,bias:b,preluActivationWeights:x},k={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:i,activation:l,leakyreluAlpha:h};if(null==o){const e=ql(((e,t,n)=>{let s=ta.runKernel(ps,v,k);return n([t,e,s]),m&&(s=oo(s,[s.shape[1],s.shape[2],s.shape[3]])),{value:s,gradFunc:w}}));return e(f,d)}{const e=ql(((e,t,n,s)=>{let r=ta.runKernel(ps,v,k);return s([t,e,r,n]),m&&(r=oo(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:w}}));return e(f,d,b)}}});const Mh=fa({depthwiseConv2dNativeBackpropFilter_:function(e,t,n,s,r,a=[1,1],i){let o=e;3===e.rank&&(o=oo(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;3===l.rank&&(l=oo(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const u={x:o,dy:l},c={strides:s,pad:r,dimRoundingMode:i,dilations:a,filterShape:n};return ta.runKernel(Ge,u,c)}});const Lh=fa({depthwiseConv2dNativeBackpropInput_:function(e,t,n,s,r,a=[1,1],i){let o=t,l=!1;3===t.rank&&(l=!0,o=oo(t,[1,t.shape[0],t.shape[1],t.shape[2]]));const u={dy:o,filter:n},c={strides:s,pad:r,dimRoundingMode:i,dilations:a,inputShape:e},h=ta.runKernel(He,u,c);return l?oo(h,[h.shape[1],h.shape[2],h.shape[3]]):h}});const zh=fa({fusedDepthwiseConv2d_:function({x:e,filter:t,strides:n,pad:s,dataFormat:r="NHWC",dilations:a=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:h}){if(!1===Dh(ta.state.gradientDepth,l)){let c=jo(e,t,n,s,r,a,i);return null!=o&&(c=Ei(c,o)),Fh(c,l,u,h)}const p=ha(e,"x","depthwiseConv2d","float32"),d=ha(t,"filter","depthwiseConv2d","float32");let f=p,m=!1;3===p.rank&&(m=!0,f=oo(p,[1,p.shape[0],p.shape[1],p.shape[2]])),c(4===f.rank,(()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${f.rank}.`)),c(4===d.rank,(()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${d.rank}.`)),c(f.shape[3]===d.shape[2],(()=>`Error in fused depthwiseConv2d: number of input channels (${f.shape[3]}) must match the inChannels dimension in filter ${d.shape[2]}.`)),null==a&&(a=[1,1]),c(so(n,a),(()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`)),io("fused depthwiseConv2d",s,i);const g=Xi(f.shape,d.shape,n,a,s,i,!0);let y,b;null!=o&&(y=ha(o,"bias","fused conv2d"),[y]=Hr(y,p),Zo(g.outShape,y.shape)),null!=u&&(b=ha(u,"prelu weights","fused depthwiseConv2d"));const x=(e,t)=>{c(no(a),(()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`));const[r,o,u,h]=t,p=Rh(e,u,l),d=Lh(o.shape,p,r,n,s,a,i),f=Mh(o,p,r.shape,n,s,a,i);if(null!=h){return[d,f,_h(y,p)]}return[d,f]},w={x:f,filter:d,bias:y,preluActivationWeights:b},v={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:i,activation:l,leakyreluAlpha:h};if(null==o){const e=ql(((e,t,n)=>{let s=ta.runKernel(ds,w,v);return n([t,e,s]),m&&(s=oo(s,[s.shape[1],s.shape[2],s.shape[3]])),{value:s,gradFunc:x}}));return e(f,d)}{const e=ql(((e,t,n,s)=>{let r=ta.runKernel(ds,w,v);return s([t,e,r,n]),m&&(r=oo(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:x}}));return e(f,d,y)}}});const Ph=fa({fusedMatMul_:function({a:e,b:t,transposeA:n=!1,transposeB:s=!1,bias:r,activation:a="linear",preluActivationWeights:i,leakyreluAlpha:o=.2}){if(!1===Dh(ta.state.gradientDepth,a)){let l=ho(e,t,n,s);return null!=r&&(l=Ei(l,r)),Fh(l,a,i,o)}let l=ha(e,"a","fused matMul"),u=ha(t,"b","fused matMul");[l,u]=Hr(l,u);const h=n?l.shape[l.rank-2]:l.shape[l.rank-1],p=s?u.shape[u.rank-1]:u.shape[u.rank-2],f=n?l.shape[l.rank-1]:l.shape[l.rank-2],m=s?u.shape[u.rank-2]:u.shape[u.rank-1],g=l.shape.slice(0,-2),y=u.shape.slice(0,-2),b=d(g),x=d(y);c(h===p,(()=>`Error in fused matMul: inner shapes (${h}) and (${p}) of Tensors with shapes ${l.shape} and ${u.shape} and transposeA=${n} and transposeB=${s} must match.`));const w=Zo(l.shape.slice(0,-2),u.shape.slice(0,-2)).concat([f,m]),v=oo(l,n?[b,h,f]:[b,f,h]),k=oo(u,s?[x,m,p]:[x,p,m]);let N,I;null!=r&&(N=ha(r,"bias","fused matMul"),[N]=Hr(N,l),Zo(w,N.shape)),null!=i&&(I=ha(i,"prelu weights","fused matMul"));const S=(e,t)=>{const[i,o,l,u]=t,c=Rh(oo(e,l.shape),l,a);let h,p;if(n||s?!n&&s?(h=ho(c,o,!1,!1),p=ho(c,i,!0,!1)):n&&!s?(h=ho(o,c,!1,!0),p=ho(i,c,!1,!1)):(h=ho(o,c,!0,!0),p=ho(c,i,!0,!0)):(h=ho(c,o,!1,!0),p=ho(i,c,!0,!1)),null!=r){return[h,p,_h(u,c)]}return[h,p]},T={a:v,b:k,bias:N,preluActivationWeights:I},C={transposeA:n,transposeB:s,activation:a,leakyreluAlpha:o};if(null==r){const e=ql(((e,t,n)=>{const s=ta.runKernel(hs,T,C);return n([e,t,s]),{value:oo(s,w),gradFunc:S}}));return e(v,k)}{const e=ql(((e,t,n,s)=>{const r=ta.runKernel(hs,T,C);return s([e,t,r,n]),{value:oo(r,w),gradFunc:S}}));return e(v,k,N)}}});var Bh=Object.freeze({__proto__:null,conv2d:Oh,depthwiseConv2d:zh,matMul:Ph});const Wh=fa({hammingWindow_:function(e){return $h(e,.54,.46)}});const Vh=fa({hannWindow_:function(e){return $h(e,.5,.5)}});const Uh=fa({frame_:function(e,t,n,s=!1,r=0){let a=0;const i=[];for(;a+t<=e.size;)i.push(fo(e,a,t)),a+=n;if(s)for(;a<e.size;){const s=a+t-e.size,o=co([fo(e,a,t-s),Co([s],r)]);i.push(o),a+=n}return 0===i.length?th([],[0,t]):oo(co(i),[i.length,t])}});const Gh=fa({stft_:function(e,t,n,s,r=Vh){null==s&&(s=Ch(t));const a=Uh(e,t,n),i=_i(a,r(t));return qc(i,s)}});const Hh=fa({cropAndResize_:function(e,t,n,s,r="bilinear",a=0){const i=ha(e,"image","cropAndResize"),o=ha(t,"boxes","cropAndResize","float32"),l=ha(n,"boxInd","cropAndResize","int32"),u=o.shape[0];c(4===i.rank,(()=>`Error in cropAndResize: image must be rank 4,but got rank ${i.rank}.`)),c(2===o.rank&&4===o.shape[1],(()=>`Error in cropAndResize: boxes must be have size [${u},4] but had shape ${o.shape}.`)),c(1===l.rank&&l.shape[0]===u,(()=>`Error in cropAndResize: boxInd must be have size [${u}] but had shape ${o.shape}.`)),c(2===s.length,(()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${s.length}.`)),c(s[0]>=1&&s[1]>=1,(()=>`cropSize must be atleast [1,1], but was ${s}`)),c("bilinear"===r||"nearest"===r,(()=>`method must be bilinear or nearest, but was ${r}`));const h={image:i,boxes:o,boxInd:l},p={method:r,extrapolationValue:a,cropSize:s};return ta.runKernel(Be,h,p)}});const jh=fa({flipLeftRight_:function(e){const t=ha(e,"image","flipLeftRight","float32");c(4===t.rank,(()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`));const n={image:t};return ta.runKernel(lt,n,{})}});const qh=fa({grayscaleToRGB_:function(e){const t=ha(e,"image","grayscaleToRGB"),n=t.rank-1,s=t.shape[n];c(t.rank>=2,(()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`)),c(1===s,(()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${s}.`));const r=new Array(t.rank);return r.fill(1,0,n),r[n]=3,El(t,r)}});const Kh=fa({rgbToGrayscale_:function(e){const t=ha(e,"image","RGBToGrayscale"),n=t.rank-1,s=t.shape[n];c(t.rank>=2,(()=>`Error in RGBToGrayscale: images must be at least rank 2, but got rank ${t.rank}.`)),c(3===s,(()=>`Error in RGBToGrayscale: last dimension of an RGB image should be size 3, but got size ${s}.`));const r=t.dtype,a=Ti(t,"float32"),i=eh([.2989,.587,.114]);let o;switch(t.rank){case 2:o=rl("ij,j->i",a,i);break;case 3:o=rl("ijk,k->ij",a,i);break;case 4:o=rl("ijkl,l->ijk",a,i);break;case 5:o=rl("ijklm,m->ijkl",a,i);break;case 6:o=rl("ijklmn,n->ijklm",a,i);break;default:throw new Error("Not a valid tensor rank.")}return o=Cl(o,-1),Ti(o,r)}});const Xh=fa({rotateWithOffset_:function(e,t,n=0,s=.5){const r=ha(e,"image","rotateWithOffset","float32");c(4===r.rank,(()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${r.rank}.`));const a={image:r},i={radians:t,fillValue:n,center:s};return ta.runKernel(cs,a,i)}});function Yh(e,t,n,s,r,a){null==s&&(s=.5),null==r&&(r=Number.NEGATIVE_INFINITY),null==a&&(a=0);const i=e.shape[0];return n=Math.min(n,i),c(0<=s&&s<=1,(()=>`iouThreshold must be in [0, 1], but was '${s}'`)),c(2===e.rank,(()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`)),c(4===e.shape[1],(()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`)),c(1===t.rank,(()=>"scores must be a 1D tensor")),c(t.shape[0]===i,(()=>`scores has incompatible shape with boxes. Expected ${i}, but was ${t.shape[0]}`)),c(0<=a&&a<=1,(()=>`softNmsSigma must be in [0, 1], but was '${a}'`)),{maxOutputSize:n,iouThreshold:s,scoreThreshold:r,softNmsSigma:a}}const Zh=fa({nonMaxSuppression_:function(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY){const a=ha(e,"boxes","nonMaxSuppression","float32"),i=ha(t,"scores","nonMaxSuppression","float32"),o=Yh(a,i,n,s,r),l={maxOutputSize:n=o.maxOutputSize,iouThreshold:s=o.iouThreshold,scoreThreshold:r=o.scoreThreshold};return ta.runKernel(Yt,{boxes:a,scores:i},l)}});function Jh(e,t,n){const s=function(e,t,n){return function(e,t,n){let s=0,r=e.length,a=0,i=!1;for(;s<r;){a=s+(r-s>>>1);const o=n(t,e[a]);o>0?s=a+1:(r=a,i=!o)}return i?s:-s-1}(e,t,n||Qh)}(e,t,n),r=s<0?-(s+1):s;e.splice(r,0,t)}function Qh(e,t){return e>t?1:e<t?-1:0}function ep(e,t,n,s,r){return sp(e,t,n,s,r,0)}function tp(e,t,n,s,r,a){return sp(e,t,n,s,r,0,!1,a,!0)}function np(e,t,n,s,r,a){return sp(e,t,n,s,r,a,!0)}function sp(e,t,n,s,r,a,i=!1,o=!1,l=!1){const u=[];for(let e=0;e<t.length;e++)t[e]>r&&u.push({score:t[e],boxIndex:e,suppressBeginIndex:0});u.sort(ip);const c=a>0?-.5/a:0,h=[],p=[];for(;h.length<n&&u.length>0;){const t=u.pop(),{score:n,boxIndex:a,suppressBeginIndex:i}=t;if(n<r)break;let o=!1;for(let n=h.length-1;n>=i;--n){const i=rp(e,a,h[n]);if(i>=s){o=!0;break}if(t.score=t.score*ap(s,c,i),t.score<=r)break}t.suppressBeginIndex=h.length,o||(t.score===n?(h.push(a),p.push(t.score)):t.score>r&&Jh(u,t,ip))}const d=h.length,f=n-d;o&&f>0&&(h.push(...new Array(f).fill(0)),p.push(...new Array(f).fill(0)));const m={selectedIndices:h};return i&&(m.selectedScores=p),l&&(m.validOutputs=d),m}function rp(e,t,n){const s=e.subarray(4*t,4*t+4),r=e.subarray(4*n,4*n+4),a=Math.min(s[0],s[2]),i=Math.min(s[1],s[3]),o=Math.max(s[0],s[2]),l=Math.max(s[1],s[3]),u=Math.min(r[0],r[2]),c=Math.min(r[1],r[3]),h=Math.max(r[0],r[2]),p=Math.max(r[1],r[3]),d=(o-a)*(l-i),f=(h-u)*(p-c);if(d<=0||f<=0)return 0;const m=Math.max(a,u),g=Math.max(i,c),y=Math.min(o,h),b=Math.min(l,p),x=Math.max(y-m,0)*Math.max(b-g,0);return x/(d+f-x)}function ap(e,t,n){const s=Math.exp(t*n*n);return n<=e?s:0}function ip(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}const op=async function(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY){const a=ha(e,"boxes","nonMaxSuppressionAsync"),i=ha(t,"scores","nonMaxSuppressionAsync"),o=Yh(a,i,n,s,r);n=o.maxOutputSize,s=o.iouThreshold,r=o.scoreThreshold;const l=await Promise.all([a.data(),i.data()]),u=l[0],c=l[1],{selectedIndices:h}=ep(u,c,n,s,r);return a!==e&&a.dispose(),i!==t&&i.dispose(),eh(h,"int32")};const lp=fa({nonMaxSuppressionWithScore_:function(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=0){const i=ha(e,"boxes","nonMaxSuppression"),o=ha(t,"scores","nonMaxSuppression"),l=Yh(i,o,n,s,r,a),u={boxes:i,scores:o},c={maxOutputSize:n=l.maxOutputSize,iouThreshold:s=l.iouThreshold,scoreThreshold:r=l.scoreThreshold,softNmsSigma:a=l.softNmsSigma},h=ta.runKernel(Jt,u,c);return{selectedIndices:h[0],selectedScores:h[1]}}});const up=async function(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=0){const i=ha(e,"boxes","nonMaxSuppressionAsync"),o=ha(t,"scores","nonMaxSuppressionAsync"),l=Yh(i,o,n,s,r,a);n=l.maxOutputSize,s=l.iouThreshold,r=l.scoreThreshold,a=l.softNmsSigma;const u=await Promise.all([i.data(),o.data()]),c=u[0],h=u[1],{selectedIndices:p,selectedScores:d}=np(c,h,n,s,r,a);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:eh(p,"int32"),selectedScores:eh(d)}};const cp=fa({nonMaxSuppressionPadded_:function(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=!1){const i=ha(e,"boxes","nonMaxSuppression"),o=ha(t,"scores","nonMaxSuppression"),l=Yh(i,o,n,s,r,null),u={boxes:i,scores:o},c={maxOutputSize:l.maxOutputSize,iouThreshold:l.iouThreshold,scoreThreshold:l.scoreThreshold,padToMaxOutputSize:a},h=ta.runKernel(Zt,u,c);return{selectedIndices:h[0],validOutputs:h[1]}}});const hp=async function(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=!1){const i=ha(e,"boxes","nonMaxSuppressionAsync"),o=ha(t,"scores","nonMaxSuppressionAsync"),l=Yh(i,o,n,s,r,null),u=l.maxOutputSize,c=l.iouThreshold,h=l.scoreThreshold,[p,d]=await Promise.all([i.data(),o.data()]),{selectedIndices:f,validOutputs:m}=tp(p,d,u,c,h,a);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:eh(f,"int32"),validOutputs:xl(m,"int32")}};const pp=fa({resizeBilinear_:function(e,t,n=!1,s=!1){const r=ha(e,"images","resizeBilinear");c(3===r.rank||4===r.rank,(()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${r.rank}.`)),c(2===t.length,(()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`)),c(!1===s||!1===n,(()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false."));let a=r,i=!1;3===r.rank&&(i=!0,a=oo(r,[1,r.shape[0],r.shape[1],r.shape[2]]));const[]=t,o={images:a},l={alignCorners:n,halfPixelCenters:s,size:t},u=ta.runKernel(yn,o,l);return i?oo(u,[u.shape[1],u.shape[2],u.shape[3]]):u}});const dp=fa({resizeNearestNeighbor_:function(e,t,n=!1,s=!1){const r=ha(e,"images","resizeNearestNeighbor");c(3===r.rank||4===r.rank,(()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${r.rank}.`)),c(2===t.length,(()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`)),c("float32"===r.dtype||"int32"===r.dtype,(()=>"`images` must have `int32` or `float32` as dtype")),c(!1===s||!1===n,(()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false."));let a=r,i=!1;3===r.rank&&(i=!0,a=oo(r,[1,r.shape[0],r.shape[1],r.shape[2]]));const[]=t,o={images:a},l={alignCorners:n,halfPixelCenters:s,size:t},u=ta.runKernel(mn,o,l);return i?oo(u,[u.shape[1],u.shape[2],u.shape[3]]):u}});const fp=fa({threshold_:function(e,t="binary",n=!1,s=.5){const r=ha(e,"image","threshold"),a=r.shape[0]*r.shape[1];let i,o,l,u,h=_i(eh([s]),255);if(c(3===r.rank,(()=>`Error in threshold: image must be rank 3,but got rank ${r.rank}.`)),c(3===r.shape[2]||1===r.shape[2],(()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${r.shape[2]}.`)),c("int32"===r.dtype||"float32"===r.dtype,(()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${r.dtype}.`)),c("otsu"===t||"binary"===t,(()=>`Method must be binary or otsu, but was ${t}`)),3===r.shape[2]){[i,o,l]=jc(r,[1,1,1],-1);const e=_i(i,.2989),t=_i(o,.587),n=_i(l,.114);u=Ei(Ei(e,t),n)}else u=e;if("otsu"===t){h=function(e,t){let n,s,r,a,i,o,l=eh([-1]),u=eh([0]),c=eh([0]);for(let h=0;h<e.size-1;h++){n=fo(e,0,h+1),s=fo(e,h+1),i=Ri(kl(n),t),o=Ri(kl(s),t);const p=kl(_i(n,wc(0,n.size)));r=Ri(p,kl(n));const d=Co(s.shape,n.size),f=Ei(wc(0,s.size),d),m=_i(s,f);a=Ri(kl(m),kl(s));const g=Jl(r,a),y=Jl(r,a),b=_i(i,o);c=_i(_i(b,g),y);const x=Fl(c,u);u=el(x,c,u),l=el(x,eh([h]),l)}return l}(ko(Ti(Ac(u),"int32"),ya([]),256),a)}const p=n?Wl(u,h):Fl(u,h);return Ti(_i(p,255),"int32")}});const mp=fa({transform_:function(e,t,n="nearest",s="constant",r=0,a){const i=ha(e,"image","transform","float32"),o=ha(t,"transforms","transform","float32");c(4===i.rank,(()=>`Error in transform: image must be rank 4,but got rank ${i.rank}.`)),c(2===o.rank&&(o.shape[0]===i.shape[0]||1===o.shape[0])&&8===o.shape[1],(()=>"Error in transform: Input transform should be batch x 8 or 1 x 8")),c(null==a||2===a.length,(()=>`Error in transform: outputShape must be [height, width] or null, but got ${a}.`));const l={image:i,transforms:o},u={interpolation:n,fillMode:s,fillValue:r,outputShape:a};return ta.runKernel(ns,l,u)}});const gp=fa({bandPart_:function(e,t,n){const s=ha(e,"a","bandPart");c(s.rank>=2,(()=>`bandPart(): Rank must be at least 2, got ${s.rank}.`));const r=s.shape,[a,i]=s.shape.slice(-2);let o,l;"number"==typeof t?(c(t%1==0,(()=>`bandPart(): numLower must be an integer, got ${t}.`)),c(t<=a,(()=>`bandPart(): numLower (${t}) must not be greater than the number of rows (${a}).`)),o=ha(t<0?a:t,"numLower","bandPart")):(c("int32"===t.dtype,(()=>"bandPart(): numLower's dtype must be an int32.")),o=el(Bl(t,0),a,gu(t,a))),"number"==typeof n?(c(n%1==0,(()=>`bandPart(): numUpper must be an integer, got ${n}.`)),c(n<=i,(()=>`bandPart(): numUpper (${n}) must not be greater than the number of columns (${i}).`)),l=ha(n<0?i:n,"numUpper","bandPart")):(c("int32"===n.dtype,(()=>"bandPart(): numUpper's dtype must be an int32.")),l=el(Bl(n,0),i,gu(n,i)));const u=oo(wc(0,a,1,"int32"),[-1,1]),h=wc(0,i,1,"int32"),p=Jl(u,h),d=tu(Wl(p,o),Dl(p,Xl(l))),f=du([a,i],s.dtype);return oo(Yc(mh(oo(s,[-1,a,i])).map((e=>el(d,e,f)))),r)}});const yp=fa({gramSchmidt_:function(e){let t;if(Array.isArray(e)){t=!1,c(null!=e&&e.length>0,(()=>"Gram-Schmidt process: input must not be null, undefined, or empty"));const n=e[0].shape[0];for(let t=1;t<e.length;++t)c(e[t].shape[0]===n,(()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[t].shape[0]} vs. ${n})`))}else t=!0,e=jc(e,e.shape[0],0).map((e=>Xc(e,[0])));c(e.length<=e[0].shape[0],(()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`));const n=[],s=e;for(let t=0;t<e.length;++t)n.push(ta.tidy((()=>{let e=s[t];if(t>0)for(let s=0;s<t;++s){const t=_i(kl(_i(n[s],e)),n[s]);e=Jl(e,t)}return Ri(e,Il(e,"euclidean"))})));return t?Yc(n,0):n}});function bp(e,t=!1){return ta.tidy((()=>{c(2===e.shape.length,(()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`));const n=e.shape[0],s=e.shape[1];let r=Al(n),a=Ci(e);const i=th([[1]],[1,1]);let o=Ci(i);const l=n>=s?s:n;for(let e=0;e<l;++e){const t=a,l=o,u=r;[o,a,r]=ta.tidy((()=>{const t=fo(a,[e,e],[n-e,1]),l=Il(t),u=fo(a,[e,e],[1,1]),c=el(Fl(u,0),th([[-1]]),th([[1]])),h=Jl(u,_i(c,l)),p=Ri(t,h);o=1===p.shape[0]?Ci(i):co([i,fo(p,[1,0],[p.shape[0]-1,p.shape[1]])],0);const d=Xl(Ri(ho(c,h),l)),f=fo(a,[e,0],[n-e,s]),m=_i(d,o),g=vh(o);if(0===e)a=Jl(f,ho(m,ho(g,f)));else{const t=Jl(f,ho(m,ho(g,f)));a=co([fo(a,[0,0],[e,s]),t],0)}const y=vh(m),b=fo(r,[0,e],[n,r.shape[1]-e]);if(0===e)r=Jl(b,ho(ho(b,o),y));else{const t=Jl(b,ho(ho(b,o),y));r=co([fo(r,[0,0],[n,e]),t],1)}return[o,a,r]})),Ia([t,l,u])}return!t&&n>s&&(r=fo(r,[0,0],[n,s]),a=fo(a,[0,0],[s,s])),[r,a]}))}const xp=fa({qr_:function(e,t=!1){if(c(e.rank>=2,(()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`)),2===e.rank)return bp(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce(((e,t)=>e*t)),s=mh(oo(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),r=[],a=[];s.forEach((e=>{const[n,s]=bp(e,t);r.push(n),a.push(s)}));return[oo(Yc(r,0),e.shape),oo(Yc(a,0),e.shape)]}}});var wp;e.Reduction=void 0,(wp=e.Reduction||(e.Reduction={}))[wp.NONE=0]="NONE",wp[wp.MEAN=1]="MEAN",wp[wp.SUM=2]="SUM",wp[wp.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS";const vp=fa({computeWeightedLoss_:function(t,n,s=e.Reduction.SUM_BY_NONZERO_WEIGHTS){const r=ha(t,"losses","computeWeightedLoss");let a=null;null!=n&&(a=ha(n,"weights","computeWeightedLoss"));const i=null==a?r:_i(r,a);if(s===e.Reduction.NONE)return i;if(s===e.Reduction.SUM)return kl(i);if(s===e.Reduction.MEAN){if(null==a)return pu(i);{const e=r.size/a.size,t=Ri(kl(i),kl(a));return e>1?Ri(t,xl(e)):t}}if(s===e.Reduction.SUM_BY_NONZERO_WEIGHTS){if(null==a)return Ri(kl(i),xl(r.size));{const e=_i(a,fu(r.shape)),t=Ti(kl(ku(e,xl(0))),"float32");return Ri(kl(i),t)}}throw Error(`Unknown reduction: ${s}`)}});const kp=fa({absoluteDifference_:function(t,n,s,r=e.Reduction.SUM_BY_NONZERO_WEIGHTS){const a=ha(t,"labels","absoluteDifference"),i=ha(n,"predictions","absoluteDifference");let o=null;null!=s&&(o=ha(s,"weights","absoluteDifference")),h(a.shape,i.shape,"Error in absoluteDifference: ");const l=Fi(Jl(a,i));return vp(l,o,r)}});const Np=fa({cosineDistance_:function(t,n,s,r,a=e.Reduction.SUM_BY_NONZERO_WEIGHTS){const i=ha(t,"labels","cosineDistance"),o=ha(n,"predictions","cosineDistance");let l=null;null!=r&&(l=ha(r,"weights","cosineDistance")),h(i.shape,o.shape,"Error in cosineDistance: ");const u=xl(1),c=Jl(u,kl(_i(i,o),s,!0));return vp(c,l,a)}});const Ip=fa({hingeLoss_:function(t,n,s,r=e.Reduction.SUM_BY_NONZERO_WEIGHTS){let a=ha(t,"labels","hingeLoss");const i=ha(n,"predictions","hingeLoss");let o=null;null!=s&&(o=ha(s,"weights","hingeLoss")),h(a.shape,i.shape,"Error in hingeLoss: ");const l=xl(1);a=Jl(_i(xl(2),a),l);const u=Nc(Jl(l,_i(a,i)));return vp(u,o,r)}});const Sp=fa({huberLoss_:function(t,n,s,r=1,a=e.Reduction.SUM_BY_NONZERO_WEIGHTS){const i=ha(t,"labels","huberLoss"),o=ha(n,"predictions","huberLoss");let l=null;null!=s&&(l=ha(s,"weights","huberLoss")),h(i.shape,o.shape,"Error in huberLoss: ");const u=xl(r),c=Fi(Jl(o,i)),p=gu(c,u),d=Jl(c,p),f=Ei(_i(xl(.5),vl(p)),_i(u,d));return vp(f,l,a)}});const Tp=fa({logLoss_:function(t,n,s,r=1e-7,a=e.Reduction.SUM_BY_NONZERO_WEIGHTS){const i=ha(t,"labels","logLoss"),o=ha(n,"predictions","logLoss");let l=null;null!=s&&(l=ha(s,"weights","logLoss")),h(i.shape,o.shape,"Error in logLoss: ");const u=xl(1),c=xl(r),p=Xl(_i(i,Gl(Ei(o,c)))),d=_i(Jl(u,i),Gl(Ei(Jl(u,o),c))),f=Jl(p,d);return vp(f,l,a)}});const Cp=fa({meanSquaredError_:function(t,n,s,r=e.Reduction.SUM_BY_NONZERO_WEIGHTS){const a=ha(t,"labels","meanSquaredError"),i=ha(n,"predictions","meanSquaredError");let o=null;null!=s&&(o=ha(s,"weights","meanSquaredError")),h(a.shape,i.shape,"Error in meanSquaredError: ");const l=Kc(a,i);return vp(l,o,r)}});const $p=fa({sigmoidCrossEntropy_:function(t,n,s,r=0,a=e.Reduction.SUM_BY_NONZERO_WEIGHTS){let i=ha(t,"multiClassLabels","sigmoidCrossEntropy");const o=ha(n,"logits","sigmoidCrossEntropy");let l=null;if(null!=s&&(l=ha(s,"weights","sigmoidCrossEntropy")),h(i.shape,o.shape,"Error in sigmoidCrossEntropy: "),r>0){const e=xl(r),t=xl(1),n=xl(.5);i=Ei(_i(i,Jl(t,e)),_i(n,e))}const u=function(e,t){const n=ha(e,"labels","sigmoidCrossEntropyWithLogits"),s=ha(t,"logits","sigmoidCrossEntropyWithLogits");h(n.shape,s.shape,"Error in sigmoidCrossEntropyWithLogits: ");const r=Nc(s),a=_i(s,n),i=Hl(Tl(Xl(Fi(s))));return Ei(Jl(r,a),i)}(i,o);return vp(u,l,a)}});const Ep=fa({softmaxCrossEntropy_:function(t,n,s,r=0,a=e.Reduction.SUM_BY_NONZERO_WEIGHTS){let i=ha(t,"onehotLabels","softmaxCrossEntropy");const o=ha(n,"logits","softmaxCrossEntropy");let l=null;if(null!=s&&(l=ha(s,"weights","softmaxCrossEntropy")),h(i.shape,o.shape,"Error in softmaxCrossEntropy: "),r>0){const e=xl(r),t=xl(1),n=xl(i.shape[1]);i=Ei(_i(i,Jl(t,e)),Ri(e,n))}const u=function(e,t,n=-1){if(-1===n&&(n=t.rank-1),n!==t.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${t.rank} and dim was ${n}`);const s=ql(((e,t,s)=>{const r=eu(t,[n],!0),a=Jl(Ti(t,"float32"),r);s([e,a]);const i=Xl(_i(a,e));return{value:kl(i,[n]),gradFunc:(e,t)=>{const[s,r]=t,a=hl(e.shape,[n]);return[_i(oo(e,a),Jl(Ti(s,"float32"),Tl(r))),_i(oo(e,a),Jl(Tl(r),Ti(s,"float32")))]}}}));return s(e,t)}(i,o);return vp(u,l,a)}});const Ap=fa({sparseFillEmptyRows_:function(e,t,n,s){const r=ha(e,"indices","sparseFillEmptyRows","int32"),a=ha(t,"values","sparseFillEmptyRows"),i=ha(n,"denseShape","sparseFillEmptyRows","int32"),o=ha(s,"defaultValue","sparseFillEmptyRows",a.dtype);if(2!==r.rank)throw new Error(`Indices should be Tensor2D but received shape\n        ${r.shape}`);if(1!==a.rank)throw new Error(`Values should be Tensor1D but received shape ${a.shape}`);if(1!==i.rank)throw new Error(`Dense shape should be Tensor1D but received shape ${i.shape}`);if(0!==o.rank)throw new Error(`Default value should be a scalar but received shape ${o.shape}`);const l={indices:r,values:a,denseShape:i,defaultValue:o},u=ta.runKernel(Pn,l);return{outputIndices:u[0],outputValues:u[1],emptyRowIndicator:u[2],reverseIndexMap:u[3]}}});const Rp=fa({sparseReshape_:function(e,t,n){const s=ha(e,"inputIndices","sparseReshape","int32"),r=ha(t,"inputShape","sparseReshape","int32"),a=ha(n,"newShape","sparseReshape","int32");if(2!==s.rank)throw new Error(`Input indices should be Tensor2D but received shape\n        ${s.shape}`);if(1!==r.rank)throw new Error(`Input shape should be Tensor1D but received shape ${r.shape}`);if(1!==a.rank)throw new Error(`New shape should be Tensor1D but received shape ${a.shape}`);const i={inputIndices:s,inputShape:r,newShape:a},o=ta.runKernel(Bn,i);return{outputIndices:o[0],outputShape:o[1]}}});const _p=fa({sparseSegmentMean_:function(e,t,n){const s=ha(e,"data","sparseSegmentMean"),r=ha(t,"indices","sparseSegmentMean","int32"),a=ha(n,"segmentIds","sparseSegmentMean","int32");if(s.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==r.rank)throw new Error(`Indices should be Tensor1D but received shape\n          ${r.shape}`);if(1!==a.rank)throw new Error(`Segment ids should be Tensor1D but received shape\n          ${a.shape}`);const i={data:s,indices:r,segmentIds:a};return ta.runKernel(Wn,i)}});const Fp=fa({sparseSegmentSum_:function(e,t,n){const s=ha(e,"data","sparseSegmentSum"),r=ha(t,"indices","sparseSegmentSum","int32"),a=ha(n,"segmentIds","sparseSegmentSum","int32");if(s.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==r.rank)throw new Error(`Indices should be Tensor1D but received shape\n         ${r.shape}`);if(1!==a.rank)throw new Error(`Segment ids should be Tensor1D but received shape\n         ${a.shape}`);const i={data:s,indices:r,segmentIds:a};return ta.runKernel(Vn,i)}});const Dp=fa({stringNGrams_:function(e,t,n,s,r,a,i,o){const l=ha(e,"data","stringNGrams","string");if("string"!==l.dtype)throw new Error("Data must be of datatype string");if(1!==l.shape.length)throw new Error(`Data must be a vector, saw: ${l.shape}`);const u=ha(t,"dataSplits","stringNGrams");if("int32"!==u.dtype)throw new Error("Data splits must be of datatype int32");const c={separator:n,nGramWidths:s,leftPad:r,rightPad:a,padWidth:i,preserveShortSequences:o},h={data:l,dataSplits:u},p=ta.runKernel(Kn,h,c);return{nGrams:p[0],nGramsSplits:p[1]}}});const Op=fa({stringSplit_:function(e,t,n=!0){const s=ha(e,"input","stringSplit","string"),r=ha(t,"delimiter","stringSplit","string");if(1!==s.rank)throw new Error(`Input should be Tensor1D but received shape ${s.shape}`);if(0!==r.rank)throw new Error(`Delimiter should be a scalar but received shape ${r.shape}`);const a={skipEmpty:n},i={input:s,delimiter:r},o=ta.runKernel(Xn,i,a);return{indices:o[0],values:o[1],shape:o[2]}}});const Mp=fa({stringToHashBucketFast_:function(e,t){const n=ha(e,"input","stringToHashBucketFast","string"),s={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");const r={input:n};return ta.runKernel(Yn,r,s)}});const Lp=fa({staticRegexReplace_:function(e,t,n,s=!0){const r=ha(e,"input","staticRegexReplace","string"),a={pattern:t,rewrite:n,replaceGlobal:s};return ta.runKernel(jn,{x:r},a)}}),zp={fft:Uc,ifft:Gc,rfft:qc,irfft:Hc},Pp={hammingWindow:Wh,hannWindow:Vh,frame:Uh,stft:Gh},Bp={flipLeftRight:jh,grayscaleToRGB:qh,resizeNearestNeighbor:dp,resizeBilinear:pp,rgbToGrayscale:Kh,rotateWithOffset:Xh,cropAndResize:Hh,nonMaxSuppression:Zh,nonMaxSuppressionAsync:op,nonMaxSuppressionWithScore:lp,nonMaxSuppressionWithScoreAsync:up,nonMaxSuppressionPadded:cp,nonMaxSuppressionPaddedAsync:hp,threshold:fp,transform:mp},Wp={bandPart:gp,gramSchmidt:yp,qr:xp},Vp={absoluteDifference:kp,computeWeightedLoss:vp,cosineDistance:Np,hingeLoss:Ip,huberLoss:Sp,logLoss:Tp,meanSquaredError:Cp,sigmoidCrossEntropy:$p,softmaxCrossEntropy:Ep},Up={sparseFillEmptyRows:Ap,sparseReshape:Rp,sparseSegmentMean:_p,sparseSegmentSum:Fp},Gp={stringNGrams:Dp,stringSplit:Op,stringToHashBucketFast:Mp,staticRegexReplace:Lp},Hp=new Map,jp=new Map;class qp{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class Kp{constructor(){this.classNameMap={}}static getMap(){return null==Kp.instance&&(Kp.instance=new Kp),Kp.instance}static register(e){Kp.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function Xp(e,t,n){c(null!=e.className,(()=>"Class being registered does not have the static className property defined.")),c("string"==typeof e.className,(()=>"className is required to be a string, but got type "+typeof e.className)),c(e.className.length>0,(()=>"Class being registered has an empty-string as its className, which is disallowed.")),void 0===t&&(t="Custom"),void 0===n&&(n=e.className);const s=t+">"+n;return Kp.register(e),Hp.set(s,e),jp.set(e,s),e}var Yp=Object.freeze({__proto__:null,Serializable:qp,SerializationMap:Kp,getRegisteredName:function(e){return jp.has(e)?jp.get(e):e.className},registerClass:Xp});class Zp extends qp{minimize(e,t=!1,n){const{value:s,grads:r}=this.computeGradients(e,n);if(null!=n){const e=n.map((e=>({name:e.name,tensor:r[e.name]})));this.applyGradients(e)}else this.applyGradients(r);return Ia(r),t?s:(s.dispose(),null)}get iterations(){return null==this.iterations_&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return jl(e,t)}dispose(){null!=this.iterations_&&Ia(this.iterations_)}async saveIterations(){return null==this.iterations_&&(this.iterations_=0),{name:"iter",tensor:xl(this.iterations_,"int32")}}async getWeights(){throw new Error("getWeights() is not implemented for this optimizer yet.")}async setWeights(e){throw new Error(`setWeights() is not implemented for this optimizer class ${this.getClassName()}`)}async extractIterations(e){return this.iterations_=(await e[0].tensor.data())[0],e.slice(1)}}Object.defineProperty(Zp,Symbol.hasInstance,{value:e=>null!=e.minimize&&null!=e.computeGradients&&null!=e.applyGradients});class Jp extends Zp{static get className(){return"Adadelta"}constructor(e,t,n=null){super(),this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],null==n&&(this.epsilon=ta.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const s=ta.registeredVariables[t];null==this.accumulatedGrads[n]&&(this.accumulatedGrads[n]={originalName:`${t}/accum_grad`,variable:Na((()=>tl(s).variable(false)))}),null==this.accumulatedUpdates[n]&&(this.accumulatedUpdates[n]={originalName:`${t}/accum_var`,variable:Na((()=>tl(s).variable(false)))});const r=Array.isArray(e)?e[n].tensor:e[t];if(null==r)return;const a=this.accumulatedGrads[n].variable,i=this.accumulatedUpdates[n].variable;Na((()=>{const e=Ei(_i(a,this.rho),_i(vl(r),1-this.rho)),t=_i(Ri(wl(Ei(i,this.epsilon)),wl(Ei(a,this.epsilon))),r),n=Ei(_i(i,this.rho),_i(vl(t),1-this.rho));a.assign(e),i.assign(n);const o=Ei(_i(t,-this.learningRate),s);s.assign(o)}))})),this.incrementIterations()}dispose(){null!=this.accumulatedUpdates&&(Ia(this.accumulatedGrads.map((e=>e.variable))),Ia(this.accumulatedUpdates.map((e=>e.variable))))}async getWeights(){const e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){const t=(e=await this.extractIterations(e)).length/2;this.accumulatedGrads=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(false)}))),this.accumulatedUpdates=e.slice(t,2*t).map((e=>({originalName:e.name,variable:e.tensor.variable(false)})))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}}class Qp extends Zp{static get className(){return"Adagrad"}constructor(e,t=.1){super(),this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const s=ta.registeredVariables[t];if(null==this.accumulatedGrads[n]){const e=!1;this.accumulatedGrads[n]={originalName:`${t}/accumulator`,variable:Na((()=>Co(s.shape,this.initialAccumulatorValue).variable(e)))}}const r=Array.isArray(e)?e[n].tensor:e[t];if(null==r)return;const a=this.accumulatedGrads[n].variable;Na((()=>{const e=Ei(a,vl(r));a.assign(e);const t=Ei(_i(Ri(r,wl(Ei(e,ta.backend.epsilon()))),-this.learningRate),s);s.assign(t)}))})),this.incrementIterations()}dispose(){null!=this.accumulatedGrads&&Ia(this.accumulatedGrads.map((e=>e.variable)))}async getWeights(){return[await this.saveIterations()].concat(this.accumulatedGrads.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e);this.accumulatedGrads=e.map((e=>({originalName:e.name,variable:e.tensor.variable(false)})))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}}class ed extends Zp{static get className(){return"Adam"}constructor(e,t,n,s=null){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=s,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],Na((()=>{this.accBeta1=xl(t).variable(),this.accBeta2=xl(n).variable()})),null==s&&(this.epsilon=ta.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);Na((()=>{const n=Jl(1,this.accBeta1),s=Jl(1,this.accBeta2);t.forEach(((t,r)=>{const a=ta.registeredVariables[t];null==this.accumulatedFirstMoment[r]&&(this.accumulatedFirstMoment[r]={originalName:`${t}/m`,variable:Na((()=>tl(a).variable(false)))}),null==this.accumulatedSecondMoment[r]&&(this.accumulatedSecondMoment[r]={originalName:`${t}/v`,variable:Na((()=>tl(a).variable(false)))});const i=Array.isArray(e)?e[r].tensor:e[t];if(null==i)return;const o=this.accumulatedFirstMoment[r].variable,l=this.accumulatedSecondMoment[r].variable,u=Ei(_i(o,this.beta1),_i(i,1-this.beta1)),c=Ei(_i(l,this.beta2),_i(vl(i),1-this.beta2)),h=Ri(u,n),p=Ri(c,s);o.assign(u),l.assign(c);const d=Ei(_i(Ri(h,Ei(wl(p),this.epsilon)),-this.learningRate),a);a.assign(d)})),this.accBeta1.assign(_i(this.accBeta1,this.beta1)),this.accBeta2.assign(_i(this.accBeta2,this.beta2))})),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&Ia(this.accumulatedFirstMoment.map((e=>e.variable))),null!=this.accumulatedSecondMoment&&Ia(this.accumulatedSecondMoment.map((e=>e.variable)))}async getWeights(){const e=[...this.accumulatedFirstMoment,...this.accumulatedSecondMoment];return[await this.saveIterations()].concat(e.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e),Na((()=>{this.accBeta1.assign(bl(this.beta1,this.iterations_+1)),this.accBeta2.assign(bl(this.beta2,this.iterations_+1))}));const t=e.length/2;this.accumulatedFirstMoment=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(false)}))),this.accumulatedSecondMoment=e.slice(t,2*t).map((e=>({originalName:e.name,variable:e.tensor.variable(false)})))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}}class td extends Zp{static get className(){return"Adamax"}constructor(e,t,n,s=null,r=0){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=s,this.decay=r,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],Na((()=>{this.iteration=xl(0).variable(),this.accBeta1=xl(t).variable()})),null==s&&(this.epsilon=ta.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);Na((()=>{const n=Jl(1,this.accBeta1),s=Ri(-this.learningRate,Ei(_i(this.iteration,this.decay),1));t.forEach(((t,r)=>{const a=ta.registeredVariables[t];null==this.accumulatedFirstMoment[r]&&(this.accumulatedFirstMoment[r]={originalName:`${t}/m`,variable:tl(a).variable(false)}),null==this.accumulatedWeightedInfNorm[r]&&(this.accumulatedWeightedInfNorm[r]={originalName:`${t}/v`,variable:tl(a).variable(false)});const i=Array.isArray(e)?e[r].tensor:e[t];if(null==i)return;const o=this.accumulatedFirstMoment[r].variable,l=this.accumulatedWeightedInfNorm[r].variable,u=Ei(_i(o,this.beta1),_i(i,1-this.beta1)),c=_i(l,this.beta2),h=Fi(i),p=hu(c,h);o.assign(u),l.assign(p);const d=Ei(_i(Ri(s,n),Ri(u,Ei(p,this.epsilon))),a);a.assign(d)})),this.iteration.assign(Ei(this.iteration,1)),this.accBeta1.assign(_i(this.accBeta1,this.beta1))})),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&Ia(this.accumulatedFirstMoment.map((e=>e.variable))),null!=this.accumulatedWeightedInfNorm&&Ia(this.accumulatedWeightedInfNorm.map((e=>e.variable)))}async getWeights(){throw new Error("getWeights() is not implemented for Adamax yet.")}async setWeights(e){throw new Error("setWeights() is not implemented for Adamax yet.")}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon,decay:this.decay}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon,t.decay)}}class nd extends Zp{static get className(){return"SGD"}constructor(e){super(),this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const s=Array.isArray(e)?e[n].tensor:e[t];if(null==s)return;const r=ta.registeredVariables[t];Na((()=>{const e=Ei(_i(this.c,s),r);r.assign(e)}))})),this.incrementIterations()}setLearningRate(e){this.learningRate=e,null!=this.c&&this.c.dispose(),this.c=Sa(xl(-e))}dispose(){this.c.dispose()}async getWeights(){return[await this.saveIterations()]}async setWeights(e){if(0!==(e=await this.extractIterations(e)).length)throw new Error("SGD optimizer does not have settable weights.")}getConfig(){return{learningRate:this.learningRate}}static fromConfig(e,t){return new e(t.learningRate)}}class sd extends nd{static get className(){return"Momentum"}constructor(e,t,n=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=xl(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const s=ta.registeredVariables[t];if(null==this.accumulations[n]){const e=!1;this.accumulations[n]={originalName:`${t}/momentum`,variable:Na((()=>tl(s).variable(e)))}}const r=this.accumulations[n].variable,a=Array.isArray(e)?e[n].tensor:e[t];null!=a&&Na((()=>{let e;const t=Ei(_i(this.m,r),a);e=this.useNesterov?Ei(_i(this.c,Ei(a,_i(t,this.m))),s):Ei(_i(this.c,t),s),r.assign(t),s.assign(e)}))})),this.incrementIterations()}dispose(){this.m.dispose(),null!=this.accumulations&&Ia(this.accumulations.map((e=>e.variable)))}setMomentum(e){this.momentum=e}async getWeights(){return[await this.saveIterations()].concat(this.accumulations.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e);this.accumulations=e.map((e=>({originalName:e.name,variable:e.tensor.variable(false)})))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}}class rd extends Zp{static get className(){return"RMSProp"}constructor(e,t=.9,n=0,s=null,r=!1){if(super(),this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=s,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=r,null==s&&(this.epsilon=ta.backend.epsilon()),null==e)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const s=ta.registeredVariables[t],r=!1;null==this.accumulatedMeanSquares[n]&&(this.accumulatedMeanSquares[n]={originalName:`${t}/rms`,variable:Na((()=>tl(s).variable(r)))}),null==this.accumulatedMoments[n]&&(this.accumulatedMoments[n]={originalName:`${t}/momentum`,variable:Na((()=>tl(s).variable(r)))}),null==this.accumulatedMeanGrads[n]&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${t}/mg`,variable:Na((()=>tl(s).variable(r)))});const a=Array.isArray(e)?e[n].tensor:e[t];if(null==a)return;const i=this.accumulatedMeanSquares[n].variable,o=this.accumulatedMoments[n].variable;Na((()=>{const e=Ei(_i(i,this.decay),_i(vl(a),1-this.decay));if(this.centered){const t=this.accumulatedMeanGrads[n].variable,r=Ei(_i(t,this.decay),_i(a,1-this.decay)),l=Ri(_i(a,this.learningRate),wl(Jl(e,Ei(vl(r),this.epsilon)))),u=Ei(_i(o,this.momentum),l);i.assign(e),t.assign(r),o.assign(u);const c=Jl(s,u);s.assign(c)}else{const e=Ei(_i(i,this.decay),_i(vl(a),1-this.decay)),t=Ei(_i(o,this.momentum),Ri(_i(a,this.learningRate),wl(Ei(e,this.epsilon))));i.assign(e),o.assign(t);const n=Jl(s,t);s.assign(n)}}))})),this.incrementIterations()}dispose(){null!=this.accumulatedMeanSquares&&Ia(this.accumulatedMeanSquares.map((e=>e.variable))),null!=this.accumulatedMeanGrads&&this.centered&&Ia(this.accumulatedMeanGrads.map((e=>e.variable))),null!=this.accumulatedMoments&&Ia(this.accumulatedMoments.map((e=>e.variable)))}async getWeights(){const e=[...this.accumulatedMeanSquares,...this.accumulatedMoments];return this.centered&&e.push(...this.accumulatedMeanGrads),[await this.saveIterations()].concat(e.map((e=>({name:e.originalName,tensor:e.variable}))))}async setWeights(e){e=await this.extractIterations(e);const t=this.centered?e.length/3:e.length/2,n=!1;this.accumulatedMeanSquares=e.slice(0,t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)}))),this.accumulatedMoments=e.slice(t,2*t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)}))),this.centered&&(this.accumulatedMeanGrads=e.slice(2*t,3*t).map((e=>({originalName:e.name,variable:e.tensor.variable(n)}))))}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)}}const ad=[Jp,Qp,ed,td,sd,rd,nd];function id(e){return new Promise((e=>setTimeout(e))).then(e)}class od{constructor(e){if(!Y().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(od.URL_SCHEME)&&(e=e.slice(od.URL_SCHEME.length)),null!=e&&0!==e.length||(e="model"),this.modelJsonFileName=e+".json",this.weightDataFileName=e+".weights.bin"}async save(e){if("undefined"==typeof document)throw new Error("Browser downloads are not supported in this environment since `document` is not present");const t=xa.join(e.weightData),n=window.URL.createObjectURL(new Blob([t],{type:"application/octet-stream"}));if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{const t=Va(e,[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}]),s=window.URL.createObjectURL(new Blob([JSON.stringify(t)],{type:"application/json"})),r=null==this.modelJsonAnchor?document.createElement("a"):this.modelJsonAnchor;if(r.download=this.modelJsonFileName,r.href=s,await id((()=>r.dispatchEvent(new MouseEvent("click")))),null!=e.weightData){const e=null==this.weightDataAnchor?document.createElement("a"):this.weightDataAnchor;e.download=this.weightDataFileName,e.href=n,await id((()=>e.dispatchEvent(new MouseEvent("click"))))}return{modelArtifactsInfo:Ha(e)}}}}od.URL_SCHEME="downloads://";class ld{constructor(e){if(null==e||e.length<1)throw new Error(`When calling browserFiles, at least 1 file is required, but received ${e}`);this.jsonFile=e[0],this.weightsFiles=e.slice(1)}async load(){return new Promise(((e,t)=>{const n=new FileReader;n.onload=n=>{const s=JSON.parse(n.target.result),r=s.modelTopology;if(null==r)return void t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));if(null==s.weightsManifest)return void t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));if(0===this.weightsFiles.length)return void e({modelTopology:r});const a=Ga(s,(e=>this.loadWeights(e)));e(a)},n.onerror=e=>t(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),n.readAsText(this.jsonFile)}))}loadWeights(e){const t=[],n=[];for(const s of e)t.push(...s.weights),n.push(...s.paths);const s=this.checkManifestAndWeightFiles(e),r=n.map((e=>this.loadWeightsFile(e,s[e])));return Promise.all(r).then((e=>[t,e]))}loadWeightsFile(e,t){return new Promise(((n,s)=>{const r=new FileReader;r.onload=e=>{const t=e.target.result;n(t)},r.onerror=t=>s(`Failed to weights data from file of path '${e}'.`),r.readAsArrayBuffer(t)}))}checkManifestAndWeightFiles(e){const t=[],n=this.weightsFiles.map((e=>Wa(e.name))),s={};for(const r of e)r.paths.forEach((e=>{const r=Wa(e);if(-1!==t.indexOf(r))throw new Error(`Duplicate file basename found in weights manifest: '${r}'`);if(t.push(r),-1===n.indexOf(r))throw new Error(`Weight file with basename '${r}' is not provided.`);s[e]=this.weightsFiles[n.indexOf(r)]}));if(t.length!==this.weightsFiles.length)throw new Error(`Mismatch in the number of files in weights manifest (${t.length}) and the number of weight files provided (${this.weightsFiles.length}).`);return s}}function ud(e,t,n,s){!function(e){c(null!=e&&Array.isArray(e)&&e.length>0,(()=>"promises must be a none empty array"))}(e),function(e,t){c(e>=0&&e<=1,(()=>`Progress fraction must be in range [0, 1], but got startFraction ${e}`)),c(t>=0&&t<=1,(()=>`Progress fraction must be in range [0, 1], but got endFraction ${t}`)),c(t>=e,(()=>`startFraction must be no more than endFraction, but got startFraction ${e} and endFraction ${t}`))}(n=null==n?0:n,s=null==s?1:s);let r=0;return Promise.all(e.map((a=>(a.then((a=>{const i=n+ ++r/e.length*(s-n);return t(i),a})),a))))}async function cd(e,t){null==t&&(t={});const n=null==t.fetchFunc?Y().platform.fetch:t.fetchFunc,s=e.map((e=>n(e,t.requestInit,{isBinary:!0}))),r=(null==t.onProgress?await Promise.all(s):await ud(s,t.onProgress,0,.5)).map((e=>e.arrayBuffer()));return null==t.onProgress?await Promise.all(r):await ud(r,t.onProgress,.5,1)}async function hd(e,t="",n,s){return pd((e=>cd(e,{requestInit:s})))(e,t,n)}function pd(e){return async(t,n="",s)=>{const r=t.map((()=>!1)),a={},i=null!=s?s.map((()=>!1)):[],o=[];if(t.forEach(((e,t)=>{let n=0;e.weights.forEach((e=>{const l="quantization"in e?e.quantization.dtype:e.dtype,u=ba[l]*d(e.shape),c=()=>{r[t]=!0,null==a[t]&&(a[t]=[]),a[t].push({manifestEntry:e,groupOffset:n,sizeBytes:u})};null!=s?s.forEach(((t,n)=>{t===e.name&&(c(),i[n]=!0)})):c(),o.push(e.name),n+=u}))})),!i.every((e=>e))){const e=s.filter(((e,t)=>!i[t]));throw new Error(`Could not find weights in manifest with names: ${e.join(", ")}. \nManifest JSON has weights with names: ${o.join(", ")}.`)}const l=r.reduce(((e,t,n)=>(t&&e.push(n),e)),[]),u=[];l.forEach((e=>{t[e].paths.forEach((e=>{const t=n+(n.endsWith("/")?"":"/")+e;u.push(t)}))}));const c=await e(u),h={};let p=0;return l.forEach((e=>{const n=t[e].paths.length,s=new xa(c.slice(p,p+n));a[e].forEach((e=>{const t=Ra(s.slice(e.groupOffset,e.groupOffset+e.sizeBytes),[e.manifestEntry]);for(const e in t)h[e]=t[e]})),p+=n})),h}}qa.registerSaveRouter((e=>Y().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(od.URL_SCHEME)?function(e="model"){return new od(e)}(e.slice(od.URL_SCHEME.length)):null));class dd{constructor(e,t){if(this.DEFAULT_METHOD="POST",null==t&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.weightUrlConverter=t.weightUrlConverter,null!=t.fetchFunc?(c("function"==typeof t.fetchFunc,(()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)")),this.fetch=t.fetchFunc):this.fetch=Y().platform.fetch,c(null!=e&&e.length>0,(()=>"URL path for http must not be null, undefined or empty.")),Array.isArray(e)&&c(2===e.length,(()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`)),this.path=e,null!=t.requestInit&&null!=t.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{},this.loadOptions=t}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");const t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;const n=Va(e,[{paths:["./model.weights.bin"],weights:e.weightSpecs}]);if(t.body.append("model.json",new Blob([JSON.stringify(n)],{type:"application/json"}),"model.json"),null!=e.weightData){const n=xa.join(e.weightData);t.body.append("model.weights.bin",new Blob([n],{type:"application/octet-stream"}),"model.weights.bin")}const s=await this.fetch(this.path,t);if(s.ok)return{modelArtifactsInfo:Ha(e),responses:[s]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${s.status}.`)}async loadModelJSON(){const e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch(e){let t=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?t+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":t+=" Please make sure the server is serving valid JSON for this request.",new Error(t)}const n=t.modelTopology,s=t.weightsManifest;if(null==n&&null==s)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return t}async load(){if(this.loadOptions.streamWeights)return this.loadStream();return Ga(await this.loadModelJSON(),(e=>this.loadWeights(e)))}async loadStream(){const e=await this.loadModelJSON(),t=await this.getWeightUrls(e.weightsManifest),n=ja(e.weightsManifest);return Object.assign(Object.assign({},e),{weightSpecs:n,getWeightStream:()=>function(e,t){var n;const s=null==t.fetchFunc?Y().platform.fetch:t.fetchFunc;let r,a=0;return null===(n=t.onProgress)||void 0===n||n.call(t,0),new ReadableStream({pull:async n=>{for(var i;a<e.length;){if(!r){const n=(await s(e[a],t.requestInit,{isBinary:!0})).body;r=n.getReader()}const{done:o,value:l}=await r.read();if(!o)return void n.enqueue(l);a++,r=void 0,null===(i=t.onProgress)||void 0===i||i.call(t,a/e.length)}n.close()}})}(t,this.loadOptions)})}async getWeightUrls(e){const t=Array.isArray(this.path)?this.path[1]:this.path,[n,s]=function(e){const t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),s=e.substring(0,t),r=n>t?e.substring(n):"";return[s+"/",r]}(t),r=this.weightPathPrefix||n,a=[],i=[];for(const t of e)for(const e of t.paths)null!=this.weightUrlConverter?i.push(this.weightUrlConverter(e)):a.push(r+e+s);return this.weightUrlConverter&&a.push(...await Promise.all(i)),a}async loadWeights(e){const t=await this.getWeightUrls(e);return[ja(e),await cd(t,this.loadOptions)]}}function fd(e){return null!=e.match(dd.URL_SCHEME_REGEX)}dd.URL_SCHEME_REGEX=/^https?:\/\//;const md=(e,t)=>{if("undefined"==typeof fetch&&(null==t||null==t.fetchFunc))return null;{let n=!0;if(n=Array.isArray(e)?e.every((e=>fd(e))):fd(e),n)return gd(e,t)}return null};function gd(e,t){return new dd(e,t)}function yd(e,t){return gd(e,t)}qa.registerSaveRouter(md),qa.registerLoadRouter(md);class bd{constructor(e){this.modelArtifacts=e}load(){return this.modelArtifacts}}class xd{constructor(e){this.saveHandler=e}save(e){return this.saveHandler(e)}}class wd{constructor(e){e.load&&(this.load=()=>Promise.resolve(e.load())),e.save&&(this.save=t=>Promise.resolve(e.save(t)))}}function vd(e,t,n,s){if(1===arguments.length){return null!=e.modelTopology||null!=e.weightSpecs?new bd(e):(console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new bd({modelTopology:e}))}return console.warn("Please call tf.io.fromMemory() with only one argument. The argument should be of type ModelArtifacts. The multi-argument signature of tf.io.fromMemory() has been deprecated and will be removed in a future release."),new bd({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:s})}var kd=Object.freeze({__proto__:null,CompositeArrayBuffer:xa,browserFiles:function(e){return new ld(e)},browserHTTPRequest:yd,concatenateArrayBuffers:Ba,copyModel:async function(e,t){return wi(e,t,!1)},decodeWeights:Ra,decodeWeightsStream:Ma,encodeWeights:Aa,fromMemory:function(e,t,n,s){const r=arguments;return new wd(vd(...r))},fromMemorySync:vd,getLoadHandlers:Xa,getModelArtifactsForJSON:Ga,getModelArtifactsForJSONSync:Ua,getModelArtifactsInfoForJSON:Ha,getSaveHandlers:Ka,getWeightSpecs:ja,http:gd,isHTTPScheme:fd,listModels:async function(){const e=bi.getSchemes(),t={};for(const n of e){const e=await bi.getManager(n).listModels();for(const s in e){t[n+yi+s]=e[s]}}return t},loadWeights:hd,moveModel:async function(e,t){return wi(e,t,!0)},registerLoadRouter:e=>qa.registerLoadRouter(e),registerSaveRouter:e=>qa.registerSaveRouter(e),removeModel:async function(e){const t=xi(e);return bi.getManager(t.scheme).removeModel(t.path)},weightsLoaderFactory:pd,withSaveHandler:function(e){return new xd(e)},withSaveHandlerSync:function(e){return new xd(e)}});const Nd=fa({confusionMatrix_:function(e,t,n){const s=ha(e,"labels","confusionMatrix"),r=ha(t,"predictions","confusionMatrix");c(null==n||n>0&&Number.isInteger(n),(()=>`If provided, numClasses must be a positive integer, but got ${n}`)),c(1===s.rank,(()=>`Expected the rank of labels to be 1, but got ${s.rank}`)),c(1===r.rank,(()=>`Expected the rank of predictions to be 1, but got ${r.rank}`)),c(s.shape[0]===r.shape[0],(()=>`Mismatch in the number of examples: ${s.shape[0]} vs. ${r.shape[0]}. Labels and predictions should have the same number of elements.`)),c(n>0&&Number.isInteger(n),(()=>`numClasses is required to be a positive integer, but got ${n}`));const a=Nu(Ti(s,"int32"),n),i=Nu(Ti(r,"int32"),n),o=vh(a),l=ho(o,i);return Ti(l,"int32")}});var Id=Object.freeze({__proto__:null,confusionMatrix:Nd});let Sd,Td=!1;function Cd(e,t=3){if(t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(null==e)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let n=!1,s=!1,r=!1,a=!1,i=!1,o=!1;if(e.data instanceof Uint8Array)n=!0;else if("undefined"!=typeof ImageData&&e instanceof ImageData)s=!0;else if("undefined"!=typeof HTMLVideoElement&&e instanceof HTMLVideoElement)r=!0;else if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement)a=!0;else if(null!=e.getContext)i=!0;else{if(!("undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap))throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${e.constructor.name}`);o=!0}if(null!=ys(us,ta.backendName)){const n={pixels:e},s={numChannels:t};return ta.runKernel(us,n,s)}const[l,u]=r?[e.videoWidth,e.videoHeight]:[e.width,e.height];let c,h;if(i)c=e.getContext("2d").getImageData(0,0,l,u).data;else if(s||n)c=e.data;else if(a||r||o){if(null==Sd)if("undefined"==typeof document){if("undefined"==typeof OffscreenCanvas||"undefined"==typeof OffscreenCanvasRenderingContext2D)throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");Sd=new OffscreenCanvas(1,1).getContext("2d")}else Sd=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});Sd.canvas.width=l,Sd.canvas.height=u,Sd.drawImage(e,0,0,l,u),c=Sd.getImageData(0,0,l,u).data}if(4===t)h=new Int32Array(c);else{const e=l*u;h=new Int32Array(e*t);for(let n=0;n<e;n++)for(let e=0;e<t;++e)h[n*t+e]=c[4*n+e]}return nh(h,[u,l,t],"int32")}function $d(e){return"undefined"!=typeof window&&"undefined"!=typeof ImageBitmap&&window.hasOwnProperty("createImageBitmap")&&!(e instanceof ImageBitmap)&&function(e){return null!=e&&0!==e.width&&0!==e.height}(e)&&!function(e){return null!=e&&e.data instanceof Uint8Array}(e)}function Ed(e){if(2!==e.rank&&3!==e.rank)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${e.rank}.`);const t=2===e.rank?1:e.shape[2];if(t>4||2===t)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${t}`);if("float32"!==e.dtype&&"int32"!==e.dtype)throw new Error(`Unsupported type for toPixels: ${e.dtype}. Please use float32 or int32 tensors.`)}const Ad=fa({fromPixels_:Cd});var Rd=Object.freeze({__proto__:null,draw:function(e,t,n){let s=ha(e,"img","draw");if(!(e instanceof _r)){const e=s;s=Ti(e,"int32"),e.dispose()}Ed(s),function(e){const t=(null==e?void 0:e.alpha)||1;if(t>1||t<0)throw new Error(`Alpha value ${t} is suppoed to be in range [0 - 1].`)}(null==n?void 0:n.imageOptions);const r={image:s},a={canvas:t,options:n};ta.runKernel(Ye,r,a)},fromPixels:Ad,fromPixelsAsync:async function(e,t=3){let n=null;if(Y().getBool("WRAP_TO_IMAGEBITMAP")&&$d(e)){let t;try{t=await createImageBitmap(e,{premultiplyAlpha:"none"})}catch(e){t=null}n=null!=t&&t.width===e.width&&t.height===e.height?t:e}else n=e;return Cd(n,t)},toPixels:async function(e,t){let n=ha(e,"img","toPixels");if(!(e instanceof _r)){const e=n;n=Ti(e,"int32"),e.dispose()}Ed(n);const[s,r]=n.shape.slice(0,2),a=2===n.rank?1:n.shape[2],i=await n.data(),o="float32"===n.dtype?255:1,l=new Uint8ClampedArray(r*s*4);for(let e=0;e<s*r;++e){const t=[0,0,0,255];for(let s=0;s<a;s++){const r=i[e*a+s];if("float32"===n.dtype){if(r<0||r>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${r}.`)}else if("int32"===n.dtype&&(r<0||r>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${r}.`);1===a?(t[0]=r*o,t[1]=r*o,t[2]=r*o):t[s]=r*o}const s=4*e;l[s+0]=Math.round(t[0]),l[s+1]=Math.round(t[1]),l[s+2]=Math.round(t[2]),l[s+3]=Math.round(t[3])}if(null!=t){if(!Td){null!=ys(Ye,ta.backendName)&&(console.warn("tf.browser.toPixels is not efficient to draw tensor on canvas. Please try tf.browser.draw instead."),Td=!0)}t.width=r,t.height=s;const e=t.getContext("2d"),n=new ImageData(l,r,s);e.putImageData(n,0,0)}return n!==e&&n.dispose(),l}});function _d(e,t){const n=e.shape.length,s=t.shape.length;if(n<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${n}.`);if(s<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${s}.`);if("int32"!==t.dtype)throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[s-1]>n)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[s-1]} vs. ${n}`);if(0===d(e.shape))throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);const r=t.shape,a=r[r.length-1];let i=1;for(let e=0;e<r.length-1;++e)i*=r[e];const o=e.shape,l=r.slice();l.pop();let u=1;for(let e=a;e<n;++e)u*=o[e],l.push(o[e]);const c=[...M(e.shape).map((e=>e/u)),1].slice(0,a);return[l,i,u,c]}var Fd=Object.freeze({__proto__:null,prepareAndValidate:_d});function Dd(e,t,n){const s=e.shape.length;c(s===t.length,(()=>`Error in slice${s}D: Length of begin ${t} must match the rank of the array (${s}).`)),c(s===n.length,(()=>`Error in slice${s}D: Length of size ${n} must match the rank of the array (${s}).`));for(let r=0;r<s;++r)c(t[r]+n[r]<=e.shape[r],(()=>`Error in slice${s}D: begin[${r}] + size[${r}] (${t[r]+n[r]}) would overflow input.shape[${r}] (${e.shape[r]})`))}function Od(e,t,n){const s=[];for(let r=0;r<e.length;r++)s[r]=Math.ceil((t[r]-e[r])/n[r]);return s}function Md(e,t,n,s){const r=[...e];for(let e=r.length;e<s.length;e++)r.push(1);for(let e=0;e<n;e++)0===e?r[t]=1:(r.splice(t,0,1),r.pop());return r}function Ld(e,t,n){return n<=e?n:n-(t-1)}function zd(e,t){const n=[];for(let s=0;s<e;s++)n.push(t+s);return n}function Pd(e,t,n,s,r){const a=[...r],i=zd(n,t);for(let r=0;r<a.length;r++)if(i.indexOf(r)>-1)a[r]=0;else{const i=Ld(t,n,r);let o=s[i];e&1<<i&&(o=0),a[r]=o}return a}function Bd(e,t,n,s,r){const a=[...r],o=zd(n,t);for(let r=0;r<a.length;r++)if(o.indexOf(r)>-1)a[r]=Number.MAX_SAFE_INTEGER;else{const i=Ld(t,n,r);let o=s[i];e&1<<i&&(o=Number.MAX_SAFE_INTEGER),a[r]=o}for(let e=0;e<a.length;e++){const t=r[e];a[e]<0&&(a[e]+=t),a[e]=i(0,a[e],r[e])}return a}function Wd(e,t,n){let s=e[t];return(n&1<<t||null==s)&&(s=1),s}function Vd(e,t,n,s,r,a){let o=t[r];const l=n[r]||1;(e&1<<r||a&1<<r||null==o)&&(o=l>0?Number.MIN_SAFE_INTEGER:Number.MAX_SAFE_INTEGER);const u=s[r];return o<0&&(o+=u),o=i(0,o,u-1),o}function Ud(e,t,n,s,r,a){let o=t[r];const l=n[r]||1;(e&1<<r||a&1<<r||null==o)&&(o=l>0?Number.MAX_SAFE_INTEGER:Number.MIN_SAFE_INTEGER);const u=s[r];return o<0&&(o+=u),o=l>0?i(0,o,u):i(-1,o,u-1),o}function Gd(e,t,n){let s=n.length;for(let e=0;e<n.length;e++)if(n[e]>1){s=e;break}for(let r=s+1;r<n.length;r++)if(t[r]>0||n[r]!==e[r])return!1;return!0}function Hd(e,t){let n=e.length>0?e[e.length-1]:1;for(let s=0;s<e.length-1;s++)n+=e[s]*t[s];return n}function jd(e,t,n){let s;const r=e.shape.length;let a;return s="number"==typeof t?[t,...new Array(r-1).fill(0)]:t.length<r?t.concat(new Array(r-t.length).fill(0)):t.slice(),s.forEach((e=>{c(-1!==e,(()=>"slice() does not support negative begin indexing."))})),a=null==n?new Array(r).fill(-1):"number"==typeof n?[n,...new Array(r-1).fill(-1)]:n.length<r?n.concat(new Array(r-n.length).fill(-1)):n,a=a.map(((t,n)=>t>=0?t:(c(-1===t,(()=>`Negative size values should be exactly -1 but got ${t} for the slice() size at index ${n}.`)),e.shape[n]-s[n]))),[s,a]}function qd(e,t,n,s,r,a,i,o,l){let u;if(null==s?(u=new Array(t.length),u.fill(1)):u=s,null!=i&&0!=(i&i-1))throw new Error("Multiple ellipses in slice is not allowed.");let c=!1;const h={dims:u.length,numAddAxisAfterEllipsis:0,begin:t.slice(),end:n.slice(),strides:u.slice(),beginMask:r,endMask:a,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};for(let e=0;e<h.dims;e++)c&&0!=(1<<e&o)&&h.numAddAxisAfterEllipsis++,1<<e&i&&(c=!0);c||(h.ellipsisMask|=1<<h.dims,h.dims++);const p={dims:e.length,beginMask:0,endMask:0,beginValid:!1,endValid:!1};!function(e,t){t.beginMask=0,t.endMask=0,t.shrinkAxisMask=0;let n=0;t.beginValid=null!=e.begin,t.endValid=null!=e.end,t.begin=new Array(t.dims),t.end=new Array(t.dims),t.strides=new Array(t.dims),t.finalShapeGatherIndices=[],t.finalShapeGatherIndicesSparse=[],t.inputShapeGatherIndicesSparse=new Array(t.dims);for(let s=0;s<e.dims;s++)if(1<<s&e.ellipsisMask){const r=Math.min(t.dims-(e.dims-s)+1+e.numAddAxisAfterEllipsis,t.dims);for(;n<r;n++)t.begin[n]=0,t.end[n]=0,t.strides[n]=1,t.beginMask|=1<<n,t.endMask|=1<<n,t.finalShapeGatherIndices.push(n),t.finalShapeGatherIndicesSparse.push(-1),t.inputShapeGatherIndicesSparse[n]=s}else if(1<<s&e.newAxisMask)t.finalShapeGatherIndices.push(-2),t.finalShapeGatherIndicesSparse.push(-1);else{if(n===t.begin.length)throw Error(`Index out of range using input dim ${n}; input has only ${t.dims} dims, ${t.begin.length}.`);null!=e.begin&&(t.begin[n]=e.begin[s]),null!=e.end&&(t.end[n]=e.end[s]),t.strides[n]=e.strides[s],e.beginMask&1<<s&&(t.beginMask|=1<<n),e.endMask&1<<s&&(t.endMask|=1<<n),e.shrinkAxisMask&1<<s?(t.finalShapeGatherIndices.push(-1),t.finalShapeGatherIndicesSparse.push(-1),t.shrinkAxisMask|=1<<n):(t.finalShapeGatherIndices.push(n),t.finalShapeGatherIndicesSparse.push(s)),t.inputShapeGatherIndicesSparse[n]=s,n++}}(h,p);let d=!0,f=!0,m=!0;const g=[],y=[];for(let t=0;t<e.length;++t){if(0===p.strides[t])throw Error(`strides[${t}] must be non-zero`);const n=!!(p.shrinkAxisMask&1<<t),s=e[t];if(-1===s){g.push(n?1:-1);continue}const r=[p.beginMask&1<<t,p.endMask&1<<t],a=[p.strides[t]>0?0:-1,p.strides[t]>0?s:s-1];if(n&&p.strides[t]<=0)throw Error("only stride 1 allowed on non-range indexing.");m=m&&1===p.strides[t];const i=!!(p.beginMask&1<<t&&p.endMask&1<<t);if(p.beginValid&&p.endValid){if(n){const e=p.begin[t]<0?s+p.begin[t]:p.begin[t];if(p.begin[t]=e,p.end[t]=p.begin[t]+1,e<0||e>=s)throw Error(`slice index ${p.begin[t]} of dimension ${t} out of bounds.`)}else p.begin[t]=Kd(p.begin[t],0,p.strides[t],s,r,a),p.end[t]=Kd(p.end[t],1,p.strides[t],s,r,a);const e=1===p.strides[t]&&0===p.begin[t]&&p.end[t]===s;d=d&&e,f=f&&(0===t&&1===p.strides[t]||e)}else d=d&&1===p.strides[t]&&i,f=f&&(0===t&&1===p.strides[t]||i);let o,l=!1;if(p.beginValid&&p.endValid?(o=p.end[t]-p.begin[t],l=!0):n?(o=1,l=!0):i&&s>=0&&(o=p.strides[t]<0?-s:s,l=!0),l){let e;e=0===o||o<0!=p.strides[t]<0?0:Math.trunc(o/p.strides[t])+(o%p.strides[t]!=0?1:0),g.push(e)}else g.push(-1)}for(let e=0;e<p.finalShapeGatherIndices.length;++e){const t=p.finalShapeGatherIndices[e];t>=0?y.push(g[t]):-2===t&&y.push(1)}return{finalShapeSparse:y.filter(((e,t)=>-2!==p.finalShapeGatherIndices[t])),finalShape:y,isIdentity:d,sliceDim0:f,isSimpleSlice:m,begin:p.begin,end:p.end,strides:p.strides}}function Kd(e,t,n,s,r,a){if(r[t])return n>0?a[t]:a[t+1&1];{const t=e<0?s+e:e;return t<a[0]?a[0]:t>a[1]?a[1]:t}}var Xd=Object.freeze({__proto__:null,assertParamsValid:Dd,computeFlatOffset:Hd,computeOutShape:Od,getNormalizedAxes:function(e,t,n,s,r,a,i,o,l){const u=e.length;let c=new Array(u),h=new Array(u),p=new Array(u);if(t.length&&n>0){const l=t[0],u=n+1;c=Pd(i,l,u,s,e),h=Bd(o,l,u,r,e),p=Md(a,l,u,e)}else for(let t=0;t<u;t++)c[t]=Vd(i,s,a,e,t,l),h[t]=Ud(o,r,a,e,t,l),p[t]=Wd(a,t,l);return{begin:c,end:h,strides:p}},isSliceContinous:Gd,maskToAxes:function(e){const t=[];let n=0;for(;e>0;)1&e&&t.push(n),e/=2,n++;return t},parseSliceParams:jd,sliceInfo:qd,startForAxis:Vd,startIndicesWithElidedDims:Pd,stopForAxis:Ud,stopIndicesWithElidedDims:Bd,stridesForAxis:Wd,stridesWithElidedDims:Md});const Yd="4.15.0";class Zd{static sgd(e){return new nd(e)}static momentum(e,t,n=!1){return new sd(e,t,n)}static rmsprop(e,t=.9,n=0,s=null,r=!1){return new rd(e,t,n,s,r)}static adam(e=.001,t=.9,n=.999,s=null){return new ed(e,t,n,s)}static adadelta(e=.001,t=.95,n=null){return new Jp(e,t,n)}static adamax(e=.002,t=.9,n=.999,s=null,r=0){return new td(e,t,n,s,r)}static adagrad(e,t=.1){return new Qp(e,t)}}const Jd=Zd,Qd="undefined"!=typeof requestAnimationFrame?requestAnimationFrame:"undefined"!=typeof setImmediate?setImmediate:e=>e();function ef(){return new Promise((e=>Qd((()=>e()))))}function tf(e,t){const n=e[0].length;e.forEach(((e,t)=>{c(e.length===n,(()=>`Error in concat${n}D: rank of tensors[${t}] must be the same as the rank of the rest (${n})`))})),c(t>=0&&t<n,(()=>`Error in concat${n}D: axis must be between 0 and ${n-1}.`));const s=e[0];e.forEach(((e,r)=>{for(let a=0;a<n;a++)c(a===t||e[a]===s[a],(()=>`Error in concat${n}D: Shape of tensors[${r}] (${e}) does not match the shape of the rest (${s}) along the non-concatenated axis ${r}.`))}))}function nf(e,t){const n=e[0].slice();for(let s=1;s<e.length;s++)n[t]+=e[s][t];return n}var sf;function rf(e,t,n){let s=new Array;if(null==n&&null==t)return s;if(null==t)for(;s.length<e+n.length;)s.push(-1);else s=t.slice();if(null==n)return s;if(e+n.length!==s.length)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.rank = ${e+n.length}, but shape.rank = ${s.length}`);for(let r=1;r<n.length;++r){const a=n[r],i=s[s.length-n.length+r],o=s[i];if(a>=0)if(o>=0){if(o!==a)throw new Error(`rt input.shape and shape=${t} are incompatible: rt input.shape[${r+e}] = ${a} but shape[${r+e}] = ${o}`)}else s[i]=a}return s}function af(e){const t={FIRST_DIM_SIZE:sf.FIRST_DIM_SIZE,VALUE_ROWIDS:sf.VALUE_ROWIDS,ROW_LENGTHS:sf.ROW_LENGTHS,ROW_SPLITS:sf.ROW_SPLITS,ROW_LIMITS:sf.ROW_LIMITS,ROW_STARTS:sf.ROW_STARTS},n=[];for(const s of e){if(!(s in t))break;n.push(t[s])}return n}function of(e){return 0===e.length?0:e[0]===sf.FIRST_DIM_SIZE?e.length-1:e.length}function lf(e,t){if(null==e||null==t)return;const n=e.length,s=t.length;if(n>=s)throw new Error(`defaultValue.shape=${e} and ragged tensor flatValues.shape=${t}, are incompatible: defaultValue.rank = ${n} must be less than ragged tensor input flatValues.rank = ${s})`);for(let r=0;r<Math.min(n,s-1);++r){const n=e[r],s=t[r+1];if(n>=0&&s>=0&&1!==n&&n!==s)throw new Error(`defaultValue.shape=${e}, and ragged tensor input flatValues.shape=${t} are incompatible: defaultValue.shape[${r-e.length}] = ${n} but ragged tensor input.flatValues.shape[${r-e.length}] = ${s}`)}}!function(e){e[e.FIRST_DIM_SIZE=0]="FIRST_DIM_SIZE",e[e.VALUE_ROWIDS=1]="VALUE_ROWIDS",e[e.ROW_LENGTHS=2]="ROW_LENGTHS",e[e.ROW_SPLITS=3]="ROW_SPLITS",e[e.ROW_LIMITS=4]="ROW_LIMITS",e[e.ROW_STARTS=5]="ROW_STARTS"}(sf||(sf={}));function uf(e){return e<=30?e:O(e,Math.floor(Math.sqrt(e)))}function cf(e,t,n){return[n*("number"==typeof e?e:e[0]),t*("number"==typeof e?e:e[1])]}function hf(e,t,n,s=!0){let r=[];if(s)r=r.concat(t.slice(0)),r.push(e[0]/n),r=r.concat(e.slice(1));else{r=r.concat(e[0]);const n=t.length;for(let s=0;s<n;++s)r=r.concat([e[s+1]/t[s],t[s]]);r=r.concat(e.slice(n+1))}return r}function pf(e,t,n=!0){const s=[];if(n){s.push(t);for(let n=t+1;n<e;++n)n<=2*t?(s.push(n),s.push(n-(t+1))):s.push(n)}else{const n=[],r=[];for(let s=1;s<e;++s)s>=2*t+1||s%2==1?r.push(s):n.push(s);s.push(...n),s.push(0),s.push(...r)}return s}function df(e,t,n,s=!0){const r=[];s?r.push(e[0]/n):r.push(e[0]*n);for(let n=1;n<e.length;++n)n<=t.length?s?r.push(t[n-1]*e[n]):r.push(e[n]/t[n-1]):r.push(e[n]);return r}function ff(e,t){const n=[0];for(let s=0;s<t;++s)n.push(e[s][0]);return n}function mf(e,t,n){const s=e.slice(0,1);for(let r=0;r<n;++r)s.push(e[r+1]-t[r][0]-t[r][1]);return s}const gf=1.7580993408473768,yf=1.0507009873554805,bf=.3275911,xf=.254829592,wf=-.284496736,vf=1.421413741,kf=-1.453152027,Nf=1.061405429;function If(e,t){if(e.length!==t.length)throw new Error(`Cannot merge real and imag arrays of different lengths. real:${e.length}, imag: ${t.length}.`);const n=new Float32Array(2*e.length);for(let s=0;s<n.length;s+=2)n[s]=e[s/2],n[s+1]=t[s/2];return n}function Sf(e){const t=new Float32Array(e.length/2),n=new Float32Array(e.length/2);for(let s=0;s<e.length;s+=2)t[s/2]=e[s],n[s/2]=e[s+1];return{real:t,imag:n}}function Tf(e){const t=Math.ceil(e.length/4),n=new Float32Array(t),s=new Float32Array(t);for(let t=0;t<e.length;t+=4)n[Math.floor(t/4)]=e[t],s[Math.floor(t/4)]=e[t+1];return{real:n,imag:s}}function Cf(e){const t=Math.floor(e.length/4),n=new Float32Array(t),s=new Float32Array(t);for(let t=2;t<e.length;t+=4)n[Math.floor(t/4)]=e[t],s[Math.floor(t/4)]=e[t+1];return{real:n,imag:s}}function $f(e,t){return{real:e[2*t],imag:e[2*t+1]}}function Ef(e,t,n,s){e[2*s]=t,e[2*s+1]=n}function Af(e,t){const n=new Float32Array(e/2),s=new Float32Array(e/2);for(let r=0;r<Math.ceil(e/2);r++){const a=(t?2:-2)*Math.PI*(r/e);n[r]=Math.cos(a),s[r]=Math.sin(a)}return{real:n,imag:s}}function Rf(e,t,n){const s=(n?2:-2)*Math.PI*(e/t);return{real:Math.cos(s),imag:Math.sin(s)}}const _f="->",Ff=/->/g;function Df(e,t){const n=((e=e.replace(/\s/g,"")).length-e.replace(Ff,"").length)/_f.length;if(n<1)throw new Error("Equations without an arrow are not supported.");if(n>1)throw new Error('Equation must contain exactly one arrow ("->").');const[s,r]=e.split(_f);c(-1===s.indexOf("..."),(()=>'The ellipsis notation ("...") is not supported yet.'));const a=s.split(","),i=a.length;if(t!==i)throw new Error(`Expected ${i} input tensors, received ${t}`);if(i>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");const o=[];for(let e=0;e<r.length;++e){const t=r[e];if(!a.some((e=>-1!==e.indexOf(t))))throw new Error(`Output subscripts contain the label ${t} not present in the input subscripts.`);-1===o.indexOf(t)&&o.push(t)}for(let e=0;e<s.length;++e){const t=s[e];-1===o.indexOf(t)&&","!==t&&o.push(t)}const l=new Array(a.length);for(let e=0;e<i;++e){if(new Set(a[e].split("")).size!==a[e].length)throw new Error(`Found duplicate axes in input component ${a[e]}. Support for duplicate axes in input is not implemented yet.`);l[e]=[];for(let t=0;t<a[e].length;++t)l[e].push(o.indexOf(a[e][t]))}const u=o.length,h=[];for(let e=r.length;e<u;++e)h.push(e);return{allDims:o,summedDims:h,idDims:l}}function Of(e,t){let n=new Array(e);n.fill(-1);for(let e=0;e<t.length;++e)n[t[e]]=e;const s=[];for(let t=0;t<e;++t)-1===n[t]&&s.push(t);return n=n.filter((e=>-1!==e)),{permutationIndices:n,expandDims:s}}function Mf(e,t,n){const s=new Array(e);for(let e=0;e<n.length;++e){const r=n[e].shape;for(let n=0;n<t[e].length;++n)void 0===s[t[e][n]]?s[t[e][n]]=r[n]:c(s[t[e][n]]===r[n],(()=>`Expected dimension ${s[t[e][n]]} at axis ${n} of input shaped ${JSON.stringify(r)}, but got dimension ${r[n]}`))}}function Lf(e,t){const n=e,s=[];let r=0;0===e.length&&n.push(-1),r=e.length+1;for(let e=0;e<r;++e)s.push([]);const a=[];for(let e=0;e<n.length;++e){const r=Pf(t,n[e]);for(const t of r)-1===a.indexOf(t)&&(s[e].push(t),a.push(t))}return{path:n,steps:s}}function zf(e){return e.every(((e,t)=>e===t))}function Pf(e,t){const n=[];for(let s=0;s<e.length;++s)0!==e[s].length&&-1===e[s].indexOf(t)&&-1!==t||n.push(s);return n}function Bf(e,t,n=0){let s=[];if("number"==typeof t)c(e.shape[n]%t==0,(()=>"Number of splits must evenly divide the axis.")),s=new Array(t).fill(e.shape[n]/t);else{const r=t.reduce(((e,t)=>(-1===t&&(e+=1),e)),0);c(r<=1,(()=>"There should be only one negative value in split array."));const a=t.indexOf(-1);if(-1!==a){const s=t.reduce(((e,t)=>t>0?e+t:e));t[a]=e.shape[n]-s}c(e.shape[n]===t.reduce(((e,t)=>e+t)),(()=>"The sum of sizes must match the size of the axis dimension.")),s=t}return s}function Wf(e){return`Received SparseTensor with denseShape[0] = 0 but\n  indices.shape[0] = ${e}`}function Vf(e,t){return`indices(${e}, 0) is invalid: ${t} < 0`}function Uf(e,t,n){return`indices(${e}, 0) is invalid: ${t} >= ${n}`}function Gf(e,t){return`only one output dimension may be -1, not both ${e} and ${t}`}function Hf(e,t){return`size ${e} must be non-negative, not ${t}`}function jf(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function qf(e,t){return`Input to reshape is a SparseTensor with ${d(e)}\n  dense values, but the requested shape requires a multiple of ${d(t)}. inputShape=${e} outputShape= ${t}`}function Kf(e,t){return`Input to reshape is a tensor with ${d(e)} dense values, but the requested shape has ${d(t)}. inputShape=${e} outputShape=${t}`}function Xf(){return"segment ids must be >= 0"}function Yf(){return"segment ids are not increasing"}function Zf(e,t){return`Segment id ${e} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function Jf(e,t,n){return`Bad: indices[${e}] == ${t} out of range [0, ${n})`}function Qf(e,t){let n,s=!1;for(e<=30?(n=e,s=!0):n=O(e,Math.floor(Math.sqrt(e)));!s;)n>t||n===e?s=!0:n=O(e,n+1);return n}function em(e,t,n){const s=[],r=e.length;for(let a=0;a<r;a++)a!==t?s.push(e[a]):s.push(n);return s}function tm(e,t,n,s){const r=t.shape.length,a=e.shape.length;if(0!==s&&(s<-r||s>r))throw new Error(`Expect batchDims in the range of [-${r}, ${r}], but got ${s}`);if(s<0&&(s+=r),s>a)throw new Error(`batchDims (${s}) must be less than rank(x) (\n    ${a}).`);if(n<s)throw new Error(`batchDims (${s}) must be less than or equal to axis (${n}).`);for(let n=0;n<s;++n)if(e.shape[n]!==t.shape[n])throw new Error(`x.shape[${n}]: ${e.shape[n]} should be equal to indices.shape[${n}]: ${t.shape[n]}.`);const i=e.shape[n],o=[];let l=1,u=1,c=1;for(let t=0;t<s;++t)o.push(e.shape[t]),l*=e.shape[t];for(let t=s;t<n;t++)o.push(e.shape[t]),u*=e.shape[t];for(let e=s;e<r;e++)o.push(t.shape[e]);for(let t=n+1;t<a;t++)o.push(e.shape[t]),c*=e.shape[t];return{batchSize:l,sliceSize:c,outerSize:u,dimSize:i,outputShape:o}}var nm=Object.freeze({__proto__:null,collectGatherOpShapeInfo:tm,computeOutShape:em,segOpComputeOptimalWindowSize:Qf});function sm(e){try{return e.map((e=>gr(e)))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}}function rm(e){return e.map((e=>mr(e)))}var am=Object.freeze({__proto__:null,ERF_A1:xf,ERF_A2:wf,ERF_A3:vf,ERF_A4:kf,ERF_A5:Nf,ERF_P:bf,PARALLELIZE_THRESHOLD:30,get RowPartitionType(){return sf},SELU_SCALE:yf,SELU_SCALEALPHA:gf,applyActivation:Fh,assertAndGetBroadcastShape:Zo,assertAxesAreInnerMostDims:pl,assertParamsConsistent:tf,assignToTypedArray:Ef,axesAreInnerMostDims:ll,calculateShapes:lh,checkEinsumDimSizes:Mf,checkPadOnDimRoundingMode:io,combineLocations:ul,combineRaggedTensorToTensorShapes:rf,complexWithEvenIndex:Tf,complexWithOddIndex:Cf,computeConv2DInfo:Xi,computeConv3DInfo:Yi,computeDefaultPad:Zi,computeDilation2DInfo:ji,computeOptimalWindowSize:uf,computeOutAndReduceShapes:cl,computeOutShape:nf,computePool2DInfo:qi,computePool3DInfo:Ki,convertConv2DDataFormat:ao,decodeEinsumEquation:Df,eitherStridesOrDilationsAreOne:so,expandShapeToKeepDim:hl,exponent:Rf,exponents:Af,fromStringArrayToUint8:rm,fromUint8ToStringArray:sm,getAxesPermutation:dl,getBroadcastDims:Xo,getComplexWithIndex:$f,getEinsumComputePath:Lf,getEinsumPermutation:Of,getFusedBiasGradient:_h,getFusedDyActivation:Rh,getImageCenter:cf,getInnerMostAxes:ml,getPermuted:pf,getRaggedRank:of,getReductionAxes:Yo,getReshaped:hf,getReshapedPermuted:df,getRowPartitionTypesHelper:af,getSliceBeginCoords:ff,getSliceSize:mf,getSparseFillEmptyRowsIndicesDenseShapeMismatch:Wf,getSparseFillEmptyRowsNegativeIndexErrorMessage:Vf,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:Uf,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:jf,getSparseReshapeInputOutputMismatchErrorMessage:Kf,getSparseReshapeInputOutputMultipleErrorMessage:qf,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:Gf,getSparseReshapeNegativeOutputDimErrorMessage:Hf,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:Jf,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:Xf,getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:Yf,getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:Zf,getUndoAxesPermutation:fl,isIdentityPermutation:zf,log:function(...e){Y().getBool("IS_TEST")||Y().getBool("PROD")||console.log(...e)},mergeRealAndImagArrays:If,prepareAndValidate:_d,prepareSplitSize:Bf,segment_util:nm,shouldFuse:Dh,slice_util:Xd,splitRealAndImagArrays:Sf,stridesOrDilationsArePositive:ro,tupleValuesAreOne:no,upcastType:Wr,validateDefaultValueShape:lf,validateInput:oh,validateUpdateShape:ih,warn:fs}),im=Object.freeze({__proto__:null,nonMaxSuppressionV3Impl:ep,nonMaxSuppressionV4Impl:tp,nonMaxSuppressionV5Impl:np,whereImpl:bh});!function(){for(const e of ad)Xp(e)}();const om={kernelName:ee,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_i(e,Zc(Ti(n,"float32"),-1))}}},lm={kernelName:te,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=vl(Ti(n,"float32")),s=wl(Jl(xl(1),t));return Xl(Ri(e,s))}}}},um={kernelName:ne,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=wl(Jl(vl(Ti(n,"float32")),1));return Ri(e,t)}}}},cm={kernelName:se,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=Zo(n.shape,s.shape);return{a:()=>{let t=e;const s=Yo(n.shape,r);return s.length>0&&(t=kl(t,s)),oo(t,n.shape)},b:()=>{let t=e;const n=Yo(s.shape,r);return n.length>0&&(t=kl(t,n)),oo(t,s.shape)}}}},hm={kernelName:re,saveAllInputs:!0,gradFunc:(e,t)=>{const n={};return t.forEach(((t,s)=>{n[s]=()=>e.clone()})),n}},pm={kernelName:oe,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>tl(n)}}},dm={kernelName:le,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>tl(n)}}},fm={kernelName:ue,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ri(e,wl(Jl(xl(1),vl(Ti(n,"float32")))))}}},mm={kernelName:ce,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=wl(Ei(xl(1),vl(Ti(n,"float32"))));return Ri(e,t)}}}},gm={kernelName:de,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=Zo(n.shape,s.shape);return{a:()=>{const t=Ei(vl(n),vl(s));let a=_i(e,Ri(s,t));const i=Yo(n.shape,r);return i.length>0&&(a=kl(a,i)),oo(a,n.shape)},b:()=>{const t=Ei(vl(n),vl(s));let a=Xl(_i(e,Ri(n,t)));const i=Yo(s.shape,r);return i.length>0&&(a=kl(a,i)),oo(a,s.shape)}}}},ym={kernelName:he,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ri(e,Ei(vl(Ti(n,"float32")),1))}}},bm={kernelName:pe,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ri(e,Jl(xl(1),vl(Ti(n,"float32"))))}}};const xm=fa({avgPool3dGrad_:function(e,t,n,s,r,a){const i=ha(e,"dy","avgPool3dGrad"),o=ha(t,"input","avgPool3dGrad");let l=i,u=o,h=!1;4===o.rank&&(h=!0,l=oo(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),u=oo(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),c(5===l.rank,(()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`)),c(5===u.rank,(()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${u.rank}.`)),io("avgPool3dGrad",r,a);const p={dy:l,input:u},d={filterSize:n,strides:s,pad:r,dimRoundingMode:a},f=ta.runKernel(ye,p,d);return h?oo(f,[f.shape[1],f.shape[2],f.shape[3],f.shape[4]]):f}}),wm={kernelName:ge,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{filterSize:r,strides:a,pad:i,dimRoundingMode:o}=n;return{x:()=>xm(e,s,r,a,i,o)}}};const vm=fa({avgPoolGrad_:function(e,t,n,s,r){const a=ha(e,"dy","avgPoolGrad"),i=ha(t,"input","avgPoolGrad");c(i.rank===a.rank,(()=>`Rank of input (${i.rank}) does not match rank of dy (${a.rank})`));let o=i,l=a,u=!1;3===i.rank&&(u=!0,o=oo(i,[1,i.shape[0],i.shape[1],i.shape[2]]),l=oo(a,[1,a.shape[0],a.shape[1],a.shape[2]])),c(4===l.rank,(()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`)),c(4===o.rank,(()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${o.rank}.`));const h={dy:l,input:o},p={filterSize:n,strides:s,pad:r},d=ta.runKernel(me,h,p);return u?oo(d,[d.shape[1],d.shape[2],d.shape[3]]):d}}),km={kernelName:fe,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{filterSize:r,strides:a,pad:i}=n;return{x:()=>vm(e,s,r,a,i)}}},Nm={kernelName:be,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{const[s,r]=t,{transposeA:a,transposeB:i}=n;return a||i?!a&&i?{a:()=>ho(e,r,!1,!1),b:()=>ho(e,s,!0,!1)}:a&&!i?{a:()=>ho(r,e,!1,!0),b:()=>ho(s,e,!1,!1)}:{a:()=>ho(r,e,!0,!0),b:()=>ho(e,s,!0,!0)}:{a:()=>ho(e,r,!1,!0),b:()=>ho(s,e,!0,!1)}}},Im={kernelName:xe,gradFunc:(e,t,n)=>{const{blockShape:s,crops:r}=n;return{x:()=>Ru(e,s,r)}}},Sm={kernelName:ke,gradFunc:(e,t,n)=>{const s=n,r=s.inputShape,a=s.shape,i=Array.from(a);for(let e=r.length-1;e>=0;e--)if(r[e]===a[e])i[e]=1;else if(1!==r[e])throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${a}].`);const o=[];for(let e=0;e<i.length;e++)i[e]>1&&o.push(e);return{x:()=>kl(e,o,!0)}}},Tm={kernelName:Ie,gradFunc:e=>({x:()=>e.clone()})},Cm={kernelName:Se,gradFunc:e=>({x:()=>tl(e)})},$m={kernelName:Te,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{clipValueMin:r,clipValueMax:a}=n;return{x:()=>el(tu(Dl(s,r),Wl(s,a)),e,tl(e))}}},Em={kernelName:$e,inputsToSave:["x"],gradFunc:om.gradFunc},Am={kernelName:Ee,saveAllInputs:!0,gradFunc:(e,t,n)=>{const s=t.map((e=>e.shape)),{axis:r}=n,a=v(r,t[0].shape)[0],i=s.map((e=>e[a]));return jc(e,i,a).map((e=>()=>e))}},Rm={kernelName:Ae,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[s,r]=t,{dilations:a,strides:i,pad:o,dataFormat:l}=n;return c(no(a),(()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`)),{x:()=>Oo(s.shape,e,r,i,o,l),filter:()=>Ah(s,e,r.shape,i,o,l)}}},_m={kernelName:_e,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{const[s,r]=t,{strides:a,pad:i,dataFormat:o,dimRoundingMode:l}=n;return{dy:()=>Fo(e,r,a,i,o,1,l),filter:()=>Ah(e,s,r.shape,a,i,o,l)}}};const Fm=fa({conv3DBackpropFilter_:function(e,t,n,s,r){let a=e;4===e.rank&&(a=oo(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let i=t;4===i.rank&&(i=oo(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),c(5===a.rank,(()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${a.shape}.`)),c(5===i.rank,(()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${i.shape}.`)),c(5===n.length,(()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`)),c(a.shape[4]===n[3],(()=>`Error in conv3dDerFilter: depth of input ${a.shape[4]}) must match input depth in filter (${n[3]}.`)),c(i.shape[4]===n[4],(()=>`Error in conv3dDerFilter: depth of dy (${i.shape[4]}) must match output depth for filter (${n[4]}).`));const o={x:a,dy:i},l={strides:s,pad:r,filterShape:n};return ta.runKernel(De,o,l)}}),Dm={kernelName:Fe,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:s,strides:r,pad:a}=n;c(no(s),(()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`));const[i,o]=t;return{x:()=>zo(i.shape,e,o,r,a),filter:()=>Fm(i,e,o.shape,r,a)}}},Om={kernelName:Me,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_i(Xl(Mc(Ti(n,"float32"))),e)}}},Mm={kernelName:Le,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_i(Lc(Ti(n,"float32")),e)}}},Lm={kernelName:Pe,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{axis:r,exclusive:a,reverse:i}=n;return{x:()=>{const t=dl([r],s.rank);let n=Uo(e,r,a,!i);return null!=t&&(n=vh(n,t)),n}}}},zm={kernelName:Ue,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:s,strides:r,pad:a,dimRoundingMode:i}=n,o=null==s?[1,1]:s;c(no(o),(()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`));const[l,u]=t;return c(4===l.rank,(()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`)),c(4===u.rank,(()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${u.rank}.`)),c(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]}.`)),c(so(r,o),(()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be  1. Got strides ${r} and dilations '${o}'.`)),io("depthwiseConv2d",a,i),{x:()=>Lh(l.shape,e,u,r,a,o,i),filter:()=>Mh(l,e,u.shape,r,a,o,i)}}},Pm={kernelName:qe,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[s,r]=t,a={x:s,filter:r,dy:e},i={x:s,filter:r,dy:e};return{x:()=>ta.runKernel(Ke,a,n),filter:()=>ta.runKernel(Xe,i,n)}}},Bm={kernelName:Qe,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t,s={dy:e,y:n};return{x:()=>ta.runKernel(et,s)}}},Wm={kernelName:tt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,s=_i(Tl(Xl(vl(n))),2/Math.sqrt(Math.PI));return{x:()=>_i(e,s)}}},Vm={kernelName:st,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_i(e,n)}}},Um={kernelName:rt,inputsToSave:["input"],gradFunc:(e,t)=>{const[n]=t;return{input:()=>oo(e,n.shape)}}},Gm={kernelName:at,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_i(e,Tl(n))}}},Hm={kernelName:ut,gradFunc:e=>({x:()=>tl(e)})},jm={kernelName:ct,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=Zo(n.shape,s.shape);return{a:()=>{const t=Ri(e,Ti(s,"float32")),a=Yo(n.shape,r);return a.length>0?oo(kl(t,a),n.shape):t},b:()=>{let t=_i(e,Ti(n,"float32"));const a=Yo(s.shape,r);a.length>0&&(t=oo(kl(t,a),s.shape));const i=vl(s);return Xl(Ri(t,Ti(i,"float32")))}}}},qm={kernelName:ht,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{const{varianceEpsilon:s}=n,[r,a,i,o]=t,l=null==o?xl(1):o,u=Yo(a.shape,r.shape),c=[];if(1===a.rank){for(let e=0;e<r.shape.length-1;++e)c.push(r.shape[e]);c.push(1)}const h=Jl(r,a),p=_i(e,l),d=Rc(Ei(i,xl(s))),f=_i(_i(_i(d,d),d),xl(-.5));return{x:()=>1===a.rank?oo(_i(_i(e,El(oo(d,[1,1,1,a.shape[0]]),c)),l),r.shape):oo(_i(_i(e,d),l),r.shape),mean:()=>{let e=_i(_i(d,xl(-1)),p);return 1===a.rank&&(e=kl(e,u)),oo(e,a.shape)},variance:()=>{let e=_i(_i(f,h),p);return 1===a.rank&&(e=kl(e,u)),oo(e,a.shape)},scale:()=>{const t=_i(h,d);let n=_i(e,t);return 1===a.rank&&(n=kl(n,u)),oo(n,a.shape)},offset:()=>{let t=e;return 1===a.rank&&(t=kl(t,u)),oo(t,a.shape)}}}},Km={kernelName:pt,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{const[s,r]=t,{axis:a,batchDims:i}=n,o=v(a,s.shape)[0],l=(e,t,n)=>()=>{const s=e.shape,r=t.size,i=s.slice(0,o),l=i.length,u=s.slice(a,s.length).slice(1),c=u.length,h=Xm(0,l),p=Xm(l+1,l+1+c),d=Ym([i,[r],u]),f=oo(n,d),m=oo(t,[r]),g=Ym([[l],h,p]),y=vh(f,g);let b=fh(y,m,e.shape[o]);const x=fl(g);return b=vh(b,x),b};if(1===i){const t=s.shape[0],n=s.split(t,0);return{x:()=>{const t=Yc(n.map(((t,n)=>l(t,r.slice(n,1),e.slice(n,1))())));return t.reshape(s.shape)},indices:()=>r}}return{x:l(s,r,e),indices:()=>r}}};function Xm(e,t){const n=[];for(let s=e;s<t;++s)n.push(s);return n}function Ym(e){const t=[];for(let n=0;n<e.length;++n)for(let s=0;s<e[n].length;++s)t.push(e[n][s]);return t}const Zm={kernelName:mt,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t;return{a:()=>tl(n),b:()=>tl(s)}}},Jm={kernelName:gt,gradFunc:e=>({x:()=>Ti(e,"float32")})},Qm={kernelName:xt,gradFunc:e=>({x:()=>tl(e)})},eg={kernelName:wt,gradFunc:e=>({x:()=>tl(e)})},tg={kernelName:vt,gradFunc:e=>({x:()=>tl(e)})},ng={kernelName:kt,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{alpha:r}=n,a=Fl(s,0);return{x:()=>el(a,e,_i(e,r))}}},sg={kernelName:Ct,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ri(e,Ei(n,1))}}},rg={kernelName:Tt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ri(e,Ti(n,"float32"))}}},ag={kernelName:Rt,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s]=t,{axis:r}=n;return{logits:()=>{const t=Tl(s);return Jl(e,_i(kl(e,r,!0),t))}}}};const ig=fa({localResponseNormalizationBackprop_:function(e,t,n,s=5,r=1,a=1,i=.5){const o={x:e,y:t,dy:n},l={depthRadius:s,bias:r,alpha:a,beta:i};return ta.runKernel(Ft,o,l)}}),og={kernelName:_t,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s,r]=t,{depthRadius:a,bias:i,alpha:o,beta:l}=n;return{x:()=>ig(s,r,e,a,i,o,l)}}};function lg(e,t,n,s){return t.rank<n.rank&&(t=oo(t,hl(t.shape,s))),e.rank<n.rank&&(e=oo(e,hl(e.shape,s))),{x:()=>_i(e,Ti(Qo(n,t),e.dtype))}}const ug={kernelName:Dt,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const s=n,{reductionIndices:r}=s,a=t[0],i=lg(e,t[1],a,v(r,a.shape));return{x:()=>i.x()}}},cg={kernelName:Ot,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t;return{a:()=>_i(e,Ti(Dl(n,s),"float32")),b:()=>_i(e,Ti(Bl(n,s),"float32"))}}};const hg=fa({maxPool3dGrad_:function(e,t,n,s,r,a,i){const o=ha(e,"dy","maxPool3dGrad"),l=ha(t,"input","maxPool3dGrad"),u=ha(n,"output","maxPool3dGrad");let h=o,p=l,d=u,f=!1;4===l.rank&&(f=!0,h=oo(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),p=oo(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),d=oo(u,[1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]])),c(5===h.rank,(()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${h.rank}.`)),c(5===p.rank,(()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${p.rank}.`)),c(5===d.rank,(()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${d.rank}.`)),io("maxPool3dGrad",a,i);const m={dy:h,input:p,output:d},g={filterSize:s,strides:r,pad:a,dimRoundingMode:i},y=ta.runKernel(Pt,m,g);return f?oo(y,[y.shape[1],y.shape[2],y.shape[3],y.shape[4]]):y}}),pg={kernelName:zt,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s,r]=t,{filterSize:a,strides:i,pad:o,dimRoundingMode:l}=n;return{x:()=>hg(e,s,r,a,i,o,l)}}};const dg=fa({maxPoolGrad_:function(e,t,n,s,r,a,i){const o=ha(e,"dy","maxPoolGrad"),l=ha(t,"input","maxPoolGrad"),u=ha(n,"output","maxPoolGrad");c(l.rank===o.rank,(()=>`Rank of input (${l.rank}) does not match rank of dy (${o.rank})`)),c(4===o.rank,(()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${o.rank}.`)),c(4===l.rank,(()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`)),io("maxPoolGrad",a,i);const h={dy:o,input:l,output:u},p={filterSize:s,strides:r,pad:a,dimRoundingMode:i};return ta.runKernel(Lt,h,p)}}),fg={kernelName:Mt,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s,r]=t,{filterSize:a,strides:i,pad:o}=n;return{x:()=>dg(e,s,r,a,i,o)}}},mg={kernelName:Gt,inputsToSave:["x"],gradFunc:(e,t,n)=>{const s=t[0],{paddings:r}=n,a=r.map((e=>e[0]));return{x:()=>fo(e,a,s.shape)}}},gg={kernelName:nn,inputsToSave:["x"],gradFunc:(e,t,n)=>{const s=t[0],{paddings:r}=n,a=r.map((e=>e[0]));return{x:()=>fo(e,a,s.shape)}}},yg={kernelName:sn,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{const[n,s,r]=t,a=n,i=s,o=Zo(a.shape,i.shape);return{a:()=>{const t=Ti(i,"float32");let n=_i(e,_i(t,bl(a,Jl(t,xl(1)))));const s=Yo(a.shape,o);return s.length>0&&(n=kl(n,s)),oo(n,a.shape)},b:()=>{const t=Fl(a,0),n=el(t,Gl(a),tl(a));let s=_i(e,_i(r,n));const l=Yo(i.shape,o);return l.length>0&&(s=kl(s,l)),oo(s,i.shape)}}}};function bg(e,t,n){const s=e.shape.length,r=s-n.length,a=dl(n,s);let i=e;null!=a&&(i=vh(e,a));const o=i.shape.slice(),l=o.splice(s-n.length,n.length).reduce(((e,t)=>e*t),1);o.push(l);let u=function(e,t,n){const s=e.shape.slice();s[n]=1;const r=oo(t,s),a=Vo(e,n,!0,!1),i=Vo(e,n,!0,!0),o=_i(a,i);return _i(r,o)}(i.reshape(o),t,r);if(u=u.reshape(i.shape),null!=a){const e=fl(a);u=vh(u,e)}return u}const xg={kernelName:Cn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=Fl(n,xl(0)),s=xl(gf),r=xl(yf),a=_i(e,r),i=_i(_i(e,s),Tl(Ti(n,"float32")));return el(t,a,i)}}}},wg={kernelName:Mn,gradFunc:(e,t,n)=>{const{blockShape:s,paddings:r}=n;return{x:()=>yo(e,s,r)}}},vg={kernelName:Ln,gradFunc:(e,t,n)=>{const{axis:s}=n;return{x:()=>co(e,s)}}};const kg=[om,lm,um,cm,hm,pm,dm,fm,mm,gm,ym,bm,wm,km,Nm,Im,Sm,Tm,Cm,$m,Em,Am,_m,Rm,Dm,Om,Mm,Lm,zm,Pm,{kernelName:Ze,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=Zo(n.shape,s.shape);return{a:()=>{const t=Ri(e,Ti(s,"float32")),a=Yo(n.shape,r);return a.length>0?oo(kl(t,a),n.shape):t},b:()=>{let t=_i(e,Ti(n,"float32"));const a=Yo(s.shape,r);a.length>0&&(t=oo(kl(t,a),s.shape));const i=vl(s);return Xl(Ri(t,Ti(i,"float32")))}}}},Bm,Wm,Vm,Um,Gm,jm,Hm,qm,Km,Zm,Jm,Qm,eg,tg,ng,sg,rg,ag,og,ug,ug,cg,pg,fg,{kernelName:Wt,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{axis:r}=n,a=v(r,s.shape),i=d(cl(s.shape,a)[1]);return{x:()=>{const t=s.shape.slice();a.forEach((e=>{t[e]=1}));const n=oo(e,t);return Ri(_i(n,fu(s.shape,"float32")),i)}}}},{kernelName:Vt,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const s=n,{axis:r}=s,[a,i]=t,o=lg(e,i,a,v(r,a.shape));return{x:()=>o.x()}}},{kernelName:Ut,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t;return{a:()=>_i(e,Ti(Wl(n,s),"float32")),b:()=>_i(e,Ti(Fl(n,s),"float32"))}}},mg,{kernelName:Ht,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=Zo(n.shape,s.shape);return{a:()=>{const t=Yo(n.shape,r);return t.length>0?oo(kl(e,t),n.shape):e},b:()=>{const t=_i(e,Xl(Rl(Ri(n,s)))),a=Yo(s.shape,r);return a.length>0?oo(kl(t,a),s.shape):t}}}},{kernelName:qt,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=Zo(n.shape,s.shape);return{a:()=>{const t=_i(e,Ti(s,"float32")),a=Yo(n.shape,r);return a.length>0?oo(kl(t,a),n.shape):t},b:()=>{const t=_i(e,Ti(n,"float32")),a=Yo(s.shape,r);return a.length>0?oo(kl(t,a),s.shape):t}}}},{kernelName:Kt,gradFunc:e=>({x:()=>Xl(e)})},{kernelName:en,inputsToSave:["indices"],gradFunc:(e,t)=>{const n=t[0];return{indices:()=>du(n.shape,"float32")}}},{kernelName:Qt,gradFunc:e=>({x:()=>tl(e)})},{kernelName:tn,saveAllInputs:!0,gradFunc:(e,t,n)=>{const{axis:s}=n;return mh(e,s).map((e=>()=>e))}},gg,gg,yg,{kernelName:rn,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{const[n,s]=t,r=Fl(n,0);return{x:()=>el(r,e,_i(e,s)),alpha:()=>{let t=el(r,tl(e),_i(e,n));const a=Yo(s.shape,e.shape);return a.length>0&&(t=kl(t,a)),oo(t,s.shape)}}}},{kernelName:an,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{axis:r}=n;let a=[];return a=null==r?s.shape.map(((e,t)=>t)):"number"==typeof r?[r]:r,{x:()=>bg(s,e,a)}}},{kernelName:pn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ri(e,Xl(vl(n)))}}},{kernelName:xn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,s=_i(Wl(n,6),Zc(n));return{x:()=>_i(e,Ti(s,"float32"))}}},{kernelName:dn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_i(e,Ti(Zc(n),"float32"))}}},{kernelName:fn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>oo(e,n.shape)}}},{kernelName:yn,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[s]=t,r={dy:e,images:s};return{images:()=>ta.runKernel(bn,r,n)}}},{kernelName:mn,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[s]=t,r={dy:e,images:s};return{images:()=>ta.runKernel(gn,r,n)}}},{kernelName:wn,gradFunc:(e,t,n)=>{const{dims:s}=n,r=v(s,e.shape);return{x:()=>Sc(e,r)}}},{kernelName:vn,gradFunc:e=>({x:()=>tl(e)})},{kernelName:kn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Xl(Ri(e,_i(bl(n,1.5),2)))}}},{kernelName:Tn,inputsToSave:["condition"],gradFunc:(e,t)=>{const[n]=t;return{condition:()=>Ti(tl(n),"float32"),t:()=>_i(e,Ti(n,e.dtype)),e:()=>_i(e,Ti(nu(n),e.dtype))}}},xg,{kernelName:_n,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_i(e,_i(n,Jl(xl(1),n)))}}},{kernelName:Rn,gradFunc:e=>({x:()=>tl(e)})},{kernelName:En,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_i(Bo(Ti(n,"float32")),e)}}},{kernelName:An,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_i(Wo(Ti(n,"float32")),e)}}},{kernelName:$n,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{begin:r,size:a}=n,i=s.shape,[o,l]=jd(s,r,a),u=[];for(let t=0;t<e.rank;t++)u.push([o[t],i[t]-o[t]-l[t]]);return{x:()=>Tu(e,u)}}},{kernelName:zn,outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s]=t,{dim:r}=n,a=_i(e,s);return{logits:()=>Jl(a,_i(kl(a,[r],true),s))}}},{kernelName:Fn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_i(e,po(n))}}},wg,wg,vg,vg,{kernelName:Dn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ri(e,_i(wl(Ti(n,"float32")),2))}}},{kernelName:Gn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=xl(2);return{a:()=>_i(e,_i(r,Jl(n,s))),b:()=>_i(e,_i(r,Jl(s,n)))}}},{kernelName:Hn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_i(e,_i(Ti(n,"float32"),2))}}},{kernelName:ls,gradFunc:e=>({x:()=>tl(e)})},{kernelName:Zn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=Zo(n.shape,s.shape);return{a:()=>{let t=e;const s=Yo(n.shape,r);return s.length>0&&(t=kl(t,s)),oo(t,n.shape)},b:()=>{let t=e;const n=Yo(s.shape,r);return n.length>0&&(t=kl(t,n)),oo(Xl(t),s.shape)}}}},{kernelName:On,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,r=s.shape.slice(),{axis:a}=n;v(a,s.shape).forEach((e=>{r[e]=1}));const i=oo(e,r),o=_i(i,fu(s.shape,"float32"));return{x:()=>o}}},{kernelName:Jn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ri(e,vl(Bo(n)))}}},{kernelName:Qn,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>_i(Jl(xl(1),vl(n)),e)}}},{kernelName:es,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{reps:r}=n;return{x:()=>{let t=tl(s);if(1===s.rank)for(let n=0;n<r[0];++n)t=Ei(t,fo(e,[n*s.shape[0]],[s.shape[0]]));else if(2===s.rank)for(let n=0;n<r[0];++n)for(let a=0;a<r[1];++a)t=Ei(t,fo(e,[n*s.shape[0],a*s.shape[1]],[s.shape[0],s.shape[1]]));else if(3===s.rank)for(let n=0;n<r[0];++n)for(let a=0;a<r[1];++a)for(let i=0;i<r[2];++i)t=Ei(t,fo(e,[n*s.shape[0],a*s.shape[1],i*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<r[0];++n)for(let a=0;a<r[1];++a)for(let i=0;i<r[2];++i)for(let o=0;o<r[3];++o)t=Ei(t,fo(e,[n*s.shape[0],a*s.shape[1],i*s.shape[2],o*s.shape[3]],[s.shape[0],s.shape[1],s.shape[2],s.shape[3]]))}return t}}}},{kernelName:ss,gradFunc:(e,t,n)=>{const s=n,{perm:r}=s,a=fl(r);return{x:()=>vh(e,a)}}},{kernelName:as,gradFunc:(e,t,n)=>{const s=n,{axis:r}=s;return{value:()=>Yc(e,r)}}},{kernelName:is,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>function(e,t){const n=hu(t,tl(t)),s=_l(e,n);let r=Dl(t,xl(0,"int32"));const a=s.rank-r.rank;for(let e=0;e<a;++e)r=Cl(r,e+1);r=tu(r,fu(s.shape,"bool"));const i=tl(s);return el(r,s,i)}(e,n)}}},{kernelName:os,gradFunc:e=>({x:()=>tl(e)})}];for(const e of kg)vs(e);Fr().prototype.abs=function(){return this.throwIfDisposed(),Fi(this)},Fr().prototype.acos=function(){return this.throwIfDisposed(),Di(this)},Fr().prototype.acosh=function(){return this.throwIfDisposed(),Oi(this)},Fr().prototype.add=function(e){return this.throwIfDisposed(),Ei(this,e)},Fr().prototype.all=function(e,t){return this.throwIfDisposed(),Li(this,e,t)},Fr().prototype.any=function(e,t){return this.throwIfDisposed(),zi(this,e,t)},Fr().prototype.argMax=function(e){return this.throwIfDisposed(),Pi(this,e)},Fr().prototype.argMin=function(e){return this.throwIfDisposed(),Bi(this,e)},Fr().prototype.asScalar=function(){return this.throwIfDisposed(),c(1===this.size,(()=>"The array must have only 1 element.")),oo(this,[])},Fr().prototype.asType=function(e){return this.throwIfDisposed(),Ti(this,e)},Fr().prototype.as1D=function(){return this.throwIfDisposed(),oo(this,[this.size])},Fr().prototype.as2D=function(e,t){return this.throwIfDisposed(),oo(this,[e,t])},Fr().prototype.as3D=function(e,t,n){return this.throwIfDisposed(),oo(this,[e,t,n])},Fr().prototype.as4D=function(e,t,n,s){return this.throwIfDisposed(),oo(this,[e,t,n,s])},Fr().prototype.as5D=function(e,t,n,s,r){return this.throwIfDisposed(),oo(this,[e,t,n,s,r])},Fr().prototype.asin=function(){return this.throwIfDisposed(),Wi(this)},Fr().prototype.asinh=function(){return this.throwIfDisposed(),Vi(this)},Fr().prototype.atan=function(){return this.throwIfDisposed(),Ui(this)},Fr().prototype.atan2=function(e){return this.throwIfDisposed(),Gi(this,e)},Fr().prototype.atanh=function(){return this.throwIfDisposed(),Hi(this)},Fr().prototype.avgPool=function(e,t,n,s){return this.throwIfDisposed(),lo(this,e,t,n,s)},Fr().prototype.batchToSpaceND=function(e,t){return this.throwIfDisposed(),yo(this,e,t)},Fr().prototype.batchNorm=function(e,t,n,s,r){return this.throwIfDisposed(),bo(this,e,t,n,s,r)},Fr().prototype.broadcastTo=function(e){return this.throwIfDisposed(),So(this,e)},Fr().prototype.cast=function(e){return this.throwIfDisposed(),Ti(this,e)},Fr().prototype.ceil=function(){return this.throwIfDisposed(),To(this)},Fr().prototype.clipByValue=function(e,t){return this.throwIfDisposed(),$o(this,e,t)},Fr().prototype.concat=function(e,t){return this.throwIfDisposed(),e instanceof _r&&(e=[e]),co([this,...e],t)},Fr().prototype.conv1d=function(e,t,n,s,r,a){return this.throwIfDisposed(),Do(this,e,t,n,s,r,a)},Fr().prototype.conv2dTranspose=function(e,t,n,s,r){return this.throwIfDisposed(),Mo(this,e,t,n,s,r)},Fr().prototype.conv2d=function(e,t,n,s,r,a){return this.throwIfDisposed(),Fo(this,e,t,n,s,r,a)},Fr().prototype.cos=function(){return this.throwIfDisposed(),Bo(this)},Fr().prototype.cosh=function(){return this.throwIfDisposed(),Wo(this)},Fr().prototype.cumprod=function(e,t,n){return this.throwIfDisposed(),Vo(this,e,t,n)},Fr().prototype.cumsum=function(e,t,n){return this.throwIfDisposed(),Uo(this,e,t,n)},Fr().prototype.depthToSpace=function(e,t){return this.throwIfDisposed(),Ho(this,e,t)},Fr().prototype.depthwiseConv2d=function(e,t,n,s,r,a){return this.throwIfDisposed(),jo(this,e,t,n,s,r,a)},Fr().prototype.dilation2d=function(e,t,n,s,r){return this.throwIfDisposed(),Ko(this,e,t,n,s,r)},Fr().prototype.divNoNan=function(e){return this.throwIfDisposed(),nl(this,e)},Fr().prototype.div=function(e){return this.throwIfDisposed(),Ri(this,e)},Fr().prototype.dot=function(e){return this.throwIfDisposed(),sl(this,e)},Fr().prototype.elu=function(){return this.throwIfDisposed(),al(this)},Fr().prototype.equal=function(e){return this.throwIfDisposed(),Qo(this,e)},Fr().prototype.erf=function(){return this.throwIfDisposed(),ol(this)},Fr().prototype.euclideanNorm=function(e,t){return this.throwIfDisposed(),Sl(this,e,t)},Fr().prototype.exp=function(){return this.throwIfDisposed(),Tl(this)},Fr().prototype.expandDims=function(e){return this.throwIfDisposed(),Cl(this,e)},Fr().prototype.expm1=function(){return this.throwIfDisposed(),$l(this)},Fr().prototype.fft=function(){return this.throwIfDisposed(),Uc(this)},Fr().prototype.flatten=function(){return this.throwIfDisposed(),oo(this,[this.size])},Fr().prototype.floor=function(){return this.throwIfDisposed(),Rl(this)},Fr().prototype.floorDiv=function(e){return this.throwIfDisposed(),Ai(this,e)},Fr().prototype.gather=function(e,t,n){return this.throwIfDisposed(),_l(this,e,t,n)},Fr().prototype.greaterEqual=function(e){return this.throwIfDisposed(),Dl(this,e)},Fr().prototype.greater=function(e){return this.throwIfDisposed(),Fl(this,e)},Fr().prototype.ifft=function(){return this.throwIfDisposed(),Gc(this)},Fr().prototype.irfft=function(){return this.throwIfDisposed(),Hc(this)},Fr().prototype.isFinite=function(){return this.throwIfDisposed(),Ml(this)},Fr().prototype.isInf=function(){return this.throwIfDisposed(),Ll(this)},Fr().prototype.isNaN=function(){return this.throwIfDisposed(),zl(this)},Fr().prototype.leakyRelu=function(e){return this.throwIfDisposed(),Pl(this,e)},Fr().prototype.lessEqual=function(e){return this.throwIfDisposed(),Wl(this,e)},Fr().prototype.less=function(e){return this.throwIfDisposed(),Bl(this,e)},Fr().prototype.localResponseNormalization=function(e,t,n,s){return this.throwIfDisposed(),Ul(this,e,t,n,s)},Fr().prototype.logSigmoid=function(){return this.throwIfDisposed(),Zl(this)},Fr().prototype.logSoftmax=function(e){return this.throwIfDisposed(),Ql(this,e)},Fr().prototype.logSumExp=function(e,t){return this.throwIfDisposed(),eu(this,e,t)},Fr().prototype.log=function(){return this.throwIfDisposed(),Gl(this)},Fr().prototype.log1p=function(){return this.throwIfDisposed(),Hl(this)},Fr().prototype.logicalAnd=function(e){return this.throwIfDisposed(),tu(this,e)},Fr().prototype.logicalNot=function(){return this.throwIfDisposed(),nu(this)},Fr().prototype.logicalOr=function(e){return this.throwIfDisposed(),su(this,e)},Fr().prototype.logicalXor=function(e){return this.throwIfDisposed(),ru(this,e)},Fr().prototype.matMul=function(e,t,n){return this.throwIfDisposed(),ho(this,e,t,n)},Fr().prototype.maxPool=function(e,t,n,s){return this.throwIfDisposed(),lu(this,e,t,n,s)},Fr().prototype.max=function(e,t){return this.throwIfDisposed(),gl(this,e,t)},Fr().prototype.maximum=function(e){return this.throwIfDisposed(),hu(this,e)},Fr().prototype.mean=function(e,t){return this.throwIfDisposed(),pu(this,e,t)},Fr().prototype.min=function(e,t){return this.throwIfDisposed(),yl(this,e,t)},Fr().prototype.minimum=function(e){return this.throwIfDisposed(),gu(this,e)},Fr().prototype.mirrorPad=function(e,t){return this.throwIfDisposed(),yu(this,e,t)},Fr().prototype.mod=function(e){return this.throwIfDisposed(),bu(this,e)},Fr().prototype.mul=function(e){return this.throwIfDisposed(),_i(this,e)},Fr().prototype.neg=function(){return this.throwIfDisposed(),Xl(this)},Fr().prototype.norm=function(e,t,n){return this.throwIfDisposed(),Il(this,e,t,n)},Fr().prototype.notEqual=function(e){return this.throwIfDisposed(),ku(this,e)},Fr().prototype.oneHot=function(e,t=1,n=0){return this.throwIfDisposed(),Nu(this,e,t,n)},Fr().prototype.onesLike=function(){return this.throwIfDisposed(),Iu(this)},Fr().prototype.pad=function(e,t){return this.throwIfDisposed(),Tu(this,e,t)},Fr().prototype.pool=function(e,t,n,s,r,a){return this.throwIfDisposed(),_u(this,e,t,n,s,r,a)},Fr().prototype.pow=function(e){return this.throwIfDisposed(),bl(this,e)},Fr().prototype.prelu=function(e){return this.throwIfDisposed(),Fu(this,e)},Fr().prototype.prod=function(e,t){return this.throwIfDisposed(),Du(this,e,t)},Fr().prototype.reciprocal=function(){return this.throwIfDisposed(),kc(this)},Fr().prototype.relu=function(){return this.throwIfDisposed(),Nc(this)},Fr().prototype.relu6=function(){return this.throwIfDisposed(),Ic(this)},Fr().prototype.reshapeAs=function(e){return this.throwIfDisposed(),oo(this,e.shape)},Fr().prototype.reshape=function(e){return this.throwIfDisposed(),oo(this,e)},Fr().prototype.resizeBilinear=function(e,t,n){return this.throwIfDisposed(),pp(this,e,t,n)},Fr().prototype.resizeNearestNeighbor=function(e,t,n){return this.throwIfDisposed(),dp(this,e,t,n)},Fr().prototype.reverse=function(e){return this.throwIfDisposed(),Sc(this,e)},Fr().prototype.rfft=function(){return this.throwIfDisposed(),qc(this)},Fr().prototype.round=function(){return this.throwIfDisposed(),Ac(this)},Fr().prototype.rsqrt=function(){return this.throwIfDisposed(),Rc(this)},Fr().prototype.selu=function(){return this.throwIfDisposed(),_c(this)},Fr().prototype.separableConv2d=function(e,t,n,s,r,a){return this.throwIfDisposed(),Fc(this,e,t,n,s,r,a)},Fr().prototype.sigmoid=function(){return this.throwIfDisposed(),po(this)},Fr().prototype.sign=function(){return this.throwIfDisposed(),Oc(this)},Fr().prototype.sin=function(){return this.throwIfDisposed(),Mc(this)},Fr().prototype.sinh=function(){return this.throwIfDisposed(),Lc(this)},Fr().prototype.slice=function(e,t){return this.throwIfDisposed(),fo(this,e,t)},Fr().prototype.softmax=function(e){return this.throwIfDisposed(),Vc(this,e)},Fr().prototype.softplus=function(){return this.throwIfDisposed(),Yl(this)},Fr().prototype.spaceToBatchND=function(e,t){return this.throwIfDisposed(),Ru(this,e,t)},Fr().prototype.split=function(e,t){return this.throwIfDisposed(),jc(this,e,t)},Fr().prototype.sqrt=function(){return this.throwIfDisposed(),wl(this)},Fr().prototype.square=function(){return this.throwIfDisposed(),vl(this)},Fr().prototype.squaredDifference=function(e){return this.throwIfDisposed(),Kc(this,e)},Fr().prototype.squeeze=function(e){return this.throwIfDisposed(),Xc(this,e)},Fr().prototype.stack=function(e,t){this.throwIfDisposed();const n=e instanceof _r?[this,e]:[this,...e];return Yc(n,t)},Fr().prototype.step=function(e){return this.throwIfDisposed(),Zc(this,e)},Fr().prototype.stridedSlice=function(e,t,n,s,r,a,i,o){return this.throwIfDisposed(),Jc(this,e,t,n,s,r,a,i,o)},Fr().prototype.sub=function(e){return this.throwIfDisposed(),Jl(this,e)},Fr().prototype.sum=function(e,t){return this.throwIfDisposed(),kl(this,e,t)},Fr().prototype.tan=function(){return this.throwIfDisposed(),Qc(this)},Fr().prototype.tanh=function(){return this.throwIfDisposed(),mo(this)},Fr().prototype.tile=function(e){return this.throwIfDisposed(),El(this,e)},Fr().prototype.toBool=function(){return this.throwIfDisposed(),Ti(this,"bool")},Fr().prototype.toFloat=function(){return this.throwIfDisposed(),Ti(this,"float32")},Fr().prototype.toInt=function(){return this.throwIfDisposed(),Ti(this,"int32")},Fr().prototype.topk=function(e,t){return this.throwIfDisposed(),hh(this,e,t)},Fr().prototype.transpose=function(e){return this.throwIfDisposed(),vh(this,e)},Fr().prototype.unique=function(e){return this.throwIfDisposed(),dh(this,e)},Fr().prototype.unsortedSegmentSum=function(e,t){return this.throwIfDisposed(),fh(this,e,t)},Fr().prototype.unstack=function(e){return this.throwIfDisposed(),mh(this,e)},Fr().prototype.where=function(e,t){return this.throwIfDisposed(),el(e,this,t)},Fr().prototype.zerosLike=function(){return this.throwIfDisposed(),tl(this)};class Ng extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Ng.prototype)}}class Ig extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Ig.prototype)}}class Sg extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Sg.prototype)}}class Tg extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Tg.prototype)}}class Cg extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Cg.prototype)}}Error;class $g{constructor(e){this.maxEntries=e||100,this.cache=new Map}get(e){let t;return this.cache.has(e)&&(t=this.cache.get(e),this.cache.delete(e),this.cache.set(e,t)),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxEntries){const e=this.cache.keys().next().value;this.cache.delete(e)}this.cache.set(e,t)}getMaxEntries(){return this.maxEntries}setMaxEntries(e){if(e<0)throw new Error(`The maxEntries of LRU caches must be at least 0, but got ${e}.`);if(this.maxEntries>e)for(let t=0;t<this.maxEntries-e;t++){const e=this.cache.keys().next().value;this.cache.delete(e)}this.maxEntries=e}}function Eg(e,t){if(Array.isArray(e)){let n=[];for(let s=0;s<t;s++)n=n.concat(e);return n}{const n=new Array(t);return n.fill(e),n}}function Ag(e,t){if(!e)throw new Cg(t)}function Rg(e,t){let n=0;for(const s of e)s===t&&n++;return n}function _g(e){return 1===e.length?e[0]:e}function Fg(e){return Array.isArray(e)?e:[e]}function Dg(e){const t=e.replace(/(.)([A-Z][a-z0-9]+)/g,"$1_$2").replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();return"_"!==t[0]?t:"private"+t}function Og(e){return e.length<=1||-1===e.indexOf("_")?e:e.replace(/[_]+(\w|$)/g,((e,t)=>t.toUpperCase()))}let Mg={};function Lg(e){if(null==e)return null;const t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function zg(e){if(null!=e&&"object"==typeof e)if(Array.isArray(e))e.forEach((e=>zg(e)));else{const t=Object.keys(e);for(const n of t){const t=e[n];null!=t&&"object"==typeof t&&(Array.isArray(t)||"ndarray"!==t.type||"number"!=typeof t.value?zg(t):e[n]=t.value)}}}function Pg(e,t={},n={},s="object",r=!1){if("string"==typeof e){const r=e;let a;if(r in n)a=n[r];else if(r in Mg)a=Mg[r];else if(a=t[r],null==a)throw new Sg(`Unknown ${s}: ${e}. 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 a}{const a=e;if(null==a.className||null==a.config)throw new Sg(`${s}: Improper config format: ${JSON.stringify(a)}.\n'className' and 'config' must set.`);const i=a.className;let o,l;if(i in n?[o,l]=n[i]:i in Mg?[o,l]=Mg.className:i in t&&([o,l]=t[i]),null==o)throw new Sg(`Unknown ${s}: ${i}. 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 e={};for(const t of Object.keys(Mg))e[t]=Mg[t];for(const t of Object.keys(n))e[t]=n[t];a.config.customObjects=e;const t=Object.assign({},Mg);for(const e of Object.keys(n))Mg[e]=n[e];zg(a.config);const s=l(o,a.config,n,r);return Mg=Object.assign({},t),s}{const e=Object.assign({},Mg);for(const e of Object.keys(n))Mg[e]=n[e];const t=new o(a.config);return Mg=Object.assign({},e),t}}}function Bg(e,t){return-1*function(e,t){return e<t?-1:e>t?1:0}(e,t)}function Wg(e){if(null==e)return e;const t=[];for(const n of e)-1===t.indexOf(n)&&t.push(n);return t}function Vg(e){if(null==e)throw new Sg(`Invalid value in obj: ${JSON.stringify(e)}`);for(const t in e)if(e.hasOwnProperty(t))return!1;return!0}function Ug(e,t,n){if(null!=n&&e.indexOf(n)<0)throw new Sg(`${n} is not a valid ${t}.  Valid values are ${e} or null/undefined.`)}function Gg(e,t,n=0,s=1/0){return Ag(n>=0),Ag(s>=n),Array.isArray(e)&&e.length>=n&&e.length<=s&&e.every((e=>typeof e===t))}function Hg(e,t){Array.isArray(e)?(c(e.length>0,(()=>`${t} is unexpectedly an empty array.`)),e.forEach(((e,n)=>Hg(e,`element ${n+1} of ${t}`)))):c(Number.isInteger(e)&&e>0,(()=>`Expected ${t} to be a positive integer, but got ${jg(e)}.`))}function jg(e){return null===e?"null":Array.isArray(e)?"["+e.map((e=>jg(e))).join(",")+"]":"string"==typeof e?`"${e}"`:`${e}`}function qg(e){return"relu"===e?"relu":"linear"===e?"linear":"elu"===e?"elu":null}let Kg=0;function Xg(){return Kg++}const Yg={};function Zg(e=""){return e in Yg||(Yg[e]=0),Yg[e]+=1,e+Yg[e].toString()}const Jg=["channelsFirst","channelsLast"],Qg=["nearest","bilinear"],ey=["valid","same","causal"],ty=["max","avg"],ny=["sum","mul","concat","ave"],sy=new Map;function ry(e){Ug(Jg,"DataFormat",e)}function ay(e){Ug(ey,"PaddingMode",e)}function iy(e){Ug(ty,"PoolMode",e)}const oy=[];function ly(e,t){oy.push(e);try{const e=t();return oy.pop(),e}catch(e){throw oy.pop(),e}}function uy(e){if(!py(e))throw new Error("Not a valid tensor name: '"+e+"'");return(0===oy.length?"":oy.join("/")+"/")+e}function cy(e){if(!py(e))throw new Error("Not a valid tensor name: '"+e+"'");sy.has(e)||sy.set(e,0);const t=sy.get(e);if(sy.set(e,sy.get(e)+1),t>0){const n=`${e}_${t}`;return sy.set(n,1),n}return e}const hy=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function py(e){return!!e.match(hy)}function dy(e,t,n){null==t&&(t=0),null==n&&(n=e.length);let s=1;for(let r=t;r<n;++r)s*=e[r];return s}function fy(e){if(0===e.length)return Number.NaN;let t=Number.POSITIVE_INFINITY;for(let n=0;n<e.length;n++){const s=e[n];s<t&&(t=s)}return t}function my(e){if(0===e.length)return Number.NaN;let t=Number.NEGATIVE_INFINITY;for(let n=0;n<e.length;n++){const s=e[n];s>t&&(t=s)}return t}function gy(e,t){if(t<e)throw new Sg(`end (${t}) < begin (${e}) is forbidden.`);const n=[];for(let s=e;s<t;++s)n.push(s);return n}let yy;function by(){return null==yy&&(yy=Ea().epsilon()),yy}function xy(e,t){return Ti(e,t)}function wy(e,t=-1){const n=e.shape.slice();return t<0&&(t=n.length+t+1),n.splice(t,0,1),oo(e,n)}function vy(e,t,n){return Na((()=>{switch(e.rank){case 1:return zc(e,t,n);case 2:return Pc(e,[t,0],[n,e.shape[1]]);case 3:return Bc(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return Wc(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return fo(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return fo(e,[t,0,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4],e.shape[5]]);default:throw new Sg(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function ky(e,t,n){return Na((()=>{switch(e.rank){case 1:return zc(e,t,n);case 2:return Pc(e,[0,t],[e.shape[0],n]);case 3:return Bc(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return Wc(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new Sg(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Ny(e,t,n,s){return Na((()=>{switch(e.rank){case 1:return zc(e,t,n);case 2:switch(s){case 1:return vy(e,t,n);case 2:return ky(e,t,n);default:throw new Sg(`The axis is not within the rank of the tensor ${s}`)}case 3:switch(s){case 1:return vy(e,t,n);case 2:return Bc(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return ky(e,t,n);default:throw new Sg(`The axis is not within the rank of the tensor ${s}`)}case 4:switch(s){case 1:return vy(e,t,n);case 2:return Wc(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return Wc(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return ky(e,t,n);default:throw new Sg(`The axis is not within the rank of the tensor ${s}`)}default:throw new Sg(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Iy(e,t=-1){let n;return t<0&&(n=e[0].rank,t=0!==n?n:0),t===e[0].rank&&(t=-1),co(e,t)}function Sy(e,t){switch(e.rank){case 1:return Eo([e,t]);case 2:return Ao([e,t],0);case 3:return Ro([e,t],0);case 4:return _o([e,t],0);default:throw new Sg(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function Ty(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new Sg(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return El(e,t)}function Cy(e,t=0,n=1,s,r){return gc(e,t,n,s,r)}function $y(e,t,n,s){if(e.rank<2||t.rank<2)throw new Tg(`dot requires both inputs to be rank >= 2 but got x shape = ${e.shape} and y shape = ${t.shape}`);if(t.rank>=3){if(e.shape.slice(-1)[0]!==t.shape.slice(-2)[0])throw new Tg(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${e.shape} and  y shape = ${t.shape}`)}if(2===e.rank&&2===t.rank){return Ph({a:e,b:t,transposeA:!1,transposeB:!1,bias:s?Ry(e.rank,s,"channelsLast"):null,activation:n})}{const r=e.shape.slice(),a=r.pop();e=oo(e,[-1,a]);const i=t.shape.slice(),o=i.pop(),l=i.pop(),u=[...i,o],c=Array.from({length:t.rank},((e,n)=>0===n?t.rank-2:n<=t.rank-2?n-1:n));t=oo(vh(t,c),[l,-1]);const h=[...r,...u];return oo(Ph({a:e,b:t,transposeA:!1,transposeB:!1,bias:s?Ry(e.rank,s,"channelsLast"):null,activation:n}),h)}}function Ey(e,t,n){return Na((()=>(t=Array.isArray(t)?eh(t,"int32"):Ti(t,"int32"),_l(e,t,n))))}function Ay(e){return _i(e,e)}function Ry(e,t,n){const s=t.shape;if(1!==t.rank&&t.rank!==e)throw new Sg(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(5===e){if("channelsFirst"===n)return 1===s.length?oo(t,[1,s[0],1,1,1]):oo(t,[1,s[3],s[0],s[1],s[2]]);if("channelsLast"===n)return 1===s.length?oo(t,[1,1,1,1,s[0]]):oo(t,[1].concat(s))}else if(4===e){if("channelsFirst"===n)return 1===s.length?oo(t,[1,s[0],1,1]):oo(t,[1,s[2],s[0],s[1]]);if("channelsLast"===n)return 1===s.length?oo(t,[1,1,1,s[0]]):oo(t,[1].concat(s))}else if(3===e){if("channelsFirst"===n)return 1===s.length?oo(t,[1,s[0],1]):oo(t,[1,s[1],s[0]]);if("channelsLast"===n)return 1===s.length?oo(t,[1,1,s[0]]):oo(t,[1].concat(s))}else if(e<3)return t;throw new Sg(`Unsupported input rank by biasAdd: ${t.rank}`)}function _y(e,t,n){return Na((()=>(null==n&&(n="channelsLast"),ry(n),Ei(e,Ry(e.rank,t,n)))))}function Fy(e,t,n,s){return Na((()=>Th(e,t,n,s)))}function Dy(e,t,n=!1){return n?e():t()}const Oy=["fanIn","fanOut","fanAvg"],My=["normal","uniform","truncatedNormal"];class Ly extends qp{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}}class zy extends Ly{apply(e,t){return du(e,t)}}zy.className="Zeros",Xp(zy);class Py extends Ly{apply(e,t){return fu(e,t)}}Py.className="Ones",Xp(Py);class By extends Ly{constructor(e){if(super(),"object"!=typeof e)throw new Sg(`Expected argument of type ConstantConfig but got ${e}`);if(void 0===e.value)throw new Sg(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return Na((()=>_i(xl(this.value),fu(e,t))))}getConfig(){return{value:this.value}}}By.className="Constant",Xp(By);class Wy extends Ly{constructor(e){super(),this.DEFAULT_MINVAL=-.05,this.DEFAULT_MAXVAL=.05,this.minval=e.minval||this.DEFAULT_MINVAL,this.maxval=e.maxval||this.DEFAULT_MAXVAL,this.seed=e.seed}apply(e,t){return bc(e,this.minval,this.maxval,t,this.seed)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}}Wy.className="RandomUniform",Xp(Wy);class Vy extends Ly{constructor(e){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if("float32"!==(t=t||"float32")&&"int32"!==t)throw new Tg(`randomNormal does not support dType ${t}.`);return Cy(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}Vy.className="RandomNormal",Xp(Vy);class Uy extends Ly{constructor(e){super(),this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if("float32"!==(t=t||"float32")&&"int32"!==t)throw new Tg(`truncatedNormal does not support dType ${t}.`);return ph(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}Uy.className="TruncatedNormal",Xp(Uy);class Gy extends Ly{constructor(e){super(),this.gain=null!=e.gain?e.gain:1}apply(e,t){return Na((()=>{if(2!==e.length||e[0]!==e[1])throw new Sg("Identity matrix initializer can only be used for 2D square matrices.");return _i(this.gain,Al(e[0]))}))}getConfig(){return{gain:this.gain}}}Gy.className="Identity",Xp(Gy);class Hy extends Ly{constructor(e){if(super(),e.scale<0)throw new Sg(`scale must be a positive float. Got: ${e.scale}`);var t;this.scale=null==e.scale?1:e.scale,this.mode=null==e.mode?"fanIn":e.mode,t=this.mode,Ug(Oy,"FanMode",t),this.distribution=null==e.distribution?"normal":e.distribution,function(e){Ug(My,"Distribution",e)}(this.distribution),this.seed=e.seed}apply(e,t){const n=function(e,t="channelsLast"){let n,s;if(ry(t),2===e.length)n=e[0],s=e[1];else if(-1!==[3,4,5].indexOf(e.length)){if("channelsFirst"===t){const t=dy(e,2);n=e[1]*t,s=e[0]*t}else if("channelsLast"===t){const t=dy(e,0,e.length-2);n=e[e.length-2]*t,s=e[e.length-1]*t}}else{const t=dy(e);n=Math.sqrt(t),s=Math.sqrt(t)}return[n,s]}(e),s=n[0],r=n[1];let a=this.scale;if("fanIn"===this.mode?a/=Math.max(1,s):"fanOut"===this.mode?a/=Math.max(1,r):a/=Math.max(1,(s+r)/2),"normal"===this.distribution){const n=Math.sqrt(a);if("float32"!==(t=t||"float32")&&"int32"!==t)throw new Tg(`${this.getClassName()} does not support dType ${t}.`);return ph(e,0,n,t,this.seed)}{const n=Math.sqrt(3*a);return bc(e,-n,n,t,this.seed)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}}Hy.className="VarianceScaling",Xp(Hy);class jy extends Hy{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return Hy.className}}jy.className="GlorotUniform",Xp(jy);class qy extends Hy{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return Hy.className}}qy.className="GlorotNormal",Xp(qy);class Ky extends Hy{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return Hy.className}}Ky.className="HeNormal",Xp(Ky);class Xy extends Hy{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return Hy.className}}Xy.className="HeUniform",Xp(Xy);class Yy extends Hy{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return Hy.className}}Yy.className="LeCunNormal",Xp(Yy);class Zy extends Hy{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return Hy.className}}Zy.className="LeCunUniform",Xp(Zy);class Jy extends Ly{constructor(e){super(),this.DEFAULT_GAIN=1,this.ELEMENTS_WARN_SLOW=2e3,this.gain=null==e.gain?this.DEFAULT_GAIN:e.gain,this.seed=e.seed}apply(e,t){return Na((()=>{if(e.length<2)throw new Tg("Shape must be at least 2D.");if("int32"!==t&&"float32"!==t&&void 0!==t)throw new TypeError(`Unsupported data type ${t}.`);const n=d(e.slice(0,-1)),s=e[e.length-1],r=n*s;r>this.ELEMENTS_WARN_SLOW&&console.warn(`Orthogonal initializer is being called on a matrix with more than ${this.ELEMENTS_WARN_SLOW} (${r}) elements: Slowness may result.`);const a=Cy([Math.max(s,n),Math.min(s,n)],0,1,t,this.seed),i=Wp.qr(a,!1);let o=i[0];const l=i[1].flatten().stridedSlice([0],[Math.min(s,n)*Math.min(s,n)],[Math.min(s,n)+1]);return o=_i(o,l.sign()),n<s&&(o=o.transpose()),_i(xl(this.gain),o.reshape(e))}))}getConfig(){return{gain:this.gain,seed:this.seed}}}Jy.className="Orthogonal",Xp(Jy);const Qy={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 eb(e,t={}){return Pg(e,Kp.getMap().classNameMap,t,"initializer")}function tb(e){return Lg(e)}function nb(e){if("string"==typeof e){const t=e in Qy?Qy[e]:e;if("GlorotNormal"===t)return new qy;if("GlorotUniform"===t)return new jy;if("HeNormal"===t)return new Ky;if("HeUniform"===t)return new Xy;if("LeCunNormal"===t)return new Yy;if("LeCunUniform"===t)return new Zy;{const e={};return e.className=t,e.config={},eb(e)}}return e instanceof Ly?e:eb(e)}function sb(e){return Array.isArray(e)&&Array.isArray(e[0])}function rb(e){return 0===e.length?[]:Array.isArray(e[0])?e:[e]}function ab(e){let t;if(Array.isArray(e)){if(1!==e.length)throw new Sg(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function ib(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(1===e.length)return e[0];throw new Sg(`Expected exactly 1 Shape; got ${e.length}`)}return e}function ob(e){let t=0;for(const n of e)0===n.shape.length?t+=1:t+=n.shape.reduce(((e,t)=>e*t));return t}const lb="Variable";class ub{constructor(e,t="float32",n="Variable",s=!0,r=null){this.dtype=null==t?"float32":t,this.shape=e.shape,this.id=Xg(),n=null==n?lb:n,this.originalName=uy(n),this.name=cy(this.originalName),this.trainable_=s,this.constraint=r,this.val=yh(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),function(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}(this.val,e),this.val.id!==e.id&&(this.val.assign(e),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(e){this.trainable_=e,this.val.trainable=e}}function cb(e){return e.map((e=>e.read()))}function hb(e){e.forEach((e=>{e[0].write(e[1])}))}class pb{constructor(e){this.dtype=e.dtype,this.shape=e.shape,null!=e.shape?this.ndim=e.shape.length:this.ndim=e.ndim,this.maxNDim=e.maxNDim,this.minNDim=e.minNDim,this.axes=e.axes||{}}}class db{constructor(e,t,n,s,r,a,i){this.dtype=e,this.shape=t,this.sourceLayer=n,this.inputs=s,this.callArgs=r,this.outputTensorIndex=i,this.id=Xg(),null!=a&&(this.originalName=uy(a),this.name=cy(this.originalName)),this.rank=t.length}}let fb=0;class mb{constructor(e,t){this.callArgs=t,this.id=fb++,this.outboundLayer=e.outboundLayer,this.inboundLayers=e.inboundLayers,this.nodeIndices=e.nodeIndices,this.tensorIndices=e.tensorIndices,this.inputTensors=e.inputTensors,this.outputTensors=e.outputTensors,this.inputMasks=e.inputMasks,this.outputMasks=e.outputMasks,this.inputShapes=e.inputShapes,this.outputShapes=e.outputShapes;for(const t of e.inboundLayers)null!=t&&t.outboundNodes.push(this);e.outboundLayer.inboundNodes.push(this)}getConfig(){const e=[];for(const t of this.inboundLayers)null!=t?e.push(t.name):e.push(null);return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:e,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}}}let gb=0;class yb extends qp{constructor(e={}){super(),this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=gb++,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 t=e.name;if(!t){const e=this.getClassName();t=Dg(e)+"_"+Zg(e)}if(this.name=t,this.trainable_=null==e.trainable||e.trainable,null!=e.inputShape||null!=e.batchInputShape){let t;if(null!=e.batchInputShape)t=e.batchInputShape;else if(null!=e.inputShape){let n=null;null!=e.batchSize&&(n=e.batchSize),t=[n].concat(e.inputShape)}this.batchInputShape=t;let n=e.dtype;null==n&&(n=e.inputDType),null==n&&(n="float32"),this.dtype=n}null!=e.weights?this.initialWeights=e.weights:this.initialWeights=null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(e,t){return e.name+"_ib-"+t.toString()}getNodeAtIndex(e,t){if(0===this.inboundNodes.length)throw new Ig(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new Sg(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return _g(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return _g(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new Ng(`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 Ng(`Layer ${this.name} is not connected, no input to return.`);return _g(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(0===this.inboundNodes.length)throw new Ng(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new Ng(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return _g(this.getNodeAtIndex(0,"output").outputTensors)}get losses(){return this._losses}calculateLosses(){return this.losses.map((e=>e()))}get updates(){return this._updates}get built(){return this._built}set built(e){this._built=e}get trainable(){return this.trainable_}set trainable(e){this._trainableWeights.forEach((t=>t.trainable=e)),this.trainable_=e}get trainableWeights(){return this.trainable_?this._trainableWeights.filter((e=>e.trainable)):[]}set trainableWeights(e){this._trainableWeights=e}get nonTrainableWeights(){return this.trainable?this._trainableWeights.filter((e=>!e.trainable)).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)}set nonTrainableWeights(e){this._nonTrainableWeights=e}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(e){const t=Fg(e);if(null==this.inputSpec||0===this.inputSpec.length)return;const n=Fg(this.inputSpec);if(t.length!==n.length)throw new Sg(`Layer ${this.name} expects ${n.length} inputs, but it received ${t.length} input tensors. Input received: ${e}`);for(let e=0;e<t.length;e++){const s=t[e],r=n[e];if(null==r)continue;const a=s.rank;if(null!=r.ndim&&a!==r.ndim)throw new Sg(`Input ${e} is incompatible with layer ${this.name}: expected ndim=${r.ndim}, found ndim=${a}`);if(null!=r.maxNDim&&a>r.maxNDim)throw new Sg(`Input ${e} is incompatible with layer ${this.name}: expected max_ndim=${r.maxNDim}, found ndim=${a}`);if(null!=r.minNDim&&a<r.minNDim)throw new Sg(`Input ${e} is incompatible with layer ${this.name}: expected min_ndim=${r.minNDim}, found ndim=${a}.`);if(null!=r.dtype&&s.dtype!==r.dtype)throw new Sg(`Input ${e} is incompatible with layer ${this.name} : expected dtype=${r.dtype}, found dtype=${s.dtype}.`);if(r.axes){const t=s.shape;for(const n in r.axes){const s=Number(n),a=r.axes[n],i=s>=0?t[s]:t[t.length+s];if(null!=a&&-1===[a,null].indexOf(i))throw new Sg(`Input ${e} is incompatible with layer ${this.name}: expected axis ${s} of input shape to have value ${a} but got shape ${t}.`)}}if(null!=r.shape)for(let t=0;t<r.shape.length;++t){const n=r.shape[t],a=s.shape[t];if(null!=n&&null!=a&&n!==a)throw new Sg(`Input ${e} is incompatible with layer ${this.name}: expected shape=${r.shape}, found shape=${s.shape}.`)}}}call(e,t){return e}invokeCallHook(e,t){null!=this._callHook&&this._callHook(e,t)}setCallHook(e){this._callHook=e}clearCallHook(){this._callHook=null}apply(e,t){t=t||{},this.assertNotDisposed();const n=Fg(e),s=function(e){let t=!0;for(const n of Fg(e))if(!(n instanceof db)){t=!1;break}return t}(e),r=function(e){let t=!0;for(const n of Fg(e))if(n instanceof db){t=!1;break}return t}(e);if(s===r)throw new Sg("Arguments to apply() must be all SymbolicTensors or all Tensors");return ly(this.name,(()=>{if(!this.built){this.assertInputCompatibility(e);const t=[];for(const n of Fg(e))t.push(n.shape);this.build(_g(t)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),null===this._refCount&&r&&(this._refCount=1)}if(this.assertInputCompatibility(e),r){let s=this.call(e,t);this.supportsMasking&&this.setMaskMetadata(e,s);const r=Fg(s),a=[];for(let e of r)-1!==n.indexOf(e)&&(e=e.clone()),a.push(e);if(s=_g(a),null!=this.activityRegularizer)throw new Tg("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return s}{const n=function(e){e=Fg(e);const t=[];for(const n of e)t.push(n.shape);return _g(t)}(e),s=this.computeOutputShape(n);let r;const a="float32";if(this.warnOnIncompatibleInputShape(Array.isArray(e)?n[0]:n),r=null!=s&&s.length>0&&Array.isArray(s[0])?s.map(((n,s)=>new db(a,n,this,Fg(e),t,this.name,s))):new db(a,s,this,Fg(e),t,this.name),this.addInboundNode(e,r,null,null,n,s,t),this._refCount++,null!=this.activityRegularizer)throw new Tg("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return r}}))}warnOnIncompatibleInputShape(e){if(null!=this.batchInputShape)if(e.length!==this.batchInputShape.length)console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(e)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);else{let t=!1;this.batchInputShape.forEach(((n,s)=>{null!=n&&null!=e[s]&&e[s]!==n&&(t=!0)})),t&&console.warn(`The shape of the input tensor (${JSON.stringify(e)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`)}}get outputShape(){if(null==this.inboundNodes||0===this.inboundNodes.length)throw new Ng(`The layer ${this.name} has never been called and thus has no defined output shape.`);const e=[];for(const t of this.inboundNodes){const n=JSON.stringify(t.outputShapes);-1===e.indexOf(n)&&e.push(n)}if(1===e.length){const e=this.inboundNodes[0].outputShapes;return Array.isArray(e)&&Array.isArray(e[0])&&1===e.length?e[0]:e}throw new Ng(`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 Ig(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return ob(this.weights)}build(e){this.built=!0}getWeights(e=!1){return cb(e?this.trainableWeights:this.weights)}setWeights(e){Na((()=>{const t=this.weights;if(t.length!==e.length)throw new Sg(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${e.length}, but the layer was expecting ${t.length} weights. Provided weights: ${e}...`);if(0===t.length)return;const n=[],s=cb(t);for(let r=0;r<s.length;++r){const a=s[r],i=t[r],o=e[r];if(!m(a.shape,o.shape))throw new Sg(`Layer weight shape ${a.shape} not compatible with provided weight shape ${o.shape}`);n.push([i,o])}hb(n)}))}addWeight(e,t,n,s,r,a,i,o){if(-1!==this._addedWeightNames.indexOf(e))throw new Sg(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),null==n&&(n="float32"),this.fastWeightInitDuringBuild&&(s=null!=o?o():nb("zeros"));const l=s.apply(t,n),u=new ub(l,n,e,a,i);return l.dispose(),null!=r&&this.addLoss((()=>r.apply(u.read()))),null==a&&(a=!0),a?this._trainableWeights.push(u):this._nonTrainableWeights.push(u),u}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){null==e||Array.isArray(e)&&0===e.length||(e=Fg(e),void 0!==this._losses&&null!==this._losses&&this.losses.push(...e))}computeOutputShape(e){return e}computeMask(e,t){if(!this.supportsMasking){if(null!=t){if(!Array.isArray(t))throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);t.forEach((e=>{if(null!=e)throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`)}))}return null}return t}setMaskMetadata(e,t,n){if(!this.supportsMasking)return;const s=this.computeMask(e,n),r=Fg(t),a=Fg(s);if(r.length!==a.length)throw new Error(`${this.name} outputs ${r.length} tensors but ${r.length} masks for those tensors`);for(let e=0;e<r.length;e++)r[e].kerasMask=a[e]}addInboundNode(e,t,n,s,r,a,i=null){const o=Fg(e);t=Fg(t),n=Fg(n),s=Fg(s),r=rb(r),a=rb(a);const l=[],u=[],c=[];for(const e of o)l.push(e.sourceLayer),u.push(e.nodeIndex),c.push(e.tensorIndex);new mb({outboundLayer:this,inboundLayers:l,nodeIndices:u,tensorIndices:c,inputTensors:o,outputTensors:t,inputMasks:n,outputMasks:s,inputShapes:r,outputShapes:a},i);for(let e=0;e<t.length;e++)t[e].sourceLayer=this,t[e].nodeIndex=this.inboundNodes.length-1,t[e].tensorIndex=e}getConfig(){const e={name:this.name,trainable:this.trainable};return null!=this.batchInputShape&&(e.batchInputShape=this.batchInputShape),null!=this.dtype&&(e.dtype=this.dtype),e}disposeWeights(){return this.weights.forEach((e=>e.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 e=0;return 0==--this._refCount&&(e=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:e}}}function bb(e,t,n){if((null==t||null!=n&&n>0)&&(t=e.sourceLayer,n=e.nodeIndex),0===t.inboundNodes.length)return[e];{const e=t.inboundNodes[n];if(0===e.inboundLayers.length)return e.inputTensors;{const t=[];for(let n=0;n<e.inboundLayers.length;n++){const s=bb(e.inputTensors[n],e.inboundLayers[n],e.nodeIndices[n]);for(const e of s)-1===t.indexOf(e)&&t.push(e)}return t}}}class xb extends yb{constructor(e){if(super({dtype:e.dtype,name:null!=e.name?e.name:Zg("input").toString()}),null==e.batchSize&&(e.batchSize=null),null==e.sparse&&(e.sparse=!1),this.trainable=!1,this.built=!0,this.sparse=e.sparse,null!=e.inputShape&&null!=e.batchInputShape)throw new Sg("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");let t=e.batchInputShape;if(null==t){if(null==e.inputShape)throw new Sg("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(null!=e.batchSize)throw new Sg("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");const n=e.dtype||"float32";this.batchInputShape=t,this.dtype=n,this.inputSpec=[{shape:t}];const s=new db(this.dtype,this.batchInputShape,this,[],{},this.name);s.nodeIndex=0,s.tensorIndex=0,new mb({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[s],outputTensors:[s],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new Sg(`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 wb(e){if(null==e.batchShape&&null==e.shape)throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");if(null!=e.batchShape&&null!=e.shape)throw new Sg("Please provide either a `shape` or `batchShape` argument to Input, but not both.");let t=e.batchShape;null!=e.shape&&null==t&&(t=[null].concat(e.shape));let n=e.dtype;null==n&&(n="float32");return new xb({batchInputShape:t,name:e.name,dtype:n,sparse:e.sparse}).inboundNodes[0].outputTensors[0]}xb.className="InputLayer",Xp(xb);class vb{constructor(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof vb)for(const t in e.id2Value)this.id2Value[t]=e.id2Value[t],t in e.id2Mask&&(this.id2Mask[t]=e.id2Mask[t]);else{if(null==e)return;for(const t of e)this.add(t.key,t.value)}}add(e,t,n){if(null!=this.id2Value[e.id])throw new Sg(`Duplicate key: name=${e.name}, id=${e.id}`);return this.id2Value[e.id]=function(e,t){if(null==e.dtype||e.dtype===t.dtype)return t;try{return Ti(t,e.dtype)}catch(n){throw new Sg(`The dtype of the feed (${t.dtype}) can not be cast to the dtype of the key '${e.name}' (${e.dtype}).`)}}(e,t),this.name2Id[e.name]=e.id,null!=n&&(this.id2Mask[e.id]=n),this}addFeed(e){this.add(e.key,e.value)}hasKey(e){return null!=this.id2Value[e.id]}names(){return Object.keys(this.name2Id)}getValue(e){if(e instanceof db){if(null==this.id2Value[e.id])throw new Sg(`Nonexistent key: ${e.name}`);return this.id2Value[e.id]}{const t=this.name2Id[e];if(null==t)throw new Sg(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Value[t]}}getMask(e){if(e instanceof db){if(null==this.id2Value[e.id])throw new Sg(`Nonexistent key: ${e.name}`);return this.id2Mask[e.id]}{const t=this.name2Id[e];if(null==t)throw new Sg(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Mask[t]}}disposeMasks(){null!=this.id2Mask&&Ia(this.id2Mask)}}const kb=new $g,Nb=new $g;function Ib(e,t,n,s){const r=null!=n&&n.training,a=Array.isArray(e),i=a?e:[e],o=i.map((e=>e.name)),l=[],u=t.names();for(const e of o)-1!==u.indexOf(e)?l.push(t.getValue(e)):l.push(null);null!=s&&(s.maxNumTensors=-1/0,s.minNumTensors=1/0);const h=o.join(",")+"|"+t.names().sort().join(",");let p,d=kb.get(h);if(null==d){const e=function(e,t){c(null!=e&&e.length>0,(()=>"Expected at least one fetch, got none"));let n=[],s={};if(1===e.length){const r=Tb(e[0],t);n=r.sorted,s=r.recipientMap}else{const r=new Set;for(const a of e){const{sorted:e,recipientMap:i}=Tb(a,t);for(const t of e)r.has(t.name)||(n.push(t),r.add(t.name));for(const e in i)null==s[e]&&(s[e]=new Set),i[e].forEach((t=>s[e].add(t)))}}return{sorted:n,recipientCounts:Sb(s)}}(i,t);d=e.sorted,p=e.recipientCounts,kb.put(h,d),Nb.put(h,p)}p={},r||Object.assign(p,Nb.get(h));const f=new vb(t);for(let e=0;e<d.length;++e){if(null!=s){const e=ka().numTensors;e>s.maxNumTensors&&(s.maxNumTensors=e),e<s.minNumTensors&&(s.minNumTensors=e)}const a=d[e],i=a.sourceLayer;if(i instanceof xb)continue;const u=[],c=[],h=[];let m=!1;for(const e of a.inputs){const n=f.getValue(e),s=f.getMask(e);u.push(n),c.push(s),null!=s&&(m=!0),r||(p[e.name]--,0!==p[e.name]||t.hasKey(e)||-1!==o.indexOf(e.name)||n.isDisposed||!0===e.sourceLayer.stateful||h.push(n))}m&&((n=n||{}).mask=c[0]);const g=Fg(i.apply(u,n));let y=null;i.supportsMasking&&(y=i.computeMask(u,c));const b=Cb(a),x=Array.isArray(b)?b:[b];for(let e=0;e<x.length;++e){f.hasKey(x[e])||f.add(x[e],g[e],Array.isArray(y)?y[0]:y);const t=o.indexOf(x[e].name);-1!==t&&(l[t]=g[e])}r||Ia(h)}return f.disposeMasks(),a?l:l[0]}function Sb(e){const t={};for(const n in e)t[n]=e[n].size;return t}function Tb(e,t){const n=new Set,s=[],r={};for(const e of t.names())n.add(e);const a=[],i=[];for(a.push(e);a.length>0;){const e=a[a.length-1];if(n.has(e.name)){a.pop();continue}const t=i[i.length-1]===a.length-1;if(0===e.inputs.length||t)a.pop(),s.push(e),n.add(e.name),t&&i.pop();else{i.push(a.length-1);for(const t of e.inputs)null==r[t.name]&&(r[t.name]=new Set),r[t.name].add(e.name),n.has(t.name)||a.push(t)}}return{sorted:s,recipientMap:r}}function Cb(e){let t;if(1===e.sourceLayer.inboundNodes.length)t=e.sourceLayer.output;else{let n=null;for(let t=0;t<e.sourceLayer.inboundNodes.length;++t)for(const s of e.sourceLayer.inboundNodes[t].outputTensors)if(s.id===e.id){n=t;break}t=e.sourceLayer.getOutputAt(n)}return t}function $b(e,t){return Na((()=>wl(kl(_i(e,e),t,!0))))}Y().registerFlag("TOPOLOGICAL_SORT_CACHE_MAX_ENTRIES",(()=>100),(function(e){null!=kb&&kb.setMaxEntries(e),null!=Nb&&Nb.setMaxEntries(e)}));class Eb extends qp{getConfig(){return{}}}class Ab extends Eb{constructor(e){super(),this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=null!=e.maxValue?e.maxValue:this.defaultMaxValue,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return Na((()=>{const t=$b(e,this.axis),n=$o(t,0,this.maxValue);return _i(e,Ri(n,Ei(by(),t)))}))}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}Ab.className="MaxNorm",Xp(Ab);class Rb extends Eb{constructor(e){super(),this.defaultAxis=0,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return Na((()=>Ri(e,Ei(by(),$b(e,this.axis)))))}getConfig(){return{axis:this.axis}}}Rb.className="UnitNorm",Xp(Rb);class _b extends Eb{apply(e){return Nc(e)}}_b.className="NonNeg",Xp(_b);class Fb extends Eb{constructor(e){super(),this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=null!=e.minValue?e.minValue:this.defaultMinValue,this.maxValue=null!=e.maxValue?e.maxValue:this.defaultMaxValue,this.rate=null!=e.rate?e.rate:this.defaultRate,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return Na((()=>{const t=$b(e,this.axis),n=Ei(_i(this.rate,$o(t,this.minValue,this.maxValue)),_i(1-this.rate,t));return _i(e,Ri(n,Ei(by(),t)))}))}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}Fb.className="MinMaxNorm",Xp(Fb);const Db={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function Ob(e){return Lg(e)}function Mb(e,t={}){return Pg(e,Kp.getMap().classNameMap,t,"constraint")}function Lb(e){if(null==e)return null;if("string"==typeof e){return Mb({className:e in Db?Db[e]:e,config:{}})}return e instanceof Eb?e:Mb(e)}var zb=Object.freeze({__proto__:null,maxNorm:function(e){return new Ab(e)},minMaxNorm:function(e){return new Fb(e)},nonNeg:function(){return new _b},unitNorm:function(e){return new Rb(e)}});var Pb,Bb=Object.freeze({__proto__:null,constant:function(e){return new By(e)},glorotNormal:function(e){return new qy(e)},glorotUniform:function(e){return new jy(e)},heNormal:function(e){return new Ky(e)},heUniform:function(e){return new Xy(e)},identity:function(e){return new Gy(e)},leCunNormal:function(e){return new Yy(e)},leCunUniform:function(e){return new Zy(e)},ones:function(){return new Py},orthogonal:function(e){return new Jy(e)},randomNormal:function(e){return new Vy(e)},randomUniform:function(e){return new Wy(e)},truncatedNormal:function(e){return new Uy(e)},varianceScaling:function(e){return new Hy(e)},zeros:function(){return new zy}});async function Wb(e){if(null==e)return;const t=[],n=[],s=[];for(const r in e){const a=e[r];if("number"!=typeof a){const e=a;t.push(e.data()),n.push(r),s.push(e)}}if(t.length>0){const r=await Promise.all(t);for(let t=0;t<r.length;++t)e[n[t]]=r[t][0];Ia(s)}}function Vb(e){if(null!=e)for(const t in e){const n=e[t];"number"!=typeof n&&n.dispose()}}!function(e){e[e.SILENT=0]="SILENT",e[e.VERBOSE=1]="VERBOSE"}(Pb||(Pb={}));class Ub{constructor(){this.validationData=null}setParams(e){this.params=e}async onEpochBegin(e,t){}async onEpochEnd(e,t){}async onBatchBegin(e,t){}async onBatchEnd(e,t){}async onTrainBegin(e){}async onTrainEnd(e){}setModel(e){}}class Gb{constructor(e,t=10){null==e&&(e=[]),this.callbacks=e,this.queueLength=t}append(e){this.callbacks.push(e)}setParams(e){for(const t of this.callbacks)t.setParams(e)}setModel(e){for(const t of this.callbacks)t.setModel(e)}async onEpochBegin(e,t){null==t&&(t={});for(const n of this.callbacks)await n.onEpochBegin(e,t)}async onEpochEnd(e,t){null==t&&(t={});for(const n of this.callbacks)await n.onEpochEnd(e,t)}async onBatchBegin(e,t){null==t&&(t={});for(const n of this.callbacks)await n.onBatchBegin(e,t)}async onBatchEnd(e,t){null==t&&(t={});for(const n of this.callbacks)await n.onBatchEnd(e,t)}async onTrainBegin(e){null==e&&(e={});for(const t of this.callbacks)await t.onTrainBegin(e)}async onTrainEnd(e){null==e&&(e={});for(const t of this.callbacks)await t.onTrainEnd(e)}}class Hb extends Ub{constructor(){super()}async onEpochBegin(e){this.seen=0,this.totals={}}async onBatchEnd(e,t){null==t&&(t={});const n=null==t.size?0:t.size;this.seen+=n;for(const e in t){const s=t[e];if("number"==typeof s)this.totals.hasOwnProperty(e)||(this.totals[e]=0),this.totals[e]=this.totals[e]+s*n;else{let t;e in this.totals?t=this.totals[e]:this.totals[e]=0;const r=Na((()=>Ei(this.totals[e],_i(s,n))));this.totals[e]=r,null!=t&&t.dispose()}}}async onEpochEnd(e,t){if(null!=t)for(const e of this.params.metrics)null!=this.totals[e]&&("number"==typeof this.totals[e]?t[e]=this.totals[e]/this.seen:Na((()=>{const n=_i(Ri(1,this.seen),this.totals[e]);t[e]=n,this.totals[e].dispose(),Sa(t[e])})))}}class jb extends Ub{async onTrainBegin(e){this.epoch=[],this.history={}}async onEpochEnd(e,t){null==t&&(t={}),this.epoch.push(e);for(const e in t)null==this.history[e]&&(this.history[e]=[]),this.history[e].push(t[e])}async syncData(){const e=[],t=[],n=[];for(const s in this.history){const r=this.history[s];for(let a=0;a<r.length;++a)if("number"!=typeof r[a]){const i=r[a];e.push(i.data()),t.push(s),n.push(a)}}const s=await Promise.all(e);for(let e=0;e<s.length;++e){this.history[t[e]][n[e]].dispose(),this.history[t[e]][n[e]]=s[e][0]}}}class qb extends Ub{constructor(e,t){if(super(),this.currentEpoch=0,this.nowFunc=e.nowFunc,this.nextFrameFunc=e.nextFrameFunc||ef,this.yieldEvery=t||"auto","auto"===this.yieldEvery&&(this.yieldEvery=125),"never"===this.yieldEvery&&null!=e.onYield)throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");_(this.yieldEvery)&&(this.maybeWait=function(e,t,n){let s,r=null!=n?n():dr();return(...a)=>{const i=null!=n?n():dr();return i-r<t||(r=i,s=e(...a)),s}}(this.maybeWait.bind(this),this.yieldEvery,this.nowFunc)),this.trainBegin=e.onTrainBegin,this.trainEnd=e.onTrainEnd,this.epochBegin=e.onEpochBegin,this.epochEnd=e.onEpochEnd,this.batchBegin=e.onBatchBegin,this.batchEnd=e.onBatchEnd,this.yield=e.onYield}async maybeWait(e,t,n){const s=[];null!=this.yield&&(await Wb(n),s.push(this.yield(e,t,n))),s.push(this.nextFrameFunc()),await Promise.all(s)}async onEpochBegin(e,t){this.currentEpoch=e,null!=this.epochBegin&&(await Wb(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){const n=[];null!=this.epochEnd&&(await Wb(t),n.push(this.epochEnd(e,t))),"epoch"===this.yieldEvery&&n.push(this.nextFrameFunc()),await Promise.all(n)}async onBatchBegin(e,t){null!=this.batchBegin&&(await Wb(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){const n=[];null!=this.batchEnd&&(await Wb(t),n.push(this.batchEnd(e,t))),"batch"===this.yieldEvery?n.push(this.nextFrameFunc()):_(this.yieldEvery)&&n.push(this.maybeWait(this.currentEpoch,e,t)),await Promise.all(n)}async onTrainBegin(e){null!=this.trainBegin&&(await Wb(e),await this.trainBegin(e))}async onTrainEnd(e){null!=this.trainEnd&&(await Wb(e),await this.trainEnd(e))}}function Kb(e,t){if(null==e&&(e={}),e instanceof Ub)return[e];if(Array.isArray(e)&&e[0]instanceof Ub)return e;return Fg(e).map((e=>new qb(e,t)))}class Xb{constructor(){}static registerCallbackConstructor(e,t){c(e>=0&&Number.isInteger(e),(()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`)),Xb.checkForDuplicate(t),null==Xb.constructors[e]&&(Xb.constructors[e]=[]),Xb.constructors[e].push(t)}static checkForDuplicate(e){for(const t in Xb.constructors){Xb.constructors[+t].forEach((t=>{if(t===e)throw new Sg("Duplicate callback constructor.")}))}}static clear(){Xb.constructors={}}static createCallbacks(e){const t=[];for(const n in Xb.constructors){const s=+n;e>=s&&t.push(...Xb.constructors[s])}return t.map((e=>new e))}}function Yb(e,t,n,s,r,a,i,o,l){const u=new jb,c=[new Hb,...Xb.createCallbacks(t)];null!=e&&c.push(...e),c.push(u);const h=new Gb(c);return h.setParams({epochs:n,initialEpoch:s,samples:r,steps:a,batchSize:i,verbose:t,doValidation:o,metrics:l}),{callbackList:h,history:u}}function Zb(e,t={},n=!1){return Pg(e,Kp.getMap().classNameMap,t,"layer",n)}function Jb(e,t){return Na((()=>{"float32"!==e.dtype&&(e=Ti(e,"float32"));const n=kl(Ay(e),t,!0),s=Co(n.shape,by()),r=wl(hu(n,s));return Ri(e,r)}))}function Qb(e,t){return Na((()=>pu(Ay(Jl(t,e)),-1)))}function ex(e,t){return Na((()=>pu(Fi(Jl(t,e)),-1)))}function tx(e,t){return Na((()=>{const n=Jl(e,t),s=$o(Fi(e),by(),Number.MAX_VALUE),r=Fi(Ri(n,s));return _i(100,pu(r,-1))}))}function nx(e,t){return Na((()=>{const n=$o(t,by(),Number.MAX_VALUE),s=Gl(Ei(1,n)),r=$o(e,by(),Number.MAX_VALUE),a=Gl(Ei(1,r));return pu(Ay(Jl(s,a)),-1)}))}function sx(e,t,n=!1){return Na((()=>{if(n)t=Vc(t);else{const e=kl(t,t.shape.length-1,!0);t=Ri(t,e)}return t=$o(t,by(),1-by()),Xl(kl(_i(Ti(e,"float32"),Gl(t)),t.shape.length-1))}))}function rx(e,t,n=!1){return Na((()=>{const s=Ti(Rl(function(e){const t=[dy(e.shape)];return oo(e,t)}(e)),"int32"),r=(t=$o(t,by(),1-by())).shape;return sx(oo(Nu(s,r[r.length-1]),r),t,n)}))}function ax(e,t){return Na((()=>{let n;return n=$o(t,by(),1-by()),n=Gl(Ri(n,Jl(1,n))),pu(function(e,t){if(!m(e.shape,t.shape))throw new Sg(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return Na((()=>{const n=Nc(t),s=Xl(Fi(t));return Ei(Jl(n,_i(t,e)),Hl(Tl(s)))}))}(e,n),-1)}))}function ix(e,t){return Na((()=>{const n=$o(e,by(),1),s=$o(t,by(),1);return kl(_i(e,Gl(Ri(n,s))),-1)}))}function ox(e,t){return Na((()=>{const n=Jb(e,-1),s=Jb(t,-1),r=_i(n,s);return Xl(kl(r,-1))}))}Xb.constructors={};const lx={meanSquaredError:Qb,meanAbsoluteError:ex,meanAbsolutePercentageError:tx,meanSquaredLogarithmicError:nx,squaredHinge:function(e,t){return Na((()=>{const n=hu(0,Jl(1,_i(e,t)));return pu(Ay(n),-1)}))},hinge:function(e,t){return Na((()=>{const n=hu(0,Jl(1,_i(e,t)));return pu(n,-1)}))},categoricalHinge:function(e,t){return Na((()=>{const n=kl(_i(e,t),-1),s=gl(_i(Jl(1,e),t),-1);return hu(0,Ei(1,Jl(s,n)))}))},logcosh:function(e,t){return Na((()=>{const n=Math.log(2),s=Jl(t,e),r=Jl(Ei(s,Yl(_i(-2,s))),n);return pu(r,-1)}))},categoricalCrossentropy:sx,sparseCategoricalCrossentropy:rx,binaryCrossentropy:ax,kullbackLeiblerDivergence:ix,poisson:function(e,t){return Na((()=>{const n=Gl(Ei(by(),t));return pu(Jl(t,_i(e,n)),-1)}))},cosineProximity:ox};function ux(e){if("string"==typeof e){if(e in lx)return lx[e];let t=`Unknown loss ${e}`;throw e.toLowerCase().includes("softmaxcrossentropy")&&(t=`Unknown loss ${e}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`),new Sg(t)}return e}function cx(e,t){return Na((()=>{const n=_i(.5,Iu(t)),s=xy(Fl(t,n),e.dtype);return pu(Qo(e,s),-1)}))}function hx(e,t){return Na((()=>xy(Qo(Pi(e,-1),Pi(t,-1)),"float32")))}function px(e,t){return Na((()=>Ti(kl(tu(Qo(e,1),Qo(t,1))),"float32")))}function dx(e,t){return Na((()=>{const n=px(e,t),s=function(e,t){return Na((()=>Ti(kl(tu(Qo(e,0),Qo(t,1))),"float32")))}(e,t),r=Ei(n,s);return Ti(el(Fl(r,0),Ri(n,r),0),"float32")}))}function fx(e,t){return Na((()=>{const n=px(e,t),s=function(e,t){return Na((()=>Ti(kl(tu(Qo(e,1),Qo(t,0))),"float32")))}(e,t),r=Ei(n,s);return Ti(el(Fl(r,0),Ri(n,r),0),"float32")}))}function mx(e,t){return ax(e,t)}function gx(e,t){return e.rank===t.rank&&(e=Xc(e,[e.rank-1])),(t=Pi(t,-1)).dtype!==e.dtype&&(t=Ti(t,e.dtype)),Ti(Qo(e,t),"float32")}const yx=sx,bx=rx,xx={binaryAccuracy:cx,categoricalAccuracy:hx,precision:dx,categoricalCrossentropy:yx,sparseCategoricalCrossentropy:bx,mse:Qb,MSE:Qb,mae:ex,MAE:ex,mape:tx,MAPE:tx,cosine:ox};function wx(e){if("string"==typeof e&&e in xx)return xx[e];if("string"!=typeof e&&null!=e)return e;throw new Sg(`Unknown metric ${e}`)}function vx(e){if(Ag(null!==e,`Unknown LossOrMetricFn ${e}`),"string"==typeof e)return e;{let t;for(const n of Object.keys(lx))if(lx[n]===e){t=n;break}if(void 0!==t)return t;for(const n of Object.keys(xx))if(xx[n]===e){t=n;break}return void 0!==t?t:e.name}}const kx=1048576;function Nx(e,t,n=!1){if(null==e||"object"!=typeof e||Object.getPrototypeOf(e)!==Object.prototype||!Ix(e))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(n){const n=JSON.stringify(e);n.length>kx&&console.warn(`User-defined metadata of model "${t}" 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 Ix(e){if(null===e)return!0;if("object"==typeof e){if(Object.getPrototypeOf(e)===Object.prototype){const t=Object.keys(e);for(const n of t){if("string"!=typeof n)return!1;if(!Ix(e[n]))return!1}return!0}if(Array.isArray(e)){for(const t of e)if(!Ix(t))return!1;return!0}return!1}{const t=typeof e;return"string"===t||"number"===t||"boolean"===t}}function Sx(e,t,n,s=console.log){const r=function(e){let t=!0;const n=[],s=[];for(const t in e.nodesByDepth)n.push(e.nodesByDepth[t]);for(const e of n){if(e.length>1||1===e.length&&e[0].inboundLayers.length>1){t=!1;break}s.push(...e)}if(t)for(const n of e.layers){let e=!1;for(const r of n.inboundNodes)if(-1!==s.indexOf(r)){if(e){t=!1;break}e=!0}if(!t)break}return t}(e),a=["Layer (type)","Input Shape","Output shape","Param #"];let i;if(r?(t=t||90,n=n||[.32,.61,.89,1]):(t=t||115,n=n||[.24,.48,.7,.8,1]),n[n.length-1]<=1&&(n=n.map((e=>Math.floor(t*e)))),!r){a.push("Receives inputs"),i=[];for(const t in e.nodesByDepth)i.push(...e.nodesByDepth[t])}s("_".repeat(t)),Tx(a,n,s),s("=".repeat(t));const o=e.layers;for(let e=0;e<o.length;++e)r?Cx(o[e],n,s):$x(o[e],n,i,s),s((e===o.length-1?"=":"_").repeat(t));e.checkTrainableWeightsConsistency();const l=function(e){let t;t=null!=e.collectedTrainableWeights?ob(e.collectedTrainableWeights):ob(e.trainableWeights);return t}(e),u=ob(e.nonTrainableWeights);s(`Total params: ${l+u}`),s(`Trainable params: ${l}`),s(`Non-trainable params: ${u}`),s("_".repeat(t))}function Tx(e,t,n=console.log){let s="";for(let n=0;n<e.length;++n)n>0&&(s=s.slice(0,s.length-1)+" "),s+=e[n],s=s.slice(0,t[n]),s+=" ".repeat(t[n]-s.length);n(s)}function Cx(e,t,n){let s,r;try{r=e.inboundNodes.map((e=>JSON.stringify(e.inputShapes))).join(",")}catch(e){r="multiple"}try{s=JSON.stringify(e.outputShape)}catch(e){s="multiple"}Tx([`${e.name} (${e.getClassName()})`,r,s,e.countParams().toString()],t,n)}function $x(e,t,n,s){let r,a;try{a=e.inboundNodes.map((e=>JSON.stringify(e.inputShapes))).join(",")}catch(e){a="multiple"}try{r=JSON.stringify(e.outputShape)}catch(e){r="multiple"}const i=[];for(const t of e.inboundNodes)if(!(null!=n&&n.length>0&&-1===n.indexOf(t)))for(let e=0;e<t.inboundLayers.length;++e){const n=t.inboundLayers[e].name,s=t.nodeIndices[e],r=t.tensorIndices[e];i.push(`${n}[${s}][${r}]`)}const o=e.name,l=e.getClassName(),u=0===i.length?"":i[0];Tx([`${o} (${l})`,a,r,e.countParams().toString(),u],t,s);for(let e=1;e<i.length;++e)Tx(["","","","",i[e]],t,s)}function Ex(e,t,n){return("inboundNodes"===e||"outputLayers"===e||"inputLayers"===e)&&0===t&&"string"==typeof n}function Ax(e,t){if(null===e)return null;if("string"==typeof e)return Og(e);if("number"==typeof e||"boolean"==typeof e)return e;if(e instanceof Array){const n=[],s=e.length;for(let r=0;r<s;++r){const s=e[r];Ex(t,r,s)?n.push(s):n.push(Ax(s,t))}return n}{const t={};for(const n of Object.keys(e)){const s=e[n];if("name"===n&&"string"==typeof s)t[n]=s;else{const e=Og(n);t[e]=Ax(s,e)}}return t}}function Rx(e,t){if(null==e)return null;if("string"==typeof e)return Dg(e);if("number"==typeof e||"boolean"==typeof e)return e;if(e instanceof Array){const n=[],s=e.length;for(let r=0;r<s;++r){const s=e[r];Ex(t,r,s)?n.push(s):n.push(Rx(s,t))}return n}{const t={};for(const n of Object.keys(e)){const s=e[n],r=Dg(n);t[r]="name"!==n&&"className"!==n||"string"!=typeof s?Rx(s,n):s}return t}}const _x="4.15.0";class Fx extends yb{constructor(e){if(super({}),this.containerNodes=new Set,this.name=e.name,null==this.name){const e=this.getClassName().toLowerCase();this.name=Zg(e)}if(this.supportsMasking=!1,this.trainable_=!0,Array.isArray(e.inputs)?this.inputs=e.inputs.slice():this.inputs=[e.inputs],Array.isArray(e.outputs)?this.outputs=e.outputs.slice():this.outputs=[e.outputs],Wg(this.inputs).length!==this.inputs.length)throw new Sg(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map((e=>e.name))}`);Wg(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((e=>e.name))}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(const e of this.outputs){const t=e.sourceLayer,n=e.nodeIndex,s=e.tensorIndex;this.outputLayers.push(t),this.outputLayersNodeIndices.push(n),this.outputLayersTensorIndices.push(s)}for(const e of this.inputs){const t=e.sourceLayer,n=e.nodeIndex,s=e.tensorIndex;Ag(0===n,"input layer has >1 nodes"),Ag(0===s,"input layer has >1 tensors"),this.inputLayers.push(t),this.inputLayersNodeIndices.push(n),this.inputLayersTensorIndices.push(s)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let t=0;t<this.inputLayers.length;t++){const n=this.inputLayers[t];if(!(n instanceof xb))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${e.inputs}. Input ${t} (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 e of this.outputLayers)this.outputNames.push(e.name);this.internalInputShapes=this.inputs.map((e=>e.shape)),this.internalOutputShapes=this.outputs.map((e=>e.shape));const t={},n={},s={},r={},a={},i=[],o=(e,t,n,s,r,l)=>{null!=s&&null!=r&&null!=l||(s=e.sourceLayer,r=e.nodeIndex,l=e.tensorIndex);const u=s.inboundNodes[r];if(-1!==n.indexOf(u))throw new Ig(`The tensor ${e.name} at layer "${s.name}" is part of a cycle.`);if(-1!==t.indexOf(u))return;this.containerNodes.add(Fx.nodeKey(s,r)),s.id in a||(a[s.id]=Object.keys(a).length),-1===n.indexOf(u)&&n.push(u);const c=u.inboundLayers.length;for(let e=0;e<c;e++){const s=u.inputTensors[e],r=u.inboundLayers[e],a=u.nodeIndices[e],i=u.tensorIndices[e];o(s,t,n,r,a,i)}for(t.push(u);n.indexOf(u)>=0;)n.splice(n.indexOf(u),1);i.push(u)},l=[],u=[];for(const e of this.outputs)o(e,l,u);const c=i.slice().reverse();for(const e of c){n[e.id]=e,e.id in t||(t[e.id]=0);let a=t[e.id];const i=null==s[e.outboundLayer.id]?0:s[e.outboundLayer.id];a=Math.max(a,i),s[e.outboundLayer.id]=a,r[e.outboundLayer.id]=e.outboundLayer,t[e.id]=a;for(let s=0;s<e.inboundLayers.length;s++){const r=e.inboundLayers[s],i=e.nodeIndices[s],o=r.inboundNodes[i],l=null==t[o.id]?0:t[o.id];t[o.id]=Math.max(a+1,l),n[o.id]=o}}const h={};for(const e in t){const s=t[e];s in h||(h[s]=[]),h[s].push(n[e])}const p={};for(const e in s){const t=s[e];t in p||(p[t]=[]),p[t].push(r[e])}let d=Object.keys(p).map((e=>parseInt(e,10))).sort(Bg);this.layers=[];for(const e of d){const t=p[e];t.sort(((e,t)=>{const n=a[e.id],s=a[t.id];return n<s?-1:n>s?1:0}));for(const e of t)e instanceof Fx&&this.internalContainerRefs.push(e),this.layers.push(e)}this.layersByDepth=p,d=Object.keys(h).map((e=>parseInt(e,10))).sort(Bg);const f=this.inputs.slice(),m=[];for(const e of d)for(const t of h[e]){const e=t.outboundLayer;if(null!=e){for(const n of t.inputTensors)if(-1===f.indexOf(n))throw new Ig(`Graph disconnected: cannot obtain value for tensor ${n} at layer "${e.name}". The following previous layers were accessed without issue: ${m}`);for(const e of t.outputTensors)f.push(e);m.push(e.name)}}this.nodesByDepth=h;const g=this.layers.map((e=>e.name));for(const e of g){const t=g.filter((t=>t===e)).length;if(1!==t)throw new Ig(`The name "${e}" is used ${t} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(g))}this.outboundNodes=[],this.inboundNodes=[],new mb({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map((e=>null)),outputMasks:this.outputs.map((e=>null)),inputShapes:this.inputs.map((e=>e.shape)),outputShapes:this.outputs.map((e=>e.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 e={refCountAfterDispose:null,numDisposedVariables:0};if(0==--this._refCount){for(const t of this.layers)e.numDisposedVariables+=t.dispose().numDisposedVariables;for(const t of this.internalContainerRefs)e.numDisposedVariables+=t.dispose().numDisposedVariables}return e.refCountAfterDispose=this._refCount,e}get trainable(){return this.trainable_}set trainable(e){this.layers.forEach((t=>{t._trainableWeights.forEach((t=>t.trainable=e))})),this.trainable_=e}get trainableWeights(){if(this._trainableWeights.length>0)throw new Sg("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 e=[];for(const t of this.layers)e=e.concat(t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.layers)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const e of this.layers)t.push(...e.trainableWeights);return t.concat(e)}return e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(e,t=!0){const n={};let s=0;const r=(e=>{const t=Object.keys(e);if(0===t.length)return!1;const n=t[0].split("/");return!isNaN(parseInt(n[n.length-1],10))})(e);r&&this.parseWeights(e);for(const e of this.layers)for(const[t,a]of e.weights.entries()){const e=r?`${a.name.split("/").slice(0,-1).join("/")+"/"}${t}`:a.originalName;if(null!=n[e])throw new Sg(`Duplicate weight name: ${e}`);n[e]=a,s++}const a=[];for(const s in e){let r=s;if(null==n[s]){const e=s.split("/");r=e.slice(0,-2).concat([e[e.length-1]]).join("/")}if(null!=n[r])a.push([n[r],e[s]]);else if(t)throw new Sg(`Provided weight data has no target variable: ${s}`);delete n[r]}if(t){const e=[];for(const t in n)e.push(t);if(e.length>0)throw new Sg(`${e.length} of ${s} weights are not set: ${e}`)}hb(a)}parseWeights(e){for(const t in Object.keys(e)){const n=t.split("/"),s=["vars","layer_checkpoint_dependencies"],r=n.map((e=>e.startsWith("_")?e.slice(1):e)).filter((e=>!s.includes(e))).join("/");r!==t&&(e[r]=e[t],delete e[t])}}updatedConfig(){const e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion="tfjs-layers 4.15.0",t.backend="TensorFlow.js",t}toJSON(e,t=!0){const n=Rx(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return Na((()=>{e=Fg(e);const n=new vb;for(let t=0;t<this.inputs.length;++t)n.add(this.inputs[t],e[t]);return Ib(this.outputs,n,t)}))}computeMask(e,t){return Na((()=>{let n;return e=Fg(e),n=null==t?Eg(null,e.length):Fg(t),this.runInternalGraph(e,n)[1]}))}computeOutputShape(e){const t=rb(e);if(t.length!==this.inputLayers.length)throw new Sg(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);const n={};for(let e=0;e<t.length;e++){const s=this.inputLayers[e],r=t[e];n[s.name+"_0_0"]=r}const s=Object.keys(this.nodesByDepth).map((e=>parseInt(e,10))).sort(Bg);if(s.length>1)for(const e of s){const t=this.nodesByDepth[e];for(const e of t){const t=e.outboundLayer;if(-1!==this.inputLayers.map((e=>e.id)).indexOf(t.id))continue;const s=[];for(let t=0;t<e.inboundLayers.length;t++){const r=e.inboundLayers[t],a=e.nodeIndices[t],i=e.tensorIndices[t],o=n[`${r.name}_${a}_${i}`];s.push(o)}const r=rb(t.computeOutputShape(_g(s))),a=t.inboundNodes.indexOf(e);for(let e=0;e<r.length;e++){n[`${t.name}_${a}_${e}`]=r[e]}}}const r=[],a=[];for(let e=0;e<this.outputLayers.length;e++){const t=this.outputLayers[e],n=this.outputLayersNodeIndices[e],s=this.outputLayersTensorIndices[e],r=`${t.name}_${n}_${s}`;a.push(r)}for(let e=0;e<a.length;e++){const t=a[e];Ag(t in n),r.push(n[t])}return _g(r)}runInternalGraph(e,t){null==t&&(t=Eg(null,e.length));const n={};for(let s=0;s<this.inputs.length;++s){const r=this.inputs[s],a=e[s],i=t[s];n[r.id]=[a,i]}const s=Object.keys(this.nodesByDepth).map((e=>parseInt(e,10))).sort(Bg);for(const e of s){const t=this.nodesByDepth[e];for(const e of t){const t=e.outboundLayer,s=e.inputTensors,r=e.outputTensors,a=new Array;for(const e of s)e.id in n&&a.push(n[e.id]);if(a.length===s.length){let s,i,o,l,u={};if(null!=e.callArgs&&(u=e.callArgs),1===a.length){const[e,n]=a[0];null==u.mask&&(u.mask=n),o=Fg(t.call(e,u)),l=Fg(t.computeMask(e,n)),s=[e],i=[n]}else s=a.map((e=>e[0])),i=a.map((e=>e[1])),null==u.mask&&(u.mask=i),o=Fg(t.call(s,u)),l=Fg(t.computeMask(s,i));if(t.activityRegularizer)throw new Tg("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let e=0;e<r.length;++e){const t=r[e],s=o[e],a=l[e];n[t.id]=[s,a]}}}}const r=[],a=[],i=[];for(const e of this.outputs){Ag(e.id in n,`Could not compute output ${e.name} : ${e.id}`);const[t,s]=n[e.id];i.push(t.shape),r.push(t),a.push(s)}return[r,a,i]}buildNodeConversionMap(e){const t={};let n;for(const e of this.layers){n=e instanceof Fx?1:0;for(let s=0;s<e.inboundNodes.length;s++){const r=Fx.nodeKey(e,s);this.containerNodes.has(r)&&(t[r]=n,n+=1)}}return t}getLayer(e,t){if(null!=t)return this.findLayer(t);if(null==e)throw new Sg("Provide either a layer name or layer index");if("number"==typeof e)return this.findLayer(e);for(const t of this.layers)if(t.name===e)return t;throw new Sg(`No such layer: ${e}`)}findLayer(e){if(this.layers.length<=e)throw new Sg(`Was asked to retrieve layer at index ${e}, but model only has ${this.layers.length} layer(s).`);return this.layers[e]}calculateLosses(){return Na((()=>{const e=[];for(const t of this.layers)for(let n=0;n<t.inboundNodes.length;++n){const s=Fx.nodeKey(t,n);this.containerNodes.has(s)&&e.push(...t.calculateLosses())}return e}))}getConfig(){const e={name:this.name},t=this.buildNodeConversionMap(this.layers),n=[];for(const e of this.layers){const s=e.getClassName(),r=e.getConfig(),a=[];for(let n=0;n<e.inboundNodes.length;n++){const s=e.inboundNodes[n],r=Fx.nodeKey(e,n);let i={};if(this.containerNodes.has(r)){if(s.callArgs)try{JSON.stringify(s.callArgs),i=s.callArgs}catch(t){console.warn(`Layer ${e.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).`),i={}}if(s.inboundLayers.length>0){const e=[];for(let n=0;n<s.inboundLayers.length;n++){const r=s.inboundLayers[n],a=s.nodeIndices[n],o=s.tensorIndices[n];let l=t[Fx.nodeKey(r,a)];null==l&&(l=0),e.push([r.name,l,o,i])}a.push(e)}}}const i={};i.name=e.name,i.className=s,i.config=r,i.inboundNodes=a,n.push(i)}e.layers=n;const s=[];for(let e=0;e<this.inputLayers.length;e++){const n=this.inputLayers[e],r=this.inputLayersNodeIndices[e],a=Fx.nodeKey(n,r);if(!this.containerNodes.has(a))continue;let i=t[a];null==i&&(i=0);const o=this.inputLayersTensorIndices[e];s.push([n.name,i,o])}e.inputLayers=s;const r=[];for(let e=0;e<this.outputLayers.length;e++){const n=this.outputLayers[e],s=this.outputLayersNodeIndices[e],a=Fx.nodeKey(n,s);if(!this.containerNodes.has(a))continue;let i=t[a];null==i&&(i=0);const o=this.outputLayersTensorIndices[e];r.push([n.name,i,o])}return e.outputLayers=r,e}static fromConfig(e,t,n={},s=!1){const r={},a={};function i(e,t){e.name in a?a[e.name].push(t):a[e.name]=[t]}function o(e,t){const n=[];let s;for(const a of t){const o=a[0],l=a[1],u=a[2];if(s=null==a[3]?{}:a[3],!(o in r))return void i(e,t);const c=r[o];if(c.inboundNodes.length<=l)return void i(e,t);const h=c.inboundNodes[l];n.push(h.outputTensors[u])}n.length>0&&e.apply(_g(n),s)}function l(e){const n=e.name,a=Zb(e,null!=t.customObjects?t.customObjects:{});a.setFastWeightInitDuringBuild(s),r[n]=a;e.inboundNodes.forEach((e=>{if(!(e instanceof Array))throw new Sg(`Corrupted configuration, expected array for nodeData: ${e}`);i(a,e)}))}const u=t.name,c=t.layers;for(const e of c)l(e);for(;!Vg(a);)for(const e of c){const t=r[e.name];if(t.name in a){const e=a[t.name];delete a[t.name];for(const n of e)o(t,n)}}const h=[],p=[],d=t.inputLayers;for(const e of d){const t=e[0],n=e[1],s=e[2];Ag(t in r);const a=r[t].inboundNodes[n].outputTensors;h.push(a[s])}const f=t.outputLayers;for(const e of f){const t=e[0],n=e[1],s=e[2];Ag(t in r);const a=r[t].inboundNodes[n].outputTensors;p.push(a[s])}return new e({inputs:h,outputs:p,name:u})}get stateful(){if(this._stateful)throw new Sg("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 e of this.layers)if(e.stateful)return!0;return!1}resetStates(){Na((()=>{this.layers.forEach((e=>{e.stateful&&e.resetStates()}))}))}}function Dx(e,t,n){const s=t.length;if(null==e||Array.isArray(e)&&0===e.length)return t.map((e=>null));if(1===s)return Array.isArray(e)&&1===e.length?e:"object"==typeof e&&t[0]in e?[e[t[0]]]:[e];if(Array.isArray(e)){if(e.length!==s)throw new Error(`Provided ${n} is an array of ${e.length} element(s), but the model has ${s} outputs. Make sure a set of weights is provided for each model output.`);return e}if("object"==typeof e&&Object.keys(e).length>0&&"object"==typeof e[Object.keys(e)[0]]){const n=[];return t.forEach((t=>{t in e?n.push(e[t]):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 ${t} keys. Provided ${n} not understood: ${JSON.stringify(e)}`)}function Ox(e,t){return Dx(e,t,"classWeight")}async function Mx(e,t,n,s){if(null!=t||null!=s)throw new Error("Support sampleWeight is not implemented yet");if(null!=n){const t=Na((()=>{if(1===e.shape.length)return Ci(e);if(2===e.shape.length){if(e.shape[1]>1){return Pi(e,1)}if(1===e.shape[1])return oo(e,[e.shape[0]]);throw new Error(`Encountered unexpected last-dimension size (${e.shape[1]}) during handling of class weights. The size is expected to be >= 1.`)}throw new Error(`Unexpected rank of target (y) tensor (${e.rank}) during handling of class weights. The rank is expected to be 1 or 2.`)})),s=Array.from(await t.data());Ia(t);const r=[];return s.forEach((e=>{if(null==n[e])throw new Error(`classWeight must contain all classes in the training data. The class ${e} exists in the data but not in classWeight`);r.push(n[e])})),eh(r,"float32")}return null}function Lx(e,t){return _i(e,t)}function zx(e,t){let n,s;const r=t;n=r.xs,s=r.ys,c(null!=n&&null!=s,(()=>`A Dataset iterator for fitDataset() is expected to generate objects of the form \`{xs: xVal, ys: yVal}\`, where the two values may be \`tf.Tensor\`, an array of Tensors, or a map of string to Tensor.  The provided Dataset instead generates ${t}`));const a=Px("input",e.inputNames,n),i=Px("output",e.outputNames,s),o=a[0].shape[0];c(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)})`)),c(i.length===e.outputs.length,(()=>`LayersModel has ${e.outputs.length} outputs, but the dataset provides ${i.length} outputs.  (Expected output keys: ${JSON.stringify(e.outputNames)})`));for(let t=0;t<a.length;t++)c(a[t].shape[0]===o,(()=>`Batch size mismatch: input ${e.inputNames[t]} has ${a[t].shape[0]}; expected  ${o} based on input ${e.inputNames[0]}.`));for(let t=0;t<i.length;t++)c(i[t].shape[0]===o,(()=>`Batch size mismatch: output ${e.outputNames[t]} has ${i[t].shape[0]}; expected  ${o} based on input ${e.inputNames[0]}.`));return{xs:a,ys:i}}function Px(e,t,n){if(n instanceof _r)return[n];if(Array.isArray(n))return c(n.length===t.length,(()=>`Received an array of ${n.length} Tensors, but expected ${t.length} to match the ${e} keys ${t}.`)),n;{const s=[];for(const r of t){if(null==n[r])throw new Sg(`The feature data generated by the dataset lacks the required ${e} key '${r}'.`);s.push(n[r])}return s}}async function Bx(e,t,n){const s=null!=n.batchesPerEpoch;if(c(null!=e.optimizer,(()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig).")),c(null!=n,(()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call.")),c(null!=n.epochs&&n.epochs>0&&Number.isInteger(n.epochs),(()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${n.epochs}`)),c(!s||n.batchesPerEpoch>0&&Number.isInteger(n.batchesPerEpoch),(()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${n.batchesPerEpoch}`)),c(null==n.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!=n.validationData;let a,i;if(r)if(Wx(n.validationData))c(null==n.validationBatches||n.validationBatches>0&&Number.isInteger(n.validationBatches),(()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${n.validationBatches}`));else{const e=function(e){if(3===e.length)throw new Tg("Validation with sample weights is not implemented yet.");return{xs:e[0],ys:e[1]}}(n.validationData);a=e.xs,i=e.ys}const o=e.makeTrainFunction(),l=e.getDedupedMetricsNames();let u;u=r?l.slice().concat(l.map((e=>"val_"+e))):l.slice();const h=Kb(n.callbacks,n.yieldEvery),p=null==n.verbose?1:n.verbose,{callbackList:d,history:f}=Yb(h,p,n.epochs,null,null,function(e,t){let n=null;null!=t.batchesPerEpoch?n=t.batchesPerEpoch:Number.isFinite(e.size)&&(n=e.size);return n}(t,n),null,r,u);d.setModel(e),e.history=f,await d.onTrainBegin(),e.stopTraining_=!1;let m=null==n.initialEpoch?0:n.initialEpoch,g=await t.iterator();for(;m<n.epochs;){const u={};await d.onEpochBegin(m);let c=0,h=0;for(s||(g=await t.iterator());!s||c<n.batchesPerEpoch;){const t=await g.next();if(s&&t.done){console.warn(`You provided \`batchesPerEpoch\` as ${n.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, `+n.batchesPerEpoch*n.epochs+" batches). You may need to use the repeat() function when building your dataset.");break}if(null!=t.value){const{xs:s,ys:r}=zx(e,t.value),a={};a.batch=h,a.size=s[0].shape[0],await d.onBatchBegin(h,a);const i=[];if(null!=n.classWeight){const t=Ox(n.classWeight,e.outputNames);for(let e=0;e<t.length;++e)i.push(await Mx(r[e],null,t[e]))}const u=s.concat(r).concat(i),p=o(u);Ia(u);for(let e=0;e<l.length;++e){const t=l[e],n=p[e];a[t]=n,Sa(n)}await d.onBatchEnd(h,a),Vb(a),h++,c++}if(s?c>=n.batchesPerEpoch:t.done){if(r){let t;t=Wx(n.validationData)?Fg(await e.evaluateDataset(n.validationData,{batches:n.validationBatches})):Fg(e.evaluate(a,i,{batchSize:null==n.validationBatchSize?32:n.validationBatchSize,verbose:0}));for(let n=0;n<e.metricsNames.length;++n)u[`val_${e.metricsNames[n]}`]=t[n]}break}if(e.stopTraining_)break}if(await d.onEpochEnd(m,u),m++,e.stopTraining_)break}return await d.onTrainEnd(),await e.history.syncData(),e.history}finally{e.isTraining=!1}}function Wx(e){return"function"==typeof e.iterator}function Vx(e){c(e>0&&Number.isInteger(e),(()=>`batchSize is required to be a positive integer, but got ${e}`))}function Ux(e,t,n){return null==e?[null]:Array.isArray(e)?e.map((e=>vy(e,t,n-t))):vy(e,t,n-t)}function Gx(e,t){return Na((()=>null==e?null:Array.isArray(e)?e.map((e=>Gx(e,t))):Ey(e,"int32"===t.dtype?t:Ti(t,"int32"))))}function Hx(e,t){const n=[];let s=0,r=null;for(;s<e;)r=s+t,r>=e&&(r=e),n.push([s,r]),s=r;return n}function jx(e){const t=[];e instanceof _r&&(e=[e]);for(let n=0;n<e.length;++n){const s=e[n];if(1===s.rank)t.push(wy(s,1));else{if(0===s.rank)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");t.push(s)}}return t}function qx(e,t){if(null==e)return;const n=[];if(t instanceof _r)n.push(t.id);else if(Array.isArray(t))t.forEach((e=>n.push(e.id)));else if(null!=t)for(const e in t){const s=t[e];n.push(s.id)}const s=[];if(e instanceof _r)-1===n.indexOf(e.id)&&s.push(e);else if(Array.isArray(e))e.forEach((e=>{-1===n.indexOf(e.id)&&s.push(e)}));else if(null!=e)for(const t in e){const r=e[t];-1===n.indexOf(r.id)&&s.push(r)}s.forEach((e=>{e.isDisposed||e.dispose()}))}function Kx(e){return Array.isArray(e)}function Xx(e){return!function(e){return e instanceof _r}(e)&&!Kx(e)}function Yx(e,t,n,s=!0,r=""){if(null==t||0===t.length){if(null!=e){let t=!1;if(Kx(e)&&e.length>0)t=!0;else if(Xx(e)){for(const n in e)if(e.hasOwnProperty(n)){t=!0;break}}else t=!0;if(t)throw new Sg(`Error when checking model ${r} expected no data, but got ${e}`)}return[]}if(null==e)return t.map((e=>null));let a;if(Xx(e)){a=[];for(const n of t){if(null==e[n])throw new Sg(`No data provided for "${n}". Need data for each key in: ${t}`);a.push(e[n])}}else if(Kx(e)){if(e.length!==t.length)throw new Sg(`Error when checking model ${r}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${t.length} Tensor(s), but instead got the following list of Tensor(s): ${e}`);a=e}else{if(t.length>1)throw new Sg(`The model ${r} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);a=[e]}if(a=jx(a),null!=n)for(let e=0;e<t.length;++e){if(null==n[e])continue;const i=a[e];if(i.shape.length!==n[e].length)throw new Sg(`Error when checking ${r}: expected ${t[e]} to have ${n[e].length} dimension(s). but got array with shape ${i.shape}`);for(let t=0;t<n[e].length;++t){if(0===t&&!s)continue;const a=i.shape[t],o=n[e][t];if(null!=o&&o>=0&&a!==o)throw new Sg(`${r} expected a batch of elements where each example has shape [${n[e].slice(1,n[e].length)}] (i.e.,tensor shape [*,${n[e].slice(1,n[e].length)}]) but the ${r} received an input with ${i.shape[0]} examples, each with shape [${i.shape.slice(1,i.shape.length)}] (tensor shape [${i.shape}])`)}}return a}function Zx(e,t,n,s=!0,r=""){let a;if(Array.isArray(e)){if(e.length!==t.length)throw new Sg(`Error when checking model ${r}: the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see ${t.length} Tensor(s), but instead got ${e.length} Tensors(s).`);a=e}else{if(t.length>1)throw new Sg(`The model expects ${t.length} ${r} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);a=[e]}if(null!=n)for(let e=0;e<t.length;++e){if(null==n[e])continue;const i=a[e];if(i.shape.length!==n[e].length)throw new Sg(`Error when checking ${r}: expected ${t[e]} to have ${n[e].length} dimension(s), but got array with shape ${JSON.stringify(i.shape)}`);for(let a=0;a<n[e].length;++a){if(0===a&&!s)continue;const o=i.shape[a],l=n[e][a];if(null!=l&&l!==o)throw new Sg(`Error when checking ${r}: expected ${t[e]} to have shape ${JSON.stringify(n[e])} but got array with shape ${JSON.stringify(i.shape)}.`)}}}class Jx extends Fx{constructor(e){super(e),this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new Sg("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).");Sx(this,e,t,n)}compile(e){if(null==e.loss&&(e.loss=[]),this.loss=e.loss,"string"==typeof e.optimizer)this.optimizer_=function(e){const t={Adagrad:()=>Jd.adagrad(.01),Adadelta:()=>Jd.adadelta(1,.95,by()),Adam:()=>Jd.adam(.001,.9,.999,by()),Adamax:()=>Jd.adamax(.002,.9,.999,by(),0),RMSProp:()=>Jd.rmsprop(.001,.9,0,by()),SGD:()=>Jd.sgd(.01)};if(t.adagrad=t.Adagrad,t.adadelta=t.Adadelta,t.adam=t.Adam,t.adamax=t.Adamax,t.rmsprop=t.RMSProp,t.sgd=t.SGD,e in t)return t[e]();throw new Sg(`Unknown Optimizer ${e}`)}(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof Zp))throw new Sg("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}let t=[];if(Array.isArray(e.loss)||"string"==typeof e.loss||"function"==typeof e.loss)if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new Sg(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${e.loss}.`);const n=e.loss;t=n.map((e=>ux(e)))}else{const n=ux(e.loss);this.outputs.forEach((e=>{t.push(n)}))}else{e.loss=e.loss;for(const t in e.loss)if(-1===this.outputNames.indexOf(t))throw new Sg(`Unknown entry in loss dictionary: "${t}". Only expected the following keys: ${this.outputNames}`);for(const n of this.outputNames)null==e.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`),t.push(ux(e.loss[n]))}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let e=0;e<this.outputs.length;++e){const t=this.internalOutputShapes[e],n=this.outputNames[e];this.feedOutputNames.push(n),this.feedOutputShapes.push(t),this.feedLossFns.push(this.lossFunctions[e])}const n=[];this.metrics=e.metrics,this.metricsNames=["loss"],this.metricsTensors=[],ly("loss",(()=>{for(let e=0;e<this.outputs.length;++e){if(-1!==n.indexOf(e))continue;const t=this.lossFunctions[e];this.outputs.length>1&&(this.metricsTensors.push([t,e]),this.metricsNames.push(this.outputNames[e]+"_loss"))}}));const s=function(e,t){if(null==e||Array.isArray(e)&&0===e.length)return t.map((e=>[]));let n;if("string"==typeof e||"function"==typeof e)n=[e];else{if(!Array.isArray(e)&&"object"!=typeof e)throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${e}`);n=e}if(Array.isArray(n))return t.map((e=>n));{const e=[];for(const s of t){let t=n.hasOwnProperty(s)?n[s]:[];Array.isArray(t)||(t=[t]),e.push(t)}return e}}(e.metrics,this.outputNames),r=(e,t,n)=>{this.outputNames.length>1&&(t=this.outputNames[e]+"_"+t),this.metricsNames.push(t),this.metricsTensors.push([n,e])};ly("metric",(()=>{for(let e=0;e<this.outputs.length;++e){if(-1!==n.indexOf(e))continue;(t=>{let n,s,a;for(const i of t){if("string"==typeof i&&-1!==["accuracy","acc","crossentropy","ce"].indexOf(i)){const t=this.internalOutputShapes[e];let r;1===t[t.length-1]||this.lossFunctions[e]===ax?-1!==["accuracy","acc"].indexOf(i)?s=cx:-1!==["crossentropy","ce"].indexOf(i)&&(s=mx):this.lossFunctions[e]===rx?-1!==["accuracy","acc"].indexOf(i)?s=gx:-1!==["crossentropy","ce"].indexOf(i)&&(s=bx):-1!==["accuracy","acc"].indexOf(i)?s=hx:-1!==["crossentropy","ce"].indexOf(i)&&(s=yx),-1!==["accuracy","acc"].indexOf(i)?r="acc":-1!==["crossentropy","ce"].indexOf(i)&&(r="ce"),a=s,n=""+r}else{const e=wx(i);a=e,n=""+vx(i)}let t;ly(n,(()=>{t=a})),r(e,n,t)}})(s[e])}})),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(e,t,n={}){const s=null==n.batchSize?32:n.batchSize;Vx(s);const r=this.standardizeUserDataXY(e,t,!0,s);try{const a=r[0].concat(r[1]);this.makeTestFunction();const i=this.testFunction;return _g(this.testLoop(i,a,s,n.verbose,n.steps))}finally{qx(r[0],e),qx(r[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),async function(e,t,n){const s=null!=(n=n||{}).batches,r=e.testFunction;let a=[];if(n.verbose>0)throw new Tg("Verbose mode is not implemented yet.");c(!s||n.batches>0&&Number.isInteger(n.batches),(()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(n.batches)}`));const i="function"==typeof t.next?t:await t.iterator();let o=0,l=0;for(;!s||l<n.batches;){const t=await i.next();if(a=Na((()=>{if(t.value){const{xs:n,ys:s}=zx(e,t.value),i=n.concat(s),u=Na((()=>r(i)));if(Ia(i),0===l)for(let e=0;e<u.length;++e)a.push(xl(0));const c=i[0].shape[0];for(let e=0;e<u.length;++e){const t=u[e],n=a[e];a[e]=Na((()=>Ei(a[e],_i(c,t)))),l>0&&Ia(n)}Ia(u),o+=c,++l}return a})),t.done){s&&console.warn(`Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least \`batches\` batches (in this case, ${n.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let e=0;e<a.length;++e){const t=a[e];a[e]=Ri(a[e],o),Ia(t)}return _g(a)}(this,e,t)}checkNumSamples(e,t,n,s="steps"){let r;if(null!=n){if(r=null,null!=t)throw new Sg(`If ${s} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else{if(null==e)throw new Sg(`Either the input data should have a defined shape, or ${s} shoud be specified.`);r=Array.isArray(e)?e[0].shape[0]:e.shape[0]}return r}execute(e,t){if(Array.isArray(t)&&0===t.length)throw new Sg("`outputs` is an empty Array, which is not allowed.");const n=Array.isArray(t),s=n?t:[t],r=this.retrieveSymbolicTensors(s),a=new vb;if(e instanceof _r&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new Sg(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let t=0;t<this.inputs.length;++t)a.add(this.inputs[t],e[t])}else for(const t of this.inputs){const n=e[t.name];if(null==n)throw new Sg(`No value is provided for the model's input ${t.name}`);a.add(t,n)}const i=Ib(r,a);return n?i:i[0]}retrieveSymbolicTensors(e){const t=Eg(null,e.length);let n=e.length;for(const s of this.layers){const r=Array.isArray(s.output)?s.output:[s.output],a=r.map((e=>e.name));for(let s=0;s<e.length;++s){const i=a.indexOf(e[s]);if(-1!==i&&(t[s]=r[i],n--),0===n)break}if(0===n)break}if(n>0){const n=[];throw t.forEach(((t,s)=>{null==t&&n.push(e[s])})),new Sg(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(n)}`)}return t}predictLoop(e,t=32,n=!1){return Na((()=>{const s=this.checkNumSamples(e);if(n)throw new Tg("Verbose predictLoop() is not implemented yet.");const r=Hx(s,t),a=this.outputs.map((e=>[]));for(let t=0;t<r.length;++t){Na((()=>{const n=r[t][0],s=r[t][1],a=Ux(e,n,s),i=[];if(Array.isArray(a))for(let e=0;e<a.length;++e)i.push({key:this.inputs[e],value:a[e]});else i.push({key:this.inputs[0],value:a});const o=new vb(i);return Ib(this.outputs,o)})).forEach(((e,t)=>a[t].push(e)))}return _g(a.map((e=>co(e,0))))}))}predict(e,t={}){const n=jx(e);Zx(n,this.inputNames,this.feedInputShapes,!1);try{const s=null==t.batchSize?32:t.batchSize;return Vx(s),this.predictLoop(n,s)}finally{qx(n,e)}}predictOnBatch(e){Zx(e,this.inputNames,this.feedInputShapes,!0);const t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,n=!0,s){if(null==this.optimizer_)throw new Ig("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");const r=[];for(let e=0;e<this.feedOutputShapes.length;++e){const t=this.feedOutputShapes[e];this.feedLossFns[e]===rx?r.push(t.slice(0,t.length-1).concat([1])):r.push(t)}if(function(e,t,n){const s=Wg(e.map((e=>e.shape[0])));s.sort();const r=Wg(t.map((e=>e.shape[0])));if(r.sort(),s.length>1)throw new Sg(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map((e=>e.shape)))}`);if(r.length>1)throw new Sg(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map((e=>e.shape)))}`);if(s.length>0&&r.length>0&&!m(s,r))throw new Sg(`Input Tensors should have the same number of samples as target Tensors. Found ${s[0]} input sample(s) and ${r[0]} target sample(s).`)}(e=Yx(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=Yx(t,this.feedOutputNames,r,!1,"target")),function(e,t,n){const s=[Qb,ax,sx];for(let r=0;r<e.length;++r){const a=e[r],i=t[r],o=n[r];if(null!=i){if(i===sx&&1===a.shape[a.shape.length-1])throw new Sg(`You are passing a target array of shape ${a.shape} while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].`);if(-1!==s.indexOf(i)){const e=a.shape.slice(1),t=o.slice(1);for(let n=0;n<e.length;++n){const s=e[n],r=t[n];if(null!=r&&s!==r)throw new Sg(`A target Tensor with shape ${a.shape} was passed for an output of shape ${o}, while using a loss function that expects targets to have the same shape as the output.`)}}}}}(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&null!=s&&s>0&&e[0].shape[0]%s!=0)throw new Sg(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${s}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,n,s,r=!0,a){const[i,o]=this.standardizeUserDataXY(e,t,r,a);if(null!=n)throw new Error("sample weight is not supported yet.");let l=null;if(null!=s){const e=Ox(s,this.outputNames);l=[];for(let t=0;t<e.length;++t)l.push(await Mx(o[t],null,e[t]))}return[i,o,l]}testLoop(e,t,n,s=0,r){return Na((()=>{const a=this.checkNumSamples(t,n,r,"steps"),i=[];if(s>0)throw new Tg("Verbose mode is not implemented yet.");if(null!=r)throw new Tg("steps mode in testLoop() is not implemented yet");{const s=Hx(a,n),r=eh(gy(0,a));for(let n=0;n<s.length;++n){const a=s[n][0],o=s[n][1],l=vy(r,a,o-a),u=Gx(t,l),c=e(u);if(0===n)for(let e=0;e<c.length;++e)i.push(xl(0));for(let e=0;e<c.length;++e){const t=c[e];i[e]=Ei(i[e],_i(o-a,t))}}for(let e=0;e<i.length;++e)i[e]=Ri(i[e],a)}return i}))}getDedupedMetricsNames(){const e=this.metricsNames,t=[];for(let n=0;n<e.length;++n){const s=e[n];let r=s;if(Rg(e,s)>1){r+=`_${Rg(e.slice(0,n),s)}`}t.push(r)}return t}makeTrainFunction(){return e=>{const t=[],n=e.slice(0,this.inputs.length),s=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=[],i=this.collectedTrainableWeights.map((e=>e.read()));return[this.optimizer_.minimize((()=>{const e=[];for(let t=0;t<this.inputs.length;++t)e.push({key:this.inputs[t],value:n[t]});const i=new vb(e),o=Ib(this.outputs,i,{training:!0});let l;for(let e=0;e<this.lossFunctions.length;++e){let n=(0,this.lossFunctions[e])(s[e],o[e]);null!=r[e]&&(n=Lx(n,r[e]));const a=pu(n);t.push(a),l=0===e?n:Ei(l,n)}for(let e=0;e<this.metricsTensors.length;++e){let n;if(this.outputs.length>1&&e<this.outputs.length)n=t[e];else{const t=this.metricsTensors[e][0],r=this.metricsTensors[e][1];n=pu(t(s[r],o[r]))}Sa(n),a.push(n)}return l=pu(l),this.calculateLosses().forEach((e=>{l=Ei(l,e)})),l}),!0,i)].concat(a)}}makeTestFunction(){this.testFunction=e=>Na((()=>{const t=[];let n;const s=e.slice(0,this.inputs.length),r=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),a=[];for(let e=0;e<this.inputs.length;++e)a.push({key:this.inputs[e],value:s[e]});const i=new vb(a),o=Ib(this.outputs,i);for(let e=0;e<this.lossFunctions.length;++e){const s=this.lossFunctions[e],a=pu(s(r[e],o[e]));n=0===e?a:Ei(n,a),t.push(n)}for(let e=0;e<this.metricsTensors.length;++e){const n=this.metricsTensors[e][0],s=this.metricsTensors[e][1],a=pu(n(r[s],o[s]));t.push(a)}return t}))}async fit(e,t,n={}){if(this.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");let s,r,a,i,o,l,u,c,h;this.isTraining=!0;try{const p=null==n.batchSize?32:n.batchSize;Vx(p);const d=!1,f=await this.standardizeUserData(e,t,n.sampleWeight,n.classWeight,d,p);s=f[0],r=f[1],h=f[2];let m,g=!1;if(null!=n.validationData&&n.validationData.length>0){if(g=!0,2!==n.validationData.length)throw 3===n.validationData.length?new Tg("validationData including sample weights is not supported yet."):new Sg(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${n.validationData} is invalid.`);o=n.validationData[0],l=n.validationData[1];const e=!0,t=await this.standardizeUserData(o,l,null,null,e,p);u=t[0],c=t[1],m=u.concat(c)}else if(null!=n.validationSplit&&n.validationSplit>0&&n.validationSplit<1){g=!0;const e=Math.floor(s[0].shape[0]*(1-n.validationSplit)),t=s[0].shape[0];u=Ux(s,e,t),a=s,s=Ux(s,0,e),c=Ux(r,e,t),i=r,r=Ux(r,0,e),m=u.concat(c)}else null!=n.validationSteps&&(g=!0);const y=s.concat(r).concat(h);this.checkTrainableWeightsConsistency();const b=this.makeTrainFunction(),x=this.getDedupedMetricsNames();let w,v;g?(this.makeTestFunction(),w=this.testFunction,v=x.slice().concat(x.map((e=>"val_"+e)))):(w=null,m=[],v=x.slice());const k=Kb(n.callbacks,n.yieldEvery);return await this.fitLoop(b,y,x,p,n.epochs,n.verbose,k,w,m,n.shuffle,v,n.initialEpoch,null,null)}finally{this.isTraining=!1,qx(s,e),qx(r,t),qx(a,e),qx(i,t),qx(u,o),qx(c,l),null!=h&&Ia(h)}}async fitLoop(e,t,n,s,r,i,o,l,u,c,h,p,d,f){null==s&&(s=32),null==r&&(r=1),null==c&&(c=!0),null==p&&(p=0);let m=!1;if(null!=l&&null!=u&&(m=!0),null!=f&&(m=!0,null==d))throw new Sg("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");const g=this.checkNumSamples(t,s,d,"steps_per_epoch");let y;null!=g&&(y=gy(0,g)),null==i&&(i=1);const{callbackList:b,history:x}=Yb(o,i,r,p,g,d,s,m,h);b.setModel(this),this.history=x,await b.onTrainBegin(),this.stopTraining_=!1;for(let i=p;i<r;++i){await b.onEpochBegin(i);const r={};if(null!=d)throw new Tg("stepsPerEpoch mode is not implemented yet.");{if("batch"===c)throw new Tg("batch shuffling is not implemneted yet");c&&a(y);const i=eh(y),o=Hx(g,s);for(let a=0;a<o.length;++a){const c={};if(await b.onBatchBegin(a,c),Na((()=>{const h=o[a][0],p=o[a][1],d=vy(i,h,p-h);c.batch=a,c.size=p-h;const f=Gx(t,d),g=e(f);for(let e=0;e<n.length;++e){const t=n[e],s=g[e];c[t]=s,Sa(s)}if(a===o.length-1&&m){const e=this.testLoop(l,u,s);for(let t=0;t<n.length;++t){const s=n[t],a=e[t];Sa(a),r["val_"+s]=a}}})),await b.onBatchEnd(a,c),Vb(c),this.stopTraining_)break}i.dispose()}if(await b.onEpochEnd(i,r),this.stopTraining_)break}return await b.onTrainEnd(),await this.history.syncData(),this.history}async fitDataset(e,t){return Bx(this,e,t)}async trainOnBatch(e,t){const n=await this.standardizeUserData(e,t),s=n[0],r=n[1],a=this.makeTrainFunction()(s.concat(r)),i=[];for(const e of a){const t=await e.data();i.push(t[0])}return Ia(a),qx(n[0],e),qx(n[1],t),_g(i)}getNamedWeights(e){const t=[],n=null!=e&&e.trainableOnly,s=n?this.trainableWeights:this.weights,r=this.getWeights(n);for(let e=0;e<s.length;++e)n&&!s[e].trainable||t.push({name:s[e].originalName,tensor:r[e]});return t}set stopTraining(e){this.stopTraining_=e}get stopTraining(){return this.stopTraining_}get optimizer(){return this.optimizer_}set optimizer(e){this.optimizer_!==e&&(this.optimizer_=e,this.isOptimizerOwned=!1)}dispose(){const e=super.dispose();if(0===e.refCountAfterDispose&&null!=this.optimizer&&this.isOptimizerOwned){const t=ka().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-ka().numTensors}return e}getLossIdentifiers(){let e;if("string"==typeof this.loss)e=Dg(this.loss);else if(Array.isArray(this.loss)){for(const e of this.loss)if("string"!=typeof e)throw new Error("Serialization of non-string loss is not supported.");e=this.loss.map((e=>Dg(e)))}else{const t=Object.keys(this.loss);e={};const n=this.loss;for(const s of t){if("string"!=typeof n[s])throw new Error("Serialization of non-string loss is not supported.");e[s]=Dg(n[s])}}return e}getMetricIdentifiers(){if("string"==typeof this.metrics||"function"==typeof this.metrics)return[Dg(vx(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map((e=>Dg(vx(e))));{const e={};for(const t in this.metrics)e[t]=Dg(vx(this.metrics[t]));return e}}getTrainingConfig(){return{loss:this.getLossIdentifiers(),metrics:this.getMetricIdentifiers(),optimizer_config:{class_name:this.optimizer.getClassName(),config:this.optimizer.getConfig()}}}loadTrainingConfig(e){if(null!=e.weighted_metrics)throw new Error("Loading weight_metrics is not supported yet.");if(null!=e.loss_weights)throw new Error("Loading loss_weights is not supported yet.");if(null!=e.sample_weight_mode)throw new Error("Loading sample_weight_mode is not supported yet.");const t=Zb(Ax(e.optimizer_config));let n,s;if("string"==typeof e.loss)n=Og(e.loss);else if(Array.isArray(e.loss))n=e.loss.map((e=>Og(e)));else if(null!=e.loss){n={};for(const t in e.loss)n[t]=Og(e.loss[t])}if(Array.isArray(e.metrics))s=e.metrics.map((e=>Og(e)));else if(null!=e.metrics){s={};for(const t in e.metrics)s[t]=Og(e.metrics[t])}this.compile({loss:n,metrics:s,optimizer:t})}async save(e,t){if("string"==typeof e){const t=Ka(e);if(0===t.length)throw new Sg(`Cannot find any save handlers for URL '${e}'`);if(t.length>1)throw new Sg(`Found more than one (${t.length}) save handlers for URL '${e}'`);e=t[0]}if(null==e.save)throw new Sg("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");const n=await Aa(this.getNamedWeights(t)),s={modelTopology:this.toJSON(null,!1),format:"layers-model",generatedBy:"TensorFlow.js tfjs-layers v4.15.0",convertedBy:null};if(null!=t&&t.includeOptimizer&&null!=this.optimizer){s.trainingConfig=this.getTrainingConfig();const e="optimizer",{data:t,specs:r}=await Aa(await this.optimizer.getWeights(),e);n.specs.push(...r),n.data=Ba([n.data,t])}if(null!=this.userDefinedMetadata){const e=!0;Nx(this.userDefinedMetadata,this.name,e),s.userDefinedMetadata=this.userDefinedMetadata}return s.weightData=n.data,s.weightSpecs=n.specs,e.save(s)}setUserDefinedMetadata(e){Nx(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}}Jx.className="Model",Xp(Jx);class Qx extends Jx{}Qx.className="Functional",Xp(Qx);class ew extends Jx{constructor(e){if(super({inputs:[],outputs:[]}),e=e||{},this.trainable=!0,this.built=!1,this.name=null!=e.name?e.name:Zg("sequential_"),null!=e.layers)for(const t of e.layers)this.add(t)}checkShape(e){if(e.inboundNodes[0].outputTensors[0].shape.some((e=>e<0)))throw new Sg(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){const t=e instanceof ew||e instanceof Jx;let n;if(t){if(n=e,1!==n.outputs.length)throw new Sg("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 Sg("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(0===this.outputs.length){if(0===e.inboundNodes.length){if(null==e.batchInputShape)throw new Sg("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");const t=wb({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(t)}if(t)this.outputs=n.outputs,this.inputs=n.inputs;else{if(1!==e.inboundNodes.length)throw new Sg(`A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer ${e.name} which has ${e.inboundNodes.length} pre-existing inbound connections.`);if(1!==e.inboundNodes[0].outputTensors.length)throw new Sg("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[e.inboundNodes[0].outputTensors[0]],this.inputs=bb(this.outputs[0])}this.inboundNodes=[],new mb({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:Eg(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map((e=>e.shape)),outputShapes:this.outputs[0].shape})}else{const t=e.apply(this.outputs[0]);if(Array.isArray(t))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[t],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(e),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 e=this.layers.length-1;this.layers[e].outboundNodes=[],this.outputs=[this.layers[e].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(e,t){return null==this.model&&this.build(),this.model.call(e,t)}build(e){if(ib(e),0===this.inputs.length||0===this.outputs.length)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new Jx({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(e,t,n=console.log){this.built||this.build(),super.summary(e,t,n)}setWeights(e){null==this.model&&this.build(),this.model.setWeights(e)}evaluate(e,t,n={}){if(!this.built)throw new Ig("The model needs to be compiled before being used.");return this.model.evaluate(e,t,n)}async evaluateDataset(e,t){if(!this.built)throw new Ig("The model needs to be compiled before being used.");return this.model.evaluateDataset(e,t)}predict(e,t={}){return null==this.model&&this.build(),this.model.predict(e,t)}predictOnBatch(e){return null==this.model&&this.build(),this.model.predictOnBatch(e)}compile(e){this.build(),this.model.compile(e),this.optimizer_=this.model.optimizer,this.isOptimizerOwned=this.model.isOptimizerOwned,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames}get optimizer(){return null==this.model?void 0:this.model.optimizer}set optimizer(e){this.model.optimizer=e}async fit(e,t,n={}){if(!this.built)throw new Ig("The model needs to be compiled before being used.");return this.model.fit(e,t,n)}async fitDataset(e,t){if(!this.built)throw new Ig("The model needs to be compiled before being used.");return this.model.fitDataset(e,t)}async trainOnBatch(e,t){return this.model.trainOnBatch(e,t)}static fromConfig(e,t,n={},s=!1){let r,a={};if(t instanceof Array){if(null==t[0].className||"Merge"===t[0].className)throw new Sg("Legacy serialization format not supported yet.");r=t}else c(null!=t.layers,(()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field.")),r=t.layers,delete t.layers,a=t;const i=new e(a);if(!(i instanceof ew))throw new Tg(`Sequential.fromConfig called on non-Sequential input: ${i}`);for(const e of r){const t=Zb(e,void 0,s);s&&t.setFastWeightInitDuringBuild(!0),i.add(t)}return i}set stopTraining(e){if(null==this.model)throw new Sg("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=e}get stopTraining(){if(null==this.model)throw new Sg("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){const e=[];for(const t of this.layers){const n={};n.className=t.getClassName(),n.config=t.getConfig(),e.push(n)}return{name:this.name,layers:e}}}function tw(e){return wb(e)}ew.className="Sequential",Xp(ew);let nw=class extends qp{getConfig(){return{}}};class sw extends nw{apply(e,t=1){return function(e,t=1){if(1!==t)throw new Tg(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return al(e)}(e,t)}}sw.className="elu",Xp(sw);class rw extends nw{apply(e){return _c(e)}}rw.className="selu",Xp(rw);class aw extends nw{apply(e){return Nc(e)}}aw.className="relu",Xp(aw);class iw extends nw{apply(e){return Na((()=>gu(6,Nc(e))))}}iw.className="relu6",Xp(iw);class ow extends nw{apply(e){return e}}ow.className="linear",Xp(ow);class lw extends nw{apply(e){return po(e)}}lw.className="sigmoid",Xp(lw);class uw extends nw{apply(e){return function(e){return Na((()=>{const t=Ei(.5,_i(.2,e));return $o(t,0,1)}))}(e)}}uw.className="hardSigmoid",Xp(uw);class cw extends nw{apply(e){return Yl(e)}}cw.className="softplus",Xp(cw);class hw extends nw{apply(e){return function(e){return Na((()=>Ri(e,Ei(Fi(e),1))))}(e)}}hw.className="softsign",Xp(hw);class pw extends nw{apply(e){return mo(e)}}pw.className="tanh",Xp(pw);let dw=class extends nw{apply(e,t=-1){return Vc(e,t)}};dw.className="softmax",Xp(dw);class fw extends nw{apply(e,t=-1){return Ql(e,t)}}fw.className="logSoftmax",Xp(fw);class mw extends nw{apply(e,t=1){return Na((()=>_i(po(_i(e,t)),e)))}}mw.className="swish",Xp(mw);class gw extends nw{apply(e){return Na((()=>_i(e,mo(Yl(e)))))}}function yw(e){return e.getClassName()}function bw(e,t={}){return Pg(e,Kp.getMap().classNameMap,t,"activation")}function xw(e){if(null==e){const e={className:"linear",config:{}};return bw(e)}if("string"==typeof e){const t={};return t.className=e,t.config={},bw(t)}return e instanceof nw?e:bw(e)}function ww(e){if(null!=e&&"object"!=typeof e)throw new Error(`Argument to L1L2 regularizer's constructor is expected to be an object, but received: ${e}`)}gw.className="mish",Xp(gw);class vw extends qp{}class kw extends vw{constructor(e){super(),ww(e),this.l1=null==e||null==e.l1?.01:e.l1,this.l2=null==e||null==e.l2?.01:e.l2,this.hasL1=0!==this.l1,this.hasL2=0!==this.l2}apply(e){return Na((()=>{let t=du([1]);return this.hasL1&&(t=Ei(t,kl(_i(this.l1,Fi(e))))),this.hasL2&&(t=Ei(t,kl(_i(this.l2,Ay(e))))),oo(t,[])}))}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}}kw.className="L1L2",Xp(kw);const Nw={l1l2:"L1L2"};function Iw(e){return Lg(e)}function Sw(e,t={}){return Pg(e,Kp.getMap().classNameMap,t,"regularizer")}function Tw(e){if(null==e)return null;if("string"==typeof e){return Sw({className:e in Nw?Nw[e]:e,config:{}})}return e instanceof vw?e:Sw(e)}class Cw extends yb{constructor(e){super(null==e?{}:e),this.supportsMasking=!0,null!=e&&(this.maxValue=e.maxValue)}call(e,t){e=ab(e);let n=Nc(e);return null!=this.maxValue&&(n=$o(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){const e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}}Cw.className="ReLU",Xp(Cw);class $w extends yb{constructor(e){super(null==e?{}:e),this.DEFAULT_ALPHA=.3,null==e&&(e={}),this.alpha=null==e.alpha?this.DEFAULT_ALPHA:e.alpha}call(e,t){const n=ab(e);return Pl(n,this.alpha)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}$w.className="LeakyReLU",Xp($w);class Ew extends yb{constructor(e){if(super(null==e?{}:e),this.DEFAULT_ALPHA_INITIALIZER="zeros",null==e&&(e={}),this.supportsMasking=!0,this.alphaInitializer=nb(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=Tw(e.alphaRegularizer),this.alphaConstraint=Lb(e.alphaConstraint),null==e.sharedAxes)this.sharedAxes=null;else if(Array.isArray(e.sharedAxes))this.sharedAxes=e.sharedAxes;else{if("number"!=typeof e.sharedAxes)throw new Sg(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`);this.sharedAxes=[e.sharedAxes]}}build(e){const t=(e=ib(e)).slice(1);if(null!=this.sharedAxes)for(const e of this.sharedAxes)t[e-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);const n={};if(null!=this.sharedAxes)for(let t=1;t<e.length;++t)n[t]=e[t];this.inputSpec=[new pb({ndim:e.length,axes:n})],this.built=!0}call(e,t){return e=ab(e),Fu(e,this.alpha.read())}getConfig(){const e={alphaInitializer:tb(this.alphaInitializer),alphaRegularizer:Iw(this.alphaRegularizer),alphaConstraint:Ob(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}}Ew.className="PReLU",Xp(Ew);let Aw=class extends yb{constructor(e){if(super(null==e?{}:e),this.DEFAULT_ALPHA=1,null==e&&(e={}),null!=e.alpha&&e.alpha!==this.DEFAULT_ALPHA)throw new Tg(`Non-default alpha value (${e.alpha}) is not supported by the ELU layer yet.`);this.alpha=null==e.alpha?this.DEFAULT_ALPHA:e.alpha}call(e,t){const n=ab(e);return al(n)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};Aw.className="ELU",Xp(Aw);class Rw extends yb{constructor(e){super(null==e?{}:e),this.DEFAULT_THETA=1,null==e&&(e={}),this.theta=null==e.theta?this.DEFAULT_THETA:e.theta}call(e,t){const n=ab(e);return _i(n,Ti(Fl(n,this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){const e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}}Rw.className="ThresholdedReLU",Xp(Rw);class _w extends yb{constructor(e){super(null==e?{}:e),this.DEFAULT_AXIS=1,null==e&&(e={}),this.softmax=(new dw).apply,this.axis=null==e.axis?this.DEFAULT_AXIS:e.axis}call(e,t){return Na((()=>{let n=ab(e);const s=t.mask;if(null!=s){const e=_i(Jl(fu(n.shape),Ti(s,n.dtype)),xl(-1e9));n=Ei(n,e)}return this.axis instanceof Array?this.axis.length>1?Tl(Jl(n,eu(n,this.axis,!0))):this.softmax(n,this.axis[0]):this.softmax(n,this.axis)}))}computeOutputShape(e){return e}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}function Fw(e,t,n){if("number"==typeof e)return Eg(e,t);if(e.length!==t)throw new Sg(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${e.length} elements.`);for(let r=0;r<t;++r){const a=e[r];if((s=a)!==parseInt(s.toString(),10))throw new Sg(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${JSON.stringify(e)} including a non-integer number ${a}`)}return e;var s}function Dw(e,t,n,s,r=1){if(null==e)return e;let a;return a="same"===n?e:e-(t+(t-1)*(r-1))+1,Math.floor((a+s-1)/s)}function Ow(e,t,n,s){if(null==e)return null;if("valid"===s)e=e*t+my([n-t,0]);else{if("same"!==s)throw new Sg(`Unsupport padding mode: ${s}.`);e*=t}return e}function Mw(e,t){return Na((()=>(ry(t),"channelsFirst"===t?vh(e,[0,2,3,1]):e)))}function Lw(e,t){return Na((()=>(ry(t),"channelsFirst"===t?vh(e,[0,2,3,4,1]):e)))}function zw(e,t,n,s=1,r="valid",a,i=1){return Na((()=>{if(null==a&&(a="channelsLast"),ry(a),3!==e.shape.length)throw new Sg(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(3!==t.shape.length)throw new Sg(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(null!=n&&1!==n.shape.length)throw new Sg(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if("channelsFirst"===a&&(e=vh(e,[0,2,1])),"causal"===r)throw new Tg("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let o=Do(e,t,s,"same"===r?"same":"valid","NWC",i);return null!=n&&(o=_y(o,n)),o}))}function Pw(e,t,n,s=[1,1],r="valid",a,i,o=null){return Na((()=>{if(null==a&&(a="channelsLast"),ry(a),3!==e.rank&&4!==e.rank)throw new Sg(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(3!==t.rank&&4!==t.rank)throw new Sg(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=Mw(e,a);if("causal"===r)throw new Tg("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=Oh({x:l,filter:t,strides:s,pad:"same"===r?"same":"valid",dilations:i,dataFormat:"NHWC",bias:n,activation:o}),"channelsFirst"===a&&(l=vh(l,[0,3,1,2])),l}))}function Bw(e,t,n,s=[1,1,1],r="valid",a,i){return Na((()=>{if(null==a&&(a="channelsLast"),ry(a),4!==e.rank&&5!==e.rank)throw new Sg(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(4!==t.rank&&5!==t.rank)throw new Sg(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let o=Lw(e,a);if("causal"===r)throw new Tg("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return o=Lo(o,t,s,"same"===r?"same":"valid","NDHWC",i),null!=n&&(o=_y(o,n)),"channelsFirst"===a&&(o=vh(o,[0,4,1,2,3])),o}))}_w.className="Softmax",Xp(_w);class Ww extends yb{constructor(e,t){if(super(t),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",Ww.verifyArgs(t),this.rank=e,Hg(this.rank,"rank"),1!==this.rank&&2!==this.rank&&3!==this.rank)throw new Tg(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=Fw(t.kernelSize,e,"kernelSize"),this.strides=Fw(null==t.strides?1:t.strides,e,"strides"),this.padding=null==t.padding?"valid":t.padding,ay(this.padding),this.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,ry(this.dataFormat),this.activation=xw(t.activation),this.useBias=null==t.useBias||t.useBias,this.biasInitializer=nb(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=Lb(t.biasConstraint),this.biasRegularizer=Tw(t.biasRegularizer),this.activityRegularizer=Tw(t.activityRegularizer),this.dilationRate=Fw(null==t.dilationRate?1:t.dilationRate,e,"dilationRate"),1===this.rank&&Array.isArray(this.dilationRate)&&1!==this.dilationRate.length)throw new Sg(`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 Sg(`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 Sg(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}static verifyArgs(e){if(Ag("kernelSize"in e,"required key 'kernelSize' not in config"),"number"!=typeof e.kernelSize&&!Gg(e.kernelSize,"number",1,3))throw new Sg(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(e.kernelSize)}.`)}getConfig(){const e={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:yw(this.activation),useBias:this.useBias,biasInitializer:tb(this.biasInitializer),biasRegularizer:Iw(this.biasRegularizer),activityRegularizer:Iw(this.activityRegularizer),biasConstraint:Ob(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}class Vw extends Ww{constructor(e,t){super(e,t),this.kernel=null,Vw.verifyArgs(t),this.filters=t.filters,Hg(this.filters,"filters"),this.kernelInitializer=nb(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=Lb(t.kernelConstraint),this.kernelRegularizer=Tw(t.kernelRegularizer)}build(e){e=ib(e);const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new Sg(`The channel dimension of the input should be defined. Found ${e[t]}`);const n=e[t],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:{[t]:n}}],this.built=!0}call(e,t){return Na((()=>{let t;e=ab(e);const n=null==this.bias?null:this.bias.read(),s=qg(this.activation.getClassName());if(null!=s&&2===this.rank)t=Pw(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate,s);else{if(1===this.rank)t=zw(e,this.kernel.read(),n,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(2===this.rank)t=Pw(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate);else{if(3!==this.rank)throw new Tg("convolutions greater than 3D are not implemented yet.");t=Bw(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate)}null!=this.activation&&(t=this.activation.apply(t))}return t}))}computeOutputShape(e){e=ib(e);const t=[],n="channelsLast"===this.dataFormat?e.slice(1,e.length-1):e.slice(2);for(let e=0;e<n.length;++e){const s=Dw(n[e],this.kernelSize[e],this.padding,this.strides[e],"number"==typeof this.dilationRate?this.dilationRate:this.dilationRate[e]);t.push(s)}let s=[e[0]];return"channelsLast"===this.dataFormat?(s=s.concat(t),s.push(this.filters)):(s.push(this.filters),s=s.concat(t)),s}getConfig(){const e={filters:this.filters,kernelInitializer:tb(this.kernelInitializer),kernelRegularizer:Iw(this.kernelRegularizer),kernelConstraint:Ob(this.kernelConstraint)},t=super.getConfig();return Object.assign(e,t),e}static verifyArgs(e){if(!("filters"in e)||"number"!=typeof e.filters||e.filters<1)throw new Sg(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}}class Uw extends Vw{constructor(e){super(2,e),Uw.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&!Gg(e.kernelSize,"number",1,2))throw new Sg(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}}Uw.className="Conv2D",Xp(Uw);class Gw extends Vw{constructor(e){super(3,e),Gw.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&(!Array.isArray(e.kernelSize)||1!==e.kernelSize.length&&3!==e.kernelSize.length))throw new Sg(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}}Gw.className="Conv3D",Xp(Gw);class Hw extends Uw{constructor(e){if(super(e),this.inputSpec=[new pb({ndim:4})],"same"!==this.padding&&"valid"!==this.padding)throw new Sg(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(4!==(e=ib(e)).length)throw new Sg("Input should have rank 4; Received input shape: "+JSON.stringify(e));const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new Sg("The channel dimension of the inputs should be defined. Found `None`.");const n=e[t],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 pb({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return Na((()=>{let t=ab(e);if(4!==t.shape.length)throw new Sg(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${t.shape.length}`);const n=t.shape,s=n[0];let r,a;"channelsFirst"===this.dataFormat?(r=2,a=3):(r=1,a=2);const i=n[r],o=n[a],l=this.kernelSize[0],u=this.kernelSize[1],c=this.strides[0],h=this.strides[1],p=[s,Ow(i,c,l,this.padding),Ow(o,h,u,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(t=vh(t,[0,2,3,1]));let d=Mo(t,this.kernel.read(),p,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(d=vh(d,[0,3,1,2])),null!=this.bias&&(d=_y(d,this.bias.read(),this.dataFormat)),null!=this.activation&&(d=this.activation.apply(d)),d}))}computeOutputShape(e){const t=(e=ib(e)).slice();let n,s,r;"channelsFirst"===this.dataFormat?(n=1,s=2,r=3):(n=3,s=1,r=2);const a=this.kernelSize[0],i=this.kernelSize[1],o=this.strides[0],l=this.strides[1];return t[n]=this.filters,t[s]=Ow(t[s],o,a,this.padding),t[r]=Ow(t[r],l,i,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}Hw.className="Conv2DTranspose",Xp(Hw);class jw extends Gw{constructor(e){if(super(e),this.inputSpec=[new pb({ndim:5})],"same"!==this.padding&&"valid"!==this.padding)throw new Sg(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(5!==(e=ib(e)).length)throw new Sg("Input should have rank 5; Received input shape: "+JSON.stringify(e));const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new Sg("The channel dimension of the inputs should be defined. Found `None`.");const n=e[t],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 pb({ndim:5,axes:{[t]:n}})],this.built=!0}call(e,t){return Na((()=>{let t=ab(e);if(5!==t.shape.length)throw new Sg(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${t.shape.length}`);const n=t.shape,s=n[0];let r,a,i;"channelsFirst"===this.dataFormat?(i=2,r=3,a=4):(i=1,r=2,a=3);const o=n[i],l=n[r],u=n[a],c=this.kernelSize[0],h=this.kernelSize[1],p=this.kernelSize[2],d=this.strides[0],f=this.strides[1],m=this.strides[2],g=[s,Ow(o,d,c,this.padding),Ow(l,f,h,this.padding),Ow(u,m,p,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(t=vh(t,[0,2,3,4,1]));let y=Po(t,this.kernel.read(),g,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(y=vh(y,[0,4,1,2,3])),null!==this.bias&&(y=_y(y,this.bias.read(),this.dataFormat)),null!==this.activation&&(y=this.activation.apply(y)),y}))}computeOutputShape(e){const t=(e=ib(e)).slice();let n,s,r,a;"channelsFirst"===this.dataFormat?(n=1,s=2,r=3,a=4):(n=4,s=1,r=2,a=3);const i=this.kernelSize[0],o=this.kernelSize[1],l=this.kernelSize[2],u=this.strides[0],c=this.strides[1],h=this.strides[2];return t[n]=this.filters,t[s]=Ow(t[s],u,i,this.padding),t[r]=Ow(t[r],c,o,this.padding),t[a]=Ow(t[a],h,l,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}jw.className="Conv3DTranspose",Xp(jw);class qw extends Vw{constructor(e,t){if(super(e,t),this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,null==t.filters)throw new Sg("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=t.kernelInitializer||null!=t.kernelRegularizer||null!=t.kernelConstraint)throw new Sg("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(null!=t.padding&&"same"!==t.padding&&"valid"!==t.padding)throw new Sg(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(t.padding)}`);this.depthMultiplier=null==t.depthMultiplier?1:t.depthMultiplier,this.depthwiseInitializer=nb(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=Tw(t.depthwiseRegularizer),this.depthwiseConstraint=Lb(t.depthwiseConstraint),this.pointwiseInitializer=nb(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=Tw(t.pointwiseRegularizer),this.pointwiseConstraint=Lb(t.pointwiseConstraint)}build(e){if((e=ib(e)).length<this.rank+2)throw new Sg(`Inputs to SeparableConv${this.rank}D should have rank ${this.rank+2}, but received input shape: ${JSON.stringify(e)}`);const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t]||e[t]<0)throw new Sg(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(e[t])}`);const n=e[t],s=this.kernelSize.concat([n,this.depthMultiplier]),r=[];for(let e=0;e<this.rank;++e)r.push(1);r.push(n*this.depthMultiplier,this.filters);const a=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",s,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,a,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",r,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,a,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,a,this.biasConstraint):this.bias=null,this.inputSpec=[new pb({ndim:this.rank+2,axes:{[t]:n}})],this.built=!0}call(e,t){return Na((()=>{let t;if(e=ab(e),1===this.rank)throw new Tg("1D separable convolution is not implemented yet.");return 2===this.rank&&("channelsFirst"===this.dataFormat&&(e=vh(e,[0,2,3,1])),t=Fc(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(t=_y(t,this.bias.read(),this.dataFormat)),null!=this.activation&&(t=this.activation.apply(t)),"channelsFirst"===this.dataFormat&&(t=vh(t,[0,3,1,2])),t}))}getConfig(){const e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=tb(this.depthwiseInitializer),e.pointwiseInitializer=tb(this.pointwiseInitializer),e.depthwiseRegularizer=Iw(this.depthwiseRegularizer),e.pointwiseRegularizer=Iw(this.pointwiseRegularizer),e.depthwiseConstraint=Ob(this.depthwiseConstraint),e.pointwiseConstraint=Ob(this.pointwiseConstraint),e}}qw.className="SeparableConv";class Kw extends qw{constructor(e){super(2,e)}}Kw.className="SeparableConv2D",Xp(Kw);class Xw extends Vw{constructor(e){super(1,e),Xw.verifyArgs(e),this.inputSpec=[{ndim:3}]}getConfig(){const e=super.getConfig();return delete e.rank,delete e.dataFormat,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&!Gg(e.kernelSize,"number",1,1))throw new Sg(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}}Xw.className="Conv1D",Xp(Xw);class Yw extends yb{constructor(e){super(e),"number"==typeof e.cropping?this.cropping=[[e.cropping,e.cropping],[e.cropping,e.cropping]]:"number"==typeof e.cropping[0]?this.cropping=[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:this.cropping=e.cropping,this.dataFormat=void 0===e.dataFormat?"channelsLast":e.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(e){return"channelsFirst"===this.dataFormat?[e[0],e[1],e[2]-this.cropping[0][0]-this.cropping[0][1],e[3]-this.cropping[1][0]-this.cropping[1][1]]:[e[0],e[1]-this.cropping[0][0]-this.cropping[0][1],e[2]-this.cropping[1][0]-this.cropping[1][1],e[3]]}call(e,t){return Na((()=>{if(e=ab(e),"channelsLast"===this.dataFormat){const t=Ny(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Ny(t,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}{const t=Ny(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Ny(t,this.cropping[1][0],e.shape[3]-this.cropping[1][1]-this.cropping[1][0],4)}}))}getConfig(){const e={cropping:this.cropping,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}Yw.className="Cropping2D",Xp(Yw);class Zw extends yb{constructor(e){var t;super(e),this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=null==e.size?this.DEFAULT_SIZE:e.size,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,ry(this.dataFormat),this.interpolation=null==e.interpolation?"nearest":e.interpolation,t=this.interpolation,Ug(Qg,"InterpolationFormat",t)}computeOutputShape(e){if("channelsFirst"===this.dataFormat){const t=null==e[2]?null:this.size[0]*e[2],n=null==e[3]?null:this.size[1]*e[3];return[e[0],e[1],t,n]}{const t=null==e[1]?null:this.size[0]*e[1],n=null==e[2]?null:this.size[1]*e[2];return[e[0],t,n,e[3]]}}call(e,t){return Na((()=>{let t=ab(e);const n=t.shape;if("channelsFirst"===this.dataFormat){t=vh(t,[0,2,3,1]);const e=this.size[0]*n[2],s=this.size[1]*n[3],r="nearest"===this.interpolation?Bp.resizeNearestNeighbor(t,[e,s]):Bp.resizeBilinear(t,[e,s]);return vh(r,[0,3,1,2])}{const e=this.size[0]*n[1],s=this.size[1]*n[2];return"nearest"===this.interpolation?Bp.resizeNearestNeighbor(t,[e,s]):Bp.resizeBilinear(t,[e,s])}}))}getConfig(){const e={size:this.size,dataFormat:this.dataFormat,interpolation:this.interpolation},t=super.getConfig();return Object.assign(e,t),e}}Zw.className="UpSampling2D",Xp(Zw);class Jw extends Ww{constructor(e){super(2,e),this.depthwiseKernel=null,this.depthMultiplier=null==e.depthMultiplier?1:e.depthMultiplier,this.depthwiseInitializer=nb(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=Lb(e.depthwiseConstraint),this.depthwiseRegularizer=Tw(e.depthwiseRegularizer)}build(e){if((e=ib(e)).length<4)throw new Sg(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(e)}.`);const t="channelsFirst"===this.dataFormat?1:3;if(null==e[t]||e[t]<0)throw new Sg(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);const n=e[t],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,t){return Na((()=>{let t=function(e,t,n=[1,1],s="valid",r,a){return Na((()=>{null==r&&(r="channelsLast"),ry(r);let i=Mw(e,r);if(4!==e.rank)throw new Sg(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(4!==t.rank)throw new Sg(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return i=jo(i,t,n,"same"===s?"same":"valid","NHWC",a),"channelsFirst"===r&&(i=vh(i,[0,3,1,2])),i}))}(e=ab(e),this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(t=_y(t,this.bias.read(),this.dataFormat)),null!=this.activation&&(t=this.activation.apply(t)),t}))}computeOutputShape(e){e=ib(e);const t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2],s="channelsFirst"===this.dataFormat?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,r=Dw(t,this.kernelSize[0],this.padding,this.strides[0]),a=Dw(n,this.kernelSize[1],this.padding,this.strides[1]);return"channelsFirst"===this.dataFormat?[e[0],s,r,a]:[e[0],r,a,s]}getConfig(){const e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=tb(this.depthwiseInitializer),e.depthwiseRegularizer=Iw(this.depthwiseRegularizer),e.depthwiseConstraint=Ob(this.depthwiseRegularizer),e}}function Qw(e,t,n,s){if(Array.isArray(e)){if(null!=t||null!=n)throw new Sg("When inputs is an array, neither initialState or constants should be provided");null!=s&&(n=e.slice(e.length-s,e.length),e=e.slice(0,e.length-s)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function r(e){return null==e||Array.isArray(e)?e:[e]}return{inputs:e,initialState:t=r(t),constants:n=r(n)}}function ev(e,t,n,s=!1,r,a,i=!1,o=!1){return Na((()=>{const l=t.shape.length;if(l<3)throw new Sg(`Input should be at least 3D, but is ${l}D.`);const u=[1,0].concat(gy(2,l));if(t=vh(t,u),null!=a)throw new Tg("The rnn() functoin of the deeplearn.js backend does not support constants yet.");i&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),null!=r&&((r=Ti(Ti(r,"bool"),"float32")).rank===l-1&&(r=Cl(r,-1)),r=vh(r,u)),s&&(t=Sc(t,0),null!=r&&(r=Sc(r,0)));const c=[];let h,p=n;const d=t.shape[0],f=mh(t);let m,g;null!=r&&(m=mh(r));for(let t=0;t<d;++t){const n=f[t],s=Na((()=>e(n,p)));if(null==r)h=s[0],p=s[1];else{const e=Na((()=>{const e=m[t],n=Jl(Iu(e),e);return{output:Ei(_i(s[0],e),_i(p[0],n)),newStates:p.map(((t,r)=>Ei(_i(s[1][r],e),_i(t,n))))}}));h=e.output,p=e.newStates}o&&c.push(h)}if(o){g=Yc(c,1)}return[h,g,p]}))}Jw.className="DepthwiseConv2D",Xp(Jw);class tv extends yb{constructor(e){let t;if(super(e),null==e.cell)throw new Sg("cell property is missing for the constructor of RNN.");if(t=Array.isArray(e.cell)?new uv({cells:e.cell}):e.cell,null==t.stateSize)throw new Sg("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=t,this.returnSequences=null!=e.returnSequences&&e.returnSequences,this.returnState=null!=e.returnState&&e.returnState,this.goBackwards=null!=e.goBackwards&&e.goBackwards,this._stateful=null!=e.stateful&&e.stateful,this.unroll=null!=e.unroll&&e.unroll,this.supportsMasking=!0,this.inputSpec=[new pb({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(null==this.states_){return gy(0,Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1).map((e=>null))}return this.states_}setStates(e){this.states_=e}computeOutputShape(e){sb(e)&&(e=e[0]);let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);const n=t[0];let s;if(s=this.returnSequences?[e[0],e[1],n]:[e[0],n],this.returnState){const n=[];for(const s of t)n.push([e[0],s]);return[s].concat(n)}return s}computeMask(e,t){return Na((()=>{Array.isArray(t)&&(t=t[0]);const e=this.returnSequences?t:null;if(this.returnState){const t=this.states.map((e=>null));return[e].concat(t)}return e}))}get states(){if(null==this.states_){const e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let n=0;n<e;++n)t.push(null);return t}return this.states_}set states(e){this.states_=e}build(e){if(null!=this.numConstants)throw new Tg("Constants support is not implemented in RNN yet.");sb(e)&&(e=e[0]);const t=this.stateful?e[0]:null,n=e.slice(2);this.inputSpec[0]=new pb({shape:[t,null,...n]});const s=[e[0]].concat(e.slice(2));let r;if(this.cell.build(s),r=Array.isArray(this.cell.stateSize)?this.cell.stateSize:[this.cell.stateSize],null!=this.stateSpec){if(!m(this.stateSpec.map((e=>e.shape[e.shape.length-1])),r))throw new Sg(`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((e=>new pb({shape:[null,e]})));this.stateful&&this.resetStates()}resetStates(e,t=!1){Na((()=>{if(!this.stateful)throw new Ng("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape[0];if(null==n)throw new Sg("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=>du([n,e]))):this.states_=[du([n,this.cell.stateSize])];else if(null==e)Ia(this.states_),null!=this.keptStates&&(Ia(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((e=>du([n,e]))):this.states_[0]=du([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new Sg(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);!0===t?this.keptStates.push(this.states_.slice()):Ia(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=[n,r];if(!m(s.shape,a))throw new Sg(`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=>Sa(e.clone())))}))}apply(e,t){let n=null==t?null:t.initialState,s=null==t?null:t.constants;null==t&&(t={});const r=Qw(e,n,s,this.numConstants);e=r.inputs,n=r.initialState,s=r.constants;let a=[],i=[];if(null!=n){t.initialState=n,a=a.concat(n),this.stateSpec=[];for(const e of n)this.stateSpec.push(new pb({shape:e.shape}));i=i.concat(this.stateSpec)}null!=s&&(t.constants=s,a=a.concat(s),this.numConstants=s.length);if(a[0]instanceof db){const n=[e].concat(a),s=this.inputSpec.concat(i),r=this.inputSpec;this.inputSpec=s;const o=super.apply(n,t);return this.inputSpec=r,o}return super.apply(e,t)}call(e,t){return Na((()=>{const n=null==t?null:t.mask,s=null==t?null:t.training;let r=null==t?null:t.initialState;e=ab(e),null==r&&(r=this.stateful?this.states_:this.getInitialState(e));const a=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(r.length!==a)throw new Sg(`RNN Layer has ${a} state(s) but was passed ${r.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");const i={training:s},o=ev(((e,t)=>{const n=this.cell.call([e].concat(t),i);return[n[0],n.slice(1)]}),e,r,this.goBackwards,n,null,this.unroll,this.returnSequences),l=o[0],u=o[1],c=o[2];this.stateful&&this.resetStates(c,s);const h=this.returnSequences?u:l;return this.returnState?[h].concat(c):h}))}getInitialState(e){return Na((()=>{let t=du(e.shape);return t=kl(t,[1,2]),t=wy(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map((e=>e>1?Ty(t,[1,e]):t)):this.cell.stateSize>1?[Ty(t,[1,this.cell.stateSize])]:[t]}))}get trainableWeights(){return this.trainable?this.cell.trainableWeights:[]}get nonTrainableWeights(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),null!=this.cell&&this.cell.setFastWeightInitDuringBuild(e)}getConfig(){const e=super.getConfig(),t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};null!=this.numConstants&&(t.numConstants=this.numConstants);const n=this.cell.getConfig();return this.getClassName()===tv.className&&(t.cell={className:this.cell.getClassName(),config:n}),Object.assign(Object.assign(Object.assign({},n),e),t)}static fromConfig(e,t,n={}){const s=Zb(t.cell,n);return new e(Object.assign(t,{cell:s}))}}tv.className="RNN",Xp(tv);class nv extends yb{}class sv extends nv{constructor(e){super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,Hg(this.units,"units"),this.activation=xw(null==e.activation?this.DEFAULT_ACTIVATION:e.activation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=nb(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=nb(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=nb(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Tw(e.kernelRegularizer),this.recurrentRegularizer=Tw(e.recurrentRegularizer),this.biasRegularizer=Tw(e.biasRegularizer),this.kernelConstraint=Lb(e.kernelConstraint),this.recurrentConstraint=Lb(e.recurrentConstraint),this.biasConstraint=Lb(e.biasConstraint),this.dropout=fy([1,my([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=fy([1,my([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=ib(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return Na((()=>{if(2!==e.length)throw new Sg(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let n=e[1];e=e[0];const s=null!=t.training&&t.training;let r;0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=cv({ones:()=>Iu(e),rate:this.dropout,training:s,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=cv({ones:()=>Iu(n),rate:this.recurrentDropout,training:s,dropoutFunc:this.dropoutFunc}));const a=this.dropoutMask,i=this.recurrentDropoutMask;r=$y(null!=a?_i(e,a):e,this.kernel.read()),null!=this.bias&&(r=_y(r,this.bias.read())),null!=i&&(n=_i(n,i));let o=Ei(r,$y(n,this.recurrentKernel.read()));return null!=this.activation&&(o=this.activation.apply(o)),[o,o]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:yw(this.activation),useBias:this.useBias,kernelInitializer:tb(this.kernelInitializer),recurrentInitializer:tb(this.recurrentInitializer),biasInitializer:tb(this.biasInitializer),kernelRegularizer:Iw(this.kernelRegularizer),recurrentRegularizer:Iw(this.recurrentRegularizer),biasRegularizer:Iw(this.biasRegularizer),activityRegularizer:Iw(this.activityRegularizer),kernelConstraint:Ob(this.kernelConstraint),recurrentConstraint:Ob(this.recurrentConstraint),biasConstraint:Ob(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign(Object.assign({},e),t)}}sv.className="SimpleRNNCell",Xp(sv);class rv extends tv{constructor(e){e.cell=new sv(e),super(e)}call(e,t){return Na((()=>{null!=this.cell.dropoutMask&&(Ia(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(Ia(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,s=null==t?null:t.training,r=null==t?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:r})}))}static fromConfig(e,t){return new e(t)}}rv.className="SimpleRNN",Xp(rv);class av extends nv{constructor(e){if(super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.resetAfter)throw new Sg("GRUCell does not support reset_after parameter set to true.");this.units=e.units,Hg(this.units,"units"),this.activation=xw(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=xw(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=nb(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=nb(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=nb(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Tw(e.kernelRegularizer),this.recurrentRegularizer=Tw(e.recurrentRegularizer),this.biasRegularizer=Tw(e.biasRegularizer),this.kernelConstraint=Lb(e.kernelConstraint),this.recurrentConstraint=Lb(e.recurrentConstraint),this.biasConstraint=Lb(e.biasConstraint),this.dropout=fy([1,my([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=fy([1,my([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){const t=(e=ib(e))[e.length-1];this.kernel=this.addWeight("kernel",[t,3*this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,3*this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[3*this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return Na((()=>{if(2!==e.length)throw new Sg(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);const n=null!=t.training&&t.training;let s=e[1];e=e[0],0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=cv({ones:()=>Iu(e),rate:this.dropout,training:n,count:3,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=cv({ones:()=>Iu(s),rate:this.recurrentDropout,training:n,count:3,dropoutFunc:this.dropoutFunc}));const r=this.dropoutMask,a=this.recurrentDropoutMask;let i,o,l;0<this.dropout&&this.dropout<1&&(e=_i(e,r[0]));let u=$y(e,this.kernel.read());this.useBias&&(u=_y(u,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(s=_i(s,a[0]));const c=this.recurrentKernel.read(),[h,p]=jc(c,[2*this.units,this.units],c.rank-1),d=$y(s,h),[f,m,g]=jc(u,3,u.rank-1),[y,b]=jc(d,2,d.rank-1);i=this.recurrentActivation.apply(Ei(f,y)),o=this.recurrentActivation.apply(Ei(m,b));const x=$y(_i(o,s),p);l=this.activation.apply(Ei(g,x));const w=Ei(_i(i,s),_i(Ei(1,Xl(i)),l));return[w,w]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:yw(this.activation),recurrentActivation:yw(this.recurrentActivation),useBias:this.useBias,kernelInitializer:tb(this.kernelInitializer),recurrentInitializer:tb(this.recurrentInitializer),biasInitializer:tb(this.biasInitializer),kernelRegularizer:Iw(this.kernelRegularizer),recurrentRegularizer:Iw(this.recurrentRegularizer),biasRegularizer:Iw(this.biasRegularizer),activityRegularizer:Iw(this.activityRegularizer),kernelConstraint:Ob(this.kernelConstraint),recurrentConstraint:Ob(this.recurrentConstraint),biasConstraint:Ob(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign(Object.assign({},e),t)}}av.className="GRUCell",Xp(av);class iv extends tv{constructor(e){0===e.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new av(e),super(e)}call(e,t){return Na((()=>{null!=this.cell.dropoutMask&&(Ia(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(Ia(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,s=null==t?null:t.training,r=null==t?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:r})}))}static fromConfig(e,t){return 0===t.implmentation&&(t.implementation=1),new e(t)}}iv.className="GRU",Xp(iv);class ov extends nv{constructor(e){super(e),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=e.units,Hg(this.units,"units"),this.activation=xw(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=xw(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=nb(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=nb(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=nb(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=Tw(e.kernelRegularizer),this.recurrentRegularizer=Tw(e.recurrentRegularizer),this.biasRegularizer=Tw(e.biasRegularizer),this.kernelConstraint=Lb(e.kernelConstraint),this.recurrentConstraint=Lb(e.recurrentConstraint),this.biasConstraint=Lb(e.biasConstraint),this.dropout=fy([1,my([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=fy([1,my([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){var t;const n=(e=ib(e))[e.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 e=this.biasInitializer,n=this.units;s=new((t=class extends Ly{apply(t,s){const r=e.apply([n]),a=(new Py).apply([n]),i=e.apply([2*n]);return Sy(Sy(r,a),i)}}).className="CustomInit",t)}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,t){return Na((()=>{const n=null!=t.training&&t.training;if(3!==e.length)throw new Sg(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let s=e[1];const r=e[2];e=e[0],0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=cv({ones:()=>Iu(e),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=cv({ones:()=>Iu(s),rate:this.recurrentDropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const a=this.dropoutMask,i=this.recurrentDropoutMask;let o,l,u,c;0<this.dropout&&this.dropout<1&&(e=_i(e,a[0]));let h=$y(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(s=_i(s,i[0])),h=Ei(h,$y(s,this.recurrentKernel.read())),this.useBias&&(h=_y(h,this.bias.read()));const[p,d,f,m]=jc(h,4,h.rank-1);o=this.recurrentActivation.apply(p),l=this.recurrentActivation.apply(d),u=Ei(_i(l,r),_i(o,this.activation.apply(f))),c=this.recurrentActivation.apply(m);const g=_i(c,this.activation.apply(u));return[g,g,u]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:yw(this.activation),recurrentActivation:yw(this.recurrentActivation),useBias:this.useBias,kernelInitializer:tb(this.kernelInitializer),recurrentInitializer:tb(this.recurrentInitializer),biasInitializer:tb(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:Iw(this.kernelRegularizer),recurrentRegularizer:Iw(this.recurrentRegularizer),biasRegularizer:Iw(this.biasRegularizer),activityRegularizer:Iw(this.activityRegularizer),kernelConstraint:Ob(this.kernelConstraint),recurrentConstraint:Ob(this.recurrentConstraint),biasConstraint:Ob(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign(Object.assign({},e),t)}}ov.className="LSTMCell",Xp(ov);class lv extends tv{constructor(e){0===e.implementation&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new ov(e),super(e)}call(e,t){return Na((()=>{null!=this.cell.dropoutMask&&(Ia(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(Ia(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);const n=null==t?null:t.mask,s=null==t?null:t.training,r=null==t?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:r})}))}static fromConfig(e,t){return 0===t.implmentation&&(t.implementation=1),new e(t)}}lv.className="LSTM",Xp(lv);class uv extends nv{constructor(e){super(e),this.cells=e.cells}get stateSize(){const e=[];for(const t of this.cells.slice().reverse())Array.isArray(t.stateSize)?e.push(...t.stateSize):e.push(t.stateSize);return e}call(e,t){return Na((()=>{let n=e.slice(1);const s=[];for(const e of this.cells.slice().reverse())Array.isArray(e.stateSize)?s.push(n.splice(0,e.stateSize.length)):s.push(n.splice(0,1));s.reverse();const r=[];let a;for(let i=0;i<this.cells.length;++i){const o=this.cells[i];n=s[i],a=0===i?[e[0]].concat(n):[a[0]].concat(n),a=o.call(a,t),r.push(a.slice(1))}n=[];for(const e of r.slice().reverse())n.push(...e);return[a[0]].concat(n)}))}build(e){let t;sb(e)&&(e=e[0]),this.cells.forEach(((n,s)=>{ly(`RNNCell_${s}`,(()=>{n.build(e),t=Array.isArray(n.stateSize)?n.stateSize[0]:n.stateSize,e=[e[0],t]}))})),this.built=!0}getConfig(){const e=super.getConfig(),t={cells:this.cells.map((e=>({className:e.getClassName(),config:e.getConfig()})))};return Object.assign(Object.assign({},e),t)}static fromConfig(e,t,n={}){const s=[];for(const e of t.cells)s.push(Zb(e,n));return new e({cells:s})}get trainableWeights(){if(!this.trainable)return[];const e=[];for(const t of this.cells)e.push(...t.trainableWeights);return e}get nonTrainableWeights(){const e=[];for(const t of this.cells)e.push(...t.nonTrainableWeights);if(!this.trainable){const t=[];for(const e of this.cells)t.push(...e.trainableWeights);return t.concat(e)}return e}getWeights(){const e=[];for(const t of this.cells)e.push(...t.weights);return cb(e)}setWeights(e){const t=[];for(const n of this.cells){const s=n.weights.length,r=e.splice(s);for(let e=0;e<n.weights.length;++e)t.push([n.weights[e],r[e]])}hb(t)}}function cv(e){const{ones:t,rate:n,training:s=!1,count:r=1,dropoutFunc:a}=e,i=()=>null!=a?a(t(),n):Fy(t(),n),o=()=>Dy(i,t,s);if(!r||r<=1)return Sa(o().clone());return Array(r).fill(void 0).map(o).map((e=>Sa(e.clone())))}uv.className="StackedRNNCells",Xp(uv);var hv=function(e,t){var n={};for(var s in e)Object.prototype.hasOwnProperty.call(e,s)&&t.indexOf(s)<0&&(n[s]=e[s]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(s=Object.getOwnPropertySymbols(e);r<s.length;r++)t.indexOf(s[r])<0&&Object.prototype.propertyIsEnumerable.call(e,s[r])&&(n[s[r]]=e[s[r]])}return n};class pv extends tv{constructor(e){if(e.unroll)throw new Tg("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new Tg("It is not possible at the moment to stack convolutional cells.");super(e),this.inputSpec=[new pb({ndim:5})]}call(e,t){return Na((()=>{if(null!=this.cell.dropoutMask&&(Ia(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(Ia(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new Sg("ConvRNN2D cell does not support constants");const n=null==t?null:t.mask,s=null==t?null:t.training,r=null==t?null:t.initialState;return super.call(e,{mask:n,training:s,initialState:r})}))}computeOutputShape(e){let t=this.computeSingleOutputShape(e);return this.returnSequences||(t=[t[0],...t.slice(2)]),this.returnState&&(t=[t,...Array(2).fill([e[0],...t.slice(-3)])]),t}getInitialState(e){return Na((()=>{const{stateSize:t}=this.cell,n=e.shape,s=this.computeSingleOutputShape(n),r=du([s[0],...s.slice(2)]);return Array.isArray(t)?Array(t.length).fill(r):[r]}))}resetStates(e,t=!1){Na((()=>{if(!this.stateful)throw new Ng("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape,s=this.computeSingleOutputShape(n),r=[s[0],...s.slice(2)];if(null==n[0])throw new Sg("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((()=>du(r))):this.states_=[du(r)];else if(null==e)Ia(this.states_),null!=this.keptStates&&(Ia(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((()=>du(r))):this.states_[0]=du(r);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new Sg(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t?this.keptStates.push(this.states_.slice()):Ia(this.states_);for(let t=0;t<this.states_.length;++t){const n=e[t],s=r;if(!m(n.shape,s))throw new Sg(`State ${t} is incompatible with layer ${this.name}: expected shape=${s}, received shape=${n.shape}`);this.states_[t]=n}}this.states_=this.states_.map((e=>Sa(e.clone())))}))}computeSingleOutputShape(e){const{dataFormat:t,filters:n,kernelSize:s,padding:r,strides:a,dilationRate:i}=this.cell,o="channelsFirst"===t,l=e[o?3:2],u=e[o?4:3],c=Dw(l,s[0],r,a[0],i[0]),h=Dw(u,s[1],r,a[1],i[1]);return[...e.slice(0,2),...o?[n,c,h]:[c,h,n]]}}pv.className="ConvRNN2D";class dv extends ov{constructor(e){const{filters:t,kernelSize:n,strides:s,padding:r,dataFormat:a,dilationRate:i}=e;super(Object.assign(Object.assign({},e),{units:t})),this.filters=t,Hg(this.filters,"filters"),this.kernelSize=Fw(n,2,"kernelSize"),this.kernelSize.forEach((e=>Hg(e,"kernelSize"))),this.strides=Fw(s||1,2,"strides"),this.strides.forEach((e=>Hg(e,"strides"))),this.padding=r||"valid",ay(this.padding),this.dataFormat=a||"channelsLast",ry(this.dataFormat),this.dilationRate=Fw(i||1,2,"dilationRate"),this.dilationRate.forEach((e=>Hg(e,"dilationRate")))}build(e){var t;e=ib(e);const n="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[n])throw new Sg(`The channel dimension of the input should be defined. Found ${e[n]}`);const s=e[n],r=this.kernelSize.concat([s,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 n=this.biasInitializer,s=this.filters;e=new((t=class extends Ly{apply(e,t){return Iy([n.apply([s]),fu([s]),n.apply([2*s])])}}).className="CustomInit",t)}else e=this.biasInitializer;this.bias=this.addWeight("bias",[4*this.filters],null,e,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return Na((()=>{if(3!==e.length)throw new Sg(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);const n=t.training||!1,s=e[0],r=e[1],a=e[2];0<this.dropout&&this.dropout<1&&null==this.dropoutMask&&(this.dropoutMask=cv({ones:()=>Iu(s),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const i=this.dropoutMask,o=(e,t,n)=>t&&t[n]?_i(t[n],e):e;let l=o(s,i,0),u=o(s,i,1),c=o(s,i,2),h=o(s,i,3);0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=cv({ones:()=>Iu(r),rate:this.recurrentDropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const p=this.recurrentDropoutMask;let d=o(r,p,0),f=o(r,p,1),m=o(r,p,2),g=o(r,p,3);const[y,b,x,w]=jc(this.kernel.read(),4,3),[v,k,N,I]=this.useBias?jc(this.bias.read(),4):[null,null,null,null];l=this.inputConv(l,y,v,this.padding),u=this.inputConv(u,b,k,this.padding),c=this.inputConv(c,x,N,this.padding),h=this.inputConv(h,w,I,this.padding);const[S,T,C,$]=jc(this.recurrentKernel.read(),4,3);d=this.recurrentConv(d,S),f=this.recurrentConv(f,T),m=this.recurrentConv(m,C),g=this.recurrentConv(g,$);const E=this.recurrentActivation.apply(Ei(l,d)),A=this.recurrentActivation.apply(Ei(u,f)),R=Ei(_i(A,a),_i(E,this.activation.apply(Ei(c,m)))),_=_i(this.recurrentActivation.apply(Ei(h,g)),this.activation.apply(R));return[_,_,R]}))}getConfig(){const e=super.getConfig(),{units:t}=e,n=hv(e,["units"]),s={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return Object.assign(Object.assign({},n),s)}inputConv(e,t,n,s){const r=Fo(e,t,this.strides,s||"valid","channelsFirst"===this.dataFormat?"NCHW":"NHWC",this.dilationRate);return n?_y(r,n,this.dataFormat):r}recurrentConv(e,t){return Fo(e,t,1,"same","channelsFirst"===this.dataFormat?"NCHW":"NHWC")}}dv.className="ConvLSTM2DCell",Xp(dv);class fv extends pv{constructor(e){const t=new dv(e);super(Object.assign(Object.assign({},e),{cell:t}))}static fromConfig(e,t){return new e(t)}}fv.className="ConvLSTM2D",Xp(fv);class mv extends yb{constructor(e){super(e),this.rate=Math.max(Math.min(e.rate,1),0),this.noiseShape=e.noiseShape,this.seed=e.seed,this.supportsMasking=!0}getNoiseShape(e){if(null==this.noiseShape)return this.noiseShape;const t=e.shape,n=[];for(let e=0;e<this.noiseShape.length;++e)n.push(null==this.noiseShape[e]?t[e]:this.noiseShape[e]);return n}call(e,t){return Na((()=>{this.invokeCallHook(e,t);const n=ab(e);if(0<this.rate&&this.rate<1){const e=null!=t.training&&t.training,s=this.getNoiseShape(n);return Dy((()=>Fy(n,this.rate,s,this.seed)),(()=>n),e)}return e}))}getConfig(){const e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},t=super.getConfig();return Object.assign(e,t),e}dispose(){return super.dispose()}}mv.className="Dropout",Xp(mv);class gv extends mv{constructor(e){super(e),this.inputSpec=[{ndim:3}]}getNoiseShape(e){const t=e.shape;return[t[0],1,t[2]]}}gv.className="SpatialDropout1D",Xp(gv);class yv extends yb{constructor(e){if(super(e),this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",null==e.batchInputShape&&null==e.inputShape&&null!=e.inputDim){let t=null;null!=e.batchSize&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,Hg(this.units,"units"),this.activation=xw(e.activation),null!=e.useBias&&(this.useBias=e.useBias),this.kernelInitializer=nb(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=nb(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=Lb(e.kernelConstraint),this.biasConstraint=Lb(e.biasConstraint),this.kernelRegularizer=Tw(e.kernelRegularizer),this.biasRegularizer=Tw(e.biasRegularizer),this.activityRegularizer=Tw(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){const t=(e=ib(e))[e.length-1];null==this.kernel&&(this.kernel=this.addWeight("kernel",[t,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]:t}}],this.built=!0}computeOutputShape(e){const t=(e=ib(e)).slice();return t[t.length-1]=this.units,t}call(e,t){return Na((()=>{this.invokeCallHook(e,t);const n=ab(e),s=qg(this.activation.getClassName());let r;return null!=s?r=$y(n,this.kernel.read(),s,this.bias?this.bias.read():null):(r=$y(n,this.kernel.read()),null!=this.bias&&(r=_y(r,this.bias.read())),null!=this.activation&&(r=this.activation.apply(r))),r}))}getConfig(){const e={units:this.units,activation:yw(this.activation),useBias:this.useBias,kernelInitializer:tb(this.kernelInitializer),biasInitializer:tb(this.biasInitializer),kernelRegularizer:Iw(this.kernelRegularizer),biasRegularizer:Iw(this.biasRegularizer),activityRegularizer:Iw(this.activityRegularizer),kernelConstraint:Ob(this.kernelConstraint),biasConstraint:Ob(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}yv.className="Dense",Xp(yv);class bv extends yb{constructor(e){super(e=e||{}),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=ib(e);for(const t of e.slice(1))if(null==t)throw new Sg(`The shape of the input to "Flatten" is not fully defined (got ${e.slice(1)}). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.`);return[e[0],dy(e,1)]}call(e,t){return Na((()=>{this.invokeCallHook(e,t);let n=ab(e);if("channelsFirst"===this.dataFormat&&n.rank>1){const e=[0];for(let t=2;t<n.rank;++t)e.push(t);e.push(1),n=vh(n,e)}return function(e){if(e.rank<=1)throw new Sg(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);const t=[e.shape[0],dy(e.shape,1)];return oo(e,t)}(n)}))}getConfig(){const e={};null!=this.dataFormat&&(e.dataFormat=this.dataFormat);const t=super.getConfig();return Object.assign(e,t),e}}bv.className="Flatten",Xp(bv);class xv extends yb{constructor(e){super(e),this.supportsMasking=!0,this.activation=xw(e.activation)}call(e,t){return Na((()=>{this.invokeCallHook(e,t);const n=ab(e);return this.activation.apply(n)}))}getConfig(){const e={activation:yw(this.activation)},t=super.getConfig();return Object.assign(e,t),e}}xv.className="Activation",Xp(xv);class wv extends yb{constructor(e){super(e),this.n=e.n,this.inputSpec=[{ndim:2}]}computeOutputShape(e){return[e[0],this.n,e[1]]}call(e,t){return Na((()=>{return e=ab(e),t=e,n=this.n,Na((()=>{if(2!==t.shape.length)throw new Sg(`repeat() expects a rank-2 tensor, but received a rank-${t.shape.length} tensor.`);return Ty(wy(t,1),[1,n,1])}));var t,n}))}getConfig(){const e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}}wv.className="RepeatVector",Xp(wv);class vv extends yb{constructor(e){super(e),this.targetShape=e.targetShape;for(let e=0;e<this.targetShape.length;++e)this.isUnknown(this.targetShape[e])&&(this.targetShape[e]=null)}isUnknown(e){return e<0||null==e}fixUnknownDimension(e,t){const n="Total size of new array must be unchanged.",s=t.slice();let r=1,a=null;for(let e=0;e<s.length;++e){const t=s[e];if(this.isUnknown(t)){if(null!==a)throw new Sg("Can only specifiy one unknown dimension.");a=e}else r*=t}const i=dy(e);if(null!==a){if(0===r||i%r!=0)throw new Sg(n);s[a]=i/r}else if(i!==r)throw new Sg(n);return s}computeOutputShape(e){let t=!1;for(let n=0;n<e.length;++n)if(this.isUnknown(e[n])){t=!0;break}return t?e.slice(0,1).concat(this.targetShape):e.slice(0,1).concat(this.fixUnknownDimension(e.slice(1),this.targetShape))}call(e,t){return Na((()=>{this.invokeCallHook(e,t);const n=ab(e),s=n.shape,r=s.slice(0,1).concat(this.fixUnknownDimension(s.slice(1),this.targetShape));return oo(n,r)}))}getConfig(){const e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}}vv.className="Reshape",Xp(vv);class kv extends yb{constructor(e){if(super(e),null==e.dims)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(e.dims))throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${e.dims} instead.`);const t=gy(1,e.dims.length+1);if(!m(e.dims.slice().sort(),t))throw new Error("Invalid permutation `dims`: "+JSON.stringify(e.dims)+" `dims` must contain consecutive integers starting from 1.");this.dims=e.dims,this.dimsIncludingBatch=[0].concat(this.dims),this.inputSpec=[new pb({ndim:this.dims.length+1})]}computeOutputShape(e){const t=(e=ib(e)).slice();return this.dims.forEach(((n,s)=>{t[s+1]=e[n]})),t}call(e,t){return vh(ab(e),this.dimsIncludingBatch)}getConfig(){const e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}}kv.className="Permute",Xp(kv);class Nv extends yb{constructor(e){super(null==e?{}:e),this.supportsMasking=!0,this.maskValue=null!=e?null==e.maskValue?0:e.maskValue:0}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={maskValue:this.maskValue};return Object.assign(t,e),t}computeMask(e,t){const n=ab(e);return zi(ku(n,this.maskValue),-1)}call(e,t){return Na((()=>{this.invokeCallHook(e,t);const n=ab(e),s=zi(ku(n,this.maskValue),-1,!0);return _i(n,Ti(s,n.dtype))}))}}Nv.className="Masking",Xp(Nv);class Iv extends yb{constructor(e){if(super(e),this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",null==e.batchInputShape&&null==e.inputShape){let t=null;null!=e.batchSize&&(t=e.batchSize),null==e.inputLength?this.batchInputShape=[t,null]:this.batchInputShape=[t].concat(Fg(e.inputLength))}this.inputDim=e.inputDim,Hg(this.inputDim,"inputDim"),this.outputDim=e.outputDim,Hg(this.outputDim,"outputDim"),this.embeddingsInitializer=nb(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=Tw(e.embeddingsRegularizer),this.activityRegularizer=Tw(e.activityRegularizer),this.embeddingsConstraint=Lb(e.embeddingsConstraint),this.maskZero=e.maskZero,this.supportsMasking=e.maskZero,this.inputLength=e.inputLength}build(e){this.embeddings=this.addWeight("embeddings",[this.inputDim,this.outputDim],this.dtype,this.embeddingsInitializer,this.embeddingsRegularizer,!0,this.embeddingsConstraint),this.built=!0}warnOnIncompatibleInputShape(e){}computeMask(e,t){return Na((()=>this.maskZero?(e=ab(e),ku(e,tl(e))):null))}computeOutputShape(e){if(e=ib(e),null==this.inputLength)return[...e,this.outputDim];const t=Fg(this.inputLength);if(t.length!==e.length-1)throw new Sg(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let n=0;for(let s=0;s<t.length;++s){const r=t[s],a=e[s+1];if(null!=r&&null!=a&&r!==a)throw new Sg(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);null==r&&(t[n]=a),n++}}return[e[0],...t,this.outputDim]}call(e,t){return Na((()=>{this.invokeCallHook(e,t);let n=ab(e);"int32"!==n.dtype&&(n=xy(n,"int32"));const s=Ey(this.embeddings.read(),oo(n,[n.size]));return oo(s,ib(this.computeOutputShape(n.shape)))}))}getConfig(){const e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:tb(this.embeddingsInitializer),embeddingsRegularizer:Iw(this.embeddingsRegularizer),activityRegularizer:Iw(this.activityRegularizer),embeddingsConstraint:Ob(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}}Iv.className="Embedding",Xp(Iv);class Sv extends yb{constructor(e){super(e||{}),this.supportsMasking=!0}mergeFunction(e){throw new Tg}computeElementwiseOpOutputShape(e,t){if(null==e||null==t)return null;if(e.length<t.length)return this.computeElementwiseOpOutputShape(t,e);if(0===t.length)return e;const n=e.slice(0,e.length-t.length);for(let s=0;s<t.length;++s){const r=e[e.length-t.length+s],a=t[s];if(null==r||null==a||r<0||a<0)n.push(null);else if(1===r)n.push(a);else if(1===a)n.push(r);else{if(r!==a)throw new Sg("Operands could not be broadcast together with shapes "+JSON.stringify(e)+" "+JSON.stringify(t));n.push(r)}}return n}build(e){if(Array.isArray(e)&&!Array.isArray(e[0])&&(e=[ib(e)]),e.length<2)throw new Sg(`A merge layer should be called on an Array of at least 2 inputs. Got ${e.length} input(s).`);let t=[];for(const n of e)null!=n&&null!==n[0]&&t.push(n[0]);if(t=Wg(t),t.length>1)throw new Sg(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let n=null==e[0]?null:e[0].slice(1);for(let t=1;t<e.length;++t){const s=null==e[t]?null:e[t].slice(1);n=this.computeElementwiseOpOutputShape(n,s)}const s=e.map((e=>e.length));-1===e.indexOf(null)&&1===Wg(s).length?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return Na((()=>{if(this.reshapeRequired){const t=[],n=e.map((e=>e.rank));if(-1===n.indexOf(null)){const s=my(n);for(let n of e){const e=n.rank;for(let t=0;t<s-e;++t)n=wy(n,1);t.push(n)}return this.mergeFunction(t)}{let n=!1;for(const s of e){const e=s.rank;if(null==e){const e=s.shape,r=e[0],a=e.slice(1).concat([r]);let i=oo(s,[r].concat(dy(e.slice(1))));i=vh(i,[1,0]),i=oo(i,a),t.push(i),n=!0}else if(e>1){const r=gy(1,e).concat([0]);t.push(vh(s,r)),n=!0}else t.push(s)}let s=this.mergeFunction(t);const r=s.rank;if(n)if(null==r){const e=s.shape,t=e[e.length-1],n=[t].concat(e.slice(0,e.length-1));s=oo(vh(oo(s,[-1,t]),[1,0]),n)}else if(r>1){const e=[r-1].concat(gy(0,r-1));s=vh(s,e)}return s}}return this.mergeFunction(e)}))}computeOutputShape(e){let t;t=null==e[0]?null:e[0].slice(1);for(let n=1;n<e.length;++n){const s=null==e[n]?null:e[n].slice(1);t=this.computeElementwiseOpOutputShape(t,s)}let n=[];for(const t of e)null!=t&&null!==t[0]&&n.push(t[0]);return n=Wg(n),t=1===n.length?n.concat(t):[null].concat(t),t}computeMask(e,t){return Na((()=>{if(null==t)return null;if(!Array.isArray(t))throw new Sg("`mask` should be an Array");if(!Array.isArray(e))throw new Sg("`inputs` should be an Array");if(t.length!==e.length)throw new Sg(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every((e=>null==e)))return null;let n=(t=t.map((e=>null==e?e:Cl(e,0))))[0];for(let e=1;e<t.length-1;++e)n=tu(n,t[e]);return n}))}}class Tv extends Sv{constructor(e){super(e)}mergeFunction(e){return Na((()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=Ei(t,e[n]);return t}))}}Tv.className="Add",Xp(Tv);class Cv extends Sv{constructor(e){super(e)}mergeFunction(e){return Na((()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=_i(t,e[n]);return t}))}}Cv.className="Multiply",Xp(Cv);class $v extends Sv{constructor(e){super(e)}mergeFunction(e){return Na((()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=Ei(t,e[n]);return _i(1/e.length,t)}))}}$v.className="Average",Xp($v);class Ev extends Sv{constructor(e){super(e)}mergeFunction(e){return Na((()=>{let t=e[0];for(let n=1;n<e.length;++n)t=hu(t,e[n]);return t}))}}Ev.className="Maximum",Xp(Ev);class Av extends Sv{constructor(e){super(e)}mergeFunction(e){return Na((()=>{let t=e[0];for(let n=1;n<e.length;++n)t=gu(t,e[n]);return t}))}}Av.className="Minimum",Xp(Av);class Rv extends Sv{constructor(e){super(e),this.DEFAULT_AXIS=-1,null==e&&(e={}),this.axis=null==e.axis?this.DEFAULT_AXIS:e.axis,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){if(!Array.isArray(e)||!Array.isArray(e[0])||1===e.length)throw new Sg("A `Concatenate` layer should be called on a list of at least 2 inputs");let t=!0;for(const n of e)if(null!=n){t=!1;break}if(t)return;const n=[];for(let t=0;t<e.length;++t){const s=e[t].slice();s.splice(this.axis,1);let r=!1;for(const e of n)if(m(e,s)){r=!0;break}r||n.push(s)}if(n.length>1)throw new Sg("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return Na((()=>Iy(e,this.axis)))}computeOutputShape(e){if(!Array.isArray(e)||!Array.isArray(e[0]))throw new Sg("A `Concatenate` layer should be called on a list of inputs.");const t=e,n=t[0].slice(),s=this.axis<0?n.length+this.axis:this.axis;for(const e of t.slice(1)){if(null==n[s]||null==e[s]){n[s]=null;break}n[s]+=e[s]}return n}computeMask(e,t){if(null==t)return null;if(!Array.isArray(t))throw new Sg("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new Sg("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new Sg(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return Na((()=>{let n=!0;if(t.forEach((e=>{null==e||(n=!1)})),n)return null;const s=[];for(let n=0;n<e.length;++n)null==t[n]?s.push(Ti(Iu(e[n]),"bool")):t[n].rank<e[n].rank?s.push(Cl(t[n],-1)):s.push(t[n]);const r=co(s,this.axis);return Li(r,-1,!1)}))}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}function _v(e,t){for(;e<0;)e+=t;return e}Rv.className="Concatenate",Xp(Rv);class Fv extends Sv{constructor(e){super(e),this.axes=e.axes,this.normalize=null!=e.normalize&&e.normalize,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){c(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 t=e[0],n=e[1];if(t.length>3||n.length>3)throw new Tg("Dot layer does not support tensors of 4D or higher rank yet.");const s=this.interpretAxes(t,n);if(t[s[0]]!==n[s[1]])throw new Sg(`Dimension incompatibility: ${t[s[0]]} !== ${n[s[1]]}`)}mergeFunction(e){if(2!==e.length)throw new Sg(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t,n=e[0],s=e[1];return t=Array.isArray(this.axes)?this.axes.map(((t,n)=>_v(t,e[n].shape.length))):[_v(this.axes,n.shape.length),_v(this.axes,s.shape.length)],this.normalize&&(n=Jb(n,t[0]),s=Jb(s,t[1])),function(e,t,n){if(e.shape.length>3||t.shape.length>3)throw new Tg("batchDot is not implemented for tensors of 4D or higher rank yet");if(c(e.shape.length>=2,(()=>`batchDot requires the rank of x to be >= 2, but got ${e.shape.length}`)),c(e.shape.length>=2,(()=>`batchDot requires the rank of y to be >= 2, but got ${t.shape.length}`)),"number"==typeof n&&(n=[n,n]),"complex64"===e.dtype||"complex64"===t.dtype)throw new Tg("batchDot is not implemented for complex64-type Tensors yet.");const s=e.shape.length,r=t.shape.length;null==n&&(n=[s-1,r-2]);const a=n;return Na((()=>{let n,i;if(s>r){n=s-r;const e=[];for(let t=0;t<n;++t)e.push(1);t=oo(t,t.shape.concat(e))}else if(r>s){n=r-s;const t=[];for(let e=0;e<n;++e)t.push(1);e=oo(e,e.shape.concat(t))}else n=0;if(2===e.shape.length&&2===t.shape.length)i=a[0]===a[1]?kl(_i(e,t),a[0]):kl(_i(vh(e,[1,0]),t),a[1]);else{const n=a[0]!==e.shape.length-1,s=a[1]===t.shape.length-1;i=ho(e,t,n,s)}if(n>0){let e;e=s>r?s+r-3:s-1;const t=[];for(let s=e;s<e+n;++s)t.push(s);i=Xc(i,t)}return 1===i.shape.length&&(i=Cl(i,1)),i}))}(n,s,t)}interpretAxes(e,t){let n;return n=Array.isArray(this.axes)?this.axes:[_v(this.axes,e.length),_v(this.axes,t.length)],n}computeOutputShape(e){c(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 t=e[0].slice(),n=e[1].slice();if(t.length>3||n.length>3)throw new Tg("Dot layer does not support tensors of 4D or higher rank yet.");const s=this.interpretAxes(t,n);t.splice(s[0],1),n.splice(s[1],1),n.splice(0,1);const r=t.concat(n);return 1===r.length&&r.push(1),r}computeMask(e,t){return null}getConfig(){const e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}}Fv.className="Dot",Xp(Fv);class Dv extends yb{constructor(e){super(e),this.supportsMasking=!0,this.stddev=e.stddev}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={stddev:this.stddev};return Object.assign(t,e),t}call(e,t){return Na((()=>{this.invokeCallHook(e,t);const n=ab(e);return Dy((()=>Ei(Cy(n.shape,0,this.stddev),n)),(()=>n),t.training||!1)}))}}Dv.className="GaussianNoise",Xp(Dv);class Ov extends yb{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return Na((()=>{this.invokeCallHook(e,t);const n=ab(e);if(this.rate>0&&this.rate<1){return Dy((()=>{const e=Math.sqrt(this.rate/(1-this.rate));return _i(n,Cy(n.shape,1,e))}),(()=>n),t.training||!1)}return n}))}}Ov.className="GaussianDropout",Xp(Ov);class Mv extends yb{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||ab(e).shape}computeOutputShape(e){return e}getConfig(){const e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return Na((()=>{if(this.rate<1&&this.rate>0){const n=this._getNoiseShape(e),s=()=>{const t=ab(e),s=-1.7580993408473766;let r=Dl(bc(n),this.rate);r=xy(r,"float32");const a=((1-this.rate)*(1+this.rate*s**2))**-.5,i=-a*s*this.rate,o=Ei(_i(t,r),_i(Ei(r,-1),s));return Ei(_i(o,a),i)};return Dy(s,(()=>ab(e)),t.training||!1)}return e}))}}function Lv(e,t,n,s,r,a=.001){let i;if(2===e.rank)i=xo(e,t,n,s,r,a);else if(3===e.rank)i=wo(e,t,n,s,r,a);else{if(4!==e.rank)throw new Tg(`batchNormalization is not implemented for array of rank ${e.rank} yet`);i=vo(e,t,n,s,r,a)}return i}function zv(e,t,n,s,r=.001){return m(s.slice().sort(),gy(0,e.rank-1))?function(e,t,n,s,r=.001){return Na((()=>{const a=xu(e,s),i=a.mean,o=a.variance;return[Lv(e,i,o,n,t,r),i,o]}))}(e,t,n,s,r):function(e,t,n,s,r=.001){return Na((()=>{const a=xu(e,s),i=a.mean,o=a.variance,l=[];for(const t of gy(0,e.rank))-1!==s.indexOf(t)?l.push(1):l.push(e.shape[t]);const u=oo(i,l),c=oo(o,l),h=null==t?null:oo(t,l),p=null==n?null:oo(n,l);return[Lv(e,u,c,p,h,r),i,o]}))}(e,t,n,s,r)}Mv.className="AlphaDropout",Xp(Mv);class Pv extends yb{constructor(e){null==e&&(e={}),super(e),this.supportsMasking=!0,this.axis=null==e.axis?-1:e.axis,this.momentum=null==e.momentum?.99:e.momentum,this.epsilon=null==e.epsilon?.001:e.epsilon,this.center=null==e.center||e.center,this.scale=null==e.scale||e.scale,this.betaInitializer=nb(e.betaInitializer||"zeros"),this.gammaInitializer=nb(e.gammaInitializer||"ones"),this.movingMeanInitializer=nb(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=nb(e.movingVarianceInitializer||"ones"),this.betaConstraint=Lb(e.betaConstraint),this.gammaConstraint=Lb(e.gammaConstraint),this.betaRegularizer=Tw(e.betaRegularizer),this.gammaRegularizer=Tw(e.gammaRegularizer)}build(e){e=ib(e);const t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(null==n)throw new Sg(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new pb({ndim:e.length,axes:{[t]: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,t){return Na((()=>{const n=null!=t.training&&t.training,s=ab(e),r=s.shape,a=r.length,i=gy(0,a),o=this.axis>=0?this.axis:this.axis+a;i.splice(o,1);const l=Eg(1,a);l[o]=r[o];const u=i.slice();u.sort();const c=!m(u,gy(0,a).slice(0,a-1));if(!n)return(()=>{if(c){const e=oo(this.movingMean.read(),l),t=oo(this.movingVariance.read(),l),n=this.center?oo(this.beta.read(),l):null,r=this.scale?oo(this.gamma.read(),l):null;return Lv(s,e,t,n,r,this.epsilon)}return Lv(s,this.movingMean.read(),this.movingVariance.read(),null==this.beta?null:this.beta.read(),null==this.gamma?null:this.gamma.read(),this.epsilon)})();const[h,p,d]=zv(s,this.gamma.read(),this.beta.read(),i,this.epsilon),f=(e,t,n)=>{Na((()=>{const s=1-n,r=e.read(),a=_i(Jl(r,t),s);e.write(Jl(r,a))}))};return(()=>{f(this.movingMean,p,this.momentum),f(this.movingVariance,d,this.momentum)})(),h}))}getConfig(){const e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:tb(this.betaInitializer),gammaInitializer:tb(this.gammaInitializer),movingMeanInitializer:tb(this.movingMeanInitializer),movingVarianceInitializer:tb(this.movingVarianceInitializer),betaRegularizer:Iw(this.betaRegularizer),gammaRegularizer:Iw(this.gammaRegularizer),betaConstraint:Ob(this.betaConstraint),gammaConstraint:Ob(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}}Pv.className="BatchNormalization",Xp(Pv);class Bv extends yb{constructor(e){if(null==e&&(e={}),super(e),this.axis=null==e.axis?-1:e.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 e of this.axis)if(!Number.isInteger(e))throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`)}this.epsilon=null==e.epsilon?.001:e.epsilon,this.center=null==e.center||e.center,this.scale=null==e.scale||e.scale,this.betaInitializer=nb(e.betaInitializer||"zeros"),this.gammaInitializer=nb(e.gammaInitializer||"ones"),this.betaRegularizer=Tw(e.betaRegularizer),this.gammaRegularizer=Tw(e.gammaRegularizer),this.supportsMasking=!0}build(e){const t=(e=ib(e)).length;"number"==typeof this.axis&&(this.axis=[this.axis]);for(let e=0;e<this.axis.length;++e)this.axis[e]<0&&(this.axis[e]+=t);for(const e of this.axis)if(e<0||e>=t)throw new Error(`Invalid axis: ${e}`);if(this.axis.length!==Wg(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);const n=this.axis.map((t=>e[t]));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,t){const n=ab(e),s=n.shape,r=s.length;return Na((()=>{let{mean:e,variance:t}=xu(n,this.axis,!0);const a=Eg(1,r);for(const e of this.axis)a[e]=s[e];const i=e=>null!=e&&e.shape.length!==r?oo(e,a):e;let o=this.scale?i(this.gamma.read()):null,l=this.center?i(this.beta.read()):null;const u=[],c=[];for(let e=0;e<r;++e)-1!==this.axis.indexOf(e)?(u.push(s[e]),c.push(1)):(u.push(1),c.push(s[e]));return e=El(e,u),t=El(t,u),null!=o&&(o=El(o,c)),null!=l&&(l=El(l,c)),Lv(n,e,t,l,o,this.epsilon)}))}getConfig(){const e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:tb(this.betaInitializer),gammaInitializer:tb(this.gammaInitializer),betaRegularizer:Iw(this.betaRegularizer),gammaRegularizer:Iw(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}}Bv.className="LayerNormalization",Xp(Bv);class Wv extends yb{constructor(e){if(null==e&&(e={}),super(e),this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,null==e.padding)this.padding=[[1,1],[1,1]];else if("number"==typeof e.padding)this.padding=[[e.padding,e.padding],[e.padding,e.padding]];else{if(e.padding=e.padding,2!==e.padding.length)throw new Sg(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${e.padding.length} array.`);let t,n;if("number"==typeof e.padding[0])t=[e.padding[0],e.padding[0]],n=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,2!==e.padding[0].length)throw new Sg(`ZeroPadding2D expects height padding to be a length-2 array, but received a length-${e.padding[0].length} array.`);if(t=e.padding[0],2!==e.padding[1].length)throw new Sg(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${e.padding[1].length} array.`);n=e.padding[1]}this.padding=[t,n]}this.inputSpec=[new pb({ndim:4})]}computeOutputShape(e){let t,n;return e=ib(e),"channelsFirst"===this.dataFormat?(t=null!=e[2]&&e[2]>=0?e[2]+this.padding[0][0]+this.padding[0][1]:null,n=null!=e[3]&&e[3]>=0?e[3]+this.padding[1][0]+this.padding[1][1]:null,[e[0],e[1],t,n]):(t=null!=e[1]&&e[1]>=0?e[1]+this.padding[0][0]+this.padding[0][1]:null,n=null!=e[2]&&e[2]>=0?e[2]+this.padding[1][0]+this.padding[1][1]:null,[e[0],t,n,e[3]])}call(e,t){return Na((()=>{return t=ab(e),n=this.padding,s=this.dataFormat,Na((()=>{if(4!==t.rank)throw new Sg(`temporalPadding expects input tensor to be 4-D, but received a ${t.rank}-D tensor.`);if(null==n&&(n=[[1,1],[1,1]]),2!==n.length||2!==n[0].length||2!==n[1].length)throw new Sg("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(null==s&&(s="channelsLast"),"channelsLast"!==s&&"channelsFirst"!==s)throw new Sg(`Unknown data format: ${s}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let e;return e="channelsFirst"===s?[[0,0],[0,0],n[0],n[1]]:[[0,0],n[0],n[1],[0,0]],Tu(t,e)}));var t,n,s}))}getConfig(){const e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}function Vv(e,t,n,s,r,a){return Na((()=>{let i;ry(r),iy(a),ay(s),null==n&&(n=[1,1]),null==s&&(s="valid"),null==r&&(r="channelsLast"),null==a&&(a="max"),e=Mw(e,r);const o="same"===s?"same":"valid";return i="max"===a?lu(e,t,n,o):lo(e,t,n,o),"channelsFirst"===r&&(i=vh(i,[0,3,1,2])),i}))}function Uv(e,t,n,s,r,a){return Na((()=>{let i;ry(r),iy(a),ay(s),null==n&&(n=[1,1,1]),null==s&&(s="valid"),null==r&&(r="channelsLast"),null==a&&(a="max"),e=Lw(e,r);const o="same"===s?"same":"valid";return i="max"===a?uu(e,t,n,o):uo(e,t,n,o),"channelsFirst"===r&&(i=vh(i,[0,4,1,2,3])),i}))}Wv.className="ZeroPadding2D",Xp(Wv);class Gv extends yb{constructor(e){if(null==e.poolSize&&(e.poolSize=2),super(e),"number"==typeof e.poolSize)this.poolSize=[e.poolSize];else{if(!Array.isArray(e.poolSize)||1!==e.poolSize.length||"number"!=typeof e.poolSize[0])throw new Sg(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);this.poolSize=e.poolSize}if(Hg(this.poolSize,"poolSize"),null==e.strides)this.strides=this.poolSize;else if("number"==typeof e.strides)this.strides=[e.strides];else{if(!Array.isArray(e.strides)||1!==e.strides.length||"number"!=typeof e.strides[0])throw new Sg(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);this.strides=e.strides}Hg(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,ay(this.padding),this.inputSpec=[new pb({ndim:3})]}computeOutputShape(e){const t=Dw((e=ib(e))[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return Na((()=>{this.invokeCallHook(e,t),e=wy(ab(e),2);const n=this.poolingFunction(ab(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return Xc(n,[2])}))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}}class Hv extends Gv{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return ry(r),ay(s),Vv(e,t,n,s,r,"max")}}Hv.className="MaxPooling1D",Xp(Hv);class jv extends Gv{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return ry(r),ay(s),Vv(e,t,n,s,r,"avg")}}jv.className="AveragePooling1D",Xp(jv);class qv extends yb{constructor(e){if(null==e.poolSize&&(e.poolSize=[2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],null==e.strides)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(2!==e.strides.length)throw new Sg(`If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides];Hg(this.poolSize,"poolSize"),Hg(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,ry(this.dataFormat),ay(this.padding),this.inputSpec=[new pb({ndim:4})]}computeOutputShape(e){e=ib(e);let t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2];return t=Dw(t,this.poolSize[0],this.padding,this.strides[0]),n=Dw(n,this.poolSize[1],this.padding,this.strides[1]),"channelsFirst"===this.dataFormat?[e[0],e[1],t,n]:[e[0],t,n,e[3]]}call(e,t){return Na((()=>(this.invokeCallHook(e,t),this.poolingFunction(ab(e),this.poolSize,this.strides,this.padding,this.dataFormat))))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class Kv extends qv{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return ry(r),ay(s),Vv(e,t,n,s,r,"max")}}Kv.className="MaxPooling2D",Xp(Kv);class Xv extends qv{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return ry(r),ay(s),Vv(e,t,n,s,r,"avg")}}Xv.className="AveragePooling2D",Xp(Xv);class Yv extends yb{constructor(e){if(null==e.poolSize&&(e.poolSize=[2,2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],null==e.strides)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(3!==e.strides.length)throw new Sg(`If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides,e.strides];Hg(this.poolSize,"poolSize"),Hg(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,ry(this.dataFormat),ay(this.padding),this.inputSpec=[new pb({ndim:5})]}computeOutputShape(e){e=ib(e);let t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2],s="channelsFirst"===this.dataFormat?e[4]:e[3];return t=Dw(t,this.poolSize[0],this.padding,this.strides[0]),n=Dw(n,this.poolSize[1],this.padding,this.strides[1]),s=Dw(s,this.poolSize[2],this.padding,this.strides[2]),"channelsFirst"===this.dataFormat?[e[0],e[1],t,n,s]:[e[0],t,n,s,e[4]]}call(e,t){return Na((()=>(this.invokeCallHook(e,t),this.poolingFunction(ab(e),this.poolSize,this.strides,this.padding,this.dataFormat))))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class Zv extends Yv{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return ry(r),ay(s),Uv(e,t,n,s,r,"max")}}Zv.className="MaxPooling3D",Xp(Zv);class Jv extends Yv{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return ry(r),ay(s),Uv(e,t,n,s,r,"avg")}}Jv.className="AveragePooling3D",Xp(Jv);class Qv extends yb{constructor(e){super(e),this.inputSpec=[new pb({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Tg}}class ek extends Qv{constructor(e){super(e||{})}call(e,t){return Na((()=>{const t=ab(e);return pu(t,1)}))}}ek.className="GlobalAveragePooling1D",Xp(ek);class tk extends Qv{constructor(e){super(e||{})}call(e,t){return Na((()=>{const t=ab(e);return gl(t,1)}))}}tk.className="GlobalMaxPooling1D",Xp(tk);class nk extends yb{constructor(e){super(e),this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,ry(this.dataFormat),this.inputSpec=[new pb({ndim:4})]}computeOutputShape(e){return"channelsLast"===this.dataFormat?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new Tg}getConfig(){const e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class sk extends nk{call(e,t){return Na((()=>{const t=ab(e);return"channelsLast"===this.dataFormat?pu(t,[1,2]):pu(t,[2,3])}))}}sk.className="GlobalAveragePooling2D",Xp(sk);class rk extends nk{call(e,t){return Na((()=>{const t=ab(e);return"channelsLast"===this.dataFormat?gl(t,[1,2]):gl(t,[2,3])}))}}rk.className="GlobalMaxPooling2D",Xp(rk);class ak extends yb{constructor(e){super(e),this.layer=e.layer}build(e){this.built=!0}get trainable(){return null!=this.layer&&this.layer.trainable}set trainable(e){null!=this.layer&&(this.layer.trainable=e)}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(e){this.layer.setWeights(e)}getConfig(){const e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},t=super.getConfig();return Object.assign(e,t),e}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),null!=this.layer&&this.layer.setFastWeightInitDuringBuild(e)}static fromConfig(e,t,n={}){const s=Zb(t.layer,n);delete t.layer;const r={layer:s};return Object.assign(r,t),new e(r)}}class ik extends ak{constructor(e){super(e),this.supportsMasking=!0}build(e){if((e=ib(e)).length<3)throw new Sg(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];const t=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(t),this.layer.built=!0),super.build(e)}computeOutputShape(e){const t=[(e=ib(e))[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),s=e[1];return[n[0],s].concat(n.slice(1))}call(e,t){return Na((()=>ev(((e,n)=>[ab(this.layer.call(e,t)),[]]),e=ab(e),[],!1,null,null,!1,!0)[1]))}}ik.className="TimeDistributed",Xp(ik);class ok extends ak{constructor(e){super(e);const t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=Zb(n),t.goBackwards=!0!==t.goBackwards;const s={};var r;if(s.className=e.layer.getClassName(),s.config=t,this.backwardLayer=Zb(s),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=void 0===e.mergeMode?"concat":e.mergeMode,r=this.mergeMode,Ug(ny,"BidirectionalMergeMode",r),e.weights)throw new Tg("weights support is not implemented for Bidirectional layer yet.");this._stateful=e.layer.stateful,this.returnSequences=e.layer.returnSequences,this.returnState=e.layer.returnState,this.supportsMasking=!0,this._trainable=!0,this.inputSpec=e.layer.inputSpec,this.numConstants=null}get trainable(){return this._trainable}set trainable(e){this._trainable=e,null!=this.forwardLayer&&(this.forwardLayer.trainable=e),null!=this.backwardLayer&&(this.backwardLayer.trainable=e)}getWeights(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())}setWeights(e){const t=e.length,n=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,n)),this.backwardLayer.setWeights(e.slice(n))}computeOutputShape(e){let t,n,s,r=this.forwardLayer.computeOutputShape(e);return Array.isArray(r)&&Array.isArray(r[0])||(r=[r]),this.returnState?(s=r.slice(1),t=r[0]):t=r[0],"concat"===this.mergeMode?(t[t.length-1]*=2,n=[t]):n=null==this.mergeMode?[t,t.slice()]:[t],this.returnState?null==this.mergeMode?n.concat(s).concat(s.slice()):[t].concat(s).concat(s.slice()):_g(n)}apply(e,t){let n=null==t?null:t.initialState,s=null==t?null:t.constants;null==t&&(t={});const r=Qw(e,n,s,this.numConstants);if(e=r.inputs,n=r.initialState,s=r.constants,Array.isArray(e)&&(n=e.slice(1),e=e[0]),(null==n||0===n.length)&&null==s)return super.apply(e,t);const a=[],i=[];if(null!=n){const e=n.length;if(e%2>0)throw new Sg("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=n,a.push(...n);const s=n.map((e=>new pb({shape:e.shape})));this.forwardLayer.stateSpec=s.slice(0,e/2),this.backwardLayer.stateSpec=s.slice(e/2),i.push(...s)}if(null!=s)throw new Tg("Support for constants in Bidirectional layers is not implemented yet.");const o=a[0]instanceof db;for(const e of a)if(e instanceof db!==o)throw new Sg("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(o){const n=[e].concat(a),s=this.inputSpec.concat(i),r=this.inputSpec;this.inputSpec=s;const o=super.apply(n,t);return this.inputSpec=r,o}return super.apply(e,t)}call(e,t){return Na((()=>{const n=t.initialState;let s,r,a,i;if(null==n)s=this.forwardLayer.call(e,t),r=this.backwardLayer.call(e,t);else{const a=n.slice(0,n.length/2),i=n.slice(n.length/2);s=this.forwardLayer.call(e,Object.assign(t,{initialState:a})),r=this.backwardLayer.call(e,Object.assign(t,{initialState:i}))}return this.returnState&&(Array.isArray(s)&&(a=s.slice(1).concat(r.slice(1))),s=s[0],r=r[0]),this.returnSequences&&(r=Sc(r,1)),"concat"===this.mergeMode?i=Iy([s,r]):"sum"===this.mergeMode?i=Ei(s,r):"ave"===this.mergeMode?i=_i(.5,Ei(s,r)):"mul"===this.mergeMode?i=_i(s,r):null==this.mergeMode&&(i=[s,r]),this.returnState?null==this.mergeMode?i.concat(a):[i].concat(a):i}))}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){ly(this.forwardLayer.name,(()=>{this.forwardLayer.build(e)})),ly(this.backwardLayer.name,(()=>{this.backwardLayer.build(e)})),this.built=!0}computeMask(e,t){let n;if(Array.isArray(t)&&(t=t[0]),n=this.returnSequences?null==this.mergeMode?[t,t]:t:null==this.mergeMode?[null,null]:null,this.returnState){const e=this.forwardLayer.states.map((e=>null));return Array.isArray(n)?n.concat(e).concat(e):[n].concat(e).concat(e)}return n}get trainableWeights(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)}get nonTrainableWeights(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),null!=this.forwardLayer&&this.forwardLayer.setFastWeightInitDuringBuild(e),null!=this.backwardLayer&&this.backwardLayer.setFastWeightInitDuringBuild(e)}getConfig(){const e={mergeMode:this.mergeMode},t=super.getConfig();return Object.assign(e,t),e}static fromConfig(e,t){const n=Zb(t.layer);if(delete t.layer,null!=t.numConstants)throw new Tg("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");const s=t;return s.layer=n,new e(s)}}ok.className="Bidirectional",Xp(ok);class lk extends yb{constructor(e){super(e),this.scale=e.scale,e.offset?this.offset=e.offset:this.offset=0}getConfig(){const e={scale:this.scale,offset:this.offset},t=super.getConfig();return Object.assign(e,t),e}call(e,t){return Na((()=>("float32"!==(e=ab(e)).dtype&&(e=xy(e,"float32")),Ei(_i(e,this.scale),this.offset))))}}lk.className="Rescaling",Xp(lk);const{resizeBilinear:uk,cropAndResize:ck}=Bp;class hk extends yb{constructor(e){super(e),this.height=e.height,this.width=e.width}centerCrop(e,t,n,s,r,a,i,o){return Na((()=>{let l,u=!1;const c=[t/a,n/i,(s+t)/a,(r+n)/i],h=[];3===e.rank?(u=!0,l=Yc([e])):l=e;for(let e=0;e<l.shape[0];e++)h.push(c);const p=ya(h,[h.length,4]),d=wc(0,h.length,1,"int32"),f=ck(l,p,d,[s,r],"nearest");return xy(u?ab(mh(f)):f,o)}))}upsize(e,t,n,s){return Na((()=>xy(uk(e,[t,n]),s)))}call(e,t){return Na((()=>{const t=ab(e),n=t.dtype,s=t.shape,r=s[s.length-3],a=s[s.length-2];let i=0;r!==this.height&&(i=Math.floor((r-this.height)/2));let o=0;return a!==this.width&&(o=Math.floor((a-this.width)/2),0===o&&(o=1)),i>=0&&o>=0?this.centerCrop(t,i,o,this.height,this.width,r,a,n):this.upsize(e,this.height,this.width,n)}))}getConfig(){const e={height:this.height,width:this.width},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){const t=(e=ib(e)).length-3,n=e.length-2;return e[t]=this.height,e[n]=this.width,e}}hk.className="CenterCrop",Xp(hk);class pk extends yb{constructor(e){super(e),this.numTokens=e.numTokens,e.outputMode?this.outputMode=e.outputMode:this.outputMode="multiHot"}getConfig(){const e={numTokens:this.numTokens,outputMode:this.outputMode},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){return null==(e=ib(e))?[this.numTokens]:"oneHot"===this.outputMode&&1!==e[e.length-1]?(e.push(this.numTokens),e):(e[e.length-1]=this.numTokens,e)}call(e,t){return Na((()=>{let n;if("int32"!==(e=ab(e)).dtype&&(e=xy(e,"int32")),void 0!==t.countWeights){if("count"!==this.outputMode)throw new Sg(`countWeights is not used when outputMode !== count.\n              Received countWeights=${t.countWeights}`);n=ab(t.countWeights)}const s=gl(e),r=yl(e),a=Fl(this.numTokens,s).bufferSync().get(0),i=Dl(r,0).bufferSync().get(0);if(!a||!i)throw new Sg(`Input values must be between 0 < values <= numTokens with numTokens=${this.numTokens}`);return function(e,t,n,s){let r=ab(e);if("int32"!==r.dtype&&(r=xy(r,"int32")),"int"===t)return r;const a=r.shape;if(0===r.rank&&(r=Cl(r,-1)),"oneHot"===t&&1!==r.shape[r.shape.length-1]&&(r=Cl(r,-1)),r.rank>2)throw new Sg(`When outputMode is not int, maximum output rank is 2 Received outputMode ${t} and input shape ${a} which would result in output rank ${r.rank}.`);const i=["multiHot","oneHot"].includes(t);let o;if(o=Go(r,void 0!==s&&"count"===t?s:[],n,i),"tfIdf"!==t)return o;if(s)return _i(o,s);throw new Sg("When outputMode is 'tfIdf', weights must be provided.")}(e,this.outputMode,this.numTokens,n)}))}}pk.className="CategoryEncoding",Xp(pk);const dk=new Set(["bilinear","nearest"]);class fk extends yb{constructor(e){if(super(e),this.height=e.height,this.width=e.width,e.interpolation){if(!dk.has(e.interpolation))throw new Sg(`Invalid interpolation parameter: ${e.interpolation} is not implemented`);this.interpolation=e.interpolation}else this.interpolation="bilinear";this.cropToAspectRatio=Boolean(e.cropToAspectRatio)}computeOutputShape(e){const t=(e=ib(e))[2];return[this.height,this.width,t]}getConfig(){const e={height:this.height,width:this.width,interpolation:this.interpolation,cropToAspectRatio:this.cropToAspectRatio},t=super.getConfig();return Object.assign(e,t),e}call(e,t){return Na((()=>{const t=[this.height,this.width];if("bilinear"===this.interpolation)return Bp.resizeBilinear(e,t,!this.cropToAspectRatio);if("nearest"===this.interpolation)return Bp.resizeNearestNeighbor(e,t,!this.cropToAspectRatio);throw new Error(`Interpolation is ${this.interpolation} but only ${[...dk]} are supported`)}))}}fk.className="Resizing",Xp(fk);class mk{constructor(e){this.seed=e}next(){if(void 0!==this.seed)return this.seed++}}mk.className="RandomSeed";class gk extends yb{constructor(e){super(e),this.randomGenerator=new mk(e.seed)}getConfig(){const e={seed:this.randomGenerator.seed},t=super.getConfig();return Object.assign(e,t),e}}gk.className="BaseRandomLayer";const yk=new Set(["bilinear","nearest"]);class bk extends gk{constructor(e){super(e);const{factor:t,interpolation:n="bilinear"}=e;if(this.factor=t,Array.isArray(this.factor)&&2===this.factor.length)this.widthLower=this.factor[0],this.widthUpper=this.factor[1];else{if(Array.isArray(this.factor)||!(this.factor>0))throw new Sg(`Invalid factor: ${this.factor}. Must be positive number or tuple of 2 numbers`);this.widthLower=-this.factor,this.widthUpper=this.factor}if(this.widthLower<-1||this.widthUpper<-1)throw new Sg(`factor must have values larger than -1. Got: ${this.factor}`);if(this.widthUpper<this.widthLower)throw new Sg(`factor cannot have upper bound less than lower bound.\n        Got upper bound: ${this.widthUpper}.\n        Got lower bound: ${this.widthLower}\n      `);if(n){if(!yk.has(n))throw new Sg(`Invalid interpolation parameter: ${n} is not implemented`);this.interpolation=n}}getConfig(){const e={factor:this.factor,interpolation:this.interpolation},t=super.getConfig();return Object.assign(e,t),e}computeOutputShape(e){const t=(e=ib(e))[2];return[this.imgHeight,-1,t]}call(e,t){return Na((()=>{const t=ab(e);this.imgHeight=t.shape[t.shape.length-3];const n=t.shape[t.shape.length-2];this.widthFactor=bc([1],1+this.widthLower,1+this.widthUpper,"float32",this.randomGenerator.next());let s=this.widthFactor.dataSync()[0]*n;s=Math.round(s);const r=[this.imgHeight,s];switch(this.interpolation){case"bilinear":return Bp.resizeBilinear(e,r);case"nearest":return Bp.resizeNearestNeighbor(e,r);default:throw new Error(`Interpolation is ${this.interpolation}\n          but only ${[...yk]} are supported`)}}))}}function xk(e){return new jv(e)}function wk(e){return new Xv(e)}function vk(e){return new Jv(e)}function kk(e){return new tk(e)}function Nk(e){return new rk(e)}function Ik(e){return new Hv(e)}function Sk(e){return new Kv(e)}bk.className="RandomWidth",Xp(bk);const Tk=kk,Ck=Nk,$k=Ik,Ek=Sk;var Ak=Object.freeze({__proto__:null,Layer:yb,RNN:tv,RNNCell:nv,activation:function(e){return new xv(e)},add:function(e){return new Tv(e)},alphaDropout:function(e){return new Mv(e)},average:function(e){return new $v(e)},averagePooling1d:xk,averagePooling2d:wk,averagePooling3d:vk,avgPool1d:function(e){return xk(e)},avgPool2d:function(e){return wk(e)},avgPool3d:function(e){return vk(e)},avgPooling1d:function(e){return xk(e)},avgPooling2d:function(e){return wk(e)},avgPooling3d:function(e){return vk(e)},batchNormalization:function(e){return new Pv(e)},bidirectional:function(e){return new ok(e)},categoryEncoding:function(e){return new pk(e)},centerCrop:function(e){return new hk(e)},concatenate:function(e){return new Rv(e)},conv1d:function(e){return new Xw(e)},conv2d:function(e){return new Uw(e)},conv2dTranspose:function(e){return new Hw(e)},conv3d:function(e){return new Gw(e)},conv3dTranspose:function(e){return new jw(e)},convLstm2d:function(e){return new fv(e)},convLstm2dCell:function(e){return new dv(e)},cropping2D:function(e){return new Yw(e)},dense:function(e){return new yv(e)},depthwiseConv2d:function(e){return new Jw(e)},dot:function(e){return new Fv(e)},dropout:function(e){return new mv(e)},elu:function(e){return new Aw(e)},embedding:function(e){return new Iv(e)},flatten:function(e){return new bv(e)},gaussianDropout:function(e){return new Ov(e)},gaussianNoise:function(e){return new Dv(e)},globalAveragePooling1d:function(e){return new ek(e)},globalAveragePooling2d:function(e){return new sk(e)},globalMaxPool1d:Tk,globalMaxPool2d:Ck,globalMaxPooling1d:kk,globalMaxPooling2d:Nk,gru:function(e){return new iv(e)},gruCell:function(e){return new av(e)},input:tw,inputLayer:function(e){return new xb(e)},layerNormalization:function(e){return new Bv(e)},leakyReLU:function(e){return new $w(e)},lstm:function(e){return new lv(e)},lstmCell:function(e){return new ov(e)},masking:function(e){return new Nv(e)},maxPool1d:$k,maxPool2d:Ek,maxPooling1d:Ik,maxPooling2d:Sk,maxPooling3d:function(e){return new Zv(e)},maximum:function(e){return new Ev(e)},minimum:function(e){return new Av(e)},multiply:function(e){return new Cv(e)},permute:function(e){return new kv(e)},prelu:function(e){return new Ew(e)},randomWidth:function(e){return new bk(e)},reLU:function(e){return new Cw(e)},repeatVector:function(e){return new wv(e)},rescaling:function(e){return new lk(e)},reshape:function(e){return new vv(e)},resizing:function(e){return new fk(e)},rnn:function(e){return new tv(e)},separableConv2d:function(e){return new Kw(e)},simpleRNN:function(e){return new rv(e)},simpleRNNCell:function(e){return new sv(e)},softmax:function(e){return new _w(e)},spatialDropout1d:function(e){return new gv(e)},stackedRNNCells:function(e){return new uv(e)},thresholdedReLU:function(e){return new Rw(e)},timeDistributed:function(e){return new ik(e)},upSampling2d:function(e){return new Zw(e)},zeroPadding2d:function(e){return new Wv(e)}});var Rk=Object.freeze({__proto__:null,MAPE:function(e,t){return tx(e,t)},MSE:function(e,t){return Qb(e,t)},binaryAccuracy:function(e,t){return cx(e,t)},binaryCrossentropy:function(e,t){return mx(e,t)},categoricalAccuracy:function(e,t){return hx(e,t)},categoricalCrossentropy:function(e,t){return yx(e,t)},cosineProximity:function(e,t){return ox(e,t)},mape:function(e,t){return tx(e,t)},meanAbsoluteError:function(e,t){return ex(e,t)},meanAbsolutePercentageError:function(e,t){return tx(e,t)},meanSquaredError:function(e,t){return Qb(e,t)},mse:function(e,t){return Qb(e,t)},precision:function(e,t){return dx(e,t)},recall:function(e,t){return fx(e,t)},sparseCategoricalAccuracy:function(e,t){return gx(e,t)}}),_k=Object.freeze({__proto__:null,modelFromJSON:async function(e,t){"modelTopology"in e||(e={modelTopology:e});let n=e.modelTopology;null!=n.model_config&&(n=n.model_config);const s=Zb(Ax(n),t);if(null!=e.weightsManifest){const t=await hd(e.weightsManifest,e.pathPrefix,s.weights.map((e=>e.originalName))),n={};for(const e of s.weights)n[e.originalName]=t[e.originalName];s.loadWeights(n),Ia(t)}return s}});var Fk=Object.freeze({__proto__:null,l1:function(e){return ww(t=e),new kw({l1:null!=t?t.l1:null,l2:0});var t},l1l2:function(e){return new kw(e)},l2:function(e){return ww(t=e),new kw({l2:null!=t?t.l2:null,l1:0});var t}});class Dk extends Ub{constructor(){super(...arguments),this.model=null}setModel(e){if(!(e instanceof Jx))throw new Error("model must be a LayersModel, not some other Container");this.model=e}}function Ok(e,t){return e<t}function Mk(e,t){return e>t}class Lk extends Dk{constructor(e){if(super(),null==e&&(e={}),e.restoreBestWeights)throw new Tg("restoreBestWeights = True is not implemented in EarlyStopping yet.");this.monitor=e.monitor||"val_loss",this.minDelta=Math.abs(e.minDelta||0),this.patience=e.patience||0,this.verbose=e.verbose||0,this.mode=e.mode||"auto",this.baseline=e.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=Ok:"max"===this.mode||-1!==this.monitor.indexOf("acc")?this.monitorFunc=Mk:this.monitorFunc=Ok,this.monitorFunc===Ok&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,null!=this.baseline?this.best=this.baseline:this.best=this.monitorFunc===Ok?1/0:-1/0}async onEpochEnd(e,t){await Wb(t);const n=this.getMonitorValue(t);null!=n&&(this.monitorFunc(n-this.minDelta,this.best)?(this.best=n,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=e,this.model.stopTraining=!0)))}async onTrainEnd(e){this.stoppedEpoch>0&&this.verbose&&console.log(`Epoch ${this.stoppedEpoch}: early stopping.`)}getMonitorValue(e){null==e&&(e={});const t=e[this.monitor];return null==t&&console.warn(`Metric for EarlyStopping ${this.monitor} is not available. Available metrics are: ${Object.keys(e)}`),t}}const zk={earlyStopping:function(e){return new Lk(e)}};var Pk,Bk;Y().registerFlag("KEEP_INTERMEDIATE_TENSORS",(()=>!1),(e=>{e&&console.warn("Keep intermediate tensors is ON. This will print the values of all intermediate tensors during model inference. Not all models support this mode. For details, check e2e/benchmarks/ model_config.js. This significantly impacts performance.")})),function(e){e[e.DT_INVALID=0]="DT_INVALID",e[e.DT_FLOAT=1]="DT_FLOAT",e[e.DT_DOUBLE=2]="DT_DOUBLE",e[e.DT_INT32=3]="DT_INT32",e[e.DT_UINT8=4]="DT_UINT8",e[e.DT_INT16=5]="DT_INT16",e[e.DT_INT8=6]="DT_INT8",e[e.DT_STRING=7]="DT_STRING",e[e.DT_COMPLEX64=8]="DT_COMPLEX64",e[e.DT_INT64=9]="DT_INT64",e[e.DT_BOOL=10]="DT_BOOL",e[e.DT_QINT8=11]="DT_QINT8",e[e.DT_QUINT8=12]="DT_QUINT8",e[e.DT_QINT32=13]="DT_QINT32",e[e.DT_BFLOAT16=14]="DT_BFLOAT16",e[e.DT_QINT16=15]="DT_QINT16",e[e.DT_QUINT16=16]="DT_QUINT16",e[e.DT_UINT16=17]="DT_UINT16",e[e.DT_COMPLEX128=18]="DT_COMPLEX128",e[e.DT_HALF=19]="DT_HALF",e[e.DT_RESOURCE=20]="DT_RESOURCE",e[e.DT_VARIANT=21]="DT_VARIANT",e[e.DT_UINT32=22]="DT_UINT32",e[e.DT_UINT64=23]="DT_UINT64",e[e.DT_FLOAT_REF=101]="DT_FLOAT_REF",e[e.DT_DOUBLE_REF=102]="DT_DOUBLE_REF",e[e.DT_INT32_REF=103]="DT_INT32_REF",e[e.DT_UINT8_REF=104]="DT_UINT8_REF",e[e.DT_INT16_REF=105]="DT_INT16_REF",e[e.DT_INT8_REF=106]="DT_INT8_REF",e[e.DT_STRING_REF=107]="DT_STRING_REF",e[e.DT_COMPLEX64_REF=108]="DT_COMPLEX64_REF",e[e.DT_INT64_REF=109]="DT_INT64_REF",e[e.DT_BOOL_REF=110]="DT_BOOL_REF",e[e.DT_QINT8_REF=111]="DT_QINT8_REF",e[e.DT_QUINT8_REF=112]="DT_QUINT8_REF",e[e.DT_QINT32_REF=113]="DT_QINT32_REF",e[e.DT_BFLOAT16_REF=114]="DT_BFLOAT16_REF",e[e.DT_QINT16_REF=115]="DT_QINT16_REF",e[e.DT_QUINT16_REF=116]="DT_QUINT16_REF",e[e.DT_UINT16_REF=117]="DT_UINT16_REF",e[e.DT_COMPLEX128_REF=118]="DT_COMPLEX128_REF",e[e.DT_HALF_REF=119]="DT_HALF_REF",e[e.DT_RESOURCE_REF=120]="DT_RESOURCE_REF",e[e.DT_VARIANT_REF=121]="DT_VARIANT_REF",e[e.DT_UINT32_REF=122]="DT_UINT32_REF",e[e.DT_UINT64_REF=123]="DT_UINT64_REF"}(Pk||(Pk={})),function(e){let t;!function(e){e[e.LEGACY=0]="LEGACY",e[e.V1=1]="V1",e[e.V2=2]="V2"}(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))}(Bk||(Bk={}));const Wk={};function Vk(e){return Wk[e]}function Uk(e,t,n,s,r){const a=t.inputParams[e];if(a&&void 0!==a.inputIndexStart){const e=a.inputIndexStart,i=0===a.inputIndexEnd?void 0:void 0===a.inputIndexEnd?e+1:a.inputIndexEnd,o=e<0?t.inputNames.length+e:e;if("tensor"===a.type)return Gk(t.inputNames[o],n,s,r);if("tensors"===a.type){const a=t.inputs.slice(e,i),o=t.inputNames.slice(e,i).filter(((e,t)=>{var n;return"NoOp"!==(null===(n=a[t])||void 0===n?void 0:n.op)}));return o.map((e=>Gk(e,n,s,r)))}const l=Gk(t.inputNames[o],n,s,r),u=l.dataSync();return"number"===a.type?u[0]:z(l.shape,u)}const i=t.attrParams[e];return i&&i.value}function Gk(e,t,n,s){const[r,a]=Kk(e,n);if(null!=s){const e=s.getHashTableHandleByName(r);if(null!=e)return e}const i=n.currentContextIds.find((e=>!!t[qk(r,e)]));return void 0!==i?t[qk(r,i)][a]:void 0}function Hk(e,t,n){return t[qk(e,n.currentContextId)]}function jk(e,t){const[n,s,r]=Kk(e,t);return[qk(n,t&&t.currentContextId),s,r]}function qk(e,t){return t?`${e}-${t}`:e}function Kk(e,t){if(""===e)return["",0,void 0];const n=null!=t&&null!=t.parseNodeNameCache;if(n){const n=t.parseNodeNameCache.get(e);if(null!=n)return n}const s=e.split(":");let r;if(1===s.length)r=[e,0,void 0];else{const e=s[0],t=3===s.length?s[1]:void 0;r=[e,Number(s[s.length-1]),t]}return n&&t.parseNodeNameCache.set(e,r),r}function Xk(e,t,n){let s=Uk("pad",e,t,n);if("explicit"===s){s=Uk("explicitPaddings",e,t,n);const r=[[0,0],[0,0],[0,0],[0,0]];for(let e=0;e<4;e++)r[e][0]=s[2*e],r[e][1]=s[2*e+1];return r}return s}function Yk(e){return e.kept?e:Ci(e)}var Zk=Object.freeze({__proto__:null,json:[{tfOpName:"Add",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddV2",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddN",category:"arithmetic",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"BiasAdd",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"Sub",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"RealDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Div",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"DivNoNan",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mul",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Maximum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Minimum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Pow",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorMod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]});var Jk=Object.freeze({__proto__:null,json:[{tfOpName:"Abs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan2",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ceil",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ClipByValue",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"clipValueMin",type:"number"},{start:2,name:"clipValueMax",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Complex",category:"basic_math",inputs:[{start:0,name:"real",type:"tensor"},{start:1,name:"imag",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ComplexAbs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Elu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Exp",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Floor",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Imag",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Neg",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Real",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Prelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"alpha",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu6",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Selu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sigmoid",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Rsqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Square",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sign",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Round",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Expm1",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log1p",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Softplus",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Erf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LeakyRelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"alpha",name:"alpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsNan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsFinite",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsInf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]});var Qk=Object.freeze({__proto__:null,json:[{tfOpName:"EmptyTensorList",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"maxNumElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"LoopCond",category:"control",inputs:[{start:0,name:"pred",type:"tensor"}]},{tfOpName:"Switch",category:"control",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"pred",type:"tensor"}]},{tfOpName:"Merge",category:"control",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"Enter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"frame_name",name:"frameName",type:"string"},{tfName:"is_constant",name:"isConstant",type:"bool"}]},{tfOpName:"Exit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NextIteration",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayV3",category:"control",inputs:[{start:0,name:"size",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"dynamic_size",name:"dynamicSize",type:"bool"},{tfName:"clear_after_read",name:"clearAfterRead",type:"bool"},{tfName:"identical_element_shapes",name:"identicalElementShapes",type:"bool"},{tfName:"tensor_array_name",name:"name",type:"string"}]},{tfOpName:"TensorArrayWriteV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayReadV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayGatherV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"}]},{tfOpName:"TensorArrayScatterV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArrayConcatV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape_except0",name:"elementShapeExcept0",type:"shape",notSupported:!0}]},{tfOpName:"TensorArraySplitV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"tensor",type:"tensor"},{start:2,name:"lengths",type:"number[]"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArraySizeV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}]},{tfOpName:"TensorArrayCloseV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"}]},{tfOpName:"StatelessIf",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"If",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"StatelessWhile",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"While",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"TensorListScatter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListScatterV2",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"},{start:3,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGather",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListSetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListReserve",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListFromTensor",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListStack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"},{tfName:"num_elements",name:"numElements",type:"dtype"}]},{tfOpName:"TensorListSplit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"},{start:2,name:"lengths",type:"number[]"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcat",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcatV2",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPopBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPushBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListLength",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}]},{tfOpName:"TensorListResize",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"size",type:"number"}]}]});var eN=Object.freeze({__proto__:null,json:[{tfOpName:"AvgPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[],notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPoolWithArgmax",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"include_batch_in_index",name:"includeBatchInIndex",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AvgPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Conv1D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"stride",name:"stride",type:"number"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NWC"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"dilation",name:"dilation",type:"number",defaultValue:1}]},{tfOpName:"Conv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"useCudnnOnGpu",name:"useCudnnOnGpu",type:"bool"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"_FusedConv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"use_cudnn_on_gpu",name:"useCudnnOnGpu",type:"bool",defaultValue:!0},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number",defaultValue:.2}]},{tfOpName:"Conv2DBackpropInput",category:"convolution",inputs:[{start:2,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:0,name:"outputShape",type:"number[]"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]",notSupported:!0}]},{tfOpName:"DepthwiseConv2d",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"DepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"FusedDepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]}]},{tfOpName:"Conv3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"Dilation2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"rates",name:"dilations",type:"number[]"},{tfName:"padding",name:"pad",type:"string"}]}]});var tN=Object.freeze({__proto__:null,json:[{tfOpName:"Fill",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"},{start:1,name:"value",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"LinSpace",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"num",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"OneHot",category:"creation",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"depth",type:"number"},{start:2,name:"onValue",type:"number",defaultValue:1},{start:3,name:"offValue",type:"number",defaultValue:0}],attrs:[{tfName:"axis",name:"axis",type:"number",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Ones",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"OnesLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"RandomStandardNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"RandomUniform",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number",defaultValue:0},{tfName:"maxval",name:"maxval",type:"number",defaultValue:1},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"RandomUniformInt",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number"},{tfName:"maxval",name:"maxval",type:"number"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Range",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"step",type:"number",defaultValue:0}],attrs:[{tfName:"Tidx",name:"dtype",type:"dtype"}]},{tfOpName:"TruncatedNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"means",name:"mean",type:"number",defaultValue:0},{tfName:"stddev",name:"stdDev",type:"number",defaultValue:1},{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Zeros",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"ZerosLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Multinomial",category:"creation",inputs:[{start:0,name:"logits",type:"tensor"},{start:1,name:"numSamples",type:"number"}],attrs:[{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number"},{tfName:"T",name:"dtype",type:"dtype"},{tfName:"output_dtype",name:"output_dtype",type:"dtype"}]}]});var nN=Object.freeze({__proto__:null,json:[{tfOpName:"NonMaxSuppressionV2",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV3",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}]},{tfOpName:"NonMaxSuppressionV4",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"T_threshold",name:"threshold",type:"dtype",notSupported:!0},{tfName:"pad_to_max_output_size",name:"padToMaxOutputSize",type:"bool"}]},{tfOpName:"NonMaxSuppressionV5",category:"dynamic",inputs:[{start:0,name:"boxes",type:"tensor"},{start:1,name:"scores",type:"tensor"},{start:2,name:"maxOutputSize",type:"number"},{start:3,name:"iouThreshold",type:"number"},{start:4,name:"scoreThreshold",type:"number"},{start:5,name:"softNmsSigma",type:"number"}]},{tfOpName:"Where",category:"dynamic",inputs:[{start:0,name:"condition",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ListDiff",category:"dynamic",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]});var sN=Object.freeze({__proto__:null,json:[{tfOpName:"LowerBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]},{tfOpName:"UpperBound",category:"evaluation",inputs:[{start:0,name:"sortedSequence",type:"tensor"},{start:1,name:"values",type:"tensor"}]},{tfOpName:"Unique",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"UniqueV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]}]});var rN=Object.freeze({__proto__:null,json:[{tfOpName:"PlaceholderWithDefault",category:"graph",inputs:[{start:0,name:"default",type:"tensor"}],attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Placeholder",category:"graph",attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Const",category:"graph"},{tfOpName:"Identity",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IdentityN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Snapshot",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Rank",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Size",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Shape",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"ShapeN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Print",category:"graph",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"data",type:"tensors"}],attrs:[{tfName:"message",name:"message",type:"string"},{tfName:"first_n",name:"firstN",type:"number",notSupported:!0},{tfName:"summarize",name:"summarize",type:"number",defaultValue:3}]},{tfOpName:"NoOp",category:"graph",inputs:[]},{tfOpName:"StopGradient",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"FakeQuantWithMinMaxVars",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"min",name:"min",type:"number"},{tfName:"max",name:"max",type:"number"}]}]});var aN=Object.freeze({__proto__:null,json:[{tfOpName:"HashTable",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"HashTableV2",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"LookupTableImport",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableImportV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFind",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFindV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableSize",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"LookupTableSizeV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"InitializeTable",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}]},{tfOpName:"InitializeTableV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}]}]});var iN=Object.freeze({__proto__:null,json:[{tfOpName:"ResizeBilinear",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ResizeNearestNeighbor",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"CropAndResize",category:"image",inputs:[{start:0,name:"image",type:"tensor"},{start:1,name:"boxes",type:"tensor"},{start:2,name:"boxInd",type:"tensor"},{start:3,name:"cropSize",type:"number[]"}],attrs:[{tfName:"method",name:"method",type:"string"},{tfName:"extrapolation_value",name:"extrapolationValue",type:"number"}]},{tfOpName:"ImageProjectiveTransformV3",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"transforms",type:"tensor"},{start:2,name:"outputShape",type:"number[]"},{start:3,name:"fillValue",type:"number"}],attrs:[{tfName:"interpolation",name:"interpolation",type:"string"},{tfName:"fill_mode",name:"fillMode",type:"string"}]}]});var oN=Object.freeze({__proto__:null,json:[{tfOpName:"Equal",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NotEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Greater",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"GreaterEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Less",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LessEqual",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalAnd",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalNot",category:"logical",inputs:[{start:0,name:"a",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LogicalOr",category:"logical",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Select",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SelectV2",category:"logical",inputs:[{start:0,name:"condition",type:"tensor"},{start:1,name:"a",type:"tensor"},{start:2,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BitwiseAnd",category:"logical",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}]}]});var lN=Object.freeze({__proto__:null,json:[{tfOpName:"_FusedMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMulV2",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Einsum",category:"matrices",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"equation",name:"equation",type:"string"},{tfName:"N",name:"n",type:"number",defaultValue:2},{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"MatrixBandPart",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"numLower",type:"tensor"},{start:1,name:"numUpper",type:"tensor"}]}]});var uN=Object.freeze({__proto__:null,json:[{tfOpName:"EuclideanNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",defaultValue:!1}]},{tfOpName:"FusedBatchNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV2",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV3",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"LRN",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"depth_radius",name:"radius",type:"number",defaultValue:5},{tfName:"bias",name:"bias",type:"number",defaultValue:1},{tfName:"alpha",name:"alpha",type:"number",defaultValue:1},{tfName:"beta",name:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"LogSoftmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]}]});var cN=Object.freeze({__proto__:null,json:[{tfOpName:"Bincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}]},{tfOpName:"DenseBincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}],attrs:[{tfName:"binary_output",name:"binaryOutput",type:"bool"}]},{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cumprod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]},{tfOpName:"Cumsum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]}]});var hN=Object.freeze({__proto__:null,json:[{tfOpName:"ConcatV2",category:"slice_join",inputs:[{start:0,end:-1,name:"tensors",type:"tensors"},{start:-1,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"Concat",category:"slice_join",inputs:[{start:1,end:0,name:"tensors",type:"tensors"},{start:0,name:"axis",type:"number"}],attrs:[{tfName:"N",name:"n",type:"number",defaultValue:2}]},{tfOpName:"GatherV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"axis",type:"number",defaultValue:0}],attrs:[{tfName:"batch_dims",name:"batchDims",type:"number",defaultValue:0}]},{tfOpName:"Gather",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",notSupported:!0}]},{tfOpName:"Reverse",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"dims",type:"bool[]"}]},{tfOpName:"ReverseV2",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}]},{tfOpName:"Slice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"size",type:"number[]"}]},{tfOpName:"StridedSlice",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"begin",type:"number[]"},{start:2,name:"end",type:"number[]"},{start:3,name:"strides",type:"number[]"}],attrs:[{tfName:"begin_mask",name:"beginMask",type:"number",defaultValue:0},{tfName:"end_mask",name:"endMask",type:"number",defaultValue:0},{tfName:"new_axis_mask",name:"newAxisMask",type:"number",defaultValue:0},{tfName:"ellipsis_mask",name:"ellipsisMask",type:"number",defaultValue:0},{tfName:"shrink_axis_mask",name:"shrinkAxisMask",type:"number",defaultValue:0}]},{tfOpName:"Pack",category:"slice_join",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0}]},{tfOpName:"Unpack",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"axis",name:"axis",type:"number",defaultValue:0},{tfName:"num",name:"num",type:"number",defaultValue:0,notSupported:!0}]},{tfOpName:"Tile",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"reps",type:"number[]"}]},{tfOpName:"Split",category:"slice_join",inputs:[{start:0,name:"axis",type:"number",defaultValue:0},{start:1,name:"x",type:"tensor"}],attrs:[{tfName:"num_split",name:"numOrSizeSplits",type:"number",defaultValue:1}]},{tfOpName:"SplitV",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"numOrSizeSplits",type:"number[]"},{start:2,name:"axis",type:"number",defaultValue:0}]},{tfOpName:"ScatterNd",category:"slice_join",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"shape",type:"number[]"}]},{tfOpName:"GatherNd",category:"slice_join",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"indices",type:"tensor"}]},{tfOpName:"SparseToDense",category:"slice_join",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!1,notSupported:!0}]},{tfOpName:"TensorScatterUpdate",category:"slice_join",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"values",type:"tensor"}]}]});var pN=Object.freeze({__proto__:null,json:[{tfOpName:"SparseFillEmptyRows",category:"sparse",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"denseShape",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}]},{tfOpName:"SparseReshape",category:"sparse",inputs:[{start:0,name:"inputIndices",type:"tensor"},{start:1,name:"inputShape",type:"tensor"},{start:2,name:"newShape",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SparseSegmentMean",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]},{tfOpName:"SparseSegmentSum",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]}]});var dN=Object.freeze({__proto__:null,json:[{tfOpName:"FFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"RFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]},{tfOpName:"IRFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]}]});var fN=Object.freeze({__proto__:null,json:[{tfOpName:"StaticRegexReplace",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"pattern",name:"pattern",type:"string"},{tfName:"rewrite",name:"rewrite",type:"string"},{tfName:"replace_global",name:"replaceGlobal",type:"bool"}]},{tfOpName:"StringNGrams",category:"string",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"dataSplits",type:"tensor"}],attrs:[{tfName:"separator",name:"separator",type:"string"},{tfName:"ngram_widths",name:"nGramWidths",type:"number[]"},{tfName:"left_pad",name:"leftPad",type:"string"},{tfName:"right_pad",name:"rightPad",type:"string"},{tfName:"pad_width",name:"padWidth",type:"number"},{tfName:"preserve_short_sequences",name:"preserveShortSequences",type:"bool"}],outputs:["ngrams","ngrams_splits"]},{tfOpName:"StringSplit",category:"string",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"delimiter",type:"tensor"}],attrs:[{tfName:"skip_empty",name:"skipEmpty",type:"bool"}],outputs:["indices","values","shape"]},{tfOpName:"StringToHashBucketFast",category:"string",inputs:[{start:0,name:"input",type:"tensor"}],attrs:[{tfName:"num_buckets",name:"numBuckets",type:"number"}]}]});var mN=Object.freeze({__proto__:null,json:[{tfOpName:"Cast",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"SrcT",name:"sdtype",type:"dtype",notSupported:!0},{tfName:"DstT",name:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"MirrorPad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"mode",name:"mode",type:"string"}]},{tfOpName:"Pad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"constant_value",name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"},{start:2,name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"EnsureShape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"Squeeze",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"axis",tfDeprecatedName:"squeeze_dims",name:"axis",type:"number[]"}]},{tfOpName:"SpaceToBatchND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"paddings",type:"number[]"}]},{tfOpName:"BatchToSpaceND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"crops",type:"number[]"}]},{tfOpName:"DepthToSpace",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"block_size",name:"blockSize",type:"number"},{tfName:"data_format",name:"dataFormat",type:"string"}]},{tfOpName:"BroadcastTo",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}],attrs:[]},{tfOpName:"BroadcastArgs",category:"transformation",inputs:[{start:0,name:"s0",type:"tensor"},{start:1,name:"s1",type:"tensor"}],attrs:[]}]});class gN{static get Instance(){return this._instance||(this._instance=new this)}constructor(){const e=[].concat(...[Zk,Jk,Qk,eN,tN,nN,sN,rN,aN,iN,oN,lN,uN,cN,hN,pN,dN,fN,mN].map((e=>e.json)));this.opMappers=e.reduce(((e,t)=>(e[t.tfOpName]=t,e)),{})}transformGraph(e,t={}){const n=e.node,s=[],r=[],a=[],i=n.reduce(((e,t)=>(e[t.name]=this.mapNode(t),t.op.startsWith("Placeholder")?s.push(e[t.name]):"Const"===t.op?r.push(e[t.name]):null!=t.input&&0!==t.input.length||a.push(e[t.name]),e)),{});let o=[];const l=[];let u={},c={};null!=t&&(u=this.mapSignatureEntries(t.inputs),c=this.mapSignatureEntries(t.outputs));const h=Object.keys(i);h.forEach((e=>{const t=i[e];t.inputNames.forEach(((e,n)=>{const[s,,r]=jk(e),a=i[s];if(null!=a.outputs){const e=a.outputs.indexOf(r);if(-1!==e){const r=`${s}:${e}`;t.inputNames[n]=r}}t.inputs.push(a),a.children.push(t)}))})),0===Object.keys(c).length?h.forEach((e=>{const t=i[e];0===t.children.length&&l.push(t)})):Object.keys(c).forEach((e=>{const[t]=jk(e),n=i[t];null!=n&&(n.signatureKey=c[e],l.push(n))})),Object.keys(u).length>0?Object.keys(u).forEach((e=>{const[t]=jk(e),n=i[t];n&&(n.signatureKey=u[e],o.push(n))})):o=s;let p={};null!=e.library&&null!=e.library.function&&(p=e.library.function.reduce(((e,t)=>(e[t.signature.name]=this.mapFunction(t),e)),{}));const d={nodes:i,inputs:o,outputs:l,weights:r,placeholders:s,signature:t,functions:p};return a.length>0&&(d.initNodes=a),d}mapSignatureEntries(e){return Object.keys(e||{}).reduce(((t,n)=>(t[e[n].name]=n,t)),{})}mapNode(e){const t=Vk(e.op)||this.opMappers[e.op]||{};null==e.attr&&(e.attr={});const n={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map((e=>e.startsWith("^")?e.slice(1):e)),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr,outputs:t.outputs};return null!=t.inputs&&(n.inputParams=t.inputs.reduce(((e,t)=>(e[t.name]={type:t.type,inputIndexStart:t.start,inputIndexEnd:t.end},e)),{})),null!=t.attrs&&(n.attrParams=t.attrs.reduce(((t,n)=>{const s=n.type;let r;switch(n.type){case"string":r=bN(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=bN(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"string[]":r=$N(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=$N(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number":r=wN(e.attr,n.tfName,n.defaultValue||0),void 0===r&&n.tfDeprecatedName&&(r=wN(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number[]":r=CN(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=CN(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool":r=xN(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=xN(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool[]":r=AN(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=AN(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape":r=TN(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=TN(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape[]":r=EN(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=EN(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype":r=NN(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=NN(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype[]":r=IN(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=IN(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"func":r=kN(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=kN(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${n.type} for op: ${e.op}`)}return t[n.name]={value:r,type:s},t}),{})),n}mapFunction(e){const t=e.nodeDef,n=[];let s={};null!=t&&(s=t.reduce(((e,t)=>(e[t.name]=this.mapNode(t),"Const"===t.op&&n.push(e[t.name]),e)),{}));const r=[],a=[];e.signature.inputArg.forEach((e=>{const[t]=jk(e.name),n={name:t,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:vN(e.type),type:"dtype"}},children:[]};n.signatureKey=e.name,r.push(n),s[t]=n}));Object.keys(s).forEach((e=>{const t=s[e];t.inputNames.forEach(((e,n)=>{const[r,,a]=jk(e),i=s[r];if(null!=i.outputs){const e=i.outputs.indexOf(a);if(-1!==e){const s=`${r}:${e}`;t.inputNames[n]=s}}t.inputs.push(i),i.children.push(t)}))}));const i=e.ret;e.signature.outputArg.forEach((e=>{const[t,n]=jk(i[e.name]),r=s[t];null!=r&&(r.defaultOutput=n,a.push(r))}));const o=this.mapArgsToSignature(e);return{nodes:s,inputs:r,outputs:a,weights:n,placeholders:[],signature:o}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce(((e,t)=>(e[t.name]=this.mapArgToTensorInfo(t),e)),{}),outputs:e.signature.outputArg.reduce(((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n,e.ret),t)),{})}}mapArgToTensorInfo(e,t){let n=e.name;return null!=t&&(n=t[n]),{name:n,dtype:e.type}}}function yN(e,t){const n=Array.isArray(e)?String.fromCharCode.apply(null,e):function(e){const t=Y().global;if(void 0!==t.atob)return t.atob(e);if("undefined"!=typeof Buffer)return new Buffer(e,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}(e);return t?n:n.toLowerCase()}function bN(e,t,n,s=!1){const r=e[t];return null!=r?yN(r.s,s):n}function xN(e,t,n){const s=e[t];return s?s.b:n}function wN(e,t,n){const s=e[t]||{},r=null!=s.i?s.i:null!=s.f?s.f:n;return"number"==typeof r?r:parseInt(r,10)}function vN(e){switch("string"==typeof e&&(e=Pk[e]),e){case Pk.DT_FLOAT:case Pk.DT_HALF:return"float32";case Pk.DT_INT32:case Pk.DT_INT64:case Pk.DT_INT8:case Pk.DT_UINT8:return"int32";case Pk.DT_BOOL:return"bool";case Pk.DT_DOUBLE:return"float32";case Pk.DT_STRING:return"string";default:return null}}function kN(e,t,n){const s=e[t];return s&&s.func?s.func.name:n}function NN(e,t,n){const s=e[t];return s&&s.type?vN(s.type):n}function IN(e,t,n){const s=e[t];return s&&s.list&&s.list.type?s.list.type.map((e=>vN(e))):n}function SN(e){if(!e.unknownRank)return null!=e.dim?e.dim.map((e=>"number"==typeof e.size?e.size:parseInt(e.size,10))):[]}function TN(e,t,n){const s=e[t];return s&&s.shape?SN(s.shape):n}function CN(e,t,n){const s=e[t];return s?((s.list.f&&s.list.f.length?s.list.f:s.list.i)||[]).map((e=>"number"==typeof e?e:parseInt(e,10))):n}function $N(e,t,n,s=!1){const r=e[t];return r&&r.list&&r.list.s?r.list.s.map((e=>yN(e,s))):n}function EN(e,t,n){const s=e[t];return s&&s.list&&s.list.shape?s.list.shape.map((e=>SN(e))):n}function AN(e,t,n){const s=e[t];return s&&s.list&&s.list.b?s.list.b:n}class RN{constructor(e,t,n){this.node=e,this.tensorMap=t,this.context=n,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map((e=>this.getInput(e))),null!=e.rawAttrs&&(this.attrs=Object.keys(e.rawAttrs).reduce(((e,t)=>(e[t]=this.getAttr(t),e)),{}))}getInput(e){return Gk(e,this.tensorMap,this.context)}getAttr(e,t){const n=this.node.rawAttrs[e];if(null!=n.tensor)return Gk(e,this.tensorMap,this.context);if(null!=n.i||null!=n.f)return wN(this.node.rawAttrs,e,t);if(null!=n.s)return bN(this.node.rawAttrs,e,t);if(null!=n.b)return xN(this.node.rawAttrs,e,t);if(null!=n.shape)return TN(this.node.rawAttrs,e,t);if(null!=n.type)return NN(this.node.rawAttrs,e,t);if(null!=n.list){if(null!=n.list.i||null!=n.list.f)return CN(this.node.rawAttrs,e,t);if(null!=n.list.s)return $N(this.node.rawAttrs,e,t);if(null!=n.list.shape)return EN(this.node.rawAttrs,e,t);if(null!=n.list.b)return AN(this.node.rawAttrs,e,t);if(null!=n.list.type)return IN(this.node.rawAttrs,e,t)}return t}}var _N=Object.freeze({__proto__:null,OP_SCOPE_SUFFIX:da,abs:Fi,acos:Di,acosh:Oi,add:Ei,addN:Mi,all:Li,any:zi,argMax:Pi,argMin:Bi,asin:Wi,asinh:Vi,atan:Ui,atan2:Gi,atanh:Hi,avgPool:lo,avgPool3d:uo,basicLSTMCell:go,batchNorm:bo,batchNorm2d:xo,batchNorm3d:wo,batchNorm4d:vo,batchToSpaceND:yo,bincount:ko,bitwiseAnd:No,booleanMaskAsync:wh,broadcastArgs:Io,broadcastTo:So,buffer:Si,cast:Ti,ceil:To,clipByValue:$o,clone:Ci,complex:ma,concat:co,concat1d:Eo,concat2d:Ao,concat3d:Ro,concat4d:_o,conv1d:Do,conv2d:Fo,conv2dTranspose:Mo,conv3d:Lo,conv3dTranspose:Po,cos:Bo,cosh:Wo,cosineWindow:$h,cumprod:Vo,cumsum:Uo,denseBincount:Go,depthToSpace:Ho,depthwiseConv2d:jo,diag:qo,dilation2d:Ko,div:Ri,divNoNan:nl,dot:sl,dropout:Th,einsum:rl,elu:al,enclosingPowerOfTwo:Ch,ensureShape:il,equal:Qo,erf:ol,euclideanNorm:Sl,exp:Tl,expandDims:Cl,expm1:$l,eye:Al,fft:Uc,fill:Co,floor:Rl,floorDiv:Ai,fused:Bh,gather:_l,gatherND:Sh,greater:Fl,greaterEqual:Dl,ifft:Gc,imag:Ol,image:Bp,inTopKAsync:Eh,irfft:Hc,isFinite:Ml,isInf:Ll,isNaN:zl,leakyRelu:Pl,less:Bl,lessEqual:Wl,linalg:Wp,linspace:Vl,localResponseNormalization:Ul,log:Gl,log1p:Hl,logSigmoid:Zl,logSoftmax:Ql,logSumExp:eu,logicalAnd:tu,logicalNot:nu,logicalOr:su,logicalXor:ru,losses:Vp,lowerBound:ou,matMul:ho,max:gl,maxPool:lu,maxPool3d:uu,maxPoolWithArgmax:cu,maximum:hu,mean:pu,meshgrid:mu,min:yl,minimum:gu,mirrorPad:yu,mod:bu,moments:xu,movingAverage:kh,mul:_i,multiRNNCell:wu,multinomial:vu,neg:Xl,norm:Il,notEqual:ku,oneHot:Nu,ones:fu,onesLike:Iu,op:fa,outerProduct:Su,pad:Tu,pad1d:Cu,pad2d:$u,pad3d:Eu,pad4d:Au,pool:_u,pow:bl,prelu:Fu,print:$i,prod:Du,raggedGather:Ou,raggedRange:Mu,raggedTensorToTensor:Lu,rand:zu,randomGamma:mc,randomNormal:gc,randomStandardNormal:yc,randomUniform:bc,randomUniformInt:xc,range:wc,real:vc,reciprocal:kc,relu:Nc,relu6:Ic,reshape:oo,reverse:Sc,reverse1d:Tc,reverse2d:Cc,reverse3d:$c,reverse4d:Ec,rfft:qc,round:Ac,rsqrt:Rc,scalar:xl,scatterND:Nh,searchSorted:iu,selu:_c,separableConv2d:Fc,setdiff1dAsync:Dc,sigmoid:po,sign:Oc,signal:Pp,sin:Mc,sinh:Lc,slice:fo,slice1d:zc,slice2d:Pc,slice3d:Bc,slice4d:Wc,softmax:Vc,softplus:Yl,spaceToBatchND:Ru,sparse:Up,sparseToDense:Ih,spectral:zp,split:jc,sqrt:wl,square:vl,squaredDifference:Kc,squeeze:Xc,stack:Yc,step:Zc,stridedSlice:Jc,string:Gp,sub:Jl,sum:kl,tan:Qc,tanh:mo,tensor:ya,tensor1d:eh,tensor2d:th,tensor3d:nh,tensor4d:sh,tensor5d:rh,tensor6d:ah,tensorScatterUpdate:ch,tile:El,topk:hh,transpose:vh,truncatedNormal:ph,unique:dh,unsortedSegmentSum:fh,unstack:mh,upperBound:gh,variable:yh,where:el,whereAsync:xh,zeros:du,zerosLike:tl});function FN(e,t,n=""){if("number"!=typeof e&&"number"!=typeof t){c(e.length===t.length,(()=>n+` Shapes ${e} and ${t} must match`));for(let s=0;s<e.length;s++){const r=e[s],a=t[s];c(r<0||a<0||r===a,(()=>n+` Shapes ${e} and ${t} must match`))}}}function DN(e){return"number"!=typeof e&&!e.some((e=>e<0))}function ON(e,t,n){let s=MN(e,n);const r=!DN(s);if(r&&0===t.length)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${s}`);if(r&&t.forEach((e=>{s=MN(e.shape,s)})),!DN(s))throw new Error(`Non-fully-defined elementShape: ${s}`);return s}function MN(e,t){if("number"==typeof e)return t;if("number"==typeof t)return e;if(e.length!==t.length)throw new Error(`Incompatible ranks during merge: ${e} vs. ${t}`);const n=[];for(let s=0;s<e.length;++s){const r=e[s],a=t[s];if(r>=0&&a>=0&&r!==a)throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);n[s]=r>=0?r:a}return n}class LN{constructor(e,t,n,s,r,a,i){this.name=e,this.dtype=t,this.maxSize=n,this.elementShape=s,this.identicalElementShapes=r,this.dynamicSize=a,this.clearAfterRead=i,this.tensors=[],this.closed_=!1,this.idTensor=xl(0),Sa(this.idTensor)}get id(){return this.idTensor.id}get closed(){return this.closed_}clearAndClose(e){this.tensors.forEach((t=>{null!=e&&e.has(t.tensor.id)||t.tensor.dispose()})),this.tensors=[],this.closed_=!0,this.idTensor.dispose()}size(){return this.tensors.length}read(e){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||e>=this.size())throw new Error(`Tried to read from index ${e}, but array size is: ${this.size()}`);const t=this.tensors[e];if(t.cleared)throw new Error(`TensorArray ${this.name}: Could not read index ${e} twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).`);return this.clearAfterRead&&(t.cleared=!0),t.read=!0,t.tensor}readMany(e){return e.map((e=>this.read(e)))}write(e,t){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||!this.dynamicSize&&e>=this.maxSize)throw new Error(`Tried to write to index ${e}, but array is not resizeable and size is: ${this.maxSize}`);const n=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e},\n          because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);if(0!==this.size()||null!=this.elementShape&&0!==this.elementShape.length||(this.elementShape=t.shape),FN(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),n.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(n.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);n.tensor=t,Sa(t),n.written=!0,this.tensors[e]=n}writeMany(e,t){if(e.length!==t.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);e.forEach(((e,n)=>this.write(e,t[n])))}gather(e,t){if(t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let t=0;t<this.size();t++)e.push(t)}if(0===e.length)return ya([],[0].concat(this.elementShape));const n=this.readMany(e);return FN(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),Yc(n,0)}concat(e){if(e&&e!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${e}`);if(0===this.size())return ya([],[0].concat(this.elementShape));const t=[];for(let e=0;e<this.size();e++)t.push(e);const n=this.readMany(t);return FN(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),co(n,0)}scatter(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);if(e.length!==t.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${e.length} vs. ${t.shape[0]}`);const n=Math.max(...e);if(!this.dynamicSize&&n>=this.maxSize)throw new Error(`Max index must be < array size (${n}  vs. ${this.maxSize})`);this.writeMany(e,mh(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);let n=0;const s=e.map((e=>(n+=e,n)));if(n!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to\n          tensor.shape[0], but sum of lengths is\n        ${n}, and tensor's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);const r=0===n?0:t.size/n,a=[];Na((()=>{t=oo(t,[1,n,r]);for(let n=0;n<e.length;++n){const i=[0,0===n?0:s[n-1],0],o=[1,e[n],r];a[n]=oo(fo(t,i,o),this.elementShape)}return a}));const i=[];for(let t=0;t<e.length;t++)i[t]=t;this.writeMany(i,a)}}class zN{get id(){return this.idTensor.id}constructor(e,t,n,s=-1){this.tensors=e,this.elementShape=t,this.elementDtype=n,null!=e&&e.forEach((e=>{if(n!==e.dtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${e.dtype}`);FN(t,e.shape,"TensorList shape mismatch: "),Sa(e)})),this.idTensor=xl(0),this.maxNumElements=s,Sa(this.idTensor)}copy(){return new zN([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach((t=>{null!=e&&e.has(t.id)||t.dispose()})),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,n=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(-1!==n&&this.tensors.length!==n)throw new Error(`Operation expected a list with ${n} elements but got a list with ${this.tensors.length} elements.`);FN(e,this.elementShape,"TensorList shape mismatch: ");const s=ON(this.elementShape,this.tensors,e);return Na((()=>{const e=this.tensors.map((e=>oo(e,s)));return Yc(e,0)}))}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(0===this.size())throw new Error("Trying to pop from an empty list.");const n=ON(this.elementShape,this.tensors,e),s=this.tensors.pop();return s.kept=!1,FN(s.shape,e,"TensorList shape mismatch: "),oo(s,n)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(FN(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Sa(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(-1!==this.maxNumElements&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);const t=new zN([],this.elementShape,this.elementDtype,this.maxNumElements);t.tensors.length=e;for(let n=0;n<Math.min(this.tensors.length,e);++n)t.tensors[n]=this.tensors[n];return t}getItem(e,t,n){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${this.elementDtype}`);if(e<0||e>this.tensors.length)throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);if(null==this.tensors[e])throw new Error(`element at index ${e} is null.`);FN(this.tensors[e].shape,t,"TensorList shape mismatch: ");const s=ON(this.elementShape,this.tensors,t);return oo(this.tensors[e],s)}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(e<0||-1!==this.maxNumElements&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);FN(this.elementShape,t.shape,"TensorList shape mismatch: "),Sa(t),null!=this.tensors[e]&&(this.tensors[e].kept=!1),this.tensors[e]=t}gather(e,t,n){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);FN(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());const s=ON(this.elementShape,this.tensors,n);return 0===e.length?ya([],[0].concat(s)):Na((()=>{const t=e.map((e=>oo(this.tensors[e],s)));return Yc(t,0)}))}concat(e,t){if(e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);FN(this.elementShape,t,"TensorList shape mismatch: ");const n=ON(this.elementShape,this.tensors,t);return 0===this.size()?ya([],[0].concat(n)):Na((()=>{const e=this.tensors.map((e=>oo(e,n)));return co(e,0)}))}}const PN=async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{const s=Uk("thenBranch",e,t,n),r=Uk("elseBranch",e,t,n),a=Uk("cond",e,t,n),i=Uk("args",e,t,n);return(await a.data())[0]?n.functionMap[s].executeFunctionAsync(i,n.tensorArrayMap,n.tensorListMap):n.functionMap[r].executeFunctionAsync(i,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{const s=Uk("body",e,t,n),r=Uk("cond",e,t,n),a=Uk("args",e,t,n),i=await n.functionMap[r].executeFunctionAsync(a,n.tensorArrayMap,n.tensorListMap),o=a.map((e=>e.id));let l=await i[0].data();i.forEach((e=>{e.kept||-1!==o.indexOf(e.id)||e.dispose()}));let u=a;for(;l[0];){const e=u;u=await n.functionMap[s].executeFunctionAsync(u,n.tensorArrayMap,n.tensorListMap);const t=u.map((e=>e.id));e.forEach((e=>{e.kept||-1!==o.indexOf(e.id)||-1!==t.indexOf(e.id)||e.dispose()}));const a=await n.functionMap[r].executeFunctionAsync(u,n.tensorArrayMap,n.tensorListMap);l=await a[0].data(),a.forEach((e=>{e.kept||-1!==o.indexOf(e.id)||-1!==t.indexOf(e.id)||e.dispose()}))}return u}case"LoopCond":return[Yk(Uk("pred",e,t,n))];case"Switch":{const s=Uk("pred",e,t,n);let r=Uk("data",e,t,n);return r.kept||(r=Yk(r)),(await s.data())[0]?[void 0,r]:[r,void 0]}case"Merge":{const s=e.inputNames.find((e=>void 0!==Gk(e,t,n)));if(s){return[Yk(Gk(s,t,n))]}return}case"Enter":{const s=Uk("frameName",e,t,n),r=Uk("tensor",e,t,n);return n.enterFrame(s),[Yk(r)]}case"Exit":{const s=Uk("tensor",e,t,n);return n.exitFrame(),[Yk(s)]}case"NextIteration":{const s=Uk("tensor",e,t,n);return n.nextIteration(),[Yk(s)]}case"TensorArrayV3":{const s=Uk("size",e,t,n),r=Uk("dtype",e,t,n),a=Uk("elementShape",e,t,n),i=Uk("dynamicSize",e,t,n),o=Uk("clearAfterRead",e,t,n),l=Uk("identicalElementShapes",e,t,n),u=Uk("name",e,t,n),c=new LN(u,r,s,a,l,i,o);return n.addTensorArray(c),[c.idTensor,xl(1)]}case"TensorArrayWriteV3":{const s=Uk("tensorArrayId",e,t,n),r=Uk("index",e,t,n),a=Uk("tensor",e,t,n),i=n.getTensorArray(s.id);return i.write(r,a),[i.idTensor]}case"TensorArrayReadV3":{const s=Uk("tensorArrayId",e,t,n),r=Uk("index",e,t,n);return[n.getTensorArray(s.id).read(r)]}case"TensorArrayGatherV3":{const s=Uk("tensorArrayId",e,t,n),r=Uk("indices",e,t,n),a=Uk("dtype",e,t,n);return[n.getTensorArray(s.id).gather(r,a)]}case"TensorArrayScatterV3":{const s=Uk("tensorArrayId",e,t,n),r=Uk("indices",e,t,n),a=Uk("tensor",e,t,n),i=n.getTensorArray(s.id);return i.scatter(r,a),[i.idTensor]}case"TensorArrayConcatV3":{const s=Uk("tensorArrayId",e,t,n),r=n.getTensorArray(s.id),a=Uk("dtype",e,t,n);return[r.concat(a)]}case"TensorArraySplitV3":{const s=Uk("tensorArrayId",e,t,n),r=Uk("tensor",e,t,n),a=Uk("lengths",e,t,n),i=n.getTensorArray(s.id);return i.split(a,r),[i.idTensor]}case"TensorArraySizeV3":{const s=Uk("tensorArrayId",e,t,n);return[xl(n.getTensorArray(s.id).size(),"int32")]}case"TensorArrayCloseV3":{const s=Uk("tensorArrayId",e,t,n),r=n.getTensorArray(s.id);return r.clearAndClose(),[r.idTensor]}case"TensorListSetItem":{const s=Uk("tensorListId",e,t,n),r=Uk("index",e,t,n),a=Uk("tensor",e,t,n),i=n.getTensorList(s.id);return i.setItem(r,a),[i.idTensor]}case"TensorListGetItem":{const s=Uk("tensorListId",e,t,n),r=Uk("index",e,t,n),a=Uk("elementShape",e,t,n),i=Uk("elementDType",e,t,n);return[n.getTensorList(s.id).getItem(r,a,i)]}case"TensorListScatterV2":case"TensorListScatter":{const s=Uk("indices",e,t,n),r=function(e,t,n,s){if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);const r=Math.max(...t);if(null!=s&&-1!==s&&r>=s)throw new Error(`Max index must be < array size (${r}  vs. ${s})`);const a=new zN([],n,e.dtype,s),i=mh(e,0);return t.forEach(((e,t)=>{a.setItem(e,i[t])})),a}(Uk("tensor",e,t,n),s,Uk("elementShape",e,t,n),Uk("numElements",e,t,n));return n.addTensorList(r),[r.idTensor]}case"TensorListReserve":case"EmptyTensorList":{const s=Uk("elementShape",e,t,n),r=Uk("elementDType",e,t,n);let a;a="TensorListReserve"===e.op?"numElements":"maxNumElements";const i=Uk(a,e,t,n),o=function(e,t,n,s){return new zN([],e,t,s)}(s,r,0,"TensorListReserve"===e.op?-1:i);return n.addTensorList(o),[o.idTensor]}case"TensorListGather":{const s=Uk("tensorListId",e,t,n),r=Uk("indices",e,t,n),a=Uk("elementShape",e,t,n),i=Uk("elementDType",e,t,n);return[n.getTensorList(s.id).gather(r,i,a)]}case"TensorListStack":{const s=Uk("tensorListId",e,t,n),r=Uk("elementShape",e,t,n),a=Uk("elementDType",e,t,n),i=Uk("numElements",e,t,n);return[n.getTensorList(s.id).stack(r,a,i)]}case"TensorListFromTensor":{const s=function(e,t,n){const s=e.dtype;if(e.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${e.shape}`);if(e.dtype!==n)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${n}`);FN(e.shape.slice(1),t,"TensorList shape mismatch: ");const r=mh(e);return new zN(r,t,s)}(Uk("tensor",e,t,n),Uk("elementShape",e,t,n),Uk("elementDType",e,t,n));return n.addTensorList(s),[s.idTensor]}case"TensorListConcat":case"TensorListConcatV2":{const s=Uk("tensorListId",e,t,n),r=n.getTensorList(s.id),a=Uk("dtype",e,t,n),i=Uk("elementShape",e,t,n);return[r.concat(a,i)]}case"TensorListPushBack":{const s=Uk("tensorListId",e,t,n),r=Uk("tensor",e,t,n),a=n.getTensorList(s.id);return a.pushBack(r),[a.idTensor]}case"TensorListPopBack":{const s=Uk("tensorListId",e,t,n),r=Uk("elementShape",e,t,n),a=Uk("elementDType",e,t,n);return[n.getTensorList(s.id).popBack(r,a)]}case"TensorListSplit":{const s=Uk("tensor",e,t,n),r=Uk("elementShape",e,t,n),a=function(e,t,n){let s=0;const r=t.map((e=>(s+=e,s)));if(s!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to\n          tensor.shape[0], but sum of lengths is\n        ${s}, and tensor's shape is: ${e.shape}`);const a=MN(e.shape.slice(1),n),i=0===s?0:e.size/s,o=Na((()=>{const n=[];e=oo(e,[1,s,i]);for(let s=0;s<t.length;++s){const o=[0,0===s?0:r[s-1],0],l=[1,t[s],i];n[s]=oo(fo(e,o,l),a)}return e.dispose(),n})),l=new zN([],n,e.dtype,t.length);for(let e=0;e<o.length;e++)l.setItem(e,o[e]);return l}(s,Uk("lengths",e,t,n),r);return n.addTensorList(a),[a.idTensor]}case"TensorListLength":{const s=Uk("tensorListId",e,t,n);return[xl(n.getTensorList(s.id).size(),"int32")]}case"TensorListResize":{const s=Uk("tensorListId",e,t,n),r=Uk("size",e,t,n),a=n.getTensorList(s.id).resize(r);return n.addTensorList(a),[a.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};function BN(e,t,n){const[s,r]=Uk("fusedOps",e,t,n),a="biasadd"===s,i=!a,o="prelu"===r,l="fusedbatchnorm"===s,u=Uk("numArgs",e,t,n);if(a){if(o&&2!==u)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&a&&1!==u)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(l)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported");const c=Uk("strides",e,t,n),h=Xk(e,t,n),p=Uk("dataFormat",e,t,n).toUpperCase(),d=Uk("dilations",e,t,n);let[f,m]=Uk("args",e,t,n);i&&(m=f,f=void 0);return{stride:c,pad:h,dataFormat:p,dilations:d,biasArg:f,preluArg:m,activationFunc:r,leakyreluAlpha:Uk("leakyreluAlpha",e,t,n)}}function WN(e,t,n){return{boxes:Uk("boxes",e,t,n),scores:Uk("scores",e,t,n),maxOutputSize:Uk("maxOutputSize",e,t,n),iouThreshold:Uk("iouThreshold",e,t,n),scoreThreshold:Uk("scoreThreshold",e,t,n),softNmsSigma:Uk("softNmsSigma",e,t,n)}}class VN{get id(){return this.handle.id}constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=xl(0),this.tensorMap=new Map,Sa(this.handle)}clearAndClose(){this.tensorMap.forEach((e=>e.dispose())),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return xl(this.size(),"int32")}async import(e,t){this.checkKeyAndValueTensor(e,t);const n=await e.data();return this.tensorMap.forEach((e=>e.dispose())),this.tensorMap.clear(),Na((()=>{const e=mh(t),s=n.length,r=e.length;c(s===r,(()=>`The number of elements doesn't match, keys has ${s} elements, the values has ${r} elements.`));for(let t=0;t<s;t++){const s=n[t],r=e[t];Sa(r),this.tensorMap.set(s,r)}return this.handle}))}async find(e,t){this.checkKeyAndValueTensor(e,t);const n=await e.data();return Na((()=>{const e=[];for(let s=0;s<n.length;s++){const r=n[s],a=this.findWithDefault(r,t);e.push(a)}return Yc(e)}))}findWithDefault(e,t){const n=this.tensorMap.get(e);return null!=n?n:t}checkKeyAndValueTensor(e,t){if(e.dtype!==this.keyDType)throw new Error(`Expect key dtype ${this.keyDType}, but got ${e.dtype}`);if(t.dtype!==this.valueDType)throw new Error(`Expect value dtype ${this.valueDType}, but got ${t.dtype}`)}}function UN(e,t,n,s,r=Na){const a=((e,t,n)=>{switch(e.category){case"arithmetic":return r((()=>((e,t,n,s=_N)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[s.add(Uk("a",e,t,n),Uk("b",e,t,n))];case"AddN":return[s.addN(Uk("tensors",e,t,n))];case"FloorMod":case"Mod":return[s.mod(Uk("a",e,t,n),Uk("b",e,t,n))];case"Mul":return[s.mul(Uk("a",e,t,n),Uk("b",e,t,n))];case"RealDiv":case"Div":return[s.div(Uk("a",e,t,n),Uk("b",e,t,n))];case"DivNoNan":return[s.divNoNan(Uk("a",e,t,n),Uk("b",e,t,n))];case"FloorDiv":return[s.floorDiv(Uk("a",e,t,n),Uk("b",e,t,n))];case"Sub":return[s.sub(Uk("a",e,t,n),Uk("b",e,t,n))];case"Minimum":return[s.minimum(Uk("a",e,t,n),Uk("b",e,t,n))];case"Maximum":return[s.maximum(Uk("a",e,t,n),Uk("b",e,t,n))];case"Pow":return[s.pow(Uk("a",e,t,n),Uk("b",e,t,n))];case"SquaredDifference":return[s.squaredDifference(Uk("a",e,t,n),Uk("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"basic_math":return r((()=>((e,t,n,s=_N)=>{switch(e.op){case"Abs":case"ComplexAbs":return[s.abs(Uk("x",e,t,n))];case"Acos":return[s.acos(Uk("x",e,t,n))];case"Acosh":return[s.acosh(Uk("x",e,t,n))];case"Asin":return[s.asin(Uk("x",e,t,n))];case"Asinh":return[s.asinh(Uk("x",e,t,n))];case"Atan":return[s.atan(Uk("x",e,t,n))];case"Atan2":return[s.atan2(Uk("x",e,t,n),Uk("y",e,t,n))];case"Atanh":return[s.atanh(Uk("x",e,t,n))];case"Ceil":return[s.ceil(Uk("x",e,t,n))];case"Complex":return[s.complex(Uk("real",e,t,n),Uk("imag",e,t,n))];case"Cos":return[s.cos(Uk("x",e,t,n))];case"Cosh":return[s.cosh(Uk("x",e,t,n))];case"Elu":return[s.elu(Uk("x",e,t,n))];case"Erf":return[s.erf(Uk("x",e,t,n))];case"Exp":return[s.exp(Uk("x",e,t,n))];case"Expm1":return[s.expm1(Uk("x",e,t,n))];case"Floor":return[s.floor(Uk("x",e,t,n))];case"Log":return[s.log(Uk("x",e,t,n))];case"Log1p":return[s.log1p(Uk("x",e,t,n))];case"Imag":return[s.imag(Uk("x",e,t,n))];case"Neg":return[s.neg(Uk("x",e,t,n))];case"Reciprocal":return[s.reciprocal(Uk("x",e,t,n))];case"Real":return[s.real(Uk("x",e,t,n))];case"Relu":return[s.relu(Uk("x",e,t,n))];case"Round":return[s.round(Uk("x",e,t,n))];case"Selu":return[s.selu(Uk("x",e,t,n))];case"Sigmoid":return[s.sigmoid(Uk("x",e,t,n))];case"Sin":return[s.sin(Uk("x",e,t,n))];case"Sign":return[s.sign(Uk("x",e,t,n))];case"Sinh":return[s.sinh(Uk("x",e,t,n))];case"Softplus":return[s.softplus(Uk("x",e,t,n))];case"Sqrt":return[s.sqrt(Uk("x",e,t,n))];case"Square":return[s.square(Uk("x",e,t,n))];case"Tanh":return[s.tanh(Uk("x",e,t,n))];case"Tan":return[s.tan(Uk("x",e,t,n))];case"ClipByValue":return[s.clipByValue(Uk("x",e,t,n),Uk("clipValueMin",e,t,n),Uk("clipValueMax",e,t,n))];case"Relu6":return[s.relu6(Uk("x",e,t,n))];case"Rsqrt":return[s.rsqrt(Gk(e.inputNames[0],t,n))];case"LeakyRelu":return[s.leakyRelu(Uk("x",e,t,n),Uk("alpha",e,t,n))];case"Prelu":return[s.prelu(Uk("x",e,t,n),Uk("alpha",e,t,n))];case"IsNan":return[s.isNaN(Gk(e.inputNames[0],t,n))];case"IsInf":return[s.isInf(Gk(e.inputNames[0],t,n))];case"IsFinite":return[s.isFinite(Gk(e.inputNames[0],t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"control":return PN(e,t,n);case"convolution":return r((()=>((e,t,n,s=_N)=>{switch(e.op){case"Conv1D":{const r=Uk("stride",e,t,n),a=Uk("pad",e,t,n),i=Uk("dataFormat",e,t,n).toUpperCase(),o=Uk("dilation",e,t,n);return[s.conv1d(Uk("x",e,t,n),Uk("filter",e,t,n),r,a,i,o)]}case"Conv2D":{const r=Uk("strides",e,t,n),a=Xk(e,t,n),i=Uk("dataFormat",e,t,n).toUpperCase(),o=Uk("dilations",e,t,n);return[s.conv2d(Uk("x",e,t,n),Uk("filter",e,t,n),[r[1],r[2]],a,i,[o[1],o[2]])]}case"_FusedConv2D":{const{stride:r,pad:a,dataFormat:i,dilations:o,biasArg:l,preluArg:u,activationFunc:c,leakyreluAlpha:h}=BN(e,t,n);return[s.fused.conv2d({x:Uk("x",e,t,n),filter:Uk("filter",e,t,n),strides:[r[1],r[2]],pad:a,dataFormat:i,dilations:[o[1],o[2]],bias:l,activation:c,preluActivationWeights:u,leakyreluAlpha:h})]}case"FusedDepthwiseConv2dNative":{const{stride:r,pad:a,dataFormat:i,dilations:o,biasArg:l,preluArg:u,activationFunc:c,leakyreluAlpha:h}=BN(e,t,n);return[s.fused.depthwiseConv2d({x:Uk("x",e,t,n),filter:Uk("filter",e,t,n),strides:[r[1],r[2]],pad:a,dataFormat:i,dilations:[o[1],o[2]],bias:l,activation:c,preluActivationWeights:u,leakyreluAlpha:h})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{const r=Uk("outputShape",e,t,n),a=Uk("strides",e,t,n),i=Xk(e,t,n);return[s.conv2dTranspose(Uk("x",e,t,n),Uk("filter",e,t,n),r,[a[1],a[2]],i)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{const r=Uk("strides",e,t,n),a=Xk(e,t,n),i=Uk("dilations",e,t,n),o=Uk("dataFormat",e,t,n).toUpperCase();return[s.depthwiseConv2d(Uk("input",e,t,n),Uk("filter",e,t,n),[r[1],r[2]],a,o,[i[1],i[2]])]}case"Conv3D":{const r=Uk("strides",e,t,n),a=Uk("pad",e,t,n),i=Uk("dataFormat",e,t,n).toUpperCase(),o=Uk("dilations",e,t,n);return[s.conv3d(Uk("x",e,t,n),Uk("filter",e,t,n),[r[1],r[2],r[3]],a,i,[o[1],o[2],o[3]])]}case"AvgPool":{const r=Uk("strides",e,t,n),a=Uk("pad",e,t,n),i=Uk("kernelSize",e,t,n);return[s.avgPool(Uk("x",e,t,n),[i[1],i[2]],[r[1],r[2]],a)]}case"MaxPool":{const r=Uk("strides",e,t,n),a=Uk("pad",e,t,n),i=Uk("kernelSize",e,t,n);return[s.maxPool(Uk("x",e,t,n),[i[1],i[2]],[r[1],r[2]],a)]}case"MaxPoolWithArgmax":{const r=Uk("strides",e,t,n),a=Uk("pad",e,t,n),i=Uk("kernelSize",e,t,n),o=Uk("includeBatchInIndex",e,t,n),{result:l,indexes:u}=s.maxPoolWithArgmax(Uk("x",e,t,n),[i[1],i[2]],[r[1],r[2]],a,o);return[l,u]}case"AvgPool3D":{const r=Uk("strides",e,t,n),a=Uk("pad",e,t,n),i=Uk("kernelSize",e,t,n);return[s.avgPool3d(Uk("x",e,t,n),[i[1],i[2],i[3]],[r[1],r[2],r[3]],a)]}case"MaxPool3D":{const r=Uk("strides",e,t,n),a=Uk("pad",e,t,n),i=Uk("kernelSize",e,t,n);return[s.maxPool3d(Uk("x",e,t,n),[i[1],i[2],i[3]],[r[1],r[2],r[3]],a)]}case"Dilation2D":{const r=Uk("strides",e,t,n),a=Uk("pad",e,t,n),i=Uk("dilations",e,t,n),o=r[1],l=r[2],u=i[1],c=i[2];return[s.dilation2d(Uk("x",e,t,n),Uk("filter",e,t,n),[o,l],a,[u,c],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"creation":return r((()=>((e,t,n,s=_N)=>{switch(e.op){case"Fill":{const r=Uk("shape",e,t,n),a=Uk("dtype",e,t,n),i=Uk("value",e,t,n);return[s.fill(r,i,a)]}case"LinSpace":{const r=Uk("start",e,t,n),a=Uk("stop",e,t,n),i=Uk("num",e,t,n);return[s.linspace(r,a,i)]}case"Multinomial":{const r=Uk("logits",e,t,n),a=Uk("numSamples",e,t,n),i=Uk("seed",e,t,n);return[s.multinomial(r,a,i)]}case"OneHot":{const r=Uk("indices",e,t,n),a=Uk("depth",e,t,n),i=Uk("onValue",e,t,n),o=Uk("offValue",e,t,n),l=Uk("dtype",e,t,n);return[s.oneHot(r,a,i,o,l)]}case"Ones":return[s.ones(Uk("shape",e,t,n),Uk("dtype",e,t,n))];case"OnesLike":return[s.onesLike(Uk("x",e,t,n))];case"RandomStandardNormal":return[s.randomStandardNormal(Uk("shape",e,t,n),Uk("dtype",e,t,n),Uk("seed",e,t,n))];case"RandomUniform":return[s.randomUniform(Uk("shape",e,t,n),Uk("minval",e,t,n),Uk("maxval",e,t,n),Uk("dtype",e,t,n))];case"RandomUniformInt":return[s.randomUniformInt(Uk("shape",e,t,n),Uk("minval",e,t,n),Uk("maxval",e,t,n),Uk("seed",e,t,n))];case"Range":{const r=Uk("start",e,t,n),a=Uk("stop",e,t,n),i=Uk("step",e,t,n);return[s.range(r,a,i,Uk("dtype",e,t,n))]}case"TruncatedNormal":{const r=Uk("shape",e,t,n),a=Uk("mean",e,t,n),i=Uk("stdDev",e,t,n),o=Uk("seed",e,t,n);return[s.truncatedNormal(r,a,i,Uk("dtype",e,t,n),o)]}case"Zeros":return[s.zeros(Uk("shape",e,t,n),Uk("dtype",e,t,n))];case"ZerosLike":return[s.zerosLike(Uk("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"dynamic":return(async(e,t,n,s,r=_N)=>{switch(e.op){case"NonMaxSuppressionV5":{const{boxes:s,scores:a,maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:u}=WN(e,t,n),c=await r.image.nonMaxSuppressionWithScoreAsync(s,a,i,o,l,u);return[c.selectedIndices,c.selectedScores]}case"NonMaxSuppressionV4":{const{boxes:s,scores:a,maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=WN(e,t,n),u=Uk("padToMaxOutputSize",e,t,n),c=await r.image.nonMaxSuppressionPaddedAsync(s,a,i,o,l,u);return[c.selectedIndices,c.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{const{boxes:s,scores:a,maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=WN(e,t,n);return[await r.image.nonMaxSuppressionAsync(s,a,i,o,l)]}case"Where":{const s=r.cast(Uk("condition",e,t,n),"bool"),a=[await r.whereAsync(s)];return s.dispose(),a}case"ListDiff":return r.setdiff1dAsync(Uk("x",e,t,n),Uk("y",e,t,n));default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n);case"evaluation":return r((()=>((e,t,n,s=_N)=>{switch(e.op){case"LowerBound":{const r=Uk("sortedSequence",e,t,n),a=Uk("values",e,t,n);return[s.lowerBound(r,a)]}case"TopKV2":{const r=Uk("x",e,t,n),a=Uk("k",e,t,n),i=Uk("sorted",e,t,n),o=s.topk(r,a,i);return[o.values,o.indices]}case"UpperBound":{const r=Uk("sortedSequence",e,t,n),a=Uk("values",e,t,n);return[s.upperBound(r,a)]}case"Unique":{const r=Uk("x",e,t,n),a=s.unique(r);return[a.values,a.indices]}case"UniqueV2":{const r=Uk("x",e,t,n),a=Uk("axis",e,t,n),i=s.unique(r,a);return[i.values,i.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"image":return r((()=>((e,t,n,s=_N)=>{switch(e.op){case"ResizeBilinear":{const r=Uk("images",e,t,n),a=Uk("size",e,t,n),i=Uk("alignCorners",e,t,n),o=Uk("halfPixelCenters",e,t,n);return[s.image.resizeBilinear(r,[a[0],a[1]],i,o)]}case"ResizeNearestNeighbor":{const r=Uk("images",e,t,n),a=Uk("size",e,t,n),i=Uk("alignCorners",e,t,n),o=Uk("halfPixelCenters",e,t,n);return[s.image.resizeNearestNeighbor(r,[a[0],a[1]],i,o)]}case"CropAndResize":{const r=Uk("image",e,t,n),a=Uk("boxes",e,t,n),i=Uk("boxInd",e,t,n),o=Uk("cropSize",e,t,n),l=Uk("method",e,t,n),u=Uk("extrapolationValue",e,t,n);return[s.image.cropAndResize(r,a,i,o,l,u)]}case"ImageProjectiveTransformV3":{const r=Uk("images",e,t,n),a=Uk("transforms",e,t,n),i=Uk("outputShape",e,t,n),o=Uk("fillValue",e,t,n),l=Uk("interpolation",e,t,n),u=Uk("fillMode",e,t,n);return[s.image.transform(r,a,l.toLowerCase(),u.toLowerCase(),o,i)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"graph":return r((()=>((e,t,n,s=_N)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":const r=Uk("default",e,t,n);return[Gk(e.name,t,n)||r];case"Placeholder":return[Gk(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":case"Snapshot":return[Yk(Uk("x",e,t,n))];case"IdentityN":return Uk("x",e,t,n).map((e=>Yk(e)));case"Shape":return[s.tensor1d(Uk("x",e,t,n).shape,"int32")];case"ShapeN":return Uk("x",e,t,n).map((e=>s.tensor1d(e.shape)));case"Size":return[s.scalar(Uk("x",e,t,n).size,"int32")];case"Rank":return[s.scalar(Uk("x",e,t,n).rank,"int32")];case"NoOp":return[s.scalar(1)];case"Print":const a=Uk("x",e,t,n),i=Uk("data",e,t,n),o=Uk("message",e,t,n),l=Uk("summarize",e,t,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(o);for(let e=0;e<i.length;e++)console.log(Array.prototype.slice.call(i[e].dataSync()).slice(0,l));return[a];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"logical":return r((()=>((e,t,n,s=_N)=>{switch(e.op){case"Equal":return[s.equal(Uk("a",e,t,n),Uk("b",e,t,n))];case"NotEqual":return[s.notEqual(Uk("a",e,t,n),Uk("b",e,t,n))];case"Greater":return[s.greater(Uk("a",e,t,n),Uk("b",e,t,n))];case"GreaterEqual":return[s.greaterEqual(Uk("a",e,t,n),Uk("b",e,t,n))];case"Less":return[s.less(Uk("a",e,t,n),Uk("b",e,t,n))];case"LessEqual":return[s.lessEqual(Uk("a",e,t,n),Uk("b",e,t,n))];case"LogicalAnd":return[s.logicalAnd(Uk("a",e,t,n),Uk("b",e,t,n))];case"LogicalNot":return[s.logicalNot(Uk("a",e,t,n))];case"LogicalOr":return[s.logicalOr(Uk("a",e,t,n),Uk("b",e,t,n))];case"Select":case"SelectV2":return[s.where(Uk("condition",e,t,n),Uk("a",e,t,n),Uk("b",e,t,n))];case"BitwiseAnd":return[s.bitwiseAnd(Uk("a",e,t,n),Uk("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"matrices":return r((()=>((e,t,n,s=_N)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[s.matMul(Uk("a",e,t,n),Uk("b",e,t,n),Uk("transposeA",e,t,n),Uk("transposeB",e,t,n))];case"Einsum":return[s.einsum(Uk("equation",e,t,n),...Uk("tensors",e,t,n))];case"Transpose":return[s.transpose(Uk("x",e,t,n),Uk("perm",e,t,n))];case"_FusedMatMul":const[r,a]=Uk("fusedOps",e,t,n),i="biasadd"===r,o="prelu"===a,l=Uk("numArgs",e,t,n),u=Uk("leakyreluAlpha",e,t,n);if(i){if(o&&2!==l)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&1!==l)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}const[c,h]=Uk("args",e,t,n);return[s.fused.matMul({a:Uk("a",e,t,n),b:Uk("b",e,t,n),transposeA:Uk("transposeA",e,t,n),transposeB:Uk("transposeB",e,t,n),bias:c,activation:a,preluActivationWeights:h,leakyreluAlpha:u})];case"MatrixBandPart":return[s.linalg.bandPart(Uk("a",e,t,n),Uk("numLower",e,t,n),Uk("numUpper",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"normalization":return r((()=>((e,t,n,s=_N)=>{switch(e.op){case"EuclideanNorm":return[s.euclideanNorm(Uk("x",e,t,n),Uk("axis",e,t,n),Uk("keepDims",e,t,n))];case"FusedBatchNorm":case"FusedBatchNormV2":case"FusedBatchNormV3":return[s.batchNorm(Uk("x",e,t,n),Uk("mean",e,t,n),Uk("variance",e,t,n),Uk("offset",e,t,n),Uk("scale",e,t,n),Uk("epsilon",e,t,n))];case"LRN":return[s.localResponseNormalization(Uk("x",e,t,n),Uk("radius",e,t,n),Uk("bias",e,t,n),Uk("alpha",e,t,n),Uk("beta",e,t,n))];case"Softmax":return[s.softmax(Uk("x",e,t,n))];case"LogSoftmax":return[s.logSoftmax(Uk("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"ragged":return r((()=>((e,t,n,s=_N)=>{switch(e.op){case"RaggedGather":{const{outputNestedSplits:r,outputDenseValues:a}=s.raggedGather(Uk("paramsNestedSplits",e,t,n),Uk("paramsDenseValues",e,t,n),Uk("indices",e,t,n),Uk("outputRaggedRank",e,t,n));return r.concat(a)}case"RaggedRange":{const{rtNestedSplits:r,rtDenseValues:a}=s.raggedRange(Uk("starts",e,t,n),Uk("limits",e,t,n),Uk("splits",e,t,n));return[r,a]}case"RaggedTensorToTensor":return[s.raggedTensorToTensor(Uk("shape",e,t,n),Uk("values",e,t,n),Uk("defaultValue",e,t,n),Uk("rowPartitionTensors",e,t,n),Uk("rowPartitionTypes",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"reduction":return r((()=>((e,t,n,s=_N)=>{switch(e.op){case"Max":{const r=Uk("axis",e,t,n),a=Uk("keepDims",e,t,n);return[s.max(Uk("x",e,t,n),r,a)]}case"Mean":{const r=Uk("axis",e,t,n),a=Uk("keepDims",e,t,n);return[s.mean(Uk("x",e,t,n),r,a)]}case"Min":{const r=Uk("axis",e,t,n),a=Uk("keepDims",e,t,n);return[s.min(Uk("x",e,t,n),r,a)]}case"Sum":{const r=Uk("axis",e,t,n),a=Uk("keepDims",e,t,n);return[s.sum(Uk("x",e,t,n),r,a)]}case"All":{const r=Uk("axis",e,t,n),a=Uk("keepDims",e,t,n);return[s.all(Uk("x",e,t,n),r,a)]}case"Any":{const r=Uk("axis",e,t,n),a=Uk("keepDims",e,t,n);return[s.any(Uk("x",e,t,n),r,a)]}case"ArgMax":{const r=Uk("axis",e,t,n);return[s.argMax(Uk("x",e,t,n),r)]}case"ArgMin":{const r=Uk("axis",e,t,n);return[s.argMin(Uk("x",e,t,n),r)]}case"Prod":{const r=Uk("axis",e,t,n),a=Uk("keepDims",e,t,n);return[s.prod(Uk("x",e,t,n),r,a)]}case"Cumprod":{const r=Uk("axis",e,t,n),a=Uk("exclusive",e,t,n),i=Uk("reverse",e,t,n);return[s.cumprod(Uk("x",e,t,n),r,a,i)]}case"Cumsum":{const r=Uk("axis",e,t,n),a=Uk("exclusive",e,t,n),i=Uk("reverse",e,t,n);return[s.cumsum(Uk("x",e,t,n),r,a,i)]}case"Bincount":const r=Uk("x",e,t,n),a=Uk("weights",e,t,n),i=Uk("size",e,t,n);return[s.bincount(r,a,i)];case"DenseBincount":{const r=Uk("x",e,t,n),a=Uk("weights",e,t,n),i=Uk("size",e,t,n),o=Uk("binaryOutput",e,t,n);return[s.denseBincount(r,a,i,o)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"slice_join":return r((()=>((e,t,n,s=_N)=>{switch(e.op){case"ConcatV2":case"Concat":{const r=Uk("n",e,t,n),a=Uk("axis",e,t,n);let i=Uk("tensors",e,t,n);return i=i.slice(0,r),[s.concat(i,a)]}case"Gather":{const r=Uk("x",e,t,n),a=Uk("indices",e,t,n);return[s.gather(r,s.cast(a,"int32"),0)]}case"GatherV2":{const r=Uk("axis",e,t,n),a=Uk("batchDims",e,t,n),i=Uk("x",e,t,n),o=Uk("indices",e,t,n);return[s.gather(i,s.cast(o,"int32"),r,a)]}case"Reverse":{const r=Uk("dims",e,t,n),a=[];for(let e=0;e<r.length;e++)r[e]&&a.push(e);const i=Uk("x",e,t,n);return[s.reverse(i,a)]}case"ReverseV2":{const r=Uk("axis",e,t,n),a=Uk("x",e,t,n);return[s.reverse(a,r)]}case"Slice":{const r=Uk("begin",e,t,n),a=Uk("size",e,t,n);return[s.slice(Uk("x",e,t,n),r,a)]}case"StridedSlice":{const r=Uk("begin",e,t,n),a=Uk("end",e,t,n),i=Uk("strides",e,t,n),o=Uk("beginMask",e,t,n),l=Uk("endMask",e,t,n),u=Uk("ellipsisMask",e,t,n),c=Uk("newAxisMask",e,t,n),h=Uk("shrinkAxisMask",e,t,n),p=Uk("x",e,t,n);return[s.stridedSlice(p,r,a,i,o,l,u,c,h)]}case"Pack":return Na((()=>{const r=Uk("axis",e,t,n),a=Uk("tensors",e,t,n),i=a[0].shape,o=s.squeeze(a[0]).shape,l=a.map((e=>{const t=m(e.shape,i);if(!t&&!m(s.squeeze(e).shape,o))throw new Error("the input tensors shape does not match");return t?e:s.reshape(e,i)}));return[s.stack(l,r)]}));case"Unpack":{const r=Uk("axis",e,t,n),a=Uk("tensor",e,t,n);return s.unstack(a,r)}case"Tile":{const r=Uk("reps",e,t,n);return[s.tile(Uk("x",e,t,n),r)]}case"Split":case"SplitV":{const r=Uk("axis",e,t,n),a=Uk("numOrSizeSplits",e,t,n),i=Uk("x",e,t,n);return s.split(i,a,r)}case"ScatterNd":{const r=Uk("indices",e,t,n),a=Uk("values",e,t,n),i=Uk("shape",e,t,n);return[s.scatterND(r,a,i)]}case"GatherNd":{const r=Uk("x",e,t,n),a=Uk("indices",e,t,n);return[s.gatherND(r,a)]}case"SparseToDense":{const r=Uk("sparseIndices",e,t,n),a=Uk("outputShape",e,t,n),i=Uk("sparseValues",e,t,n),o=Uk("defaultValue",e,t,n);return[s.sparseToDense(r,i,a,i.dtype===o.dtype?o:s.cast(o,i.dtype))]}case"TensorScatterUpdate":{const r=Uk("indices",e,t,n),a=Uk("values",e,t,n),i=Uk("tensor",e,t,n);return[s.tensorScatterUpdate(i,r,a)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"sparse":return r((()=>((e,t,n,s=_N)=>{switch(e.op){case"SparseFillEmptyRows":{const{outputIndices:r,outputValues:a,emptyRowIndicator:i,reverseIndexMap:o}=s.sparse.sparseFillEmptyRows(Uk("indices",e,t,n),Uk("values",e,t,n),Uk("denseShape",e,t,n),Uk("defaultValue",e,t,n));return[r,a,i,o]}case"SparseReshape":{const{outputIndices:r,outputShape:a}=s.sparse.sparseReshape(Uk("inputIndices",e,t,n),Uk("inputShape",e,t,n),Uk("newShape",e,t,n));return[r,a]}case"SparseSegmentMean":return[s.sparse.sparseSegmentMean(Uk("data",e,t,n),Uk("indices",e,t,n),Uk("segmentIds",e,t,n))];case"SparseSegmentSum":return[s.sparse.sparseSegmentSum(Uk("data",e,t,n),Uk("indices",e,t,n),Uk("segmentIds",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"spectral":return r((()=>((e,t,n,s=_N)=>{switch(e.op){case"FFT":return[s.fft(Uk("x",e,t,n))];case"IFFT":return[s.ifft(Uk("x",e,t,n))];case"RFFT":return[s.rfft(Uk("x",e,t,n))];case"IRFFT":return[s.irfft(Uk("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"string":return r((()=>((e,t,n,s=_N)=>{switch(e.op){case"StaticRegexReplace":return[s.string.staticRegexReplace(Uk("input",e,t,n),Uk("pattern",e,t,n),Uk("rewrite",e,t,n),Uk("replaceGlobal",e,t,n))];case"StringNGrams":{const{nGrams:r,nGramsSplits:a}=s.string.stringNGrams(Uk("data",e,t,n),Uk("dataSplits",e,t,n),Uk("separator",e,t,n),Uk("nGramWidths",e,t,n),Uk("leftPad",e,t,n),Uk("rightPad",e,t,n),Uk("padWidth",e,t,n),Uk("preserveShortSequences",e,t,n));return[r,a]}case"StringSplit":{const{indices:r,values:a,shape:i}=s.string.stringSplit(Uk("input",e,t,n),Uk("delimiter",e,t,n),Uk("skipEmpty",e,t,n));return[r,a,i]}case"StringToHashBucketFast":return[s.string.stringToHashBucketFast(Uk("input",e,t,n),Uk("numBuckets",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"transformation":return r((()=>((e,t,n,s=_N)=>{switch(e.op){case"Cast":return[s.cast(Uk("x",e,t,n),Uk("dtype",e,t,n))];case"ExpandDims":{const r=Uk("axis",e,t,n);return[s.expandDims(Uk("x",e,t,n),r)]}case"Squeeze":{const r=Uk("axis",e,t,n);return[s.squeeze(Uk("x",e,t,n),r)]}case"Reshape":return[s.reshape(Uk("x",e,t,n),Uk("shape",e,t,n))];case"EnsureShape":return[s.ensureShape(Uk("x",e,t,n),Uk("shape",e,t,n))];case"MirrorPad":return[s.mirrorPad(Uk("x",e,t,n),Uk("padding",e,t,n),Uk("mode",e,t,n))];case"PadV2":case"Pad":return[s.pad(Uk("x",e,t,n),Uk("padding",e,t,n),Uk("constantValue",e,t,n))];case"SpaceToBatchND":{const r=Uk("blockShape",e,t,n),a=Uk("paddings",e,t,n);return[s.spaceToBatchND(Uk("x",e,t,n),r,a)]}case"BatchToSpaceND":{const r=Uk("blockShape",e,t,n),a=Uk("crops",e,t,n);return[s.batchToSpaceND(Uk("x",e,t,n),r,a)]}case"DepthToSpace":{const r=Uk("blockSize",e,t,n),a=Uk("dataFormat",e,t,n).toUpperCase();return[s.depthToSpace(Uk("x",e,t,n),r,a)]}case"BroadcastTo":return[s.broadcastTo(Uk("x",e,t,n),Uk("shape",e,t,n))];case"BroadcastArgs":return[s.broadcastArgs(Uk("s0",e,t,n),Uk("s1",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"hash_table":return(async(e,t,n,s)=>{switch(e.op){case"HashTable":case"HashTableV2":{const r=s.getHashTableHandleByName(e.name);if(null!=r)return[r];{const r=Uk("keyDType",e,t,n),a=Uk("valueDType",e,t,n),i=new VN(r,a);return s.addHashTable(e.name,i),[i.handle]}}case"InitializeTable":case"InitializeTableV2":case"LookupTableImport":case"LookupTableImportV2":{const r=Uk("tableHandle",e,t,n,s),a=Uk("keys",e,t,n),i=Uk("values",e,t,n),o=s.getHashTableById(r.id);return[await o.import(a,i)]}case"LookupTableFind":case"LookupTableFindV2":{const r=Uk("tableHandle",e,t,n,s),a=Uk("keys",e,t,n),i=Uk("defaultValue",e,t,n),o=s.getHashTableById(r.id);return[await o.find(a,i)]}case"LookupTableSize":case"LookupTableSizeV2":{const r=Uk("tableHandle",e,t,n,s);return[s.getHashTableById(r.id).tensorSize()]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n,s);case"custom":const a=Vk(e.op);if(a&&a.customExecutor)return a.customExecutor(new RN(e,t,n));throw TypeError(`Custom op ${e.op} is not registered.`);default:throw TypeError(`Unknown op '${e.op}'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()`)}})(e,t,n);return j(a)?a.then((e=>[].concat(e))):[].concat(a)}class GN{constructor(e={},t={},n={},s={},r){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=n,this.functionMap=s,this.parseNodeNameCache=r,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}newFrame(e,t){return{id:e,frameName:t,iterationId:0}}set currentContext(e){this.contexts!==e&&(this.contexts=e,this.generateCurrentContextIds())}get currentContext(){return this.contexts}get currentContextId(){return this._currentContextIds[0]}get currentContextIds(){return this._currentContextIds}generateCurrentContextIds(){const e=[];for(let t=0;t<this.contexts.length-1;t++){const n=this.contexts.slice(0,this.contexts.length-t);e.push(this.contextIdforContexts(n))}e.push(""),this._currentContextIds=e}contextIdforContexts(e){return e?e.map((e=>0===e.id&&0===e.iterationId?"":`${e.frameName}-${e.iterationId}`)).join("/"):""}enterFrame(e){this.contexts&&(this.lastId++,this.contexts=this.contexts.slice(),this.contexts.push(this.newFrame(this.lastId,e)),this._currentContextIds.unshift(this.contextIdforContexts(this.contexts)))}exitFrame(){if(!(this.contexts&&this.contexts.length>1))throw new Error("Cannot exit frame, the context is empty");this.contexts=this.contexts.slice(),this.contexts.splice(-1),this.currentContextIds.shift()}nextIteration(){if(!(this.contexts&&this.contexts.length>0))throw new Error("Cannot increase frame iteration, the context is empty");{this.contexts=this.contexts.slice(),this.lastId++;const e=Object.assign({},this.contexts[this.contexts.length-1]);e.iterationId+=1,e.id=this.lastId,this.contexts.splice(-1,1,e),this._currentContextIds.splice(0,1,this.contextIdforContexts(this.contexts))}}getWeight(e){return this.weightMap[e]}addTensorArray(e){this.tensorArrayMap[e.id]=e}getTensorArray(e){return this.tensorArrayMap[e]}addTensorList(e){this.tensorListMap[e.id]=e}getTensorList(e){return this.tensorListMap[e]}dispose(e){for(const t in this.tensorArrayMap)this.tensorArrayMap[t].clearAndClose(e);for(const t in this.tensorListMap)this.tensorListMap[t].clearAndClose(e)}}function HN(e,t,n,s){const r=new Set,a=[];let i=null,o=null;const l=new Set,u=new Set(Object.keys(e).map((e=>Kk(e)[0])));s=s||[];const c=new Set(s.map((e=>Kk(e.name)[0]))),h=[...t];for(;h.length>0;){const e=h.pop();(ZN(e)||JN(e)||QN(e))&&null==i&&(i=e,o=i.children.map((e=>e.name)).filter((e=>r.has(e)))),r.add(e.name),null==n[e.name]&&(u.has(e.name)||c.has(e.name)||(0!==e.inputs.length?e.inputs.forEach((e=>{l.has(e.name)||(l.add(e.name),h.push(e))})):a.push(e.name)))}return{inputs:e,outputs:t,usedNodes:r,missingInputs:a,dynamicNode:i,syncInputs:o}}function jN(e,t){const{usedNodes:n,inputs:s}=t,r=Object.keys(s).map((e=>Kk(e)[0])).map((t=>e.nodes[t])),a=e.initNodes||[],i=e=>n.has("string"==typeof e?e:e.name);function o(e){return[...new Map(e.map((e=>[e.name,e]))).values()]}const l=o([...r,...e.weights,...a]).filter(i),u=o([...l,...Object.values(e.nodes)]).filter(i),c=new Map(u.map((e=>[e.name,e]))),h={};for(const e of u){h[e.name]=h[e.name]||0;for(const t of e.children)i(t)||(h[t.name]=Number.POSITIVE_INFINITY),h[t.name]=(h[t.name]||0)+1}const p=Object.entries(h).filter((([,e])=>0===e)).map((([e])=>e)),d=[...p];for(;p.length>0;){const e=p.pop(),t=c.get(e);for(const e of t.children.filter(i))0==--h[e.name]&&(d.push(e.name),p.push(e.name))}const f=function(e,t){const n=new Map(e.map((e=>[e.name,e]))),s=t.map((e=>e.name)),r=new Set(s);for(;s.length>0;){const e=s.pop(),t=n.get(e);for(const e of t.children)n.has(e.name)&&!r.has(e.name)&&(r.add(e.name),s.push(e.name))}return e.filter((e=>r.has(e.name)))}(d.map((e=>c.get(e))),l);return function(e,t){const n=new Map(e.map(((e,t)=>[e.name,t]))),s=new Set(t.map((e=>e.name))),r=e=>s.has("string"==typeof e?e:e.name),a=new Set(e.map((e=>e.name))),i=e=>a.has("string"==typeof e?e:e.name);for(const t of e){for(const e of t.children.filter(i)){if(!n.has(e.name))throw new qN(`Child ${e.name} of node ${t.name} is unreachable.`);if(n.get(t.name)>n.get(e.name))throw new qN(`Node ${t.name} is scheduled to run after its child ${e.name}.`)}if(!r(t))for(const e of t.inputs){if(!n.has(e.name))throw new qN(`Input ${e.name} of node ${t.name} is unreachable.`);if(n.get(e.name)>n.get(t.name))throw new qN(`Node ${t.name} is scheduled to run before its input ${e.name}.`)}}}(f,l),f}class qN extends Error{constructor(e){super(`NodesExecutionOrderError: ${e}`)}}const KN=new Set(["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"]),XN=new Set(["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"]),YN=new Set(["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"]);function ZN(e){return KN.has(e.op)}function JN(e){return XN.has(e.op)}function QN(e){return YN.has(e.op)}class eI{get weightIds(){return this.parent?this.parent.weightIds:this._weightIds}get functionExecutorMap(){return this.parent?this.parent.functionExecutorMap:this._functionExecutorMap}get weightMap(){return this.parent?this.parent.weightMap:this._weightMap}set weightMap(e){const t=Object.keys(e).map((t=>e[t].map((e=>e.id))));this._weightIds=[].concat(...t),this._weightMap=e}set resourceManager(e){this._resourceManager=e}get inputs(){return this._inputs.map((e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0})))}get outputs(){return this._outputs.map((e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0})))}get inputNodes(){return this._inputs.map((e=>e.signatureKey||e.name))}get outputNodes(){return this._outputs.map((e=>{const t=e.signatureKey||e.name;return e.defaultOutput?`${t}:${e.defaultOutput}`:t}))}get functions(){return Object.keys(this._functions).reduce(((e,t)=>(e[t]=this._functions[t].signature,e)),{})}constructor(e,t){this.graph=e,this.parent=t,this.compiledMap=new Map,this.parseNodeNameCache=new Map,this._weightMap={},this.SEPARATOR=",",this._functions={},this._functionExecutorMap={},this.keepIntermediateTensors=!1,this._outputs=e.outputs,this._inputs=e.inputs,this._initNodes=e.initNodes,this._signature=e.signature,this._functions=e.functions,null!=e.functions&&Object.keys(e.functions).forEach((t=>{this._functionExecutorMap[t]=new eI(e.functions[t],this)}))}getCompilationKey(e,t){const n=e.map((e=>e.name)).sort(),s=t.map((e=>e.name)).sort();return n.join(this.SEPARATOR)+"--"+s.join(this.SEPARATOR)}compile(e,t){const n=HN(e,t,this.weightMap,this._initNodes),{missingInputs:s,dynamicNode:r,syncInputs:a}=n;if(null!=r)throw new Error(`This execution contains the node '${r.name}', which has the dynamic op '${r.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${a}]`);if(s.length>0){const n=t.map((e=>e.name)),r=Object.keys(e);throw new Error(`Cannot compute the outputs [${n}] from the provided inputs [${r}]. Missing the following inputs: [${s}]`)}const i=jN(this.graph,n),o=function(e){const t=new Map(e.map(((e,t)=>[e.name,t]))),n=Number.MAX_SAFE_INTEGER,s=e.map(((e,t)=>ZN(e)?n:t)),r=e=>{const n=s[t.get(e.name)];return null==n?-1:n},a=e.map(((e,t)=>e.children.map(r).reduce(((e,t)=>Math.max(e,t)),s[t]))),i=new Map;for(let t=0;t<e.length;++t){const s=a[t];if(s===n)continue;const r=e[t],o=e[s];i.has(o.name)||i.set(o.name,[]),i.get(o.name).push(r)}return i}(i);return{orderedNodes:i,nodeLiveUntilMap:o}}cloneAndKeepTensor(e){if(null==e)return null;const t=e.clone();return Sa(t),t}cloneTensorList(e){if(!e)return null;const t=e.map((e=>this.cloneAndKeepTensor(e)));return t}cloneTensorMap(e){return Object.fromEntries(Object.entries(e).map((([e,t])=>[e,this.cloneTensorList(t)])))}execute(e,t){this.disposeIntermediateTensors(),e=this.mapInputs(e);const n=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t);const s=n.map((e=>this.graph.nodes[Kk(e)[0]])),r=t.map((e=>Kk(e)[0])),a=new Set(r);let i=r.map((e=>this.graph.nodes[e]));0===i.length&&(i=this._outputs);const o=this.getCompilationKey(s,i);let l=this.compiledMap.get(o);null==l&&(l=this.compile(e,i),this.compiledMap.set(o,l));try{this.keepIntermediateTensors=Y().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(e){this.keepIntermediateTensors=!1,console.warn(e.message)}const u={},c={};return Na((()=>{const n=new GN(this.weightMap,u,c,this.functionExecutorMap,this.parseNodeNameCache),s=Object.assign({},this.weightMap);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap)),Object.keys(e).forEach((t=>{const[r,a]=Kk(t,n),i=[];i[a]=e[t],s[r]=i,this.keepIntermediateTensors&&(this.clonedTensorsMap[r]=this.cloneTensorList(i))}));const r=this.getFrozenTensorIds(s),{orderedNodes:i,nodeLiveUntilMap:o}=l;for(const e of i){if(s[e.name])continue;const t=UN(e,s,n,this._resourceManager);if(j(t))throw new Error(`The execution of the op '${e.op}' returned a promise. Please use model.executeAsync() instead.`);s[e.name]=t,this.keepIntermediateTensors&&(this.clonedTensorsMap[e.name]=this.cloneTensorList(t)),this.checkTensorForDisposalWithNodeLiveUntilInfo(e,s,n,r,a,o.get(e.name))}return null==this.parent&&n.dispose(r),t.map((e=>Gk(e,s,n)))}))}getFrozenTensorIds(e){const t=[].concat.apply([],Object.keys(e).map((t=>e[t])).map((e=>e.map((e=>e.id)))));return new Set(t)}checkTensorForDisposal(e,t,n,s,r,a,i){if(!ZN(t)&&!a.has(e)){for(const s of n[e])null!=s&&(i[s.id]=(i[s.id]||0)+t.children.length);for(const e of t.inputs){if(ZN(e))continue;const t=Hk(e.name,n,s);if(null!=t)for(const e of t){if(!e||e.kept||r.has(e.id))continue;const t=i[e.id];1===t?(e.dispose(),delete i[e.id]):null!=t&&i[e.id]--}}}}checkTensorForDisposalWithNodeLiveUntilInfo(e,t,n,s,r,a){function i(e){return ZN(e)||r.has(e.name)}if(!ZN(e)&&null!=a)for(const e of a){if(i(e))continue;const r=Hk(e.name,t,n);for(const e of r)!e||e.kept||s.has(e.id)||e.dispose()}}async executeAsync(e,t){return this._executeAsync(e,t)}disposeIntermediateTensors(){this.clonedTensorsMap&&(Object.values(this.clonedTensorsMap).forEach((e=>{for(const t of e)t&&!t.isDisposed&&t.dispose()})),this.clonedTensorsMap=null)}getIntermediateTensors(){return this.clonedTensorsMap}async _executeAsync(e,t,n=!1,s={},r={}){this.disposeIntermediateTensors(),n||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));try{this.keepIntermediateTensors=Y().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(e){this.keepIntermediateTensors=!1,console.warn(e.message)}const a=new GN(this.weightMap,s,r,this.functionExecutorMap,this.parseNodeNameCache);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap));const i=await this.executeWithControlFlow(e,a,t,n),o=t.map((e=>Gk(e,i,a))),l=o.map((e=>e.id)),u=Object.keys(e).map((t=>e[t].id)),c=new Set([...l,...u,...this.weightIds]);return Object.values(i).forEach((e=>{e.forEach((e=>{!e||e.isDisposed||c.has(e.id)||e.dispose()}))})),null==this.parent&&a.dispose(c),o}async executeFunctionAsync(e,t,n){const s=e.reduce(((e,t,n)=>(e[this.inputs[n].name]=t,e)),{});return this._executeAsync(s,this.outputNodes,!0,t,n)}async executeWithControlFlow(e,t,n,s){const r=Object.keys(e),a=r.map((e=>this.graph.nodes[Kk(e)[0]])),i=n.map((e=>Kk(e)[0])),o=new Set(i);let l=i.map((e=>this.graph.nodes[e]));0===l.length&&(l=this._outputs);const{usedNodes:u,missingInputs:c,dynamicNode:h,syncInputs:p}=HN(e,l,this.weightMap,this._initNodes),d=[...a,...this.graph.weights,...this._initNodes||[]].map((e=>({node:e,contexts:t.currentContext}))),f=Object.assign({},this.weightMap);Object.keys(e).forEach((t=>{const[n,s]=Kk(t),r=[];r[s]=e[t],f[n]=r}));const m={},g=this.getFrozenTensorIds(f),y={};for(;d.length>0;){const e=this.processStack(a,d,t,f,y,g,o,m,u);await Promise.all(e)}null!=h||s||console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");const b=l.filter((e=>!ZN(e)&&!Gk(e.name,f,t))).map((e=>e.name));if(b.length>0){let e="";throw null!=h&&(e=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${p}]`),new Error(`Cannot compute the outputs [${b}] from the provided inputs [${r}]. Consider providing the following inputs: [${c}]. ${e}`)}return f}processStack(e,t,n,s,r,a,i,o,l){const u=[];for(;t.length>0;){const e=t.pop();n.currentContext=e.contexts;let c="";if("Enter"===e.node.op&&Uk("isConstant",e.node,s,n)&&([c]=jk(e.node.name,n)),null==s[e.node.name]){const h=UN(e.node,s,n,this._resourceManager);c||([c]=jk(e.node.name,n));const p=n.currentContext;j(h)?u.push(h.then((u=>(s[c]=u,this.keepIntermediateTensors&&(this.clonedTensorsMap[c]=this.cloneTensorList(u)),n.currentContext=p,this.checkTensorForDisposal(c,e.node,s,n,a,i,o),this.processChildNodes(e.node,t,n,s,r,l),u)))):(s[c]=h,this.keepIntermediateTensors&&(this.clonedTensorsMap[c]=this.cloneTensorList(h)),this.checkTensorForDisposal(c,e.node,s,n,a,i,o),this.processChildNodes(e.node,t,n,s,r,l))}else this.processChildNodes(e.node,t,n,s,r,l)}return u}processChildNodes(e,t,n,s,r,a){e.children.forEach((e=>{const[i]=jk(e.name,n);!r[i]&&a.has(e.name)&&("Merge"===e.op?e.inputNames.some((e=>!!Gk(e,s,n)))&&(r[i]=!0,t.push({contexts:n.currentContext,node:e})):e.inputNames.every((e=>!!Gk(e,s,n)))&&(r[i]=!0,t.push({contexts:n.currentContext,node:e})))}))}dispose(){Object.keys(this.weightMap).forEach((e=>this.weightMap[e].forEach((e=>e.dispose()))))}checkInputShapeAndType(e){Object.keys(e).forEach((t=>{const n=e[t],[s]=Kk(t),r=this.graph.nodes[s];if(r.attrParams.shape&&r.attrParams.shape.value){const e=r.attrParams.shape.value,t=e.length===n.shape.length&&n.shape.every(((t,n)=>-1===e[n]||e[n]===t));c(t,(()=>`The shape of dict['${r.name}'] provided in model.execute(dict) must be [${e}], but was [${n.shape}]`))}r.attrParams.dtype&&r.attrParams.dtype.value&&c(n.dtype===r.attrParams.dtype.value,(()=>`The dtype of dict['${r.name}'] provided in model.execute(dict) must be ${r.attrParams.dtype.value}, but was ${n.dtype}`))}))}mapInputs(e){var t,n;const s={};for(const r in e){const a=null===(n=null===(t=this._signature)||void 0===t?void 0:t.inputs)||void 0===n?void 0:n[r];null!=a?s[a.name]=e[r]:s[r]=e[r]}return s}checkInputs(e){const t=Object.keys(e).filter((e=>{const[t]=Kk(e);return null==this.graph.nodes[t]}));if(t.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${t}] that are not part of graph`)}mapOutputs(e){return e.map((e=>{var t,n;const s=null===(n=null===(t=this._signature)||void 0===t?void 0:t.outputs)||void 0===n?void 0:n[e];return null!=s?s.name:e}),{})}checkOutputs(e){e.forEach((e=>{const[t]=Kk(e);if(!this.graph.nodes[t])throw new Error(`The output '${e}' is not found in the graph`)}))}}class tI{constructor(e={},t={}){this.hashTableNameToHandle=e,this.hashTableMap=t}addHashTable(e,t){this.hashTableNameToHandle[e]=t.handle,this.hashTableMap[t.id]=t}getHashTableHandleByName(e){return this.hashTableNameToHandle[e]}getHashTableById(e){return this.hashTableMap[e]}dispose(){for(const e in this.hashTableMap)this.hashTableMap[e].clearAndClose(),delete this.hashTableMap[e];for(const e in this.hashTableNameToHandle)this.hashTableNameToHandle[e].dispose(),delete this.hashTableNameToHandle[e]}}class nI{get modelVersion(){return this.version}get inputNodes(){return this.executor.inputNodes}get outputNodes(){return this.executor.outputNodes}get inputs(){return this.executor.inputs}get outputs(){return this.executor.outputs}get weights(){return this.executor.weightMap}get metadata(){return this.artifacts.userDefinedMetadata}get modelSignature(){return this.signature}get modelStructuredOutputKeys(){return this.structuredOutputKeys}constructor(e,t={},n=kd){this.modelUrl=e,this.loadOptions=t,this.version="n/a",this.io=n,null==t&&(this.loadOptions={}),this.resourceManager=new tI}findIOHandler(){const e=this.modelUrl;if(null!=e.load)this.handler=e;else if(null!=this.loadOptions.requestInit)this.handler=this.io.browserHTTPRequest(e,this.loadOptions);else{const t=this.io.getLoadHandlers(e,this.loadOptions);if(0===t.length)t.push(this.io.browserHTTPRequest(e,this.loadOptions));else if(t.length>1)throw new Error(`Found more than one (${t.length}) load handlers for URL '${[e]}'`);this.handler=t[0]}}load(){if(this.findIOHandler(),null==this.handler.load)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");const e=this.handler.load();return j(e)?e.then((e=>null==e.getWeightStream?this.loadSync(e):this.loadStreaming(e))):this.loadSync(e)}loadSync(e){const t=this.io.decodeWeights(e.weightData,e.weightSpecs);return this.loadWithWeightMap(e,t)}async loadStreaming(e){if(null==e.getWeightStream)throw new Error("Model artifacts missing streamWeights function");const t=await Ma(e.getWeightStream(),e.weightSpecs);return this.loadWithWeightMap(e,t)}loadWithWeightMap(e,t){this.artifacts=e;const n=this.artifacts.modelTopology;let s=this.artifacts.signature;if(null!=this.artifacts.userDefinedMetadata){const e=this.artifacts.userDefinedMetadata;null!=e.signature&&(s=e.signature),null!=e.structuredOutputKeys&&(this.structuredOutputKeys=e.structuredOutputKeys)}if(this.signature=s,this.version=`${n.versions.producer}.${n.versions.minConsumer}`,this.executor=new eI(gN.Instance.transformGraph(n,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(t),this.executor.resourceManager=this.resourceManager,null!=e.modelInitializer&&null!=e.modelInitializer.node){const t=gN.Instance.transformGraph(e.modelInitializer);this.initializer=new eI(t),this.initializer.weightMap=this.executor.weightMap,this.initializer.resourceManager=this.resourceManager,this.initializerSignature=e.initializerSignature}return!0}async save(e,t){if("string"==typeof e){const t=this.io.getSaveHandlers(e);if(0===t.length)throw new Error(`Cannot find any save handlers for URL '${e}'`);if(t.length>1)throw new Error(`Found more than one (${t.length}) save handlers for URL '${e}'`);e=t[0]}if(null==e.save)throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return e.save(this.artifacts)}addStructuredOutputNames(e){if(this.structuredOutputKeys){const t={};return(e instanceof _r?[e]:e).forEach(((e,n)=>t[this.structuredOutputKeys[n]]=e)),t}return e}predict(e,t){const n=this.execute(e,this.outputNodes);return this.addStructuredOutputNames(n)}async predictAsync(e,t){const n=await this.executeAsync(e,this.outputNodes);return this.addStructuredOutputNames(n)}normalizeInputs(e){var t;if(!(e instanceof _r||Array.isArray(e))){const n=null===(t=this.signature)||void 0===t?void 0:t.inputs;if(null!=n)for(const t in n){const s=n[t];null!=s.resourceId&&(e[t]=this.resourceIdToCapturedInput[s.resourceId])}return e}e=Array.isArray(e)?e:[e];const n=Object.keys(this.resourceIdToCapturedInput).length;if(e.length+n!==this.inputNodes.length)throw new Error(`Input tensor count mismatch, the graph model has ${this.inputNodes.length-n} non-resource placeholders, while there are ${e.length} input tensors provided.`);let s=0;return this.inputNodes.reduce(((t,n)=>{var r,a,i;const o=null===(i=null===(a=null===(r=this.signature)||void 0===r?void 0:r.inputs)||void 0===a?void 0:a[n])||void 0===i?void 0:i.resourceId;return t[n]=null!=o?this.resourceIdToCapturedInput[o]:e[s++],t}),{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}executeInitializerGraph(){return null==this.initializer?[]:null==this.initializerSignature?this.initializer.execute({},[]):this.initializer.execute({},Object.keys(this.initializerSignature.outputs))}async executeInitializerGraphAsync(){return null==this.initializer?[]:null==this.initializerSignature?this.initializer.executeAsync({},[]):this.initializer.executeAsync({},Object.keys(this.initializerSignature.outputs))}setResourceIdToCapturedInput(e){if(this.resourceIdToCapturedInput={},this.initializerSignature){const t=this.initializerSignature.outputs,n=Object.keys(t);for(let s=0;s<n.length;s++){const r=t[n[s]];this.resourceIdToCapturedInput[r.resourceId]=e[s]}}}execute(e,t){null==this.resourceIdToCapturedInput&&this.setResourceIdToCapturedInput(this.executeInitializerGraph()),e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const n=this.executor.execute(e,t);return n.length>1?n:n[0]}async executeAsync(e,t){null==this.resourceIdToCapturedInput&&this.setResourceIdToCapturedInput(await this.executeInitializerGraphAsync()),e=this.normalizeInputs(e),t=this.normalizeOutputs(t);const n=await this.executor.executeAsync(e,t);return n.length>1?n:n[0]}getIntermediateTensors(){return this.executor.getIntermediateTensors()}disposeIntermediateTensors(){this.executor.disposeIntermediateTensors()}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce(((t,n)=>(t[n]=[e[n]],t)),{})}dispose(){this.executor.dispose(),this.initializer&&(this.initializer.dispose(),this.resourceIdToCapturedInput&&Ia(this.resourceIdToCapturedInput)),this.resourceManager.dispose()}}const sI="4.15.0";function rI(e,t,n=new Map,s=new Set){if(null==e)return null;if("function"==typeof Blob&&e instanceof Blob)return e.slice();if(s.has(e))throw new Error("Circular references are not supported.");if(n.has(e))return n.get(e);const r=t(e);if(r.recurse&&null!==r.value)throw new Error("A deep map function may not return both a value and recurse=true.");if(r.recurse){if(uI(e)){const r=Array.isArray(e)?[]:{};s.add(e);for(const a in e){const i=rI(e[a],t,n,s);r[a]=i}return s.delete(e),e.__proto__&&(r.__proto__=e.__proto__),r}throw new Error(`Can't recurse into non-iterable type: ${e}`)}return n.set(e,r.value),r.value}function aI(e,t=oI){return iI(e,t)}function iI(e,t,n=new Set){const s=e[0];if(n.has(s))throw new Error("Circular references are not supported.");const r=t(e);if(r.recurse&&null!==r.value)throw new Error("A deep zip function may not return both a value and recurse=true.");if(r.recurse){if(uI(s)){const r=Array.isArray(s)?[]:{};n.add(s);for(const a in s){const s=iI(e.map((e=>e[a])),t,n);r[a]=s}return n.delete(s),r}throw new Error(`Can't recurse into non-iterable type: ${s}`)}return r.value}function oI(e){return null===e?null:uI(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}async function lI(e,t){const n=new Map;rI(e,t,n);for(const e of Array.from(n.keys())){const t=n.get(e);if(j(t)){const s=await t;n.set(e,s)}}return rI(e,t,n)}function uI(e){let t=!1;if(Y().get("IS_BROWSER"))t=e instanceof TextDecoder;else{const{StringDecoder:n}=require("string_decoder");t=e instanceof n}return null!=e&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||"object"==typeof e&&!(e instanceof _r)&&!(e instanceof Promise)&&!t)}function cI(e){return function(e,t){return rI(e,t)}(e,hI)}function hI(e){return e instanceof _r?{value:e.clone(),recurse:!1}:uI(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}class pI{constructor(e){if(this.capacity=e,this.begin=0,this.end=0,null==e)throw new RangeError("Can't create a ring buffer of unknown capacity.");if(e<1)throw new RangeError("Can't create ring buffer of capacity < 1.");this.data=new Array(e),this.doubledCapacity=2*e}wrap(e){for(;e<0;)e+=this.doubledCapacity;return e%this.doubledCapacity}get(e){if(e<0)throw new RangeError("Can't get item at a negative index.");return this.data[e%this.capacity]}set(e,t){if(e<0)throw new RangeError("Can't set item at a negative index.");this.data[e%this.capacity]=t}length(){let e=this.end-this.begin;return e<0&&(e=this.doubledCapacity+e),e}isFull(){return this.length()===this.capacity}isEmpty(){return 0===this.length()}push(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.set(this.end,e),this.end=this.wrap(this.end+1)}pushAll(e){for(const t of e)this.push(t)}pop(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");this.end=this.wrap(this.end-1);const e=this.get(this.end);return this.set(this.end,void 0),e}unshift(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.begin=this.wrap(this.begin-1),this.set(this.begin,e)}shift(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");const e=this.get(this.begin);return this.set(this.begin,void 0),this.begin=this.wrap(this.begin+1),e}shuffleExcise(e){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");const t=this.wrap(this.begin+e),n=this.get(t);return this.set(t,this.pop()),n}}class dI extends pI{constructor(){super(dI.INITIAL_CAPACITY)}isFull(){return!1}push(e){super.isFull()&&this.expand(),super.push(e)}unshift(e){super.isFull()&&this.expand(),super.unshift(e)}expand(){const e=2*this.capacity,t=new Array(e),n=this.length();for(let e=0;e<n;e++)t[e]=this.get(this.wrap(this.begin+e));this.data=t,this.capacity=e,this.doubledCapacity=2*this.capacity,this.begin=0,this.end=n}}function fI(e){return new bI(e)}function mI(e){return new xI(e)}function gI(e,t){return new AI(e,t)}dI.INITIAL_CAPACITY=32;class yI{async toArray(){const e=[];let t=await this.next();for(;!t.done;)e.push(t.value),t=await this.next();return e}async toArrayForTest(){const e=this.prefetch(100),t=[];let n=await e.next();for(;!n.done;)t.push(n.value),n=await e.next();return t}async resolveFully(){let e=await this.next();for(;!e.done;)e=await this.next()}async resolveWhile(e){let t=await this.next(),n=e(t.value);for(;!t.done&&n;)t=await this.next(),n=e(t.value)}handleErrors(e){return new TI(this,e)}filter(e){return new II(this,e)}map(e){return new SI(this,e)}mapAsync(e){return new CI(this,e)}serialMapAsync(e){return new CI(this,e).serial()}flatmap(e){return new EI(this,e)}async forEachAsync(e){return this.map(e).resolveFully()}async serialForEach(e){return this.serialMapAsync(e).resolveWhile((e=>!0===e))}rowMajorBatch(e,t=!0){return new NI(this,e,t)}columnMajorBatch(e,t=!0,n=oI){return this.rowMajorBatch(e,t).map((e=>aI(e,n)))}concatenate(e,t){return new AI(fI([this,e]),t)}take(e){return e<0||null==e?this:new kI(this,e)}skip(e){return e<0||null==e?this:new vI(this,e)}prefetch(e){return new FI(this,e)}shuffle(e,t){return new DI(this,e,t)}serial(){return new wI(this)}}class bI extends yI{constructor(e){super(),this.items=e,this.trav=0}summary(){return`Array of ${this.items.length} items`}async next(){if(this.trav>=this.items.length)return{value:null,done:!0};const e=this.items[this.trav];return this.trav++,{value:cI(e),done:!1}}}class xI extends yI{constructor(e){super(),this.nextFn=e}summary(){return"Function call"}async next(){try{return this.nextFn()}catch(e){throw e.message=`Error thrown while iterating through a dataset: ${e.message}`,e}}}class wI extends yI{constructor(e){super(),this.upstream=e,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Serial`}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){return this.upstream.next()}}class vI extends yI{constructor(e,t){super(),this.upstream=e,this.maxCount=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Skip`}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){for(;this.count++<this.maxCount;){const e=await this.upstream.next();if(e.done)return e;Ia(e.value)}return this.upstream.next()}}class kI extends yI{constructor(e,t){super(),this.upstream=e,this.maxCount=t,this.count=0}summary(){return`${this.upstream.summary()} -> Take`}async next(){return this.count++>=this.maxCount?{value:null,done:!0}:this.upstream.next()}}class NI extends yI{constructor(e,t,n=!0){super(),this.upstream=e,this.batchSize=t,this.enableSmallLastBatch=n,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> RowMajorBatch`}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){const e=[];for(;e.length<this.batchSize;){const t=await this.upstream.next();if(t.done)return this.enableSmallLastBatch&&e.length>0?{value:e,done:!1}:{value:null,done:!0};e.push(t.value)}return{value:e,done:!1}}}class II extends yI{constructor(e,t){super(),this.upstream=e,this.predicate=t,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Filter`}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){for(;;){const e=await this.upstream.next();if(e.done||this.predicate(e.value))return e;Ia(e.value)}}}class SI extends yI{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Map`}async next(){const e=await this.upstream.next();if(e.done)return{value:null,done:!0};const t=Kr(e.value),n=this.transform(e.value),s=Kr(n);for(const e of t)qr(e,s)||e.dispose();return{value:n,done:!1}}}class TI extends yI{constructor(e,t){super(),this.upstream=e,this.handler=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> handleErrors`}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){for(;;)try{return await this.upstream.next()}catch(e){if(!this.handler(e))return{value:null,done:!0}}}}class CI extends yI{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> AsyncMap`}async next(){const e=await this.upstream.next();if(e.done)return{value:null,done:!0};const t=Kr(e.value),n=await this.transform(e.value),s=Kr(n);for(const e of t)qr(e,s)||e.dispose();return{value:n,done:!1}}}class $I extends yI{constructor(){super(),this.outputQueue=new dI,this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}async serialNext(){for(;0===this.outputQueue.length();)if(!await this.pump())return{value:null,done:!0};return{value:this.outputQueue.shift(),done:!1}}}class EI extends $I{constructor(e,t){super(),this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Flatmap`}async pump(){const e=await this.upstream.next();if(e.done)return!1;const t=Kr(e.value),n=this.transform(e.value),s=Kr(n);this.outputQueue.pushAll(n);for(const e of t)qr(e,s)||e.dispose();return!0}}class AI extends yI{constructor(e,t){super(),this.baseErrorHandler=t,this.lastRead=null,this.iterator=null,this.moreIterators=e}summary(){return"TODO: fill in upstream of chained summaries -> Chained"}async next(){return this.lastRead=this.readFromChain(this.lastRead),this.lastRead}async readFromChain(e){if(await e,null==this.iterator){const e=await this.moreIterators.next();if(e.done)return{value:null,done:!0};this.iterator=e.value,null!=this.baseErrorHandler&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler))}const t=await this.iterator.next();return t.done?(this.iterator=null,this.readFromChain(e)):t}}var RI;!function(e){e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST"}(RI||(RI={}));class _I extends yI{constructor(e,t=RI.FAIL){super(),this.iterators=e,this.mismatchMode=t,this.count=0,this.currentPromise=null}summary(){return"{TODO: fill in upstream of zip summaries} -> Zip"}async nextState(e){await e;let t=0,n=0;const s=await lI(this.iterators,(function(e){if(e instanceof yI){return{value:e.next().then((e=>(t++,e.done&&n++,e.value))),recurse:!1}}return{value:null,recurse:!0}}));if(t===n)return{value:null,done:!0};if(n>0)switch(this.mismatchMode){case RI.FAIL:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case RI.SHORTEST:return{value:null,done:!0};case RI.LONGEST:}return this.count++,{value:s,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}}class FI extends yI{constructor(e,t){super(),this.upstream=e,this.bufferSize=t,this.buffer=new pI(t)}summary(){return`${this.upstream.summary()} -> Prefetch`}refill(){for(;!this.buffer.isFull();){const e=this.upstream.next();this.buffer.push(e)}}next(){return this.refill(),this.buffer.shift()}}class DI extends FI{constructor(e,t,n){super(e,t),this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=ic.alea(n||dr().toString()),this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then((()=>this.serialNext())),this.lastRead}randomInt(e){return Math.floor(this.random()*e)}chooseIndex(){return this.randomInt(this.buffer.length())}async serialNext(){for(this.upstreamExhausted||this.refill();!this.buffer.isEmpty();){const e=this.chooseIndex(),t=await this.buffer.shuffleExcise(e);if(!t.done)return this.refill(),t;this.upstreamExhausted=!0}return{value:null,done:!0}}}class OI{constructor(){this.size=null}batch(e,t=!0){const n=this;let s;return c(e>0,(()=>`batchSize needs to be positive, but it is\n      ${e}`)),s=this.size===1/0||null==this.size?this.size:t?Math.ceil(this.size/e):Math.floor(this.size/e),MI((async()=>(await n.iterator()).columnMajorBatch(e,t,LI)),s)}concatenate(e){const t=this;let n;return n=this.size===1/0||e.size===1/0?1/0:null!=this.size&&null!=e.size?this.size+e.size:null,MI((async()=>(await t.iterator()).concatenate(await e.iterator())),n)}filter(e){const t=this;let n;return n=this.size===1/0?1/0:null,MI((async()=>(await t.iterator()).filter((t=>Na((()=>e(t)))))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){const t=this;return MI((async()=>(await t.iterator()).map((t=>Na((()=>e(t)))))),this.size)}mapAsync(e){const t=this;return MI((async()=>(await t.iterator()).mapAsync(e)),this.size)}prefetch(e){if(null==e)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");const t=this;return MI((async()=>(await t.iterator()).prefetch(e)),this.size)}repeat(e){const t=this;let n;return n=null!=this.size&&e>0?this.size*e:0===e?0:null!=this.size&&(void 0===e||e<0)?1/0:null,MI((async()=>gI(mI((async()=>({value:await t.iterator(),done:!1}))).take(e))),n)}skip(e){const t=this;let n;return n=null!=this.size&&e>=0&&this.size>=e?this.size-e:null!=this.size&&(this.size<e||void 0===e||e<0)?0:null,MI((async()=>(await t.iterator()).skip(e)),n)}shuffle(e,t,n=!0){if(null==e||e<0)throw null==this.size?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError(`\`Dataset.shuffle()\` requires bufferSize to be specified.  If your data fits in main memory (for regular JS objects), and/or GPU memory (for \`tf.Tensor\`s), consider setting bufferSize to the dataset size (${this.size} elements)`);const s=this,r=ic.alea(t||dr().toString());return MI((async()=>{let t=r.int32();return n&&(t+=r.int32()),(await s.iterator()).shuffle(e,t.toString())}),this.size)}take(e){const t=this;let n;return n=null!=this.size&&this.size>e?e:null!=this.size&&this.size<=e?this.size:null,MI((async()=>(await t.iterator()).take(e)),n)}async toArray(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArray()}async toArrayForTest(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArrayForTest()}}function MI(e,t=null){return new class extends OI{constructor(){super(...arguments),this.size=t}async iterator(){return e()}}}function LI(e){if(null===e)return null;const t=e[0];if(null==(n=t)||null===(s=n)||"object"!=typeof s&&"function"!=typeof s||Array.isArray(n)||"object"==typeof n&&n instanceof _r||yr(n)){return{value:function(e){if(0===e.length)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof _r?Yc(e):ya(e)}(e),recurse:!1}}var n,s;return{value:null,recurse:!0}}OI.MAX_BUFFER_SIZE=1e4;class zI extends OI{constructor(e){super(),this.input=e}async iterator(){return(await this.input.iterator()).decodeUTF8().split("\n").map((e=>(e.endsWith("\r")&&(e=e.slice(0,-1)),e)))}}const PI='"',BI=Symbol("out"),WI=Symbol("field"),VI=Symbol("quote"),UI=Symbol("quoteafterquote"),GI=Symbol("quoteinquote");class HI extends OI{async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){const e=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&e&&c(e.length===this.fullColumnNames.length,(()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+").")),this.fullColumnNames||(this.fullColumnNames=e);const t=this.fullColumnNames.reduce(((e,t)=>(e[t]=e[t]+1||1,e)),{}),n=Object.keys(t).filter((e=>t[e]>1));if(c(0===n.length,(()=>"Duplicate column names found: "+n.toString())),this.columnConfigs)for(const e of Object.keys(this.columnConfigs)){if(-1===this.fullColumnNames.indexOf(e))throw new Error('The key "'+e+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){const e=await this.base.iterator(),t=await e.next();if(t.done)throw new Error("No data was found for CSV parsing.");const n=t.value;return this.parseRow(n,!1)}return null}constructor(e,t){super(),this.input=e,this.hasHeader=!0,this.fullColumnNames=null,this.columnNamesValidated=!1,this.columnConfigs=null,this.configuredColumnsOnly=!1,this.delimiter=",",this.delimWhitespace=!1,this.base=new zI(e),t||(t={}),this.hasHeader=!1!==t.hasHeader,this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(c(null==t.delimiter,(()=>"Delimiter should not be provided when delimWhitespace is true.")),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=t.delimiter?t.delimiter:","}async iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map((e=>this.makeDataElement(e)))}makeDataElement(e){const t=this.parseRow(e),n={},s={};for(let r=0;r<this.fullColumnNames.length;r++){const a=this.fullColumnNames[r],i=this.columnConfigs?this.columnConfigs[a]:null;if(!this.configuredColumnsOnly||i){const o=t[r];let l=null;if(""===o)if(i&&void 0!==i.default)l=i.default;else{if(i&&(i.required||i.isLabel))throw new Error(`Required column ${a} is empty in this line: ${e}`);l=void 0}else{const e=Number(o);if(isNaN(e))l=i&&"bool"===i.dtype?this.getBoolean(o):o;else if(i&&i.dtype)switch(i.dtype){case"float32":default:l=e;break;case"int32":l=Math.floor(e);break;case"bool":l=this.getBoolean(o)}else l=e}i&&i.isLabel?s[a]=l:n[a]=l}}return 0===Object.keys(s).length?n:{xs:n,ys:s}}getBoolean(e){return"1"===e||"true"===e.toLowerCase()?1:0}parseRow(e,t=!0){const n=[];let s=0;const r=e.length;let a=BI;for(let t=0;t<r;t++)switch(a){case BI:switch(e.charAt(t)){case PI:s=t+1,a=VI;break;case this.delimiter:if(s=t+1," "===this.delimiter&&this.delimWhitespace)break;n.push(""),a=BI;break;default:a=WI,s=t}break;case WI:if(e.charAt(t)===this.delimiter)n.push(e.substring(s,t)),a=BI,s=t+1;break;case VI:if(e.charAt(t)===PI)a=UI;break;case UI:switch(e.charAt(t)){case this.delimiter:n.push(e.substring(s,t-1)),a=BI,s=t+1;break;case PI:a=VI;break;default:a=GI}break;case GI:if(e.charAt(t)===PI)a=VI}if(a===UI?n.push(e.substring(s,r-1)):n.push(e.substring(s)),t&&n.length!==this.fullColumnNames.length)throw new Error(`Invalid row in csv file. Should have ${this.fullColumnNames.length} elements in a row, but got ${n}`);return n}}class jI extends yI{constructor(e){super(),this.microphoneConfig=e,this.isClosed=!1,this.fftSize=e.fftSize||1024;const t=Math.log2(this.fftSize);if(this.fftSize<0||t<4||t>14||!Number.isInteger(t))throw new Error(`Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got ${this.fftSize}`);if(this.numFrames=e.numFramesPerSpectrogram||43,this.sampleRateHz=e.sampleRateHz,this.columnTruncateLength=e.columnTruncateLength||this.fftSize,this.audioTrackConstraints=e.audioTrackConstraints,this.smoothingTimeConstant=e.smoothingTimeConstant||0,this.includeSpectrogram=!1!==e.includeSpectrogram,this.includeWaveform=!0===e.includeWaveform,!this.includeSpectrogram&&!this.includeWaveform)throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.")}summary(){return"microphone"}static async create(e={}){if(!Y().get("IS_BROWSER"))throw new Error("microphone API is only supported in browser environment.");const t=new jI(e);return await t.start(),t}async start(){try{this.stream=await navigator.mediaDevices.getUserMedia({audio:null==this.audioTrackConstraints||this.audioTrackConstraints,video:!1})}catch(e){throw new Error(`Error thrown while initializing video stream: ${e.message}`)}if(!this.stream)throw new Error("Could not obtain audio from microphone.");const e=window.AudioContext||window.webkitAudioContext;if(this.audioContext=new e,this.sampleRateHz){if(this.audioContext.sampleRate!==this.sampleRateHz)throw new Error(`Mismatch in sampling rate: Expected: ${this.sampleRateHz}; Actual: ${this.audioContext.sampleRate}`)}else this.sampleRateHz=this.audioContext.sampleRate;const t=this.audioContext.createMediaStreamSource(this.stream);this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=2*this.fftSize,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,t.connect(this.analyser),this.freqData=new Float32Array(this.fftSize),this.timeData=new Float32Array(this.fftSize)}async next(){if(this.isClosed)return{value:null,done:!0};let e,t;const n=await this.getAudioData();if(this.includeSpectrogram){const t=this.flattenQueue(n.freqDataQueue);e=this.getTensorFromAudioDataArray(t,[this.numFrames,this.columnTruncateLength,1])}if(this.includeWaveform){const e=this.flattenQueue(n.timeDataQueue);t=this.getTensorFromAudioDataArray(e,[this.numFrames*this.fftSize,1])}return{value:{spectrogram:e,waveform:t},done:!1}}async capture(){return(await this.next()).value}async getAudioData(){const e=[],t=[];let n=0;return new Promise((s=>{const r=setInterval((()=>{this.includeSpectrogram&&(this.analyser.getFloatFrequencyData(this.freqData),this.freqData[0]===-1/0&&s({freqDataQueue:e,timeDataQueue:t}),e.push(this.freqData.slice(0,this.columnTruncateLength))),this.includeWaveform&&(this.analyser.getFloatTimeDomainData(this.timeData),t.push(this.timeData.slice())),++n===this.numFrames&&(clearInterval(r),s({freqDataQueue:e,timeDataQueue:t}))}),this.fftSize/this.sampleRateHz*1e3)}))}stop(){this.isClosed||(this.isClosed=!0,this.analyser.disconnect(),this.audioContext.close(),null!=this.stream&&this.stream.getTracks().length>0&&this.stream.getTracks()[0].stop())}toArray(){throw new Error("Can not convert infinite audio stream to array.")}getSampleRate(){return this.sampleRateHz}flattenQueue(e){const t=e[0].length,n=new Float32Array(e.length*t);return e.forEach(((e,s)=>n.set(e,s*t))),n}getTensorFromAudioDataArray(e,t){const n=new Float32Array(d(t));return n.set(e,n.length-e.length),ya(n,t)}}class qI extends yI{constructor(e,t){if(super(),this.webcamVideoElement=e,this.webcamConfig=t,this.isClosed=!0,this.resize=!1,this.needToResize())if(this.resize=!0,this.cropSize=[this.webcamConfig.resizeHeight,this.webcamConfig.resizeWidth],this.cropBoxInd=eh([0],"int32"),this.webcamConfig.centerCrop){const e=1*this.webcamConfig.resizeWidth/this.webcamVideoElement.width,t=1*this.webcamConfig.resizeHeight/this.webcamVideoElement.height,n=(1-e)/2,s=(1-t)/2,r=n+e,a=t+s;this.cropBox=th([s,n,a,r],[1,4])}else this.cropBox=th([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(!Y().get("IS_BROWSER"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!e){if(e=document.createElement("video"),!t.resizeWidth||!t.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");e.width=t.resizeWidth,e.height=t.resizeHeight}const n=new qI(e,t);return await n.start(),n}async start(){this.webcamConfig.facingMode&&c("user"===this.webcamConfig.facingMode||"environment"===this.webcamConfig.facingMode,(()=>`Invalid webcam facing mode: ${this.webcamConfig.facingMode}. Please provide 'user' or 'environment'`));try{this.stream=await navigator.mediaDevices.getUserMedia({video:{deviceId:this.webcamConfig.deviceId,facingMode:this.webcamConfig.facingMode?this.webcamConfig.facingMode:"user",width:this.webcamVideoElement.width,height:this.webcamVideoElement.height}})}catch(e){throw e.message=`Error thrown while initializing video stream: ${e.message}`,e}if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream}catch(e){console.log(e),this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}return this.webcamVideoElement.play(),this.isClosed=!1,new Promise((e=>{this.webcamVideoElement.onloadedmetadata=()=>{e()}}))}async next(){if(this.isClosed)return{value:null,done:!0};let e;try{e=Ad(this.webcamVideoElement)}catch(e){throw new Error(`Error thrown converting video to pixels: ${JSON.stringify(e)}`)}if(!this.resize)return{value:e,done:!1};try{return{value:this.cropAndResizeFrame(e),done:!1}}catch(e){throw new Error(`Error thrown cropping the video: ${e.message}`)}finally{e.dispose()}}needToResize(){return!(!this.webcamConfig.resizeWidth||!this.webcamConfig.resizeHeight||this.webcamVideoElement.width===this.webcamConfig.resizeWidth&&this.webcamVideoElement.height===this.webcamConfig.resizeHeight)}cropAndResizeFrame(e){return Na((()=>{const t=Cl(Ti(e,"float32"),0);let n;n=Bp.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");const s=n.shape;return oo(n,s.slice(1))}))}async capture(){return(await this.next()).value}stop(){this.stream.getTracks().forEach((e=>e.stop()));try{this.webcamVideoElement.srcObject=null}catch(e){console.log(e),this.webcamVideoElement.src=null}this.isClosed=!0}toArray(){throw new Error("Can not convert infinite video stream to array.")}}class KI{}class XI extends yI{split(e){return new YI(this,e)}}class YI extends XI{constructor(e,t){super(),this.upstream=e,this.impl=new ZI(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class ZI extends $I{constructor(e,t){super(),this.upstream=e,this.separator=t,this.carryover=""}summary(){return`${this.upstream.summary()} -> Split('${this.separator}')`}async pump(){const e=await this.upstream.next();if(e.done)return""!==this.carryover&&(this.outputQueue.push(this.carryover),this.carryover="",!0);const t=e.value.split(this.separator);t[0]=this.carryover+t[0];for(const e of t.slice(0,-1))this.outputQueue.push(e);return this.carryover=t[t.length-1],!0}}class JI extends yI{decodeUTF8(){return new QI(this)}}class QI extends XI{constructor(e){super(),this.upstream=e,this.impl=new eS(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class eS extends $I{constructor(e){if(super(),this.upstream=e,Y().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{const{StringDecoder:e}=require("string_decoder");this.decoder=new e("utf8")}}summary(){return`${this.upstream.summary()} -> Utf8`}async pump(){const e=await this.upstream.next();let t,n;return!e.done&&(t=e.value,n=Y().get("IS_BROWSER")?this.decoder.decode(t,{stream:!0}):this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(n),!0)}}class tS extends JI{constructor(e,t={}){super(),this.file=e,this.options=t,c(e instanceof Uint8Array||!!Y().get("IS_BROWSER")&&(e instanceof File||e instanceof Blob),(()=>"FileChunkIterator only supports File, Blob and Uint8Array right now.")),this.offset=t.offset||0,this.chunkSize=t.chunkSize||1048576}summary(){return`FileChunks ${this.file}`}async next(){if(this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size))return{value:null,done:!0};const e=new Promise(((e,t)=>{const n=this.offset+this.chunkSize;if(this.file instanceof Uint8Array)e(new Uint8Array(this.file.slice(this.offset,n)));else{const s=new FileReader;s.onload=n=>{let r=s.result;if(r instanceof ArrayBuffer&&(r=new Uint8Array(r)),!(r instanceof Uint8Array))return t(new TypeError("FileReader returned unknown type."));e(r)},s.onabort=e=>t(new Error("Aborted")),s.onerror=e=>t(new Error(e.type));const r=this.file.slice(this.offset,n);s.readAsArrayBuffer(r)}this.offset=n}));return{value:await e,done:!1}}}const nS=e=>({method:e.method,headers:e.headers,body:e.body,mode:e.mode,credentials:e.credentials,cache:e.cache,redirect:e.redirect,referrer:e.referrer,integrity:e.integrity});function sS(e){return"string"==typeof e&&"file://"===e.slice(0,7)}class rS extends KI{constructor(e,t={}){super(),this.input=e,this.options=t}async iterator(){if(sS(this.input)&&Y().get("IS_NODE")){const e=require("fs");this.input=e.readFileSync(this.input.slice(7))}return new tS(this.input,this.options)}}class aS extends KI{constructor(e,t={}){super(),this.url=e,this.fileOptions=t}async iterator(){return sS(this.url)?new rS(this.url,this.fileOptions).iterator():async function(e,t={},n){let s,r;"string"==typeof e?s=e:(s=e.url,r=nS(e));const a=await(n||fr)(s,r);if(a.ok){const e=new Uint8Array(await a.arrayBuffer());return new tS(e,t)}throw new Error(a.statusText)}(this.url,this.fileOptions)}}const iS="4.15.0";var oS=Object.freeze({__proto__:null,CSVDataset:HI,Dataset:OI,FileDataSource:rS,TextLineDataset:zI,URLDataSource:aS,array:function(e){return MI((async()=>fI(e)),e.length)},csv:function(e,t={}){return new HI(new aS(e),t)},func:function(e){const t=mI(e);return MI((async()=>t))},generator:function(e){return MI((async()=>{const t=await e();return mI((()=>t.next()))}))},microphone:async function(e){return jI.create(e)},version_data:iS,webcam:async function(e,t){return qI.create(e,t)},zip:function(e){if(!uI(e))throw new Error("The argument to zip() must be an object or array.");let t;if(Array.isArray(e))for(let n=0;n<e.length;n++)t=null==t?e[n].size:Math.min(t,e[n].size);else if(e instanceof Object)for(const n in e)t=null==t?e[n].size:Math.min(t,e[n].size);return MI((async()=>function(e,t=RI.FAIL){return new _I(e,t)}(await lI(e,(e=>{if(e instanceof OI)return{value:e.iterator(),recurse:!1};if(uI(e))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")})),RI.SHORTEST)),t)}});function lS(e,t){Array.isArray(e)||(e=[e]),e.forEach((e=>{null!=e&&c("complex64"!==e.dtype,(()=>`${t} does not support complex64 tensors in the CPU backend.`))}))}const uS=bh;class cS extends s{nextDataId(){return cS.nextDataId++}constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new n(this,va())}write(e,t,n){this.firstUse&&(this.firstUse=!1,Y().get("IS_NODE")&&fs("\n============================\nHi, looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, visit https://github.com/tensorflow/tfjs-node for more details. \n============================"));const s={id:this.nextDataId()};return this.data.set(s,{values:e,dtype:n,refCount:1}),s}makeTensorInfo(e,t,n){let s;if("string"===t&&null!=n&&n.length>0&&A(n[0])){const r=n.map((e=>mr(e)));s=this.write(r,e,t)}else s=this.write(n,e,t);return{dataId:s,shape:e,dtype:t}}refCount(e){if(this.data.has(e)){return this.data.get(e).refCount}return 0}incRef(e){this.data.get(e).refCount++}decRef(e){if(this.data.has(e)){this.data.get(e).refCount--}}move(e,t,n,s,r){this.data.set(e,{values:t,dtype:s,refCount:r})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){const{dtype:t,complexTensorInfos:n}=this.data.get(e);if("complex64"===t){return If(this.readSync(n.real.dataId),this.readSync(n.imag.dataId))}return P(this.data.get(e).values,t)}bufferSync(e){const t=this.readSync(e.dataId);if("string"===e.dtype)try{const n=t.map((e=>gr(e)));return Si(e.shape,e.dtype,n)}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return Si(e.shape,e.dtype,t)}makeOutput(e,t,n){return va().makeTensorFromTensorInfo(this.makeTensorInfo(t,n,e),this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;const{complexTensorInfos:n}=this.data.get(e);null!=n&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){const t=dr();e();return{kernelMs:dr()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){lS([e],"where");const t=this.readSync(e.dataId);return uS(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}}function hS(e){const t=new Float32Array(e.length);for(let n=0;n<e.length;++n)t[n]=Math.abs(e[n]);return t}cS.nextDataId=0;const pS={kernelName:ee,backendName:"cpu",kernelFunc:e=>{const{x:t}=e.inputs,n=e.backend;lS(t,"abs");let s=new Float32Array(d(t.shape));return s=hS(n.data.get(t.dataId).values),n.makeOutput(s,t.shape,t.dtype)}};function dS(e){return(t,n,s,r,a)=>{const i=Zo(t,n),o=i.length,l=M(i),u=N(a,d(i)),c=t.length,h=n.length,p=M(t),f=M(n),m=Xo(t,i),g=Xo(n,i);if(m.length+g.length===0)for(let t=0;t<u.length;++t)u[t]=e(s[t%s.length],r[t%r.length]);else for(let t=0;t<u.length;++t){const n=H(t,o,l),a=n.slice(-c);m.forEach((e=>a[e]=0));const i=G(a,c,p),d=n.slice(-h);g.forEach((e=>d[e]=0));const y=G(d,h,f);u[t]=e(s[i],r[y])}return[u,i]}}function fS(e){const{inputs:t,backend:n}=e,{real:s,imag:r}=t,a=n.data.get(s.dataId).values,i=n.data.get(r.dataId).values,o=n.makeTensorInfo(s.shape,"complex64");return n.data.get(o.dataId).complexTensorInfos={real:n.makeTensorInfo(s.shape,"float32",a),imag:n.makeTensorInfo(r.shape,"float32",i)},o}const mS={kernelName:Ce,backendName:"cpu",kernelFunc:fS};function gS(e,t,n="float32"){if("complex64"===n){return fS({inputs:{real:gS(e,t,"float32"),imag:gS(e,t,"float32")},backend:e})}const s=W(d(t),n);return e.makeTensorInfo(t,n,s)}function yS(e){const{inputs:t,backend:n}=e,{x:s}=t;return n.incRef(s.dataId),{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}const bS={kernelName:gt,backendName:"cpu",kernelFunc:yS};function xS(e){const{inputs:t,backend:n}=e,{input:s}=t,r=n.data.get(s.dataId).complexTensorInfos.real,a=n.data.get(r.dataId).values;return n.makeTensorInfo(r.shape,r.dtype,a)}const wS={kernelName:hn,backendName:"cpu",kernelFunc:xS};function vS(e,t,n,s){if("int32"===s){return[t,"int32",Int32Array.from(e)]}if("bool"===s){const s=pr([0],n),[r,a]=dS(((e,t)=>e!==t?1:0))(t,[],e,s,"bool");return[a,"bool",r]}throw new Error(`Error in Cast: failed to cast ${n} to ${s}`)}function kS(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dtype:a}=s;if("complex64"===a){if("complex64"===r.dtype)return yS({inputs:{x:r},backend:n});const e=gS(n,r.shape,r.dtype),t=kS({inputs:{x:r},backend:n,attrs:{dtype:"float32"}}),s=fS({inputs:{real:t,imag:e},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),s}if("complex64"===r.dtype){const e=xS({inputs:{input:r},backend:n}),t=kS({inputs:{x:e},backend:n,attrs:{dtype:a}});return n.disposeIntermediateTensorInfo(e),t}if(!C(r.dtype,a)){const e=yS({inputs:{x:r},backend:n});return{dataId:e.dataId,shape:e.shape,dtype:a}}const i=n.data.get(r.dataId).values,[o,l,u]=vS(i,r.shape,r.dtype,a);return n.makeTensorInfo(o,l,u)}const NS={kernelName:Ie,backendName:"cpu",kernelFunc:kS};function IS(e,t,n,s){return null==n?({inputs:n,backend:r})=>{const{a:a,b:i}=n,o=r;lS([a,i],e);const l=o.data.get(a.dataId).values,u=o.data.get(i.dataId).values,c="string"===a.dtype?sm(l):l,h="string"===a.dtype?sm(u):u,p=s||a.dtype,[d,f]=t(a.shape,i.shape,c,h,p);return o.makeTensorInfo(f,p,d)}:({inputs:e,backend:r})=>{const{a:a,b:i}=e,o=r;if("complex64"===a.dtype||"complex64"===i.dtype){const e=kS({inputs:{x:a},backend:o,attrs:{dtype:"complex64"}}),t=o.data.get(e.dataId),s=t.complexTensorInfos.real,r=t.complexTensorInfos.imag,l=o.data.get(s.dataId).values,u=o.data.get(r.dataId).values,c=kS({inputs:{x:i},backend:o,attrs:{dtype:"complex64"}}),h=o.data.get(c.dataId),p=h.complexTensorInfos.real,d=h.complexTensorInfos.imag,f=o.data.get(p.dataId).values,m=o.data.get(d.dataId).values,[g,y,b]=n(a.shape,i.shape,l,u,f,m),x=o.makeTensorInfo(b,"float32",g),w=o.makeTensorInfo(b,"float32",y),v=fS({inputs:{real:x,imag:w},backend:o});return o.disposeIntermediateTensorInfo(e),o.disposeIntermediateTensorInfo(c),o.disposeIntermediateTensorInfo(x),o.disposeIntermediateTensorInfo(w),v}{const e=o.data.get(a.dataId).values,n=o.data.get(i.dataId).values,r=s||a.dtype,[l,u]=t(a.shape,i.shape,e,n,r);return o.makeTensorInfo(u,r,l)}}}function SS(e){return(t,n,s,r,a,i)=>{const o=Zo(t,n),l=d(o),u=o.length,c=M(o),h=N("float32",l),p=N("float32",l),f=Xo(t,o),m=Xo(n,o),g=If(s,r),y=If(a,i),b=t.length,x=M(t),w=n.length,v=M(n);if(f.length+m.length===0)for(let t=0;t<h.length;t++){const n=t%g.length,s=t%y.length,r=e(g[2*n],g[2*n+1],y[2*s],y[2*s+1]);h[t]=r.real,p[t]=r.imag}else for(let t=0;t<h.length;t++){const n=H(t,u,c),s=n.slice(-b);f.forEach((e=>s[e]=0));const r=G(s,b,x),a=n.slice(-w);m.forEach((e=>a[e]=0));const i=G(a,w,v),o=e(g[2*r],g[2*r+1],y[2*i],y[2*i+1]);h[t]=o.real,p[t]=o.imag}return[h,p,o]}}const TS=dS(((e,t)=>e+t)),CS=SS(((e,t,n,s)=>({real:e+n,imag:t+s}))),$S=IS(se,TS,CS),ES={kernelName:se,backendName:"cpu",kernelFunc:$S};function AS(e,t,n,s,r){const a=d(s),i=W(r,n);for(let n=0;n<e.length;n++){const s=e[n];if(s<0)throw new Error("Input x must be non-negative!");s>=r||(i[s]+=a>0?t[n]:1)}return i}function RS(e,t,n,s=!1){const r=e.shape[0],a=e.shape[1],i=Si([r,n],t.dtype);for(let o=0;o<r;o++)for(let r=0;r<a;r++){const a=e.get(o,r);if(a<0)throw new Error("Input x must be non-negative!");a>=n||(s?i.set(1,o,a):t.size>0?i.set(i.get(o,a)+t.get(o,r),o,a):i.set(i.get(o,a)+1,o,a))}return i}const _S=dS(((e,t)=>e&t)),FS=IS(ve,_S),DS={kernelName:ve,backendName:"cpu",kernelFunc:FS};function OS(e){return(t,n,s)=>{const r=I(n,t.length);for(let n=0;n<t.length;++n)r[n]=e(t[n],s);return r}}function MS(e,t,n){return LS(e,OS(t),n)}function LS(e,t,n){return({inputs:s,attrs:r,backend:a})=>{const{x:i}=s;lS(i,e);const o=a,l=o.data.get(i.dataId).values;let u;if("string"===i.dtype){if(!Array.isArray(l))throw new Error("String tensor's value was not an instance of Array");u=sm(l)}else u=l;const c=n||i.dtype,h=t(u,c,r);return o.makeTensorInfo(i.shape,c,h)}}const zS=OS((e=>Math.ceil(e))),PS=LS(Se,zS),BS={kernelName:Se,backendName:"cpu",kernelFunc:PS};function WS(e,t,n,s){const r=I(n,d(t));if(s&&"string"!==n){let t=0;e.forEach((e=>{const n=d(e.shape);r.set(e.vals,t),t+=n}))}else{let s=0;e.forEach((e=>{const a="string"===n?sm(e.vals):e.vals;let i=0;for(let n=0;n<e.shape[0];++n){const o=n*t[1]+s;for(let t=0;t<e.shape[1];++t)r[o+t]=a[i++]}s+=e.shape[1]}))}return r}const VS=dS(((e,t)=>e===t?1:0)),US=IS(nt,VS,null,"bool"),GS={kernelName:nt,backendName:"cpu",kernelFunc:US},HS=OS((e=>Math.exp(e))),jS=LS(st,HS,"float32"),qS={kernelName:st,backendName:"cpu",kernelFunc:jS},KS=OS((e=>Math.expm1(e))),XS=LS(at,KS),YS={kernelName:at,backendName:"cpu",kernelFunc:XS},ZS=OS((e=>Math.floor(e))),JS=LS(ut,ZS),QS={kernelName:ut,backendName:"cpu",kernelFunc:JS},eT=dS(((e,t)=>Math.floor(e/t))),tT=IS(ct,eT,null,"int32"),nT={kernelName:ct,backendName:"cpu",kernelFunc:tT};function sT(e,t,n,s,r,a,i,o,l){const u=Si([s,a],n);for(let n=0;n<s;n++){const s=[];let c=0;for(let t=0;t<r;t++){const a=e[n*r+t];c+=a*i[t],s.push(a)}if(c<0||c>=l/a)throw new Error(`Invalid indices: ${s} does not index into ${o}`);for(let e=0;e<a;e++)u.values[n*a+e]=t.get(...t.indexToLoc(c*a+e))}return u}function rT(e,t,n){const s=Si(n,e.dtype);for(let n=0;n<s.size;++n){const r=s.indexToLoc(n).slice(),a=r[0],i=r[2],o=t.locToIndex([a,i]);r[2]=t.values[o];const l=e.locToIndex(r);0<=l&&l<e.values.length&&(s.values[n]=e.values[l])}return s}const aT=dS(((e,t)=>e>t?1:0)),iT=IS(ft,aT,null,"bool"),oT={kernelName:ft,backendName:"cpu",kernelFunc:iT},lT=dS(((e,t)=>e>=t?1:0)),uT=IS(mt,lT,null,"bool"),cT={kernelName:mt,backendName:"cpu",kernelFunc:uT},hT=dS(((e,t)=>e<t?1:0)),pT=IS(Nt,hT,null,"bool"),dT={kernelName:Nt,backendName:"cpu",kernelFunc:pT},fT=dS(((e,t)=>e<=t?1:0)),mT=IS(It,fT,null,"bool"),gT={kernelName:It,backendName:"cpu",kernelFunc:mT};function yT(e,t,n){const s=(t-e)/(n-1),r=W(n,"float32");r[0]=e;for(let e=1;e<r.length;e++)r[e]=r[e-1]+s;return r}const bT=OS((e=>Math.log(e))),xT=LS(Tt,bT),wT={kernelName:Tt,backendName:"cpu",kernelFunc:xT};function vT(e,t,n,s){const r=N(s,d(n));for(let n=0;n<r.length;++n){const s=n*t;let a=e[s];for(let n=0;n<t;++n){const t=e[s+n];(Number.isNaN(t)||t>a)&&(a=t)}r[n]=a}return r}const kT=dS(((e,t)=>Math.max(e,t))),NT=IS(Ot,kT),IT={kernelName:Ot,backendName:"cpu",kernelFunc:NT},ST=dS(((e,t)=>Math.min(e,t))),TT=IS(Ut,ST),CT={kernelName:Ut,backendName:"cpu",kernelFunc:TT},$T=dS(((e,t)=>e*t)),ET=SS(((e,t,n,s)=>({real:e*n-t*s,imag:e*s+t*n}))),AT=IS(qt,$T,ET),RT={kernelName:qt,backendName:"cpu",kernelFunc:AT};function _T(e,t,n){const s=hr(-1,n);return $T([],t,s,e,n)}const FT={kernelName:Kt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:s}=t;lS(s,"neg");const r=n.data.get(s.dataId).values,[a,i]=_T(r,s.shape,s.dtype);return n.makeTensorInfo(i,s.dtype,a)}},DT=dS(((e,t)=>e!==t?1:0)),OT=IS(Xt,DT,null,"bool"),MT={kernelName:Xt,backendName:"cpu",kernelFunc:OT};function LT(e,t,n,s,r){const a=t.length,i=d(t),o=M(t),l=M(r),u=N(n,d(r));for(let t=0;t<i;++t){const n=H(t,a,o),r=new Array(n.length);for(let e=0;e<r.length;e++)r[e]=n[s[e]];u[G(r,a,l)]=e[t]}return u}function zT(e){const{inputs:t,attrs:n,backend:s}=e,{x:r}=t,{perm:a}=n;lS(r,"transpose");const i=r.shape.length,o=new Array(i);for(let e=0;e<o.length;e++)o[e]=r.shape[a[e]];const l=LT(s.data.get(r.dataId).values,r.shape,r.dtype,a,o);return{dataId:s.write(l,o,r.dtype),shape:o,dtype:r.dtype}}const PT={kernelName:ss,backendName:"cpu",kernelFunc:zT};function BT(e,t,n,s){const[r,a]=cl(e,s),i=Wr(t,"int32"),o=W(d(r),i),l=d(a);for(let e=0;e<o.length;++e){const t=e*l;let s=1;for(let e=0;e<l;++e)s*=n[t+e];o[e]=s}return{outVals:o,outShape:r,outDtype:i}}const WT={kernelName:an,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s;lS(r,"prod");const o=r.shape.length,l=v(a,r.shape),u=dl(l,o);let c=l,h=r;const p=[];null!=u&&(h=zT({inputs:{x:r},backend:n,attrs:{perm:u}}),p.push(h),c=ml(c.length,o));const d=n.data.get(h.dataId).values,{outVals:f,outShape:m,outDtype:g}=BT(h.shape,h.dtype,d,c);let y=m;return i&&(y=hl(m,l)),p.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(y,g,f)}};function VT(e,t,n,s){const r=[];let a=0;const i=t.length-1+n.length,o=new Array(i).fill(null).map((()=>[0]));!function(e,t){for(let n=0;n<e.length;++n){const s=e[n],r=n===e.length-1?t:e[n+1].length;if(0===s.length)throw new Error("Ragged splits may not be empty");if(s[0]<0)throw new Error("Ragged splits must be non-negative");if(s[s.length-1]>r)throw new Error("Ragged splits must not point past values");for(let e=1;e<s.length;++e)if(s[e-1]>s[e])throw new Error("Ragged splits must be sorted in ascending order")}}(n,s);let l=1;for(let e=0;e<t.length-1;++e){l*=t[e];const n=t[e+1];for(let t=1;t<l+1;++t)o[e].push(t*n)}for(let s=0;s<e.length;++s){let i=e[s],l=e[s]+1;for(let e=0;e<n.length;++e){const s=n[e],r=e+t.length-1;if(r>=0){const e=o[r],t=e[e.length-1]-s[i];for(let e=i;e<l;++e)o[r].push(s[e+1]+t)}i=s[i],l=s[l]}l!==i&&(r.push([i,l]),a+=l-i)}return{outSplits:o,valueSlices:r,numValues:a}}function UT(e,t){const n=e.slice(0,t);for(;n.length<t;)n.push(1);for(let s=t;s<e.length;s++)n[t-1]*=e[s];return n}function GT(e,t,n,s,r){const a=t.slice();a[0]=r;const i=I(n,d(a)),o=e.length;return function(e,t,n,s,r,a){const i=UT(t,2)[1],o=UT(a,2)[1];let l=0;for(const t of n)for(let n=t[0];n<t[1];++n){for(let t=0;t<s;++t)r[l*o+t]=e[n*i+t];++l}}(e,t,s,0===o?0:o/t[0],i,a),[i,a]}function HT(e,t,n,s,r,a,i,o){if(0===e.length)throw new Error("paramsNestedSplits must be non empty");if(0===t[0].length)throw new Error("Split tensors must not be scalars");if(function(e,t,n){e.forEach(((e,s)=>{if(e<0||e>=n){const r=H(s,t.length,M(t)).join(",");throw new Error(`indices[${r}] = ${e} is not in [0, ${n})`)}}))}(a,i,t[0][0]-1),0===s.length)throw new Error("params.rank must be nonzero");const l=s[0],{outSplits:u,valueSlices:c,numValues:h}=VT(a,i,e,l),p=function(e){const t=[];for(let n=0;n<e.length;++n){const s=I("int32",e[n].length);t.push(s),e[n].forEach(((e,t)=>s[t]=e))}return t}(u),d=GT(n,s,r,c,h);return[p,d[0],d[1]]}const jT=2147483647;function qT(e,t,n,s,r,a,i){if(t.length>1)throw new Error("starts must be a scalar or vector");if(r.length>1)throw new Error("limits must be a scalar or vector");if(i.length>1)throw new Error("deltas must be a scalar or vector");const o=0===t.length,l=0===r.length,u=0===i.length,c=[];o||c.push(t[0]),l||c.push(r[0]),u||c.push(i[0]);for(let e=1;e<c.length;++e)if(c[e]!==c[e-1])throw new Error("starts, limits, and deltas must have the same shape");const h=0===c.length?1:c[0],p=I("int32",h+1);p[0]=0;for(let t=0;t<h;++t){const n=o?e[0]:e[t],r=l?s[0]:s[t],i=u?a[0]:a[t];if(0===i)throw new Error("Requires delta != 0");let c;if(i>0&&r<n||i<0&&r>n)c=0;else if(c=Math.ceil(Math.abs((r-n)/i)),c>jT)throw new Error("Requires ((limit - start) / delta) <= 2147483647");p[t+1]=p[t]+c}const d=I(n,p[h]);let f=0;for(let t=0;t<h;++t){const n=p[t+1]-p[t];let s=o?e[0]:e[t];const r=u?a[0]:a[t];for(let e=0;e<n;++e)d[f++]=s,s+=r}return[p,d]}var KT=sf;class XT{constructor(e,t,n,s,r,a,i,o,l,u){this.shape=e,this.shapeShape=t,this.values=n,this.valuesShape=s,this.valuesDType=r,this.defaultValue=a,this.defaultValueShape=i,this.rowPartitionValues=o,this.rowPartitionValuesShapes=l,this.rowPartitionTypes=af(u),this.raggedRank=of(this.rowPartitionTypes)}getRowPartitionTypeByDimension(e){return this.rowPartitionTypes[0]===KT.FIRST_DIM_SIZE?this.rowPartitionTypes[e+1]:this.rowPartitionTypes[e]}getRowPartitionTensor(e){return this.rowPartitionTypes[0]===KT.FIRST_DIM_SIZE?this.rowPartitionValues[e+1]:this.rowPartitionValues[e]}getMaxWidth(e){const t=this.getRowPartitionTensor(e-1);switch(this.getRowPartitionTypeByDimension(e-1)){case KT.VALUE_ROWIDS:return XT.getMaxWidthValueRowID(t);case KT.ROW_SPLITS:return XT.getMaxWidthRowSplit(t);default:throw new Error(`Cannot handle partition type ${KT[this.getRowPartitionTypeByDimension(e-1)]}`)}}static getMaxWidthRowSplit(e){const t=e.length;if(0===t||1===t)return 0;let n=0;for(let s=0;s<t-1;++s){const t=e[s+1]-e[s];t>n&&(n=t)}return n}static getMaxWidthValueRowID(e){const t=e.length;if(0===t)return 0;let n=0,s=e[0],r=0;for(let a=1;a<t;++a){const t=e[a];t!==s&&(s=t,r=Math.max(a-n,r),n=a)}return Math.max(t-n,r)}tensorShapeFromTensor(e,t,n=!0){if(0===t.length){if(-1===e[0])return[];throw new Error("The only valid scalar shape tensor is the fully unknown shape specified as -1.")}return ZT(e,n)}calculateOutputSize(e){const t=this.valuesShape;lf(this.defaultValueShape,t);const n=this.tensorShapeFromTensor(this.shape,this.shapeShape),s=rf(this.raggedRank,n,t);s[0]<0&&(s[0]=e);for(let e=1;e<=this.raggedRank;++e)s[e]<0&&(s[e]=this.getMaxWidth(e));return s}calculateFirstParentOutputIndex(e,t,n){const s=Math.min(e,n),r=[];let a=0;for(let e=0;e<s;++e,a+=t)r.push(a);for(let t=s;t<e;++t)r.push(-1);return c(r.length===e,(()=>"Final length of result must be equal to firstDimension.")),r}calculateOutputIndexRowSplit(e,t,n,s){const r=e.length,a=[];for(let i=0;i<r-1;++i){const r=e[i+1]-e[i];let o=Math.min(s,r),l=t[i];-1===l&&(o=0);for(let e=0;e<o;++e)a.push(l),l+=n;for(let e=0;e<r-o;++e)a.push(-1)}if(r>0&&a.length!==e[r-1])throw new Error("Invalid row split size.");return a}calculateOutputIndexValueRowID(e,t,n,s){const r=e.length,a=[];if(0===r)return[];let i=0,o=e[0];if(o>=t.length)throw new Error(`Got currentValueRowId=${o}, which is not less than ${t.length}`);let l=t[o];a.push(l);for(let u=1;u<r;++u){const r=e[u];if(r===o)l>=0&&(++i,i<s?l+=n:l=-1);else{if(i=0,o=r,r>=t.length)throw new Error(`Got nextValueRowId=${r} which is not less than ${t.length}`);l=t[r]}a.push(l)}if(a.length!==e.length)throw new Error("Invalid row ids.");return a}calculateOutputIndex(e,t,n,s){const r=this.getRowPartitionTensor(e),a=this.getRowPartitionTypeByDimension(e);switch(a){case KT.VALUE_ROWIDS:return this.calculateOutputIndexValueRowID(r,t,n,s);case KT.ROW_SPLITS:if(r.length-1>t.length)throw new Error(`Row partition size is greater than output size: ${r.length-1} > ${t.length}`);return this.calculateOutputIndexRowSplit(r,t,n,s);default:throw new Error(`Unsupported partition type: ${KT[a]}`)}}getFirstDimensionSize(){const e=this.rowPartitionValues[0];if(0===this.rowPartitionTypes.length)throw new Error("No row_partition_types given.");const t=this.rowPartitionTypes[0];switch(t){case KT.FIRST_DIM_SIZE:return e[0];case KT.VALUE_ROWIDS:throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");case KT.ROW_SPLITS:return this.rowPartitionValuesShapes[0][0]-1;default:throw new Error(`Cannot handle type ${KT[t]}`)}}compute(){if(this.rowPartitionValues[0].length<=0)throw new Error("Invalid first partition input. Tensor requires at least one element.");const e=this.getFirstDimensionSize(),t=this.calculateOutputSize(e),n=new Array(this.raggedRank+1);n[n.length-1]=1;for(let e=n.length-2;e>=0;--e)n[e]=n[e+1]*t[e+1];const s=ZT(t,!1),r=I(this.valuesDType,d(s));if(n[0]*t[0]>0){let a=this.calculateFirstParentOutputIndex(e,n[0],t[0]);for(let e=1;e<=this.raggedRank;++e){a=this.calculateOutputIndex(e-1,a,n[e],t[e])}this.setOutput(this.raggedRank,a,r,s)}return[s,r]}setOutput(e,t,n,s){if(0===n.length)return;const r=this.values,a=n;let i=s.slice();i=i.slice(e+1);const o=d(i),l=t.length;let u=this.defaultValue;if(u.length!==o&&1!==u.length){const e=this.defaultValueShape;Na((()=>{const t=oo(u,e),n=So(t,i);u=n.dataSync()}))}let c=0,h=0,p=0;for(let e=0;e<=l;++e){let s=e<l?t[e]:-1;if(s!==p){if(h<p){const e=r.subarray(c*o);YT(a.subarray(h*o),e,(p-h)*o)}if(e>=l){const e=n.length;s=Math.floor(e/o)}if(s>p)if(1===this.defaultValue.length)a.subarray(p*o,s*o).fill(this.defaultValue[0]),p=s;else for(;s>p;){YT(a.slice(p*o),u,o),++p}s<0?(c=e+1,h=p):(c=e,h=p,p=h+1)}else++p}}}function YT(e,t,n){for(let s=0;s<n;s++)e[s]=t[s]}function ZT(e,t){const n=[];for(let s of e){if(s<0){if(!t)throw new Error(`Dimension ${s} must be >= 0`);if(s<-1)throw new Error(`Dimension ${s} must be >= -1`);s=-1}n.push(s)}return n}function JT(e,t,n,s,r,a,i,o,l,u){return new XT(e,t,n,s,r,a,i,o,l,u).compute()}function QT(e,t,n,s){if(e===t||e<t&&n<0||t<e&&n>1)return W(0,s);const r=W(Math.abs(Math.ceil((t-e)/n)),s);t<e&&1===n&&(n=-1),r[0]=e;for(let e=1;e<r.length;e++)r[e]=r[e-1]+n;return r}const eC=OS((e=>1/Math.sqrt(e))),tC=LS(kn,eC),nC={kernelName:kn,backendName:"cpu",kernelFunc:tC};function sC(e,t,n,s,r,a,i,o,l,u){const c=[s/r,r],h=e.values,p=t.values;if(0===s)return Si(n,t.dtype);const d=l instanceof $r?l:Si(c,t.dtype);"string"==typeof l||"number"==typeof l?d.values.fill(l):"boolean"==typeof l&&d.values.fill(+l);for(let e=0;e<a;e++){const a=[];let l=0;for(let t=0;t<i;t++){const n=h[e*i+t];a.push(n),l+=n*o[t]}if(l<0||l>=s/r)throw new Error(`Invalid indices: ${a} does not index into ${n}`);for(let n=0;n<r;n++)u?d.values[l*r+n]+=p[e*r+n]:d.values[l*r+n]=0===t.rank?p[0]:p[e*r+n]}return d}const rC=OS((e=>1/(1+Math.exp(-e)))),aC=MS(_n,(e=>1/(1+Math.exp(-e)))),iC={kernelName:_n,backendName:"cpu",kernelFunc:aC};function oC(e,t,n,s,r){const a=Gd(s,t,n),i=d(n),o=M(s);if(a){const n=Hd(t,o);return"string"===r?e.slice(n,n+i):e.subarray(n,n+i)}const l=Si(s,r,"string"===r?sm(e):e),u=Si(n,r);for(let e=0;e<u.size;++e){const n=u.indexToLoc(e),s=n.map(((e,n)=>e+t[n]));u.set(l.get(...s),...n)}return"string"===r?rm(u.values):u.values}function lC(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,size:i}=s;lS(r,"slice");const[o,l]=jd(r,a,i);Dd(r,o,l);const u=oC(n.data.get(r.dataId).values,o,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,u)}const uC={kernelName:$n,backendName:"cpu",kernelFunc:lC};function cC(e,t,n,s,r,a,i){const o=t[0],l=a[0],u=new Array(l),c=new Array(o),h=t[1];if(0===l){if(0!==o)throw new Error(Wf(o));return[I(n,0),[0,h],I(r,0),u,c]}let p=!0,d=0;const f=new Array(l).fill(0);for(let t=0;t<o;++t){const n=e[t*h];if(n<0)throw new Error(Vf(t,n));if(n>=l)throw new Error(Uf(t,n,l));++f[n],p=p&&n>=d,d=n}let m=!0;for(let e=0;e<l;++e){const t=0===f[e];u[e]=t,m=m&&!t,f[e]=Math.max(f[e],1),e>0&&(f[e]+=f[e-1])}if(m&&p){const t=e,n=s;for(let e=0;e<o;++e)c[e]=e;return[t,[o,h],n,u,c]}{const t=f[l-1],a=I(n,t*h),p=I(r,t),d=new Array(l).fill(0);for(let t=0;t<o;++t){const n=e[t*h],r=d[n],i=(0===n?0:f[n-1])+r;d[n]++;for(let n=0;n<h;++n)a[i*h+n]=e[t*h+n];p[i]=s[t],c[t]=i}for(let e=0;e<l;++e){if(0===d[e]){const t=0===e?0:f[e-1];a[t*h+0]=e;for(let e=1;e<h;++e)a[t*h+e]=0;p[t]=i}}return[a,[t,h],p,u,c]}}function hC(e,t,n,s,r){const a=d(s),i=t[0],o=r.length,l=[];let u=1,c=-1;for(let e=0;e<o;++e){const t=r[e];if(-1===t){if(-1!==c)throw new Error(Gf(c,e));c=e,l.push(1)}else{if(t<0)throw new Error(Hf(e,t));u*=t,l.push(t)}}if(-1!==c){if(u<=0)throw new Error("reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero");const e=Math.trunc(a/u);if(u*e!==a)throw new Error(qf(s,l));l[c]=e}if(d(l)!==a)throw new Error(Kf(s,l));const h=s.length,p=[];if(h>0){p[h-1]=1;for(let e=h-2;e>=0;--e)p[e]=p[e+1]*s[e+1]}const f=[];if(o>0){f[o-1]=1;for(let e=o-2;e>=0;--e)f[e]=f[e+1]*l[e+1]}const m=I(n,i*o);for(let t=0;t<i;++t){let n=0;for(let s=0;s<h;++s)n+=e[t*h+s]*p[s];for(let e=0;e<o;++e)m[t*o+e]=Math.trunc(n/f[e]),n%=f[e]}return[m,[i,o],l]}function pC(e,t,n,s,r,a=!1,i=0){const o=s.length,l=[t[0],e.length/t[0]],u=l[1],c=o>0?r[o-1]+1:0;if(c<0)throw new Error("segment ids must be >= 0");const h=t.slice();h[0]=c;const p=I(n,h.reduce(((e,t)=>e*t),1));if(0===o)return c>0&&p.fill(i),[p,h];if(c<=0)throw new Error("segment ids must be >= 0");let d=0,f=1,m=0,g=r[d];for(;;){let t=0;if(f<o){if(t=r[f],g===t){++f;continue}if(g>=t)throw new Error("segment ids are not increasing")}if(g<0||g>=c)throw new Error(Zf(g,c));g>m&&p.fill(i,m*u,g*u);for(let t=d;t<f;++t){const n=s[t];if(n<0||n>=l[0])throw new Error(Jf(t,s[t],l[0]));for(let t=0;t<u;t++)p[g*u+t]+=e[n*u+t]}if(a)for(let e=0;e<u;e++)p[g*u+e]/=f-d;if(d=f,++f,m=g+1,g=t,f>o)break}return m<c&&p.fill(i,m*u,c*u),[p,h]}const dC=OS((e=>Math.sqrt(e))),fC=MS(Dn,(e=>Math.sqrt(e))),mC={kernelName:Dn,backendName:"cpu",kernelFunc:fC},gC=dS(((e,t)=>{const n=e-t;return n*n})),yC=IS(Gn,gC),bC={kernelName:Gn,backendName:"cpu",kernelFunc:yC},xC=OS(((e,t)=>{const{pattern:n,replaceGlobal:s,rewrite:r}=t;return e.replace(new RegExp(n,s?"g":""),r)})),wC=LS(jn,xC),vC={kernelName:jn,backendName:"cpu",kernelFunc:wC};function kC(e,t,n,s){const r=Si(e,t.dtype);for(let e=0;e<r.size;e++){const a=r.indexToLoc(e),i=new Array(a.length);for(let e=0;e<i.length;e++)i[e]=a[e]*n[e]+s[e];r.set(t.get(...i),...a)}return r}class NC{constructor(e,t,n,s,r,a){this.separator=mr(e),this.nGramWidths=t,this.leftPad=mr(n),this.rightPad=mr(s),this.padWidth=r,this.preserveShort=a}getPadWidth(e){return Math.min(this.padWidth<0?e-1:this.padWidth,e-1)}getNumNGrams(e,t){const n=this.getPadWidth(t);return Math.max(0,e+2*n-t+1)}createNGrams(e,t,n,s,r,a){for(let i=0;i<r;++i){const o=this.getPadWidth(a),l=Math.max(0,o-i),u=Math.max(0,o-(r-(i+1))),c=a-(l+u),h=t+(l>0?0:i-o);let p=0;p+=l*this.leftPad.length;for(let t=0;t<c;++t)p+=e[h+t].length;p+=u*this.rightPad.length;p+=(l+u+c-1)*this.separator.length,n[s+i]=new Uint8Array(p);const d=n[s+i];let f=0;const m=e=>e.forEach((e=>d[f++]=e));for(let e=0;e<l;++e)m(this.leftPad),m(this.separator);for(let t=0;t<c-1;++t)m(e[h+t]),m(this.separator);if(c>0){m(e[h+c-1]);for(let e=0;e<u;++e)m(this.separator),m(this.rightPad)}else{for(let e=0;e<u-1;++e)m(this.rightPad),m(this.separator);m(this.rightPad)}}}compute(e,t){const n=e.length,s=t.length;if(s>0){let e=t[0];if(0!==e)throw new Error(`First split value must be 0, got ${e}`);for(let r=1;r<s;++r){let s=t[r]>=e;if(s=s&&t[r]<=n,!s)throw new Error(`Invalid split value ${t[r]}, must be in [${e}, ${n}]`);e=t[r]}if(e!==n)throw new Error(`Last split value must be data size. Expected ${n}, got ${e}`)}const r=s-1,a=I("int32",s);if(0===n||0===s){const e=new Array(n);for(let e=0;e<=r;++e)a[e]=0;return[e,a]}a[0]=0;for(let e=1;e<=r;++e){const n=t[e]-t[e-1];let s=0;this.nGramWidths.forEach((e=>{s+=this.getNumNGrams(n,e)})),this.preserveShort&&n>0&&0===s&&(s=1),a[e]=a[e-1]+s}const i=new Array(a[r]);for(let n=0;n<r;++n){const s=t[n];let r=a[n];if(this.nGramWidths.forEach((a=>{const o=t[n+1]-t[n],l=this.getNumNGrams(o,a);this.createNGrams(e,s,i,r,l,a),r+=l})),this.preserveShort&&r===a[n]){const a=t[n+1]-t[n];if(0===a)continue;const o=a+2*this.padWidth,l=1;this.createNGrams(e,s,i,r,l,o)}}return[i,a]}}function IC(e,t,n,s,r,a,i,o){return new NC(n,s,r,a,i,o).compute(e,t)}function SC(e,t,n,s){if(!e.length)return;if(0===t.length){for(let t=0;t<e.length;++t)s.push(e.subarray(t,t+1));return}if(1===t.length){const r=t[0];let a=e.indexOf(r);for(;-1!==a;){const t=e.subarray(0,a);n&&0===t.length||s.push(t),a=(e=e.subarray(a+1)).indexOf(r)}return void(n&&0===e.length||s.push(e))}let r=0;for(let a=0;a<e.length+1;a++)if(a===e.length||-1!==t.indexOf(e[a])){const t=e.subarray(r,a);n&&0===t.length||s.push(t),r=a+1}}function TC(e,t,n){const s=e.length,r=[];let a=0,i=0;const o=new Array(s);for(let l=0;l<s;++l){const s=r.length;SC(e[l],t,n,r);const u=r.length-s;o[l]=u,a+=u,i=Math.max(i,u)}const l=I("int32",2*a),u=new Array(a),c=[s,i];let h=0;for(let e=0;e<s;++e)for(let t=0;t<o[e];++t)l[2*h]=e,l[2*h+1]=t,u[h]=r[h],++h;return[l,u,c]}function CC(e,t){const n=I("int32",e.length);for(let s=0;s<e.length;++s)n[s]=cr(e[s]).modulo(t).getLowBitsUnsigned();return n}const $C=dS(((e,t)=>e-t)),EC=SS(((e,t,n,s)=>({real:e-n,imag:t-s}))),AC=IS(Zn,$C,EC),RC={kernelName:Zn,backendName:"cpu",kernelFunc:AC};function _C(e,t){const n=new Array(e.rank);for(let s=0;s<n.length;s++)n[s]=e.shape[s]*t[s];const s=Si(n,e.dtype);for(let t=0;t<s.values.length;++t){const n=s.indexToLoc(t),r=new Array(e.rank);for(let t=0;t<r.length;t++)r[t]=n[t]%e.shape[t];const a=e.locToIndex(r);s.values[t]=e.values[a]}return s}const FC=(e,t)=>{const n=t.value-e.value;return 0===n?e.index-t.index:n};function DC(e,t,n=0,s=e.length-1){for(;s>n;){if(s-n>600){const r=s-n+1,a=t-n+1,i=Math.log(r),o=.5*Math.exp(2*i/3),l=.5*Math.sqrt(i*o*(r-o)/r)*Math.sign(a-r/2);DC(e,t,Math.max(n,Math.floor(t-a*o/r+l)),Math.min(s,Math.floor(t+(r-a)*o/r+l)))}const r=e[t];let a=n,i=s;for(l(e,n,t),FC(e[s],r)>0&&l(e,n,s);a<i;){for(l(e,a,i),a++,i--;FC(e[a],r)<0;)a+=1;for(;FC(e[i],r)>0;)i-=1}0===FC(e[n],r)?l(e,n,i):(i+=1,l(e,i,s)),i<=t&&(n=i+1),t<=i&&(s=i-1)}}function OC(e,t,n,s,r){const a=t[t.length-1],[i,o]=[e.length/a,a],l=N(n,i*s),u=N("int32",i*s);for(let t=0;t<i;t++){const n=t*o,a=e.subarray(n,n+o);let i=new Array(a.length);a.forEach(((e,t)=>i[t]={value:e,index:t})),s<i.length&&(DC(i,s),i=i.slice(0,s)),r&&i.sort(FC);const c=t*s,h=l.subarray(c,c+s),p=u.subarray(c,c+s);for(let e=0;e<s;e++)h[e]=i[e].value,p[e]=i[e].index}const c=t.slice();return c[c.length-1]=s,[Si(c,n,l),Si(c,"int32",u)]}function MC(e,t,n,s){const r=v(t,n)[0],a=[1,n[0],1];for(let e=0;e<r;e++)a[0]*=n[e];a[1]=n[r];for(let e=r+1;e<n.length;e++)a[2]*=n[e];const i=new Map,o=new Int32Array(n[r]),l=new $r(a,s,e),u=[],c=1===a[0]&&1===a[2];for(let t=0;t<n[r];t++){let n;if(c)n=e[t].toString();else{const e=[];for(let n=0;n<a[0];n++)for(let s=0;s<a[2];s++)e.push(l.get(n,t,s));n=e.join(",")}const s=i.get(n);if(null!=s)o[t]=s;else{const e=i.size;i.set(n,e),o[t]=e,u.push(t)}}const h=a.slice();h[1]=i.size;const p=new $r(h,s);u.forEach(((e,t)=>{for(let n=0;n<a[0];n++)for(let s=0;s<a[2];s++)p.set(l.get(n,e,s),n,t,s)}));const d=n.slice();return d[r]=h[1],{outputValues:p.values,outputShape:d,indices:o}}var LC=Object.freeze({__proto__:null,addImpl:TS,bincountImpl:AS,bincountReduceImpl:RS,bitwiseAndImpl:_S,castImpl:vS,ceilImpl:zS,concatImpl:WS,equalImpl:VS,expImpl:HS,expm1Impl:KS,floorDivImpl:eT,floorImpl:ZS,gatherNdImpl:sT,gatherV2Impl:rT,greaterEqualImpl:lT,greaterImpl:aT,lessEqualImpl:fT,lessImpl:hT,linSpaceImpl:yT,logImpl:bT,maxImpl:vT,maximumImpl:kT,minimumImpl:ST,multiplyImpl:$T,negImpl:_T,notEqualImpl:DT,prodImpl:BT,raggedGatherImpl:HT,raggedRangeImpl:qT,raggedTensorToTensorImpl:JT,rangeImpl:QT,rsqrtImpl:eC,scatterImpl:sC,sigmoidImpl:rC,simpleAbsImpl:hS,sliceImpl:oC,sparseFillEmptyRowsImpl:cC,sparseReshapeImpl:hC,sparseSegmentReductionImpl:pC,sqrtImpl:dC,squaredDifferenceImpl:gC,staticRegexReplaceImpl:xC,stridedSliceImpl:kC,stringNGramsImpl:IC,stringSplitImpl:TC,stringToHashBucketFastImpl:CC,subImpl:$C,tileImpl:_C,topKImpl:OC,transposeImpl:LT,uniqueImpl:MC});const zC="4.15.0";$a("cpu",(()=>new cS),1);const PC=MS(Qe,(e=>e>=0?e:Math.exp(e)-1)),BC={kernelName:Qe,backendName:"cpu",kernelFunc:PC};function WC(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{alpha:a}=s;lS([r],"leakyRelu");const i=d(r.shape),o=n.data.get(r.dataId).values,l=N("float32",i);for(let e=0;e<o.length;e++)l[e]=o[e]<0?a*o[e]:o[e];return n.makeTensorInfo(r.shape,"float32",l)}const VC={kernelName:kt,backendName:"cpu",kernelFunc:WC},UC=dS(((e,t)=>e<0?t*e:e));function GC(e){const{inputs:t,backend:n}=e,{x:s,alpha:r}=t;lS([s,r],"prelu");const a=n.data.get(s.dataId).values,i=n.data.get(r.dataId).values,[o,l]=UC(s.shape,r.shape,a,i,"float32");return n.makeTensorInfo(l,"float32",o)}const HC={kernelName:rn,backendName:"cpu",kernelFunc:GC},jC=MS(dn,(e=>Math.max(0,e))),qC={kernelName:dn,backendName:"cpu",kernelFunc:jC},KC=MS(xn,(e=>Math.min(Math.max(0,e),6))),XC={kernelName:xn,backendName:"cpu",kernelFunc:KC};function YC(e,t,n,s,r){if("linear"===n)return yS({inputs:{x:t},backend:e});if("relu"===n)return jC({inputs:{x:t},backend:e});if("elu"===n)return PC({inputs:{x:t},backend:e});if("relu6"===n)return KC({inputs:{x:t},backend:e});if("prelu"===n)return GC({inputs:{x:t,alpha:s},backend:e});if("leakyrelu"===n)return WC({inputs:{x:t},backend:e,attrs:{alpha:r}});if("sigmoid"===n)return aC({inputs:{x:t},backend:e});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}function ZC(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{shape:a}=s,i=d(r.shape),o=w(a,i),l=d(o);c(i===l,(()=>`The new shape (${o}) has ${l} elements and the old shape (${r.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`)),n.incRef(r.dataId);const u=n.data.get(r.dataId);if(null!=u.complexTensorInfos){const e=u.complexTensorInfos.real,t=u.complexTensorInfos.imag;e.shape=o,t.shape=o}return{dataId:r.dataId,shape:o,dtype:r.dtype}}const JC={kernelName:fn,backendName:"cpu",kernelFunc:ZC};function QC(e){const{inputs:t,backend:n,attrs:s}=e,{a:r,b:a}=t,{transposeA:i,transposeB:o}=s;lS([r,a],"matMul");const l=r.shape.length,u=a.shape.length,h=i?r.shape[l-2]:r.shape[l-1],p=o?a.shape[u-1]:a.shape[u-2],f=i?r.shape[l-1]:r.shape[l-2],m=o?a.shape[u-2]:a.shape[u-1],g=r.shape.slice(0,-2),y=a.shape.slice(0,-2),b=d(g),x=d(y),w=Zo(r.shape.slice(0,-2),a.shape.slice(0,-2)).concat([f,m]);c(h===p,(()=>`Error in matMul: inner shapes (${h}) and (${p}) of Tensors with shapes ${r.shape} and ${a.shape} and transposeA=${i} and transposeB=${o} must match.`));const v=o?[x,m,p]:[x,p,m],k=ZC({inputs:{x:r},backend:n,attrs:{shape:i?[b,h,f]:[b,f,h]}}),N=ZC({inputs:{x:a},backend:n,attrs:{shape:v}}),I=i?k.shape[1]:k.shape[2],S=i?k.shape[2]:k.shape[1],T=o?N.shape[1]:N.shape[2],C=Math.max(b,x),$=n.data.get(k.dataId).values,E=n.data.get(N.dataId).values,A=M(k.shape),R=M(N.shape),[_,F,D]=i?[A[0],1,A[1]]:[A[0],A[1],1],[O,L,z]=o?[1,R[1],R[0]]:[R[1],1,R[0]],P=S*T,B=Si([C,S,T],k.dtype),W=B.values,V=n.blockSize;for(let e=0;e<C;e++){const t=e%b,n=e%x;for(let s=0;s<S;s+=V){const r=Math.min(s+V,S);for(let a=0;a<T;a+=V){const i=Math.min(a+V,T);for(let o=0;o<I;o+=V){const l=Math.min(o+V,I);for(let u=s;u<r;u++)for(let s=a;s<i;s++){let r=0;for(let e=o;e<l;e++){r+=$[t*_+u*F+e*D]*E[e*O+s*L+n*z]}W[e*P+(u*T+s)]+=r}}}}}return n.disposeIntermediateTensorInfo(k),n.disposeIntermediateTensorInfo(N),n.makeTensorInfo(w,B.dtype,B.values)}const e$={kernelName:be,backendName:"cpu",kernelFunc:QC};const t$={kernelName:hs,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{a:r,b:a,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:u,activation:c,leakyreluAlpha:h}=s;let p,d,f;const m=[];p=QC({inputs:{a:r,b:a},attrs:{transposeA:l,transposeB:u},backend:n}),i&&(d=$S({inputs:{a:p,b:i},backend:n}),m.push(p),p=d),c&&(f=YC(n,p,c,o,h),m.push(p),p=f);for(const e of m)n.disposeIntermediateTensorInfo(e);return p}},n$=MS(te,(e=>Math.acos(e))),s$={kernelName:te,backendName:"cpu",kernelFunc:n$},r$=MS(ne,(e=>Math.acosh(e))),a$={kernelName:ne,backendName:"cpu",kernelFunc:r$};const i$={kernelName:re,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,s=t;lS(t,"addN");const r=s.map((e=>n.data.get(e.dataId).values)),a=Si(s[0].shape,s[0].dtype),i=a.values;for(let e=0;e<s.length;e++){const t=r[e];for(let e=0;e<i.length;e++)i[e]+=t[e]}return n.makeTensorInfo(a.shape,a.dtype,a.values)}};const o$={kernelName:ae,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s;lS(r,"all");const o=v(a,r.shape);let l=o;const u=dl(l,r.shape.length);let c=r;null!=u&&(c=zT({inputs:{x:r},backend:n,attrs:{perm:u}}),l=ml(l.length,r.shape.length)),pl("all",l,c.shape.length);const[h,p]=cl(c.shape,l),f=d(p),m=W(d(h),c.dtype),g=n.data.get(c.dataId).values;for(let e=0;e<m.length;++e){const t=e*f;let n=g[t];for(let e=0;e<f;++e){const s=g[t+e];n=n&&s}m[e]=n}null!=u&&n.disposeIntermediateTensorInfo(c);const y=n.makeTensorInfo(h,c.dtype,m);if(i){const e=ZC({inputs:{x:y},backend:n,attrs:{shape:hl(h,o)}});return n.disposeIntermediateTensorInfo(y),e}return y}};const l$={kernelName:ie,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s;lS(r,"any");const o=v(a,r.shape);let l=o;const u=dl(l,r.shape.length);let c=r;null!=u&&(c=zT({inputs:{x:r},backend:n,attrs:{perm:u}}),l=ml(l.length,r.shape.length)),pl("any",l,c.shape.length);const[h,p]=cl(c.shape,l),f=d(p),m=W(d(h),c.dtype),g=n.data.get(c.dataId).values;for(let e=0;e<m.length;++e){const t=e*f;let n=g[t];for(let e=0;e<f;++e){const s=g[t+e];n=n||s}m[e]=n}null!=u&&n.disposeIntermediateTensorInfo(c);const y=n.makeTensorInfo(h,c.dtype,m);if(i){const e=ZC({inputs:{x:y},backend:n,attrs:{shape:hl(h,o)}});return n.disposeIntermediateTensorInfo(y),e}return y}};const u$={kernelName:oe,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s;lS(r,"argMax");let i=v(a,r.shape);const o=dl(i,r.shape.length);let l=r;const u=[];null!=o&&(l=zT({inputs:{x:r},backend:n,attrs:{perm:o}}),u.push(l),i=ml(i.length,l.shape.length)),i=[i[0]],pl("argMax",i,l.shape.length);const[c,h]=cl(l.shape,i),p=W(d(c),"int32"),f=d(h),m=n.data.get(l.dataId).values;for(let e=0;e<p.length;++e){const t=e*f;let n=m[t],s=0;for(let e=0;e<f;++e){const r=m[t+e];r>n&&(n=r,s=e)}p[e]=s}return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(c,"int32",p)}};const c$={kernelName:le,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s;lS(r,"argMin");let i=v(a,r.shape);const o=dl(i,r.shape.length);let l=r;const u=[];null!=o&&(l=zT({inputs:{x:r},backend:n,attrs:{perm:o}}),u.push(l),i=ml(i.length,l.shape.length)),i=[i[0]],pl("argMin",i,l.shape.length);const[c,h]=cl(l.shape,i),p=W(d(c),"int32"),f=d(h),m=n.data.get(l.dataId).values;for(let e=0;e<p.length;++e){const t=e*f;let n=m[t],s=0;for(let e=0;e<f;++e){const r=m[t+e];r<n&&(n=r,s=e)}p[e]=s}return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(c,"int32",p)}},h$=MS(ue,(e=>Math.asin(e))),p$={kernelName:ue,backendName:"cpu",kernelFunc:h$},d$=MS(ce,(e=>Math.asinh(e))),f$={kernelName:ce,backendName:"cpu",kernelFunc:d$},m$=MS(he,(e=>Math.atan(e))),g$={kernelName:he,backendName:"cpu",kernelFunc:m$},y$=dS(((e,t)=>Math.atan2(e,t))),b$=IS(de,y$),x$={kernelName:de,backendName:"cpu",kernelFunc:b$},w$=MS(pe,(e=>Math.atanh(e))),v$={kernelName:pe,backendName:"cpu",kernelFunc:w$};function k$(e,t,n,s,r,a){const i=r.strideHeight,o=r.strideWidth,l=r.dilationHeight,u=r.dilationWidth,c=r.effectiveFilterHeight,h=r.effectiveFilterWidth,p=r.padInfo.top,d=r.padInfo.left,f="max"===a?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=Si(r.outShape,n),g=m.values,y=r.outShape[1]*r.outShape[2]*r.outShape[3],b=r.outShape[2]*r.outShape[3],x=r.outShape[3];for(let t=0;t<r.batchSize;++t){const n=t*y,m=t*s[0];for(let t=0;t<r.inChannels;++t)for(let y=0;y<r.outHeight;++y){const w=y*i-p,v=Math.max(0,w),k=Math.min(r.inHeight,c+w),N=n+y*b;for(let n=0;n<r.outWidth;++n){const i=n*o-d,c=Math.max(0,i),p=Math.min(r.inWidth,h+i);let y=f,b=0,w=0;for(let n=v;n<k;n+=l){const r=m+n*s[1];for(let n=c;n<p;n+=u){const i=e[r+n*s[2]+t];"max"===a&&i>y?y=i:"avg"===a&&(b+=i,w++)}if(isNaN(y))break}g[N+n*x+t]="avg"===a?b/w:y}}}return m}function N$(e,t,n,s,r=!1,a=!1){const i=Si(s.outShape,"int32"),o=s.strideHeight,l=s.strideWidth,u=s.dilationHeight,c=s.dilationWidth,h=s.effectiveFilterHeight,p=s.effectiveFilterWidth,d=s.padInfo.top,f=s.padInfo.left,m=Si(t,n,e);for(let e=0;e<s.batchSize;++e)for(let t=0;t<s.inChannels;++t)for(let n=0;n<s.outHeight;++n){const g=n*o-d;let y=g;for(;y<0;)y+=u;const b=Math.min(s.inHeight,h+g);for(let o=0;o<s.outWidth;++o){const h=o*l-f;let d=h;for(;d<0;)d+=c;const x=Math.min(s.inWidth,p+h);let w=Number.NEGATIVE_INFINITY,v=-1;for(let n=y;n<b;n+=u){const i=n-g;for(let o=d;o<x;o+=c){const l=o-h,u=m.get(e,n,o,t);u>w&&(w=u,v=r?a?((e*s.inHeight+n)*s.inWidth+o)*s.inChannels+t:(n*s.inWidth+o)*s.inChannels+t:i*p+l)}}i.set(v,e,n,o,t)}}return i}function I$(e,t,n,s,r,a){const i=r.strideDepth,o=r.strideHeight,l=r.strideWidth,u=r.dilationDepth,c=r.dilationHeight,h=r.dilationWidth,p=r.effectiveFilterDepth,d=r.effectiveFilterHeight,f=r.effectiveFilterWidth,m=r.padInfo.front,g=r.padInfo.top,y=r.padInfo.left,b="max"===a?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,x=Si(r.outShape,n),w=x.values,v=r.outShape[1]*r.outShape[2]*r.outShape[3]*r.outShape[4],k=r.outShape[2]*r.outShape[3]*r.outShape[4],N=r.outShape[3]*r.outShape[4],I=r.outShape[4];for(let t=0;t<r.batchSize;++t){const n=t*v,x=t*s[0];for(let t=0;t<r.inChannels;++t)for(let v=0;v<r.outDepth;++v){const S=v*i-m;let T=S;for(;T<0;)T+=u;const C=Math.min(r.inDepth,p+S),$=n+v*k;for(let n=0;n<r.outHeight;++n){const i=n*o-g;let p=i;for(;p<0;)p+=c;const m=Math.min(r.inHeight,d+i),v=$+n*N;for(let n=0;n<r.outWidth;++n){const i=n*l-y;let o=i;for(;o<0;)o+=h;const d=Math.min(r.inWidth,f+i),g=v+n*I;let k=b,N=0,S=0;for(let n=T;n<C;n+=u){const r=x+n*s[1];for(let n=p;n<m;n+=c){const i=r+n*s[2];for(let n=o;n<d;n+=h){const r=e[i+n*s[3]+t];if("max"===a&&r>k?k=r:"avg"===a&&(N+=r,S++),isNaN(k))break}if(isNaN(k))break}if(isNaN(k))break}w[g+t]="avg"===a?N/Math.max(S,1):k}}}}return x}const S$={kernelName:fe,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t;lS(r,"avgPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:l}=s;c(so(i,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const u=qi(r.shape,a,i,1,o,l);let h;if(1===u.filterWidth&&1===u.filterHeight&&m(u.inShape,u.outShape))h=yS({inputs:{x:r},backend:n});else{const e=n.data.get(r.dataId).values,t=M(r.shape),s=k$(e,r.shape,r.dtype,t,u,"avg");h=n.makeTensorInfo(u.outShape,r.dtype,s.values)}return h}};const T$={kernelName:ge,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=s;lS(r,"avgPool3d");const c=Ki(r.shape,a,i,1,o,l,u),h=I$(n.data.get(r.dataId).values,r.shape,r.dtype,M(r.shape),c,"avg");return n.makeTensorInfo(h.shape,"float32",h.values)}};const C$={kernelName:ye,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=s;lS([r,a],"avgPool3DGrad");const c=Ki(a.shape,i,o,1,l,u),h=c.strideDepth,p=c.strideHeight,d=c.strideWidth,f=c.filterDepth,m=c.filterHeight,g=c.filterWidth,y=c.dilationDepth,b=c.dilationHeight,x=c.dilationWidth,w=c.effectiveFilterDepth,v=c.effectiveFilterHeight,k=c.effectiveFilterWidth,N=w-1-c.padInfo.front,I=k-1-c.padInfo.left,S=v-1-c.padInfo.top,T=Si(a.shape,"float32"),C=1/(f*m*g),$=n.bufferSync(r);for(let e=0;e<c.batchSize;++e)for(let t=0;t<c.inChannels;++t)for(let n=0;n<c.inDepth;++n)for(let s=0;s<c.inHeight;++s)for(let r=0;r<c.inWidth;++r){const a=n-N,i=s-S,o=r-I;let l=0;for(let n=0;n<w;n+=y){const s=(a+n)/h;if(!(s<0||s>=c.outDepth||Math.floor(s)!==s))for(let n=0;n<v;n+=b){const r=(i+n)/p;if(!(r<0||r>=c.outHeight||Math.floor(r)!==r))for(let n=0;n<k;n+=x){const a=(o+n)/d;if(a<0||a>=c.outWidth||Math.floor(a)!==a)continue;l+=$.get(e,s,r,a,t)}}}T.set(l*C,e,n,s,r,t)}return n.makeTensorInfo(T.shape,T.dtype,T.values)}};const $$={kernelName:me,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,i=a;lS([r,a],"avgPoolGrad");const{filterSize:o,strides:l,pad:u}=s,c=qi(i.shape,o,l,1,u),h=c.strideHeight,p=c.strideWidth,d=c.filterHeight,f=c.filterWidth,m=c.dilationHeight,g=c.dilationWidth,y=c.effectiveFilterHeight,b=c.effectiveFilterWidth,x=b-1-c.padInfo.left,w=y-1-c.padInfo.top,v=Si(i.shape,"float32"),k=1/(d*f),N=n.data.get(r.dataId).values,I=Si(r.shape,"float32",N);for(let e=0;e<c.batchSize;++e)for(let t=0;t<c.inChannels;++t)for(let n=0;n<c.inHeight;++n)for(let s=0;s<c.inWidth;++s){const r=n-w,a=s-x;let i=0;for(let n=0;n<y;n+=m){const s=(r+n)/h;if(!(s<0||s>=c.outHeight||Math.floor(s)!==s))for(let n=0;n<b;n+=g){const r=(a+n)/p;if(r<0||r>=c.outWidth||Math.floor(r)!==r)continue;i+=I.get(e,s,r,t)}}v.set(i*k,e,n,s,t)}return n.makeTensorInfo(v.shape,v.dtype,v.values)}};const E$={kernelName:ht,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,scale:a,offset:i,mean:o,variance:l}=t;c(o.shape.length===l.shape.length,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),c(null==i||o.shape.length===i.shape.length,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),c(null==a||o.shape.length===a.shape.length,(()=>"Batch normalization gradient requires mean and scale to have equal ranks.")),lS([r,o,l,a,i],"batchNorm");let{varianceEpsilon:u}=s;null==u&&(u=.001);const h=n.data.get(r.dataId).values,p=n.data.get(o.dataId).values,d=n.data.get(l.dataId).values,f=a?n.data.get(a.dataId).values:new Float32Array([1]),m=i?n.data.get(i.dataId).values:new Float32Array([0]),g=new Float32Array(h.length),y=m.length,b=f.length,x=d.length,w=p.length;let v=0,k=0,N=0,I=0;for(let e=0;e<h.length;++e)g[e]=m[v++]+(h[e]-p[k++])*f[N++]/Math.sqrt(d[I++]+u),v>=y&&(v=0),k>=w&&(k=0),N>=b&&(N=0),I>=x&&(I=0);return n.makeTensorInfo(r.shape,r.dtype,g)}};const A$={kernelName:xe,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,crops:i}=s;lS([r],"batchToSpaceND");const o=a.reduce(((e,t)=>e*t)),l=hf(r.shape,a,o),u=pf(l.length,a.length),c=df(r.shape,a,o),h=ff(i,a.length),p=mf(c,i,a.length),d=ZC({inputs:{x:r},backend:n,attrs:{shape:l}}),f=zT({inputs:{x:d},backend:n,attrs:{perm:u}}),m=ZC({inputs:{x:f},backend:n,attrs:{shape:c}}),g=lC({inputs:{x:m},backend:n,attrs:{begin:h,size:p}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}};const R$={kernelName:we,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,weights:a}=t,{size:i}=s,o=AS(n.data.get(r.dataId).values,n.data.get(a.dataId).values,a.dtype,a.shape,i);return n.makeTensorInfo([i],a.dtype,o)}};const _$={kernelName:Ne,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{s0:s,s1:r}=t,a=n.data.get(s.dataId).values,i=n.data.get(r.dataId).values,o=Zo(Array.from(a),Array.from(i));return n.makeTensorInfo([o.length],"int32",Int32Array.from(o))}},F$=MS(Te,((e,t)=>{const n=t;return e>n.clipValueMax?n.clipValueMax:e<n.clipValueMin?n.clipValueMin:e})),D$={kernelName:Te,backendName:"cpu",kernelFunc:F$},O$={kernelName:$e,backendName:"cpu",kernelFunc:e=>{const{x:t}=e.inputs,n=e.backend,s=new Float32Array(d(t.shape)),r=n.data.get(t.dataId),a=r.complexTensorInfos.real,i=r.complexTensorInfos.imag,o=n.data.get(a.dataId).values,l=n.data.get(i.dataId).values;for(let e=0;e<o.length;e++){const t=o[e],n=l[e];s[e]=Math.hypot(t,n)}return n.makeOutput(s,t.shape,"float32")}};function M$(e){const{inputs:t,backend:n}=e,{input:s}=t,r=n.data.get(s.dataId).complexTensorInfos.imag,a=n.data.get(r.dataId).values;return n.makeTensorInfo(r.shape,r.dtype,a)}const L$={kernelName:bt,backendName:"cpu",kernelFunc:M$};function z$(e){const{inputs:t,backend:n,attrs:s}=e,{axis:r}=s,a=v(r,t[0].shape)[0];tf(t.map((e=>e.shape)),a);let i=nf(t.map((e=>e.shape)),a);if(0===d(i))return n.makeTensorInfo(i,t[0].dtype,[]);const o=t.filter((e=>d(e.shape)>0));if(1===o.length)return yS({inputs:{x:o[0]},backend:n});if("complex64"===o[0].dtype){const e=o.map((e=>xS({inputs:{input:e},backend:n}))),t=o.map((e=>M$({inputs:{input:e},backend:n}))),s=z$({inputs:e,backend:n,attrs:{axis:a}}),r=z$({inputs:t,backend:n,attrs:{axis:a}}),i=fS({inputs:{real:s,imag:r},backend:n});return e.forEach((e=>n.disposeIntermediateTensorInfo(e))),t.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(r),i}const l=o.map((e=>{const t=d(e.shape.slice(a));return ZC({inputs:{x:e},backend:n,attrs:{shape:[-1,t]}})})),u=l.map((e=>({vals:n.data.get(e.dataId).values,shape:e.shape})));i=nf(l.map((e=>e.shape)),1);const c=1===l[0].shape[0],h=WS(u,i,t[0].dtype,c),p=nf(o.map((e=>e.shape)),a),f=n.makeTensorInfo(p,t[0].dtype,h);return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),f}const P$={kernelName:Ee,backendName:"cpu",kernelFunc:z$};function B$(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:c}=s;lS([r,a],"conv2d");const h=ao(l),p=Xi(r.shape,a.shape,i,u,o,c,!1,h),d=p.filterHeight,f=p.filterWidth,m=p.dilationHeight,g=p.dilationWidth,y=p.padInfo.left,b=p.padInfo.top,x="channelsLast"===p.dataFormat,w=new $r(p.outShape,r.dtype),v=M(r.shape),k=M(a.shape),N=v[0],I=x?v[1]:v[2],S=x?v[2]:1,T=x?1:v[1],C=w.strides[0],$=x?w.strides[1]:w.strides[2],E=x?w.strides[2]:1,A=x?1:w.strides[1],R=n.data.get(r.dataId).values,_=n.data.get(a.dataId).values,F=w.values;for(let e=0;e<p.batchSize;++e){const t=e*N,n=e*C;for(let e=0;e<p.outHeight;++e){const s=n+e*$,r=e*p.strideHeight-b;for(let e=0;e<d;++e){const n=r+e*m;if(n<0||n>=p.inHeight)continue;const a=e*k[0],i=t+n*I;for(let e=0;e<p.outWidth;++e){const t=s+e*E,n=e*p.strideWidth-y;for(let e=0;e<f;++e){const s=n+e*g;if(s<0||s>=p.inWidth)continue;const r=i+s*S;let o=a+e*k[1];for(let e=0;e<p.inChannels;++e){const n=R[r+e*T];for(let e=0;e<p.outChannels;++e)F[t+e*A]+=n*_[o+e];o+=p.outChannels}}}}}}return n.makeTensorInfo(w.shape,w.dtype,F)}const W$={kernelName:Ae,backendName:"cpu",kernelFunc:B$};const V$={kernelName:Re,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,dy:a}=t,{strides:i,pad:o,dataFormat:l,dimRoundingMode:u,filterShape:c}=s;lS([r,a],"conv2dBackpropFilter");const h=ao(l),p=Xi(r.shape,c,i,1,o,u,!1,h),{strideHeight:d,strideWidth:f,filterHeight:m,filterWidth:g}=p,y="channelsLast"===p.dataFormat,b=new $r(p.filterShape,"float32"),x=p.padInfo.left,w=p.padInfo.top,v=n.data.get(r.dataId).values,k=n.data.get(a.dataId).values,N=new $r(r.shape,r.dtype,v),I=new $r(a.shape,a.dtype,k);for(let e=0;e<m;++e){const t=Math.max(0,Math.ceil((w-e)/d)),n=Math.min(p.outHeight,(p.inHeight+w-e)/d);for(let s=0;s<g;++s){const r=Math.max(0,Math.ceil((x-s)/f)),a=Math.min(p.outWidth,(p.inWidth+x-s)/f);for(let i=0;i<p.inChannels;++i)for(let o=0;o<p.outChannels;++o){let l=0;for(let u=0;u<p.batchSize;++u)for(let c=t;c<n;++c){const t=e+c*d-w;for(let e=r;e<a;++e){const n=s+e*f-x;l+=y?N.get(u,t,n,i)*I.get(u,c,e,o):N.get(u,i,t,n)*I.get(u,o,c,e)}}b.set(l,e,s,i,o)}}}return n.makeTensorInfo(b.shape,b.dtype,b.values)}};const U$={kernelName:_e,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,filter:a}=t,{inputShape:i,strides:o,pad:l,dataFormat:u,dimRoundingMode:c}=s;lS([r,a],"conv2dBackpropInput");const h=M(a.shape),p=M(r.shape);let d=ao(u);const f=Xi(i,a.shape,o,1,l,c,!1,d),m=new $r(f.inShape,"float32"),g=m.values,y=n.data.get(r.dataId).values,b=n.data.get(a.dataId).values,[x,w,v]=h,{batchSize:k,filterHeight:N,filterWidth:I,inChannels:S,inHeight:T,inWidth:C,outChannels:$,outHeight:E,outWidth:A,strideHeight:R,strideWidth:_}=f;d=f.dataFormat;const F=N-1-f.padInfo.top,D=I-1-f.padInfo.left,O="channelsLast"===d,L=m.strides[0],z=O?m.strides[1]:m.strides[2],P=O?m.strides[2]:1,B=O?1:m.strides[1],W=p[0],V=O?p[1]:p[2],U=O?p[2]:1,G=O?1:p[1];for(let e=0;e<k;++e)for(let t=0;t<S;++t)for(let n=0;n<T;++n){const s=n-F,r=Math.max(0,Math.ceil(s/R)),a=Math.min(E,(N+s)/R);for(let i=0;i<C;++i){const o=i-D,l=Math.max(0,Math.ceil(o/_)),u=Math.min(A,(I+o)/_);let c=0;for(let n=r;n<a;++n){const r=n*R-s;for(let s=l;s<u;++s){const a=W*e+V*n+U*s,i=x*(N-1-r)+w*(I-1-(s*_-o))+v*t;for(let e=0;e<$;++e){c+=y[a+G*e]*b[i+e]}}}g[L*e+z*n+P*i+B*t]=c}}return n.makeTensorInfo(m.shape,m.dtype,m.values)}};const G$={kernelName:Fe,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:i,pad:o,dilations:l}=s;lS([r,a],"conv3d");const u=Yi(r.shape,a.shape,i,l,o),{filterDepth:c,filterHeight:h,filterWidth:p,dilationDepth:d,dilationHeight:f,dilationWidth:m,padInfo:g}=u,y=g.front,b=g.left,x=g.top,w=new $r(u.outShape,r.dtype),v=n.data.get(r.dataId).values,k=n.data.get(a.dataId).values,N=w.values,I=M(r.shape),S=M(a.shape);for(let e=0;e<u.batchSize;++e){const t=e*I[0],n=e*w.strides[0];for(let e=0;e<u.outDepth;++e){const s=n+e*w.strides[1],r=e*u.strideDepth-y;for(let e=0;e<c;++e){const n=r+e*d;if(n<0||n>=u.inDepth)continue;const a=e*S[0],i=t+n*I[1];for(let e=0;e<u.outHeight;++e){const t=s+e*w.strides[2],n=e*u.strideHeight-x;for(let e=0;e<h;++e){const s=n+e*f;if(s<0||s>=u.inHeight)continue;const r=a+e*S[1],o=i+s*I[2];for(let e=0;e<u.outWidth;++e){const n=t+e*u.outChannels,s=e*u.strideWidth-b;for(let e=0;e<p;++e){const t=s+e*m;if(t<0||t>=u.inWidth)continue;const a=r+e*S[2],i=o+t*u.inChannels;let l=a;for(let e=0;e<u.inChannels;++e){const t=v[i+e];for(let e=0;e<u.outChannels;++e)N[n+e]+=t*k[l+e];l+=u.outChannels}}}}}}}}return n.makeTensorInfo(w.shape,w.dtype,w.values)}};const H$={kernelName:De,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,dy:a}=t,{strides:i,pad:o,filterShape:l}=s;lS([r,a],"conv3dBackpropFilterV2");const u=M(r.shape),c=M(a.shape),h=Yi(r.shape,l,i,1,o),p=h.strideDepth,d=h.strideHeight,f=h.strideWidth,m=h.filterDepth,g=h.filterHeight,y=h.filterWidth,b=new $r(h.filterShape,"float32"),x=b.values,[w,v,k,N]=b.strides,I=n.data.get(a.dataId).values,[S,T,C,$]=c,E=n.data.get(r.dataId).values,[A,R,_,F]=u,D=h.padInfo.front,O=h.padInfo.left,L=h.padInfo.top;for(let e=0;e<m;++e){const t=Math.max(0,Math.ceil((D-e)/p)),n=Math.min(h.outDepth,(h.inDepth+D-e)/p),s=e*w;for(let r=0;r<g;++r){const a=Math.max(0,Math.ceil((L-r)/d)),i=Math.min(h.outHeight,(h.inHeight+L-r)/d),o=r*v+s;for(let s=0;s<y;++s){const l=Math.max(0,Math.ceil((O-s)/f)),u=Math.min(h.outWidth,(h.inWidth+O-s)/f),c=s*k+o;for(let o=0;o<h.inChannels;++o){const m=o*N+c;for(let c=0;c<h.outChannels;++c){let g=0;for(let m=0;m<h.batchSize;++m){const h=m*A,y=m*S;for(let m=t;m<n;++m){const t=(e+m*p-D)*R+h,n=m*T+y;for(let e=a;e<i;++e){const a=(r+e*d-L)*_+t,i=e*C+n;for(let e=l;e<u;++e){const t=e*$+i;g+=E[(s+e*f-O)*F+a+o]*I[t+c]}}}}x[m+c]=g}}}}}return n.makeTensorInfo(b.shape,b.dtype,b.values)}};const j$={kernelName:Oe,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,filter:a}=t,{pad:i,strides:o,inputShape:l}=s;lS([r],"conv3dBackpropInputV2");const u=M(r.shape),c=M(a.shape),h=Yi(l,a.shape,o,1,i),p=new $r(h.inShape,"float32"),d=p.values,[f,m,g,y]=p.strides,b=n.data.get(r.dataId).values,[x,w,v,k]=u,N=n.data.get(a.dataId).values,[I,S,T,C]=c,{batchSize:$,filterDepth:E,filterHeight:A,filterWidth:R,inChannels:_,inDepth:F,inHeight:D,inWidth:O,outChannels:L,outDepth:z,outHeight:P,outWidth:B,strideDepth:W,strideHeight:V,strideWidth:U}=h,G=E-1-h.padInfo.front,H=A-1-h.padInfo.top,j=R-1-h.padInfo.left;for(let e=0;e<$;++e)for(let t=0;t<_;++t)for(let n=0;n<F;++n){const s=n-G,r=Math.max(0,Math.ceil(s/W)),a=Math.min(z,(E+s)/W);for(let i=0;i<D;++i){const o=i-H,l=Math.max(0,Math.ceil(o/V)),u=Math.min(P,(A+o)/V);for(let c=0;c<O;++c){const h=c-j,p=Math.max(0,Math.ceil(h/U)),$=Math.min(B,(R+h)/U);let _=0;for(let n=r;n<a;++n){const r=n*W-s;for(let s=l;s<u;++s){const a=s*V-o;for(let i=p;i<$;++i){const o=x*e+w*n+v*s+k*i,l=I*(E-1-r)+S*(A-1-a)+T*(R-1-(i*U-h))+C*t;for(let e=0;e<L;++e){_+=b[o+e]*N[l+e]}}}}d[f*e+m*n+g*i+y*c+t]=_}}}return n.makeTensorInfo(p.shape,p.dtype,p.values)}},q$=MS(Me,(e=>Math.cos(e))),K$={kernelName:Me,backendName:"cpu",kernelFunc:q$},X$=MS(Le,(e=>Math.cosh(e))),Y$={kernelName:Le,backendName:"cpu",kernelFunc:X$};const Z$={kernelName:Be,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{image:r,boxes:a,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:u}=s,[c,h,p,d]=r.shape,f=a.shape[0],[m,g]=o,y=Si([f,m,g,d],"float32"),b=n.data.get(a.dataId).values,x=n.data.get(i.dataId).values,w=n.data.get(r.dataId).values,v=M(r.shape),k=M(y.shape);for(let e=0;e<f;e++){const t=4*e,n=b[t],s=b[t+1],r=b[t+2],a=b[t+3],i=x[e];if(i>=c)continue;const o=m>1?(r-n)*(h-1)/(m-1):0,f=g>1?(a-s)*(p-1)/(g-1):0;for(let t=0;t<m;t++){const c=m>1?n*(h-1)+t*o:.5*(n+r)*(h-1);if(c<0||c>h-1)for(let n=0;n<g;n++)for(let s=0;s<d;s++){const r=s+n*k[2]+t*k[1]+e*k[0];y.values[r]=u}else if("bilinear"===l){const n=Math.floor(c),r=Math.ceil(c),o=c-n;for(let l=0;l<g;l++){const c=g>1?s*(p-1)+l*f:.5*(s+a)*(p-1);if(c<0||c>p-1){for(let n=0;n<d;n++){const s=n+l*k[2]+t*k[1]+e*k[0];y.values[s]=u}continue}const h=Math.floor(c),m=Math.ceil(c),b=c-h;for(let s=0;s<d;s++){let a=s+h*v[2]+n*v[1]+i*v[0];const u=w[a];a=s+m*v[2]+n*v[1]+i*v[0];const c=w[a];a=s+h*v[2]+r*v[1]+i*v[0];const p=w[a];a=s+m*v[2]+r*v[1]+i*v[0];const d=u+(c-u)*b,f=p+(w[a]-p)*b;a=s+l*k[2]+t*k[1]+e*k[0],y.values[a]=d+(f-d)*o}}}else for(let n=0;n<g;++n){const r=g>1?s*(p-1)+n*f:.5*(s+a)*(p-1);if(r<0||r>p-1){for(let s=0;s<d;s++){const r=s+n*k[2]+t*k[1]+e*k[0];y.values[r]=u}continue}const o=Math.round(r),l=Math.round(c);for(let s=0;s<d;s++){const r=s+o*v[2]+l*v[1]+i*v[0],a=s+n*k[2]+t*k[1]+e*k[0];y.values[a]=w[r]}}}}return n.makeTensorInfo(y.shape,y.dtype,y.values)}};const J$={kernelName:ze,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,exclusive:i,reverse:o}=s;lS(r,"cumprod");const l=dl([a],r.shape.length);let u=r;null!=l&&(u=zT({inputs:{x:r},backend:n,attrs:{perm:l}}));const c=ml(1,r.shape.length)[0];if(c!==u.shape.length-1)throw new Error(`backend.cumprod in CPU expects an inner-most axis=${u.shape.length-1} but got axis=${c}`);const h=Wr(u.dtype,"int32"),p=B(d(u.shape),h),f=n.data.get(u.dataId).values,m=u.shape[u.shape.length-1],g=o?(e,t)=>e+m-t-1:(e,t)=>e+t;for(let e=0;e<f.length;e+=m)for(let t=0;t<m;t++){const n=g(e,t);if(0===t)p[n]=i?1:f[n];else{const s=g(e,t-1);p[n]=i?f[s]*p[s]:f[n]*p[s]}}const y=n.makeTensorInfo(u.shape,h,p);if(null!=l){const e=zT({inputs:{x:y},backend:n,attrs:{perm:fl(l)}});return n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(u),e}return y}};const Q$={kernelName:Pe,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,exclusive:i,reverse:o}=s;lS(r,"cumsum");const l=dl([a],r.shape.length);let u=r;null!=l&&(u=zT({inputs:{x:r},backend:n,attrs:{perm:l}}));const c=ml(1,r.shape.length)[0];if(c!==u.shape.length-1)throw new Error(`backend.cumsum in CPU expects an inner-most axis=${u.shape.length-1} but got axis=${c}`);const h=Wr(u.dtype,"int32"),p=W(d(u.shape),h),f=n.data.get(u.dataId).values,m=u.shape[u.shape.length-1],g=o?(e,t)=>e+m-t-1:(e,t)=>e+t;for(let e=0;e<f.length;e+=m)for(let t=0;t<m;t++){const n=g(e,t);if(0===t)p[n]=i?0:f[n];else{const s=g(e,t-1);p[n]=i?f[s]+p[s]:f[n]+p[s]}}const y=n.makeTensorInfo(u.shape,h,p);if(null!=l){const e=zT({inputs:{x:y},backend:n,attrs:{perm:fl(l)}});return n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(u),e}return y}};const eE={kernelName:We,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,weights:a}=t,{size:i,binaryOutput:o}=s;if(1===r.shape.length){const e=AS(n.data.get(r.dataId).values,n.data.get(a.dataId).values,a.dtype,a.shape,i);return n.makeTensorInfo([i],a.dtype,e)}if(2===r.shape.length){const e=RS(n.bufferSync(r),n.bufferSync(a),i,o);return n.makeTensorInfo(e.shape,a.dtype,e.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${r.shape.length}.`)}};const tE={kernelName:Ve,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockSize:a,dataFormat:i}=s;c("NHWC"===i,(()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${i}`));const o=r.shape[0],l=r.shape[1],u=r.shape[2],h=r.shape[3],p=l*a,d=u*a,f=h/(a*a),m=n.data.get(r.dataId).values,g=new Float32Array(o*p*d*f);let y=0;for(let e=0;e<o;++e)for(let t=0;t<p;++t){const n=Math.floor(t/a),s=t%a;for(let t=0;t<d;++t){const r=Math.floor(t/a),i=(s*a+t%a)*f;for(let t=0;t<f;++t){const s=t+i+h*(r+u*(n+l*e));g[y++]=m[s]}}}return n.makeTensorInfo([o,p,d,f],r.dtype,g)}};function nE(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:i,pad:o,dilations:l,dimRoundingMode:u}=s;lS([r,a],"depthwiseConv2DNative");const h=M(r.shape),p=M(a.shape);let d=l;null==d&&(d=[1,1]),c(so(i,d),(()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${d}'`));const f=Xi(r.shape,a.shape,i,d,o,u,!0),{filterHeight:m,filterWidth:g,dilationHeight:y,dilationWidth:b,padInfo:x}=f,w=x.left,v=x.top,k=f.outChannels/f.inChannels,N=new $r(f.outShape,r.dtype),I=n.data.get(r.dataId).values,S=n.data.get(a.dataId).values,T=N.values;for(let e=0;e<f.batchSize;++e){const t=e*h[0],n=e*N.strides[0];for(let e=0;e<f.outHeight;++e){const s=n+e*N.strides[1],r=e*f.strideHeight-v;for(let e=0;e<m;++e){const n=r+e*y;if(n<0||n>=f.inHeight)continue;const a=e*p[0],i=t+n*h[1];for(let e=0;e<f.outWidth;++e){const t=s+e*N.strides[2],n=e*f.strideWidth-w;for(let e=0;e<g;++e){const s=n+e*b;if(s<0||s>=f.inWidth)continue;const r=a+e*p[1],o=i+s*f.inChannels;let l=t,u=r;for(let e=0;e<f.inChannels;++e){const t=I[o+e];for(let e=0;e<k;++e)T[l+e]+=t*S[u+e];l+=k,u+=k}}}}}}return n.makeTensorInfo(N.shape,N.dtype,N.values)}const sE={kernelName:Ue,backendName:"cpu",kernelFunc:nE};const rE={kernelName:Ge,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,dy:a}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,filterShape:c}=s;lS([r,a],"depthwiseConv2dNativeBackpropFilter");const h=Xi(r.shape,c,i,o,l,u,!0),{strideHeight:p,strideWidth:d,filterHeight:f,filterWidth:m}=h,g=new $r(h.filterShape,"float32"),y=h.padInfo.left,b=h.padInfo.top,x=h.outChannels/h.inChannels,w=n.data.get(r.dataId).values,v=new $r(r.shape,r.dtype,w),k=n.data.get(a.dataId).values,N=new $r(a.shape,a.dtype,k);for(let e=0;e<f;++e){const t=Math.max(0,Math.ceil((b-e)/p)),n=Math.min(h.outHeight,(h.inHeight+b-e)/p);for(let s=0;s<m;++s){const r=Math.max(0,Math.ceil((y-s)/d)),a=Math.min(h.outWidth,(h.inWidth+y-s)/d);for(let i=0;i<h.outChannels;++i){const o=Math.trunc(i/x),l=i%x;let u=0;for(let l=0;l<h.batchSize;++l)for(let c=t;c<n;++c){const t=e+c*p-b;for(let e=r;e<a;++e){const n=s+e*d-y;u+=v.get(l,t,n,o)*N.get(l,c,e,i)}}g.set(u,e,s,o,l)}}}return n.makeTensorInfo(g.shape,g.dtype,g.values)}};const aE={kernelName:He,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,filter:a}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,inputShape:c}=s;lS([r,a],"depthwiseConv2DNativeBackpropInput");const h=M(r.shape),p=M(a.shape),d=Xi(c,a.shape,i,o,l,u,!0),f=new $r(d.inShape,"float32"),m=f.values,[g,y,b]=f.strides,x=n.data.get(r.dataId).values,[w,v,k]=h,N=n.data.get(a.dataId).values,[I,S,T]=p,{batchSize:C,filterHeight:$,filterWidth:E,inChannels:A,inHeight:R,inWidth:_,outChannels:F,outHeight:D,outWidth:O,strideHeight:L,strideWidth:z}=d,P=$-1-d.padInfo.top,B=E-1-d.padInfo.left,W=F/A;for(let e=0;e<C;++e)for(let t=0;t<A;++t)for(let n=0;n<R;++n){const s=n-P,r=Math.max(0,Math.ceil(s/L)),a=Math.min(D,($+s)/L);for(let i=0;i<_;++i){const o=i-B,l=Math.max(0,Math.ceil(o/z)),u=Math.min(O,(E+o)/z);let c=0;for(let n=r;n<a;++n){const r=n*L-s;for(let s=l;s<u;++s){const a=w*e+v*n+k*s,i=I*($-1-r)+S*(E-1-(s*z-o))+T*t;for(let e=0;e<W;++e){c+=x[a+(t*W+e)]*N[i+e]}}}m[g*e+y*n+b*i+t]=c}}return n.makeTensorInfo(f.shape,f.dtype,f.values)}};const iE={kernelName:je,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:s}=t,r=d(s.shape),a=n.data.get(s.dataId).values,i=Si([r,r],s.dtype),o=i.values;for(let e=0;e<a.length;e++)o[e*r+e]=a[e];const l=[...s.shape,...s.shape];return n.makeTensorInfo(l,i.dtype,i.values)}},oE={kernelName:qe,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s,filter:r}=e,{strides:a,pad:i,dilations:o}=n,l=t,u=l.data.get(s.dataId).values,c=s.shape.length,h=l.data.get(r.dataId).values,p=r.shape.length,{batchSize:f,inHeight:m,inWidth:g,inChannels:y,outHeight:b,outWidth:x,padInfo:w,strideHeight:v,strideWidth:k,filterHeight:N,filterWidth:S,dilationHeight:T,dilationWidth:C,outShape:$}=ji(s.shape,r.shape,a,i,"NHWC",o),E=d($),A=$.length,R=I(s.dtype,E);for(let e=0;e<f;++e)for(let t=0;t<b;++t){const n=t*v-w.top;for(let a=0;a<x;++a){const i=a*k-w.left;for(let o=0;o<y;++o){let l=Number.MIN_SAFE_INTEGER;for(let t=0;t<N;++t){const a=n+t*T;if(a>=0&&a<m)for(let n=0;n<S;++n){const d=i+n*C;if(d>=0&&d<g){const i=G([e,a,d,o],c,M(s.shape)),f=G([t,n,o],p,M(r.shape)),m=u[i]+h[f];m>l&&(l=m)}}}R[G([e,t,a,o],A,M($))]=l}}}return{dataId:l.write(pr(R,s.dtype),$,s.dtype),shape:$,dtype:s.dtype}}},lE={kernelName:Xe,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s,filter:r,dy:a}=e,{strides:i,pad:o,dilations:l}=n,u=t,h=z(s.shape,u.data.get(s.dataId).values),p=z(r.shape,u.data.get(r.dataId).values),{batchSize:d,inHeight:f,inWidth:m,inChannels:g,outHeight:y,outWidth:b,padInfo:x,strideHeight:w,strideWidth:v,filterHeight:k,filterWidth:N,dilationHeight:I,dilationWidth:S,outShape:T}=ji(s.shape,r.shape,i,o,"NHWC",l);c(a.rank===T.length,(()=>`Error in Dilation2DBackpropFilter, dy must have the same rank as output ${T.length}, but got ${a.rank}`));const C=z(T,u.data.get(a.dataId).values),$=V(r.shape,r.dtype);for(let e=0;e<d;++e)for(let t=0;t<y;++t){const n=t*w-x.top;for(let s=0;s<b;++s){const r=s*v-x.left;for(let a=0;a<g;++a){let i=Number.MIN_SAFE_INTEGER,o=0,l=0;for(let t=0;t<k;++t){const s=n+t*I;if(s>=0&&s<f)for(let n=0;n<N;++n){const u=r+n*S;if(u>=0&&u<m){const r=h[e][s][u][a]+p[t][n][a];r>i&&(i=r,o=t,l=n)}}}$[o][l][a]+=C[e][t][s][a]}}}return{dataId:u.write(pr($,s.dtype),r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},uE={kernelName:Ke,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s,filter:r,dy:a}=e,{strides:i,pad:o,dilations:l}=n,u=t,h=z(s.shape,u.data.get(s.dataId).values),p=z(r.shape,u.data.get(r.dataId).values),{batchSize:d,inHeight:f,inWidth:m,inChannels:g,outHeight:y,outWidth:b,padInfo:x,strideHeight:w,strideWidth:v,filterHeight:k,filterWidth:N,dilationHeight:I,dilationWidth:S,outShape:T}=ji(s.shape,r.shape,i,o,"NHWC",l);c(a.rank===T.length,(()=>`Error in Dilation2DBackpropInput, dy must have the same rank as output ${T.length}, but got ${a.rank}`));const C=z(T,u.data.get(a.dataId).values),$=V(s.shape,s.dtype);for(let e=0;e<d;++e)for(let t=0;t<y;++t){const n=t*w-x.top;for(let s=0;s<b;++s){const r=s*v-x.left;for(let a=0;a<g;++a){let i=Number.MIN_SAFE_INTEGER,o=n<0?0:n,l=r<0?0:r;for(let t=0;t<k;++t){const s=n+t*I;if(s>=0&&s<f)for(let n=0;n<N;++n){const u=r+n*S;if(u>=0&&u<m){const r=h[e][s][u][a]+p[t][n][a];r>i&&(i=r,o=s,l=u)}}}$[e][o][l][a]+=C[e][t][s][a]}}}return{dataId:u.write(pr($,s.dtype),s.shape,s.dtype),shape:s.shape,dtype:s.dtype}}};const cE={kernelName:Ye,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{image:r}=t,{canvas:a,options:i}=s,{contextOptions:o,imageOptions:l}=i||{},u=(null==l?void 0:l.alpha)||1,c=(null==o?void 0:o.contextType)||"2d";if("2d"!==c)throw new Error(`Context type ${o.contextType} is not supported by the CPU backend.`);const h=a.getContext(c,(null==o?void 0:o.contextAttributes)||{});if(null==h)throw new Error(`Could not get the context with ${c} type.`);const[p,d]=r.shape.slice(0,2),f=2===r.shape.length?1:r.shape[2],m=n.data.get(r.dataId).values,g="float32"===r.dtype?255:1,y=new Uint8ClampedArray(d*p*4);for(let e=0;e<p*d;++e){const t=[0,0,0,255*u];for(let n=0;n<f;n++){const s=m[e*f+n];if("float32"===r.dtype){if(s<0||s>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${s}.`)}else if("int32"===r.dtype&&(s<0||s>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${s}.`);1===f?(t[0]=s*g,t[1]=s*g,t[2]=s*g):t[n]=s*g}const n=4*e;y[n+0]=Math.round(t[0]),y[n+1]=Math.round(t[1]),y[n+2]=Math.round(t[2]),y[n+3]=Math.round(t[3])}a.width=d,a.height=p;const b=new ImageData(y,d,p);return h.putImageData(b,0,0),r}};function hE(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s;let o;lS(r,"sum"),o="bool"===r.dtype?kS({inputs:{x:r},backend:n,attrs:{dtype:"int32"}}):yS({inputs:{x:r},backend:n});const l=o.shape.length,u=v(a,o.shape),c=dl(u,l);let h=u,p=o;null!=c&&(p=zT({inputs:{x:o},backend:n,attrs:{perm:c}}),h=ml(h.length,l)),pl("sum",h,p.shape.length);const[f,m]=cl(p.shape,h);let g=gS(n,f,Wr(p.dtype,"int32"));const y=d(m),b=n.data.get(g.dataId).values,x=n.data.get(p.dataId).values;for(let e=0;e<b.length;++e){const t=e*y;let n=0;for(let e=0;e<y;++e)n+=x[t+e];b[e]=n}if(i){const e=g;g=ZC({inputs:{x:g},backend:n,attrs:{shape:hl(g.shape,u)}}),n.disposeIntermediateTensorInfo(e)}return n.disposeIntermediateTensorInfo(o),null!=c&&n.disposeIntermediateTensorInfo(p),g}const pE={kernelName:On,backendName:"cpu",kernelFunc:hE};const dE={kernelName:Je,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{equation:r}=s,a=t,{allDims:i,summedDims:o,idDims:l}=Df(r,a.length);Mf(i.length,l,a);const{path:u,steps:c}=Lf(o,l),h=c.length;let p=null,d=i.length;const f=[];for(let e=0;e<h;++e){for(const t of c[e]){const{permutationIndices:e,expandDims:s}=Of(d,l[t]);let r;zf(e)?r=a[t]:(r=zT({inputs:{x:a[t]},backend:n,attrs:{perm:e}}),f.push(r));const i=r.shape.slice();for(let e=0;e<s.length;++e)i.splice(s[e],0,1);m(r.shape,i)||(r=ZC({inputs:{x:r},backend:n,attrs:{shape:i}}),f.push(r)),null===p?p=r:(p=AT({inputs:{a:r,b:p},backend:n}),f.push(p))}e<h-1&&(u[e]>=0&&(p=hE({inputs:{x:p},backend:n,attrs:{axis:u[e]-(i.length-d),keepDims:!1}}),f.push(p)),d--)}for(const e of f)e!==p&&n.disposeIntermediateTensorInfo(e);return p}};const fE={kernelName:et,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{dy:s,y:r}=t;lS([s,r],"eluGrad");const a=new Float32Array(d(r.shape)),i=n.data.get(r.dataId).values,o=n.data.get(s.dataId).values;for(let e=0;e<i.length;++e){const t=i[e];a[e]=t>=0?o[e]:o[e]*(t+1)}return n.makeTensorInfo(r.shape,"float32",a)}},mE=MS(tt,(e=>{const t=Math.sign(e),n=Math.abs(e),s=1/(1+.3275911*n);return t*(1-((((1.061405429*s-1.453152027)*s+1.421413741)*s-.284496736)*s+.254829592)*s*Math.exp(-n*n))})),gE={kernelName:tt,backendName:"cpu",kernelFunc:mE};function yE(e){const{inputs:t,backend:n,attrs:s}=e,{input:r}=t,{dim:a}=s,i=r.shape.length,o=r.shape.slice();let l=a;return a<0&&(c(-(i+1)<=a,(()=>`Axis must be in the interval [${-(i+1)}, ${i}]`)),l=i+a+1),o.splice(l,0,1),ZC({inputs:{x:r},backend:n,attrs:{shape:o}})}const bE={kernelName:rt,backendName:"cpu",kernelFunc:yE},xE=dS(((e,t)=>e/t)),wE=IS(Ze,xE),vE={kernelName:Ze,backendName:"cpu",kernelFunc:wE};function kE(e,t,n){const s=e.shape,r=s[0],a=s[1],i=n.data.get(e.dataId),o=i.complexTensorInfos.real,l=i.complexTensorInfos.imag,u=[r,a],c=d(u),h=N("float32",c),p=N("float32",c);for(let e=0;e<r;e++){const s=lC({inputs:{x:o},backend:n,attrs:{begin:[e,0],size:[1,a]}}),r=lC({inputs:{x:l},backend:n,attrs:{begin:[e,0],size:[1,a]}}),i=fS({inputs:{real:s,imag:r},backend:n}),{real:u,imag:c}=NE(i,t,n),d=If(u,c);for(let t=0;t<a;t++){const n=$f(d,t);h[e*a+t]=n.real,p[e*a+t]=n.imag}n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(i)}const f=n.makeTensorInfo(u,"float32",h),m=n.makeTensorInfo(u,"float32",p),g=fS({inputs:{real:f,imag:m},backend:n});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}function NE(e,t,n){const s=d(e.shape),r=n.data.get(e.dataId),a=n.data.get(r.complexTensorInfos.real.dataId).values,i=n.data.get(r.complexTensorInfos.imag.dataId).values;if(0==((o=s)&o-1)){const r=IE(a,i,s,t,n),o=[e.shape[0],e.shape[1]];if(t){const e=n.makeTensorInfo(o,"float32",r.real),t=n.makeTensorInfo(o,"float32",r.imag),a=n.makeTensorInfo([],"float32",hr(s,"float32")),i=yS({inputs:{x:a},backend:n}),l=vE.kernelFunc({inputs:{a:e,b:a},backend:n}),u=vE.kernelFunc({inputs:{a:t,b:i},backend:n}),c=n.data.get(l.dataId).values,h=n.data.get(u.dataId).values;return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(u),{real:c,imag:h}}return r}{const e=function(e,t,n){const s=new Float32Array(2*t);for(let r=0;r<t;r++){let a=0,i=0;for(let s=0;s<t;s++){const o=Rf(r*s,t,n),l=$f(e,s);a+=l.real*o.real-l.imag*o.imag,i+=l.real*o.imag+l.imag*o.real}n&&(a/=t,i/=t),Ef(s,a,i,r)}return s}(If(a,i),s,t);return Sf(e)}var o}function IE(e,t,n,s,r){if(1===n)return{real:e,imag:t};const a=If(e,t),i=n/2,o=Tf(a),l=o.real,u=o.imag,c=[l.length],h=r.makeTensorInfo(c,"float32",l),p=r.makeTensorInfo(c,"float32",u),d=fS({inputs:{real:h,imag:p},backend:r}),f=Cf(a),m=f.real,g=f.imag,y=[m.length],b=r.makeTensorInfo(y,"float32",m),x=r.makeTensorInfo(y,"float32",g),w=fS({inputs:{real:b,imag:x},backend:r}),v=IE(l,u,i,s,r),k=v.real,N=v.imag,I=[k.length],S=r.makeTensorInfo(I,"float32",k),T=r.makeTensorInfo(I,"float32",N),C=fS({inputs:{real:S,imag:T},backend:r}),$=IE(m,g,i,s,r),E=$.real,A=$.imag,R=[E.length],_=r.makeTensorInfo(R,"float32",E),F=r.makeTensorInfo(R,"float32",A),D=fS({inputs:{real:_,imag:F},backend:r}),O=Af(n,s),M=[O.real.length],L=r.makeTensorInfo(M,"float32",O.real),z=r.makeTensorInfo(M,"float32",O.imag),P=fS({inputs:{real:L,imag:z},backend:r}),B=AT({inputs:{a:P,b:D},backend:r}),W=$S({inputs:{a:C,b:B},backend:r}),V=AC({inputs:{a:C,b:B},backend:r}),U=xS({inputs:{input:W},backend:r}),G=xS({inputs:{input:V},backend:r}),H=M$({inputs:{input:W},backend:r}),j=M$({inputs:{input:V},backend:r}),q=z$({inputs:[U,G],backend:r,attrs:{axis:0}}),K=z$({inputs:[H,j],backend:r,attrs:{axis:0}}),X=r.data.get(q.dataId).values,Y=r.data.get(K.dataId).values;return r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(p),r.disposeIntermediateTensorInfo(d),r.disposeIntermediateTensorInfo(b),r.disposeIntermediateTensorInfo(x),r.disposeIntermediateTensorInfo(w),r.disposeIntermediateTensorInfo(S),r.disposeIntermediateTensorInfo(T),r.disposeIntermediateTensorInfo(C),r.disposeIntermediateTensorInfo(_),r.disposeIntermediateTensorInfo(F),r.disposeIntermediateTensorInfo(D),r.disposeIntermediateTensorInfo(L),r.disposeIntermediateTensorInfo(z),r.disposeIntermediateTensorInfo(P),r.disposeIntermediateTensorInfo(B),r.disposeIntermediateTensorInfo(W),r.disposeIntermediateTensorInfo(V),r.disposeIntermediateTensorInfo(U),r.disposeIntermediateTensorInfo(H),r.disposeIntermediateTensorInfo(G),r.disposeIntermediateTensorInfo(j),r.disposeIntermediateTensorInfo(q),r.disposeIntermediateTensorInfo(K),{real:X,imag:Y}}const SE={kernelName:it,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:s}=t,r=d(s.shape),a=s.shape[s.shape.length-1],i=ZC({inputs:{x:s},backend:n,attrs:{shape:[r/a,a]}}),o=kE(i,!1,n),l=ZC({inputs:{x:o},backend:n,attrs:{shape:s.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}};function TE(e){const{backend:t,attrs:n}=e,{shape:s,value:r,dtype:a}=n,i=a||F(r),o=I(i,d(s));return function(e,t,n){e.fill(t)}(o,r),t.makeTensorInfo(s,i,o)}const CE={kernelName:ot,backendName:"cpu",kernelFunc:TE};const $E={kernelName:lt,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:s}=e,r=n,a=N(s.dtype,d(s.shape)),[i,o,l,u]=s.shape,c=r.data.get(s.dataId).values;for(let e=0;e<i;e++){const t=e*l*o*u;for(let e=0;e<o;e++){const n=e*(l*u);for(let e=0;e<l;e++){const s=e*u;for(let r=0;r<u;r++){const i=Math.round(l-e-1),o=t+n+s+r;let h=c[o];if(i>=0&&i<l){h=c[t+n+i*u+r]}a[o]=h}}}}return{dataId:r.write(a,s.shape,s.dtype),shape:s.shape,dtype:s.dtype}}};const EE={kernelName:ps,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:p,activation:d,leakyreluAlpha:f}=s;let m=B$({inputs:{x:r,filter:a},backend:n,attrs:{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:p}});if(i){const e=m;if("NCHW"===c&&1===i.shape.length&&1!==i.shape[0]){const e=ZC({inputs:{x:i},backend:n,attrs:{shape:[i.shape[0],1,1]}});m=$S({inputs:{a:m,b:e},backend:n}),n.disposeIntermediateTensorInfo(e)}else m=$S({inputs:{a:m,b:i},backend:n});n.disposeIntermediateTensorInfo(e)}if(d){const e=m;if("NCHW"===c&&"prelu"===d&&1===o.shape.length&&1!==o.shape[0]){const e=ZC({inputs:{x:o},backend:n,attrs:{shape:[o.shape[0],1,1]}});m=YC(n,m,d,e,f),n.disposeIntermediateTensorInfo(e)}else m=YC(n,m,d,o,f);n.disposeIntermediateTensorInfo(e)}return m}};const AE={kernelName:ds,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:p,activation:d,leakyreluAlpha:f}=s;let m=nE({inputs:{x:r,filter:a},backend:n,attrs:{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:p}});if(i){const e=m;m=$S({inputs:{a:m,b:i},backend:n}),n.disposeIntermediateTensorInfo(e)}if(d){const e=m;m=YC(n,m,d,o,f),n.disposeIntermediateTensorInfo(e)}return m}};const RE={kernelName:dt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{params:s,indices:r}=t,a=d(s.shape),i=r.shape,o=i[i.length-1],[l,u,c,h]=_d(s,r);if(0===u)return n.makeTensorInfo(l,s.dtype,[]);const p=sT(n.data.get(r.dataId).values,n.bufferSync(s),s.dtype,u,o,c,h,s.shape,a);return n.makeTensorInfo(l,s.dtype,p.values)}};const _E={kernelName:pt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,indices:a}=t,{axis:i,batchDims:o}=s;lS([r,a],"gatherV2");const l=v(i,r.shape)[0],u=n.data.get(a.dataId).values,h=r.shape[l];for(let e=0;e<u.length;++e){const t=u[e];c(t<=h-1&&t>=0,(()=>`GatherV2: the index value ${t} is not in [0, ${h-1}]`))}let p=o;null==o&&(p=0);const f=d(a.shape),m=tm(r,a,l,p),g=ZC({inputs:{x:r},backend:n,attrs:{shape:[m.batchSize,m.outerSize,m.dimSize,m.sliceSize]}}),y=ZC({inputs:{x:a},backend:n,attrs:{shape:[m.batchSize,f/m.batchSize]}}),b=[m.batchSize,m.outerSize,f/m.batchSize,m.sliceSize],x=n.bufferSync(y),w=rT(n.bufferSync(g),x,b);return n.disposeIntermediateTensorInfo(g),n.disposeIntermediateTensorInfo(y),n.makeTensorInfo(m.outputShape,w.dtype,w.values)}};const FE={kernelName:yt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:s}=t,r=d(s.shape),a=s.shape[s.shape.length-1],i=ZC({inputs:{x:s},backend:n,attrs:{shape:[r/a,a]}}),o=kE(i,!0,n),l=ZC({inputs:{x:o},backend:n,attrs:{shape:s.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}},DE=MS(xt,(e=>Number.isFinite(e)?1:0),"bool"),OE={kernelName:xt,backendName:"cpu",kernelFunc:DE},ME=MS(wt,(e=>Math.abs(e)===1/0?1:0),"bool"),LE={kernelName:wt,backendName:"cpu",kernelFunc:ME},zE=MS(vt,(e=>Number.isNaN(e)?1:0),"bool"),PE={kernelName:vt,backendName:"cpu",kernelFunc:zE};const BE={kernelName:St,backendName:"cpu",kernelFunc:function(e){const{backend:t,attrs:n}=e,{start:s,stop:r,num:a}=n,i=yT(s,r,a);return t.makeTensorInfo([i.length],"float32",i)}},WE=MS(Ct,(e=>Math.log1p(e))),VE={kernelName:Ct,backendName:"cpu",kernelFunc:WE},UE=dS(((e,t)=>e&&t)),GE=IS($t,UE,null,"bool"),HE={kernelName:$t,backendName:"cpu",kernelFunc:GE},jE=MS(Et,(e=>e?0:1),"bool"),qE={kernelName:Et,backendName:"cpu",kernelFunc:jE},KE=dS(((e,t)=>e||t)),XE=IS(At,KE,null,"bool"),YE={kernelName:At,backendName:"cpu",kernelFunc:XE};const ZE={kernelName:_t,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{depthRadius:a,bias:i,alpha:o,beta:l}=s;lS(r,"LRN");const u=r.shape[3],c=u-1,h=n.data.get(r.dataId).values,p=d(r.shape),f=new Float32Array(p);function m(e){const t=e%u;let n=e-t+Math.max(0,t-a);const s=e-t+Math.min(t+a,c);let r=0;for(;n<=s;n++){const e=h[n];r+=e*e}return r}for(let e=0;e<p;e++){const t=m(e),n=h[e]*Math.pow(i+o*t,-l);f[e]=n}return n.makeTensorInfo(r.shape,r.dtype,f)}};const JE={kernelName:Ft,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,y:a,dy:i}=t,{depthRadius:o,bias:l,alpha:u,beta:c}=s;lS(i,"LRNGrad");const h=d(i.shape),p=i.shape[3],f=n.data.get(i.dataId).values,m=n.data.get(r.dataId).values,g=n.data.get(a.dataId).values,y=new Float32Array(h),b=h;for(let e=0;e<b;e++){const t=e%p,n=e-t+Math.max(0,t-o),s=e-t+Math.min(p,t+o+1);let r=0;for(let e=n;e<s;e++)r+=Math.pow(m[e],2);r=u*r+l;for(let t=n;t<s;t++){let n=-2*u*c*m[t]*g[e]/r;e===t&&(n+=Math.pow(r,-c)),n*=f[e],y[t]+=n}}return n.makeTensorInfo(i.shape,r.dtype,y)}};function QE(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{reductionIndices:a,keepDims:i}=s,o=n;let l=r.shape;const u=l.length,c=v(a,l);let h=c;const p=dl(h,u);let f=o.data.get(r.dataId).values;if(null!=p){const e=new Array(u);for(let t=0;t<e.length;t++)e[t]=l[p[t]];f=LT(f,l,r.dtype,p,e),h=ml(h.length,u),l=e}lS(r,"max"),pl("max",h,u);const[m,g]=cl(l,h),y=vT(f,d(g),m,r.dtype),b=o.write(y,m,r.dtype);let x=m;if(i){x=hl(m,c)}return{dataId:b,shape:x,dtype:r.dtype}}const eA={kernelName:Dt,backendName:"cpu",kernelFunc:QE};const tA={kernelName:Mt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t;lS(r,"maxPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:l}=s;c(so(i,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const u=qi(r.shape,a,i,1,o,l);let h;if(1===u.filterWidth&&1===u.filterHeight&&m(u.inShape,u.outShape))h=yS({inputs:{x:r},backend:n});else{const e=n.data.get(r.dataId).values,t=M(r.shape),s=k$(e,r.shape,r.dtype,t,u,"max");h=n.makeTensorInfo(u.outShape,r.dtype,s.values)}return h}};const nA={kernelName:zt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=s;lS(r,"maxPool3d");const c=Ki(r.shape,a,i,1,o,l,u),h=I$(n.data.get(r.dataId).values,r.shape,r.dtype,M(r.shape),c,"max");return n.makeTensorInfo(h.shape,"float32",h.values)}};const sA={kernelName:Pt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=s;lS([r,a],"maxPool3DGrad");const c=Ki(a.shape,i,o,1,l,u),h=function(e,t){const n=Si(t.outShape,"int32"),s=t.strideDepth,r=t.strideHeight,a=t.strideWidth,i=t.dilationDepth,o=t.dilationHeight,l=t.dilationWidth,u=t.effectiveFilterDepth,c=t.effectiveFilterHeight,h=t.effectiveFilterWidth,p=t.padInfo.front,d=t.padInfo.top,f=t.padInfo.left;for(let m=0;m<t.batchSize;++m)for(let g=0;g<t.inChannels;++g)for(let y=0;y<t.outDepth;++y){const b=y*s-p;let x=b;for(;x<0;)x+=i;const w=Math.min(t.inDepth,u+b);for(let s=0;s<t.outHeight;++s){const u=s*r-d;let p=u;for(;p<0;)p+=o;const v=Math.min(t.inHeight,c+u);for(let r=0;r<t.outWidth;++r){const d=r*a-f;let k=d;for(;k<0;)k+=l;const N=Math.min(t.inWidth,h+d);let I=Number.NEGATIVE_INFINITY,S=-1;for(let t=x;t<w;t+=i){const n=t-b;for(let s=p;s<v;s+=o){const r=s-u;for(let a=k;a<N;a+=l){const i=a-d,o=e.get(m,t,s,a,g);o>=I&&(I=o,S=n*c*h+r*c+i)}}}n.set(S,m,y,s,r,g)}}}return n}(n.bufferSync(a),c),p=c.strideDepth,d=c.strideHeight,f=c.strideWidth,m=c.dilationDepth,g=c.dilationHeight,y=c.dilationWidth,b=c.effectiveFilterDepth,x=c.effectiveFilterHeight,w=c.effectiveFilterWidth,v=b-1-c.padInfo.front,k=w-1-c.padInfo.left,N=x-1-c.padInfo.top,I=Si(a.shape,"float32"),S=n.bufferSync(r);for(let e=0;e<c.batchSize;++e)for(let t=0;t<c.inChannels;++t)for(let n=0;n<c.inDepth;++n)for(let s=0;s<c.inHeight;++s)for(let r=0;r<c.inWidth;++r){const a=n-v,i=s-N,o=r-k;let l=0;for(let n=0;n<b;n+=m){const s=(a+n)/p;if(!(s<0||s>=c.outDepth||Math.floor(s)!==s))for(let r=0;r<x;r+=g){const a=(i+r)/d;if(!(a<0||a>=c.outHeight||Math.floor(a)!==a))for(let i=0;i<w;i+=y){const u=(o+i)/f;if(u<0||u>=c.outWidth||Math.floor(u)!==u)continue;const p=b*x*w-1-h.get(e,s,a,u,t)===n*x*w+r*w+i?1:0;if(0===p)continue;l+=S.get(e,s,a,u,t)*p}}}I.set(l,e,n,s,r,t)}return n.makeTensorInfo(I.shape,I.dtype,I.values)}};const rA={kernelName:Lt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a,output:i}=t,o=a;lS([a,i],"maxPoolGrad");const{filterSize:l,strides:u,pad:c,dimRoundingMode:h}=s,p=qi(o.shape,l,u,1,c,h),d=n.data.get(o.dataId).values,f=Si(p.outShape,o.dtype,N$(d,o.shape,o.dtype,p).values),m=p.strideHeight,g=p.strideWidth,y=p.dilationHeight,b=p.dilationWidth,x=p.effectiveFilterHeight,w=p.effectiveFilterWidth,v=w-1-p.padInfo.left,k=x-1-p.padInfo.top,N=Si(o.shape,"float32"),I=n.data.get(r.dataId).values,S=Si(r.shape,"float32",I);for(let e=0;e<p.batchSize;++e)for(let t=0;t<p.inChannels;++t)for(let n=0;n<p.inHeight;++n)for(let s=0;s<p.inWidth;++s){const r=n-k,a=s-v;let i=0;for(let n=0;n<x;n+=y){const s=(r+n)/m;if(!(s<0||s>=p.outHeight||Math.floor(s)!==s))for(let r=0;r<w;r+=b){const o=(a+r)/g;if(o<0||o>=p.outWidth||Math.floor(o)!==o)continue;const l=x*w-1-f.get(e,s,o,t)===n*w+r?1:0;if(0===l)continue;i+=S.get(e,s,o,t)*l}}N.set(i,e,n,s,t)}return n.makeTensorInfo(N.shape,N.dtype,N.values)}};const aA={kernelName:Bt,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{filterSize:r,strides:a,pad:i,includeBatchInIndex:o}=t,l=n;lS(s,"MaxPoolWithArgmax");const u=l.data.get(s.dataId).values,c=qi(s.shape,r,a,[1,1],i),[h,p]=function(e,t,n,s,r){const a=k$(e,0,n,M(t),r,"max"),i=N$(e,t,n,r,!0,s);return[a.values,i.values]}(u,s.shape,s.dtype,o,c),d=l.write(h,c.outShape,s.dtype),f=l.write(p,c.outShape,s.dtype);return[{dataId:d,shape:c.outShape,dtype:s.dtype},{dataId:f,shape:c.outShape,dtype:"int32"}]}};const iA={kernelName:Wt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s,o=v(a,r.shape),l=d(cl(r.shape,o)[1]),u=[],c=n.makeTensorInfo([],"float32",new Float32Array([l]));u.push(c);const h=kS({inputs:{x:r},backend:n,attrs:{dtype:"float32"}});u.push(h);const p=wE({inputs:{a:h,b:c},backend:n});u.push(p);const f=hE({inputs:{x:p},backend:n,attrs:{axis:a,keepDims:i}});return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),f}};const oA={kernelName:Vt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s;lS(r,"min");const o=v(a,r.shape);let l=o;const u=dl(l,r.shape.length);let c=r;null!=u&&(c=zT({inputs:{x:r},backend:n,attrs:{perm:u}}),l=ml(l.length,r.shape.length)),pl("min",l,c.shape.length);const[h,p]=cl(c.shape,l),f=d(p),m=W(d(h),c.dtype),g=n.data.get(c.dataId).values;for(let e=0;e<m.length;++e){const t=e*f;let n=g[t];for(let e=0;e<f;++e){const s=g[t+e];(Number.isNaN(s)||s<n)&&(n=s)}m[e]=n}null!=u&&n.disposeIntermediateTensorInfo(c);const y=n.makeTensorInfo(h,c.dtype,m);if(i){const e=ZC({inputs:{x:y},backend:n,attrs:{shape:hl(h,o)}});return n.disposeIntermediateTensorInfo(y),e}return y}};const lA={kernelName:Gt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{paddings:a,mode:i}=s;lS(r,"mirrorPad");const o=a.map(((e,t)=>e[0]+r.shape[t]+e[1])),l=a.map((e=>e[0])),u=a.map(((e,t)=>e[0]+r.shape[t])),c="reflect"===i?0:1,h=n.data.get(r.dataId).values,p=r.shape.length,f=M(r.shape),m=d(o),g=o.length,y=M(o),b=N(r.dtype,m);for(let e=0;e<m;e++){let t=H(e,g,y);for(let e=0;e<g;e++)t[e]<l[e]?t[e]=2*l[e]-t[e]-c:t[e]>=u[e]&&(t[e]=2*(u[e]-1)-t[e]+c);t=t.map(((e,t)=>e-l[t]));const n=G(t,p,f);b[e]=h[n]}return{dataId:n.write(b,o,r.dtype),shape:o,dtype:r.dtype}}},uA=dS(((e,t)=>{const n=e%t;return e<0&&t<0||e>=0&&t>=0?n:(n+t)%t})),cA=IS(Ht,uA),hA={kernelName:Ht,backendName:"cpu",kernelFunc:cA};function pA(e){const{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{dim:a}=s,i=r.shape.length;let o=a;if(-1===o&&(o=i-1),o!==i-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${i} and dim was ${o}`);const l=v([o],r.shape),u=QE({inputs:{x:r},backend:n,attrs:{reductionIndices:l,keepDims:!1}}),c=hl(u.shape,l),h=ZC({inputs:{x:u},backend:n,attrs:{shape:c}}),p=AC({inputs:{a:r,b:h},backend:n}),d=jS({inputs:{x:p},backend:n}),f=hE({inputs:{x:d},backend:n,attrs:{axis:l,keepDims:!1}}),m=ZC({inputs:{x:f},backend:n,attrs:{shape:c}}),g=wE({inputs:{a:d,b:m},backend:n});return n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}const dA={kernelName:zn,backendName:"cpu",kernelFunc:pA};const fA={kernelName:jt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{numSamples:a,seed:i,normalized:o}=s;lS(r,"multinomial");const l=o?r:pA({inputs:{logits:r},backend:n,attrs:{dim:-1}}),u=l.shape[0],c=l.shape[1],h=n.data.get(l.dataId).values,p=[u,a],f=W(d(p),"int32");for(let e=0;e<u;++e){const t=e*c,n=new Float32Array(c-1);n[0]=h[t];for(let e=1;e<n.length;++e)n[e]=n[e-1]+h[t+e];const s=ic.alea(i.toString()),r=e*a;for(let e=0;e<a;++e){const t=s();f[r+e]=n.length;for(let s=0;s<n.length;s++)if(t<n[s]){f[r+e]=s;break}}}return o||n.disposeIntermediateTensorInfo(l),n.makeTensorInfo(p,"int32",f)}},mA=ep;const gA={kernelName:Yt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{boxes:r,scores:a}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=s;lS(r,"NonMaxSuppression");const u=n.data.get(r.dataId).values,c=n.data.get(a.dataId).values,{selectedIndices:h}=mA(u,c,i,o,l);return n.makeTensorInfo([h.length],"int32",new Int32Array(h))}},yA=tp;const bA={kernelName:Zt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{boxes:r,scores:a}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:u}=s;lS(r,"NonMaxSuppressionPadded");const c=n.data.get(r.dataId).values,h=n.data.get(a.dataId).values,{selectedIndices:p,validOutputs:d}=yA(c,h,i,o,l,u);return[n.makeTensorInfo([p.length],"int32",new Int32Array(p)),n.makeTensorInfo([],"int32",new Int32Array([d]))]}},xA=np;const wA={kernelName:Jt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{boxes:r,scores:a}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:u}=s;lS(r,"NonMaxSuppressionWithScore");const c=n.data.get(r.dataId).values,h=n.data.get(a.dataId).values,p=i,d=o,f=l,m=u,{selectedIndices:g,selectedScores:y}=xA(c,h,p,d,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}};const vA={kernelName:en,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{indices:r}=t,{dtype:a,depth:i,onValue:o,offValue:l}=s;lS(r,"oneHot");const u=d(r.shape),c=new Float32Array(u*i);c.fill(l);const h=n.data.get(r.dataId).values;for(let e=0;e<u;++e)h[e]>=0&&h[e]<i&&(c[e*i+h[e]]=o);return n.makeTensorInfo([...r.shape,i],a,c)}};function kA(e){const{inputs:t,backend:n}=e,{x:s}=t;if("string"===s.dtype)throw new Error("zerosLike is not supported for string tensors");if("complex64"===s.dtype){const e=xS({inputs:{input:s},backend:n}),t=kA({inputs:{x:e},backend:n}),r=M$({inputs:{input:s},backend:n}),a=kA({inputs:{x:r},backend:n}),i=fS({inputs:{real:t,imag:a},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(a),i}return TE({backend:n,attrs:{shape:s.shape,value:0,dtype:s.dtype}})}const NA={kernelName:os,backendName:"cpu",kernelFunc:kA};const IA={kernelName:Qt,backendName:"cpu",kernelFunc:function e(t){const{inputs:n,backend:s}=t,{x:r}=n;if("string"===r.dtype)throw new Error("onesLike is not supported for string tensors");if("complex64"===r.dtype){const t=xS({inputs:{input:r},backend:s}),n=e({inputs:{x:t},backend:s}),a=M$({inputs:{input:r},backend:s}),i=kA({inputs:{x:a},backend:s}),o=fS({inputs:{real:n,imag:i},backend:s});return s.disposeIntermediateTensorInfo(t),s.disposeIntermediateTensorInfo(n),s.disposeIntermediateTensorInfo(a),s.disposeIntermediateTensorInfo(i),o}return TE({backend:s,attrs:{shape:r.shape,value:1,dtype:r.dtype}})}};function SA(e){const{inputs:t,backend:n,attrs:s}=e,{axis:r}=s;if(1===t.length)return yE({inputs:{input:t[0]},backend:n,attrs:{dim:r}});const a=t[0].shape,i=t[0].dtype;t.forEach((e=>{h(a,e.shape,"All tensors passed to stack must have matching shapes"),c(i===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const o=[],l=z$({inputs:t.map((e=>{const t=yE({inputs:{input:e},backend:n,attrs:{dim:r}});return o.push(t),t})),backend:n,attrs:{axis:r}});return o.forEach((e=>n.disposeIntermediateTensorInfo(e))),l}const TA={kernelName:tn,backendName:"cpu",kernelFunc:SA};const CA={kernelName:nn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{paddings:a,constantValue:i}=s;lS(r,"pad");const o=a.map(((e,t)=>e[0]+r.shape[t]+e[1])),l=a.map((e=>e[0])),u=n.data.get(r.dataId).values,c=d(r.shape),h=r.shape.length,p=M(r.shape),f=d(o),m=o.length,g=M(o),y=N(r.dtype,f);0!==i&&y.fill(i);for(let e=0;e<c;e++){y[G(H(e,h,p).map(((e,t)=>e+l[t])),m,g)]=u[e]}return{dataId:n.write(y,o,r.dtype),shape:o,dtype:r.dtype}}},$A=dS(((e,t)=>Math.pow(e,t))),EA=IS(sn,$A),AA={kernelName:sn,backendName:"cpu",kernelFunc:EA};const RA={kernelName:on,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{paramsNestedSplits:r,paramsDenseValues:a,indices:i}=t,{outputRaggedRank:o}=s,l=r.map((e=>n.data.get(e.dataId).values)),u=r.map((e=>e.shape)),c=n.data.get(a.dataId).values,h=n.data.get(i.dataId).values,[p,d,f]=HT(l,u,c,a.shape,a.dtype,h,i.shape),m=p.map((e=>n.makeTensorInfo([e.length],"int32",e))),g=n.makeTensorInfo(f,a.dtype,d);return m.concat([g])}};const _A={kernelName:ln,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{starts:s,limits:r,deltas:a}=t,i=n.data.get(s.dataId).values,o=n.data.get(r.dataId).values,l=n.data.get(a.dataId).values,[u,c]=qT(i,s.shape,s.dtype,o,r.shape,l,a.shape);return[n.makeTensorInfo([u.length],"int32",u),n.makeTensorInfo([c.length],s.dtype,c)]}};const FA={kernelName:un,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{shape:r,values:a,defaultValue:i,rowPartitionTensors:o}=t,{rowPartitionTypes:l}=s,u=n.data.get(r.dataId).values,c=n.data.get(a.dataId).values,h=n.data.get(i.dataId).values,p=o.map((e=>n.data.get(e.dataId).values)),d=o.map((e=>e.shape)),[f,m]=JT(u,r.shape,c,a.shape,a.dtype,h,i.shape,p,d,l);return n.makeTensorInfo(f,a.dtype,m)}};const DA={kernelName:cn,backendName:"cpu",kernelFunc:function(e){const{backend:t,attrs:n}=e,{start:s,stop:r,dtype:a,step:i}=n,o=QT(s,r,i,a);return t.makeTensorInfo([o.length],a,o)}},OA=MS(pn,(e=>1/e)),MA={kernelName:pn,backendName:"cpu",kernelFunc:OA};const LA={kernelName:yn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,halfPixelCenters:i,size:o}=s;lS(r,"resizeBilinear");const l=M(r.shape),[u,c]=o,[h,p,f,m]=r.shape,g=n.data.get(r.dataId).values,y=new Float32Array(d([h,u,c,m])),b=[a&&u>1?p-1:p,a&&c>1?f-1:f],x=[a&&u>1?u-1:u,a&&c>1?c-1:c];let w=0;const v=b[0]/x[0],k=b[1]/x[1];for(let e=0;e<h;e++)for(let t=0;t<u;t++){let n;n=i?v*(t+.5)-.5:v*t;const s=Math.max(0,Math.floor(n)),r=n-s,a=Math.min(p-1,Math.ceil(n)),o=e*l[0]+s*l[1],u=e*l[0]+a*l[1];for(let e=0;e<c;e++){let t;t=i?k*(e+.5)-.5:k*e;const n=Math.max(0,Math.floor(t)),s=t-n,a=Math.min(f-1,Math.ceil(t)),c=o+n*l[2],h=u+n*l[2],p=o+a*l[2],d=u+a*l[2];for(let e=0;e<m;e++){const t=g[c+e],n=g[h+e],a=t+(g[p+e]-t)*s,i=a+(n+(g[d+e]-n)*s-a)*r;y[w++]=i}}}return n.makeTensorInfo([h,u,c,m],"float32",y)}};const zA={kernelName:bn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{images:r,dy:a}=t,{alignCorners:i}=s;lS([a,r],"resizeBilinearGrad");const o=M(r.shape),[l,u,c,h]=r.shape,[,p,d]=a.shape,f=new Float32Array(l*u*c*h),m=[i&&p>1?u-1:u,i&&d>1?c-1:c],g=[i&&p>1?p-1:p,i&&d>1?d-1:d],y=m[0]/g[0],b=m[1]/g[1],x=n.data.get(a.dataId).values;let w=0;for(let e=0;e<l;e++){const t=e*o[0];for(let e=0;e<p;e++){const n=e*y,s=Math.floor(n),r=Math.min(Math.ceil(n),u-1),a=t+s*o[1],i=t+r*o[1],l=n-s,p=1-l;for(let e=0;e<d;e++){const t=e*b,n=Math.floor(t),s=Math.min(Math.ceil(t),c-1),r=t-n,u=1-r,d=a+n*o[2],m=a+s*o[2],g=i+n*o[2],y=i+s*o[2],v=p*u,k=p*r,N=l*u,I=l*r;for(let e=0;e<h;e++){const t=x[w++];f[d+e]+=t*v,f[m+e]+=t*k,f[g+e]+=t*N,f[y+e]+=t*I}}}}return n.makeTensorInfo([l,c,u,h],"float32",f)}};const PA={kernelName:mn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,halfPixelCenters:i,size:o}=s;lS(r,"resizeNearestNeighbor");const l=M(r.shape),[u,c]=o,[h,p,d,f]=r.shape,m=n.data.get(r.dataId).values,g=new Float32Array(h*u*c*f),y=[a&&u>1?p-1:p,a&&c>1?d-1:d],b=[a&&u>1?u-1:u,a&&c>1?c-1:c],x=y[0]/b[0],w=y[1]/b[1];let v=0;for(let e=0;e<h;e++){const t=e*l[0];for(let e=0;e<u;e++){const n=i?x*(e+.5):x*e;let s=Math.min(p-1,a?Math.round(n):Math.floor(n));i&&(s=Math.max(0,s));const r=t+s*l[1];for(let e=0;e<c;e++){const t=i?w*(e+.5):w*e;let n=Math.min(d-1,a?Math.round(t):Math.floor(t));i&&(n=Math.max(0,n));const s=r+n*l[2];for(let e=0;e<f;e++){const t=m[s+e];g[v++]=t}}}}return n.makeTensorInfo([h,u,c,f],r.dtype,g)}};const BA={kernelName:gn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{images:r,dy:a}=t,{alignCorners:i}=s;lS([a,r],"resizeNearestNeighborGrad");const o=M(r.shape),l=M(a.shape),[u,c,h,p]=r.shape,[,d,f]=a.shape,m=new Float32Array(u*c*h*p),g=n.data.get(a.dataId).values,y=[i&&d>1?c-1:c,i&&f>1?h-1:h],b=[i&&d>1?d-1:d,i&&f>1?f-1:f],x=y[0]/b[0],w=y[1]/b[1],v=1/x,k=1/w,N=2*Math.ceil(v)+2,I=2*Math.ceil(k)+2;for(let e=0;e<u;e++){const t=e*o[0];for(let e=0;e<c;e++){const n=t+e*o[1],s=Math.floor(e*v),r=Math.floor(s-N/2);for(let s=0;s<h;s++){const a=n+s*o[2],u=Math.floor(s*k),y=Math.floor(u-I/2);for(let n=0;n<p;n++){let o=0;for(let a=0;a<N;a++){const u=a+r;if(u<0||u>=d)continue;const p=t+u*l[1],m=u*x;if(e===Math.min(c-1,i?Math.round(m):Math.floor(m)))for(let e=0;e<I;e++){const t=e+y;if(t<0||t>=f)continue;const r=p+t*l[2],a=t*w;s===Math.min(h-1,i?Math.round(a):Math.floor(a))&&(o+=g[r+n])}}m[a+n]=o}}}}return n.makeTensorInfo(r.shape,r.dtype,m)}};const WA={kernelName:wn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dims:a}=s;lS(r,"reverse");const i=r.shape.length,o=v(a,r.shape);if(0===i)return yS({inputs:{x:r},backend:n});const l=new $r(r.shape,r.dtype),u=n.bufferSync(r);for(let e=0;e<l.size;e++){const t=l.indexToLoc(e),n=t.slice();o.forEach((e=>n[e]=r.shape[e]-1-n[e])),l.set(u.get(...n),...t)}return n.makeTensorInfo(l.shape,l.dtype,l.values)}},VA={kernelName:cs,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:s}=e,{radians:r,fillValue:a,center:i}=t,o=n,l=N(s.dtype,d(s.shape)),[u,c,h,p]=s.shape,[f,m]=cf(i,c,h),g=Math.sin(r),y=Math.cos(r),b=o.data.get(s.dataId).values;for(let e=0;e<u;e++){const t=e*h*c*p;for(let e=0;e<c;e++){const n=e*(h*p);for(let s=0;s<h;s++){const r=s*p;for(let i=0;i<p;i++){const o=[u,e,s,i],d=o[2],x=o[1];let w=(d-f)*y-(x-m)*g,v=(d-f)*g+(x-m)*y;w=Math.round(w+f),v=Math.round(v+m);let k=a;if("number"!=typeof a&&(k=3===i?255:a[i]),w>=0&&w<h&&v>=0&&v<c){k=b[t+v*(h*p)+w*p+i]}l[t+n+r+i]=k}}}}return{dataId:o.write(l,s.shape,s.dtype),shape:s.shape,dtype:s.dtype}}},UA=MS(vn,(e=>{const t=Math.floor(e);return e-t<.5?Math.floor(e):e-t>.5?Math.ceil(e):t%2==0?t:t+1})),GA={kernelName:vn,backendName:"cpu",kernelFunc:UA};const HA={kernelName:Nn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{indices:r,updates:a}=t,{shape:i}=s,{sliceRank:o,numUpdates:l,sliceSize:u,strides:c,outputSize:h}=lh(0,r,i),p=sC(n.bufferSync(r),n.bufferSync(a),i,h,u,l,o,c,0,!0);return n.makeTensorInfo(i,p.dtype,p.values)}};function jA(e,t){let n=0,s=e.length,r=0;for(;n<s;)r=Math.floor((n+s)/2),e[r]<t?n=r+1:s=r;return s}function qA(e,t){let n=0,s=e.length,r=0;for(;n<s;)r=Math.floor((n+s)/2),e[r]<=t?n=r+1:s=r;return s}const KA={kernelName:Sn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{sortedSequence:r,values:a}=t,{side:i}=s,o=function(e,t,n,s,r,a){const i=I("int32",n*r);for(let o=0;o<n;++o){const n=e.slice(o*s,(o+1)*s),l=o*r;for(let e=0;e<r;++e)i[l+e]="left"===a?jA(n,t[e+l]):qA(n,t[e+l])}return i}(n.data.get(r.dataId).values,n.data.get(a.dataId).values,r.shape[0],r.shape[1],a.shape[1],i);return n.makeTensorInfo(a.shape,"int32",o)}};const XA={kernelName:Tn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{condition:s,t:r,e:a}=t;lS([s,r,a],"select");const i=s.shape.length,o=n.data.get(s.dataId).values,l=n.data.get(r.dataId).values,u=n.data.get(a.dataId).values,c=Wr(r.dtype,a.dtype),h=W(d(r.shape),c);let p=0;const f=0===i||i>1||1===r.shape.length?1:d(r.shape.slice(1));for(let e=0;e<o.length;e++)for(let t=0;t<f;t++)1===o[e]?h[p++]=l[e]:h[p++]=u[e];return n.makeTensorInfo(r.shape,c,h)}},YA=MS(Cn,(e=>e>=0?1.0507009873554805*e:1.7580993408473768*(Math.exp(e)-1))),ZA={kernelName:Cn,backendName:"cpu",kernelFunc:YA},JA=MS(Rn,(e=>e<0?-1:e>0?1:0)),QA={kernelName:Rn,backendName:"cpu",kernelFunc:JA},eR=MS(En,(e=>Math.sin(e))),tR={kernelName:En,backendName:"cpu",kernelFunc:eR},nR=MS(An,(e=>Math.sinh(e))),sR={kernelName:An,backendName:"cpu",kernelFunc:nR},rR=Math.log(1.1920928955078125e-7)+2,aR=MS(Fn,(e=>{const t=e>-rR,n=e<rR,s=Math.exp(e);let r;return r=n?s:t?e:Math.log(1+s),r})),iR={kernelName:Fn,backendName:"cpu",kernelFunc:aR};const oR={kernelName:Mn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,paddings:i}=s;lS([r],"spaceToBatchND");const o=d(a),l=[[0,0]];l.push(...i);for(let e=1+a.length;e<r.shape.length;++e)l.push([0,0]);const u=CA.kernelFunc({inputs:{x:r},backend:n,attrs:{paddings:l,constantValue:0}}),c=hf(u.shape,a,o,!1),h=pf(c.length,a.length,!1),p=df(u.shape,a,o,!1),f=ZC({inputs:{x:u},backend:n,attrs:{shape:c}}),m=zT({inputs:{x:f},backend:n,attrs:{perm:h}}),g=ZC({inputs:{x:m},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}};const lR={kernelName:Pn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{indices:s,values:r,denseShape:a,defaultValue:i}=t;if(1!==a.shape.length)throw new Error(`Dense shape must be a vector, saw:\n        ${a.shape}`);if(2!==s.shape.length)throw new Error(`Indices must be a matrix, saw:\n        ${s.shape}`);if(1!==r.shape.length)throw new Error(`Values must be a vector, saw:\n        ${r.shape}`);if(0!==i.shape.length)throw new Error(`Default value must be a scalar, saw:\n        ${i.shape}`);const o=n.data.get(s.dataId).values,l=n.data.get(r.dataId).values,u=n.data.get(a.dataId).values,c=n.data.get(i.dataId).values[0],[h,p,d,f,m]=cC(o,s.shape,s.dtype,l,r.dtype,u,c);return[n.makeTensorInfo(p,s.dtype,h),n.makeTensorInfo([p[0]],r.dtype,d),n.makeTensorInfo([f.length],"bool",new Uint8Array(f.map((e=>Number(e))))),n.makeTensorInfo([m.length],s.dtype,new Int32Array(m))]}};const uR={kernelName:Bn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{inputIndices:s,inputShape:r,newShape:a}=t;if(2!==s.shape.length)throw new Error(`Input indices should be a matrix but received shape\n        ${s.shape}`);if(1!==r.shape.length)throw new Error(`Input shape should be a vector but received shape\n        ${r.shape}`);if(1!==a.shape.length)throw new Error(`Target shape should be a vector but received shape ${a.shape}`);const i=Array.from(n.data.get(r.dataId).values),o=n.data.get(s.dataId).values,l=Array.from(n.data.get(a.dataId).values),[u,c,h]=hC(o,s.shape,s.dtype,i,l);return[n.makeTensorInfo(c,s.dtype,u),n.makeTensorInfo([h.length],a.dtype,new Int32Array(h))]}};const cR={kernelName:Wn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{data:s,indices:r,segmentIds:a}=t;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==r.shape.length)throw new Error(`Indices should be a vector but received shape\n          ${r.shape}`);if(1!==a.shape.length)throw new Error(`Segment ids should be a vector but received shape\n          ${a.shape}`);if(r.shape[0]!==a.shape[0])throw new Error("segmentIds and indices should have same size.");const i=n.data.get(s.dataId).values,o=n.data.get(r.dataId).values,l=n.data.get(a.dataId).values,[u,c]=pC(i,s.shape,s.dtype,o,l,!0);return n.makeTensorInfo(c,s.dtype,u)}};const hR={kernelName:Vn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{data:s,indices:r,segmentIds:a}=t;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==r.shape.length)throw new Error(`Indices should be a vector but received shape\n         ${r.shape}`);if(1!==a.shape.length)throw new Error(`Segment ids should be a vector but received shape\n         ${a.shape}`);if(r.shape[0]!==a.shape[0])throw new Error("segmentIds and indices should have same size.");const i=n.data.get(s.dataId).values,o=n.data.get(r.dataId).values,l=n.data.get(a.dataId).values,[u,c]=pC(i,s.shape,s.dtype,o,l);return n.makeTensorInfo(c,s.dtype,u)}};const pR={kernelName:Un,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{sparseIndices:r,sparseValues:a,defaultValue:i}=t,{outputShape:o}=s,{sliceRank:l,numUpdates:u,sliceSize:c,strides:h,outputSize:p}=lh(0,r,o),d=!1,f=n.bufferSync(r);let m;switch(a.dtype){case"bool":m=sC(f,n.bufferSync(a),o,p,c,u,l,h,Boolean(n.data.get(i.dataId).values[0]),d);break;case"float32":m=sC(f,n.bufferSync(a),o,p,c,u,l,h,n.data.get(i.dataId).values[0],d);break;case"int32":m=sC(f,n.bufferSync(a),o,p,c,u,l,h,n.data.get(i.dataId).values[0],d);break;case"string":m=sC(f,n.bufferSync(a),o,p,c,u,l,h,gr(n.data.get(i.dataId).values[0]),d);break;default:throw new Error(`Unsupported type ${a.dtype}`)}return n.makeTensorInfo(o,m.dtype,m.values)}};const dR={kernelName:Ln,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{numOrSizeSplits:a,axis:i}=s,o=v(i,r.shape)[0],l=Bf(r,a,o),u=new Array(r.shape.length).fill(0),c=r.shape.slice();return l.map((e=>{const t=[...c];t[o]=e;const s=lC({inputs:{x:r},backend:n,attrs:{begin:u,size:t}});return u[o]+=e,s}))}},fR={kernelName:Hn,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{const{x:n}=e,s=t;lS(n,"square");const r=s.data.get(n.dataId).values,a=new Float32Array(r.length);for(let e=0;e<r.length;++e){const t=r[e];a[e]=t*t}return{dataId:s.write(a,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}},mR=MS(ls,((e,t)=>{const n=t;return isNaN(e)?NaN:e>0?1:n.alpha})),gR={kernelName:ls,backendName:"cpu",kernelFunc:mR};const yR={kernelName:qn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:h,newAxisMask:p,shrinkAxisMask:d}=s;lS(r,"stridedSlice");const{finalShapeSparse:f,finalShape:m,isIdentity:g,sliceDim0:y,isSimpleSlice:b,begin:x,end:w,strides:v}=qd(r.shape,a,i,o,l,u,h,p,d);let k;if(g)k=ZC({inputs:{x:r},backend:n,attrs:{shape:m}});else if(y||b){c(r.shape.length>=1,(()=>`Input must have rank at least 1, got: ${r.shape.length}`));const e=Od(x,w,v),t=lC({inputs:{x:r},backend:n,attrs:{begin:x,size:e}});k=ZC({inputs:{x:t},backend:n,attrs:{shape:m}}),n.disposeIntermediateTensorInfo(t)}else{const e=kC(f,n.bufferSync(r),v,x);k=n.makeTensorInfo(m,e.dtype,e.values)}return k}};const bR={kernelName:Kn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{separator:r,nGramWidths:a,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:u}=s,{data:c,dataSplits:h}=t,p=n.data.get(c.dataId).values,d=n.data.get(h.dataId).values,[f,m]=IC(p,d,r,a,i,o,l,u);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(h.shape,"int32",m)]}};const xR={kernelName:Xn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{skipEmpty:r}=s,{input:a,delimiter:i}=t;if("string"!==a.dtype)throw new Error("Input must be of datatype string");if(1!==a.shape.length)throw new Error(`Input must be a vector, got shape: ${a.shape}`);if(0!==i.shape.length)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);const o=n.data.get(a.dataId).values,l=n.data.get(i.dataId).values[0],[u,c,h]=TC(o,l,r),p=c.length;return[n.makeTensorInfo([p,2],"int32",u),n.makeTensorInfo([p],"string",c),n.makeTensorInfo([2],"int32",new Int32Array(h))]}};const wR={kernelName:Yn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{numBuckets:r}=s,{input:a}=t;if("string"!==a.dtype)throw new Error("Input must be of datatype string");if(r<=0)throw new Error("Number of buckets must be at least 1");const i=CC(n.data.get(a.dataId).values,r);return n.makeTensorInfo(a.shape,"int32",i)}},vR=MS(Jn,(e=>Math.tan(e))),kR={kernelName:Jn,backendName:"cpu",kernelFunc:vR},NR=MS(Qn,(e=>Math.tanh(e)));const IR={kernelName:In,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{tensor:s,indices:r,updates:a}=t,{sliceRank:i,numUpdates:o,sliceSize:l,strides:u,outputSize:c}=lh(0,r,s.shape),h=n.bufferSync(r),p=n.bufferSync(a),d=n.bufferSync(s),f=sC(h,p,s.shape,c,l,o,i,u,d,!1);return n.makeTensorInfo(s.shape,f.dtype,f.values)}};const SR={kernelName:es,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{reps:a}=s;lS(r,"tile");const i=_C(n.bufferSync(r),a);return n.makeTensorInfo(i.shape,i.dtype,i.values)}};const TR={kernelName:ts,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{k:a,sorted:i}=s;lS(r,"topk");const o=n.data.get(r.dataId).values,[l,u]=OC(o,r.shape,r.dtype,a,i);return[n.makeTensorInfo(l.shape,l.dtype,l.values),n.makeTensorInfo(u.shape,u.dtype,u.values)]}};const CR={kernelName:ns,backendName:"cpu",kernelFunc:function(e){const{inputs:t,attrs:n,backend:s}=e,{image:r,transforms:a}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=n,[c,h,p,f]=r.shape,[m,g]=null!=u?u:[h,p],y=[c,m,g,f],b=M(r.shape),x=b[0],w=b[1],v=b[2],k=M(y),I=k[0],S=k[1],T=k[2],C=N(r.dtype,d(y));C.fill(l);const $=s.data.get(r.dataId).values,E=s.data.get(a.dataId).values;for(let e=0;e<c;++e){const t=1===a.shape[0]?E:E.subarray(8*e,8*e+8);for(let n=0;n<m;++n)for(let s=0;s<g;++s)for(let r=0;r<f;++r){let a;const u=t[6]*s+t[7]*n+1;if(0===u)continue;const c=(t[0]*s+t[1]*n+t[2])/u,d=(t[3]*s+t[4]*n+t[5])/u,f=$R(c,p,o),m=$R(d,h,o);switch(i){case"nearest":a=AR($,h,p,x,w,v,e,m,f,r,l);break;case"bilinear":a=RR($,h,p,x,w,v,e,m,f,r,l);break;default:throw new Error(`Error in Transform: Expect 'nearest' or 'bilinear', but got ${i}`)}C[e*I+n*S+s*T+r]=a}return s.makeTensorInfo(y,r.dtype,C)}return{dataId:s.write(C,y,r.dtype),shape:r.shape,dtype:r.dtype}}};function $R(e,t,n){switch(n){case"reflect":return function(e,t){let n=e;if(n<0)if(t<=1)n=0;else{const e=2*t;n<e&&(n=e*Math.trunc(-n/e)+n),n=n<-t?n+e:-n-1}else if(n>t-1)if(t<=1)n=0;else{const e=2*t;n-=e*Math.trunc(n/e),n>=t&&(n=e-n-1)}return i(0,n,t-1)}(e,t);case"wrap":return function(e,t){let n=e;if(n<0)if(t<=1)n=0;else{const e=t-1;n+=t*(Math.trunc(-n/e)+1)}else if(n>t-1)if(t<=1)n=0;else{const e=t-1;n-=t*Math.trunc(n/e)}return i(0,n,t-1)}(e,t);case"nearest":return function(e,t){return i(0,e,t-1)}(e,t);default:return function(e,t){return e}(e)}}function ER(e,t,n,s,r,a,i,o,l,u,c){return 0<=o&&o<t&&0<=l&&l<n?e[i*s+o*r+l*a+u]:c}function AR(e,t,n,s,r,a,i,o,l,u,c){return ER(e,t,n,s,r,a,i,Math.round(o),Math.round(l),u,c)}function RR(e,t,n,s,r,a,i,o,l,u,c){const h=Math.floor(o),p=Math.floor(l),d=h+1,f=p+1;return(d-o)*((f-l)*ER(e,t,n,s,r,a,i,h,p,u,c)+(l-p)*ER(e,t,n,s,r,a,i,h,f,u,c))+(o-h)*((f-l)*ER(e,t,n,s,r,a,i,d,p,u,c)+(l-p)*ER(e,t,n,s,r,a,i,d,f,u,c))}const _R={kernelName:rs,backendName:"cpu",kernelFunc:function(e){const{inputs:t,attrs:n,backend:s}=e,{axis:r}=n,{x:a}=t;lS(a,"unique");const i=s.data.get(a.dataId).values,{outputValues:o,outputShape:l,indices:u}=MC(i,r,a.shape,a.dtype);return[s.makeTensorInfo(l,a.dtype,o),s.makeTensorInfo([u.length],"int32",u)]}};const FR={kernelName:as,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{value:r}=t;let{axis:a}=s;a<0&&(a+=r.shape.length);const i=r.shape.length,o=r.shape[a],l=new Array(i-1);let u=0;for(let e=0;e<i;e++)e!==a&&(l[u++]=r.shape[e]);const c=new Array(i).fill(0),h=r.shape.slice();h[a]=1;const p=new Array(o);for(let e=0;e<p.length;e++){c[a]=e;const t=lC({inputs:{x:r},backend:n,attrs:{begin:c,size:h}});p[e]=ZC({inputs:{x:t},backend:n,attrs:{shape:l}}),n.disposeIntermediateTensorInfo(t)}return p}};const DR={kernelName:is,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,segmentIds:a}=t,{numSegments:i}=s;lS(r,"unsortedSegmentSum");const o=[],l=[],u=r.shape.length-a.shape.length;let c=a;for(let e=0;e<u;++e){const t=yE({inputs:{input:c},backend:n,attrs:{dim:e+1}});c=t,l.push(t)}for(let e=0;e<i;++e){const t=hr(e,"int32"),s=n.makeTensorInfo([],"int32",t),a=US({inputs:{a:s,b:c},backend:n}),i=kS({inputs:{x:a},backend:n,attrs:{dtype:"float32"}}),u=AT({inputs:{a:i,b:r},backend:n}),h=hE({inputs:{x:u},backend:n,attrs:{axis:0,keepDims:!1}});o.push(h),l.push(s),l.push(a),l.push(i),l.push(u),l.push(h)}const h=SA({inputs:o,backend:n,attrs:{axis:0}});return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),h}},OR=[t$,pS,s$,a$,ES,i$,o$,l$,u$,c$,p$,f$,g$,x$,v$,S$,T$,C$,$$,e$,E$,A$,R$,DS,_$,NS,BS,D$,mS,O$,P$,W$,V$,U$,G$,H$,j$,K$,Y$,Z$,J$,Q$,eE,tE,sE,rE,aE,iE,oE,lE,uE,cE,dE,BC,fE,GS,gE,qS,bE,YS,SE,CE,$E,QS,nT,EE,AE,RE,_E,oT,cT,bS,FE,L$,OE,LE,PE,VC,dT,gT,BE,wT,VE,HE,qE,YE,ZE,JE,eA,IT,tA,nA,sA,rA,aA,iA,oA,CT,lA,hA,fA,RT,FT,gA,bA,wA,MT,vA,IA,TA,CA,AA,HC,WT,RA,_A,FA,DA,wS,vE,MA,qC,XC,JC,LA,zA,PA,BA,WA,VA,GA,nC,HA,KA,XA,ZA,iC,QA,tR,sR,uC,dA,iR,oR,lR,uR,cR,hR,pR,dR,mC,fR,bC,vC,gR,yR,bR,xR,wR,RC,pE,kR,{kernelName:Qn,backendName:"cpu",kernelFunc:NR},IR,SR,TR,CR,PT,_R,FR,DR,NA];for(const e of OR)ws(e);const MR={},LR={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function zR(e,t){MR[e]=t}function PR(e,t){if(!(e in MR)||null!=t){const n=function(e,t){if(1!==e&&2!==e)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");const n=null==t?function(e){if(Y().getBool("IS_SAFARI")||"undefined"==typeof OffscreenCanvas||2!==e){if("undefined"!=typeof document)return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}return new OffscreenCanvas(300,150)}(e):t;n.addEventListener("webglcontextlost",(t=>{t.preventDefault(),delete MR[e]}),!1),Y().getBool("SOFTWARE_WEBGL_ENABLED")&&(LR.failIfMajorPerformanceCaveat=!1);if(1===e)return n.getContext("webgl",LR)||n.getContext("experimental-webgl",LR);return n.getContext("webgl2",LR)}(e,t);if(null===n)return console.log("Could not get context for WebGL version",e),null;MR[e]=n}const n=MR[e];return null==n||n.isContextLost()?(delete MR[e],PR(e)):(n.disable(n.DEPTH_TEST),n.disable(n.STENCIL_TEST),n.disable(n.BLEND),n.disable(n.DITHER),n.disable(n.POLYGON_OFFSET_FILL),n.disable(n.SAMPLE_COVERAGE),n.enable(n.SCISSOR_TEST),n.enable(n.CULL_FACE),n.cullFace(n.BACK),MR[e])}var BR,WR,VR;function UR(e,t){return[t,e]}function GR(e){const t=d(e);return y(Math.ceil(t/4))}function HR(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function jR(e,t){const n=e;let s,r,a,i,o,l,u,c,h,p;return 2===Y().getNumber("WEBGL_VERSION")?(s=n.R32F,r=n.R16F,a=n.RGBA16F,i=n.RGBA32F,o=n.RED,u=4,c=1,h=n.HALF_FLOAT,p=n.FLOAT,l=n.RGBA8):(s=e.RGBA,r=e.RGBA,a=e.RGBA,i=n.RGBA,o=e.RGBA,u=4,c=4,h=null!=t?t.HALF_FLOAT_OES:null,p=e.FLOAT,l=e.RGBA),{internalFormatFloat:s,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:a,internalFormatPackedFloat:i,textureFormatFloat:o,downloadTextureFormat:l,downloadUnpackNumChannels:u,defaultNumChannels:c,textureTypeHalfFloat:h,textureTypeFloat:p}}function qR(e,t){const n=t();return Y().getBool("DEBUG")&&function(e){const t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+XR(e,t))}(e),n}!function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"}(BR||(BR={})),function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"}(WR||(WR={})),function(e){e[e.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",e[e.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",e[e.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",e[e.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",e[e.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"}(VR||(VR={}));function KR(e){return!!(Y().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||0===e||5.96e-8<Math.abs(e)&&Math.abs(e)<65504)}function XR(e,t){switch(t){case e.NO_ERROR:return"NO_ERROR";case e.INVALID_ENUM:return"INVALID_ENUM";case e.INVALID_VALUE:return"INVALID_VALUE";case e.INVALID_OPERATION:return"INVALID_OPERATION";case e.INVALID_FRAMEBUFFER_OPERATION:return"INVALID_FRAMEBUFFER_OPERATION";case e.OUT_OF_MEMORY:return"OUT_OF_MEMORY";case e.CONTEXT_LOST_WEBGL:return"CONTEXT_LOST_WEBGL";default:return`Unknown error code ${t}`}}function YR(e,t){return b_(e,(()=>e.getExtension(t)),'Extension "'+t+'" not supported on this browser.')}function ZR(e,t){const n=b_(e,(()=>e.createShader(e.VERTEX_SHADER)),"Unable to create vertex WebGLShader.");if(qR(e,(()=>e.shaderSource(n,t))),qR(e,(()=>e.compileShader(n))),!1===e.getShaderParameter(n,e.COMPILE_STATUS))throw console.log(e.getShaderInfoLog(n)),new Error("Failed to compile vertex shader.");return n}function JR(e,t){const n=b_(e,(()=>e.createShader(e.FRAGMENT_SHADER)),"Unable to create fragment WebGLShader.");if(qR(e,(()=>e.shaderSource(n,t))),qR(e,(()=>e.compileShader(n))),Y().get("ENGINE_COMPILE_ONLY"))return n;if(!1===e.getShaderParameter(n,e.COMPILE_STATUS))throw e_(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}const QR=/ERROR: [0-9]+:([0-9]+):/g;function e_(e,t){const n=QR.exec(t);if(null==n)return console.log(`Couldn't parse line number in error: ${t}`),void console.log(e);const s=+n[1],r=e.split("\n"),a=r.length.toString().length+2,i=r.map(((e,t)=>b((t+1).toString(),a)+e));let o=0;for(let e=0;e<i.length;e++)o=Math.max(i[e].length,o);const l=i.slice(0,s-1),u=i.slice(s-1,s),c=i.slice(s);console.log(l.join("\n")),console.log(t.split("\n")[0]),console.log(`%c ${b(u[0],o)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(c.join("\n"))}function t_(e){return b_(e,(()=>e.createProgram()),"Unable to create WebGLProgram.")}function n_(e,t){if(qR(e,(()=>e.linkProgram(t))),!Y().get("ENGINE_COMPILE_ONLY")&&!1===e.getProgramParameter(t,e.LINK_STATUS))throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function s_(e,t){if(qR(e,(()=>e.validateProgram(t))),!1===e.getProgramParameter(t,e.VALIDATE_STATUS))throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function r_(e,t){const n=b_(e,(()=>e.createBuffer()),"Unable to create WebGLBuffer");return qR(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,n))),qR(e,(()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW))),n}function a_(e,t){const n=b_(e,(()=>e.createBuffer()),"Unable to create WebGLBuffer");return qR(e,(()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n))),qR(e,(()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW))),n}function i_(e){return b_(e,(()=>e.createTexture()),"Unable to create WebGLTexture.")}function o_(e,t){const n=Y().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){throw new Error("Requested texture size "+`[${e}x${t}]`+" is invalid.")}if(e>n||t>n){throw new Error("Requested texture size "+`[${e}x${t}]`+" greater than WebGL maximum on this browser / GPU "+`[${n}x${n}]`+".")}}function l_(e){return b_(e,(()=>e.createFramebuffer()),"Unable to create WebGLFramebuffer.")}function u_(e,t,n,s,r,a,i){const o=e.getAttribLocation(t,n);return-1!==o&&(qR(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,s))),qR(e,(()=>e.vertexAttribPointer(o,r,e.FLOAT,!1,a,i))),qR(e,(()=>e.enableVertexAttribArray(o))),!0)}function c_(e,t,n){x_(e,n),qR(e,(()=>e.activeTexture(e.TEXTURE0+n))),qR(e,(()=>e.bindTexture(e.TEXTURE_2D,t)))}function h_(e,t,n){return b_(e,(()=>e.getUniformLocation(t,n)),'uniform "'+n+'" not present in program.')}function p_(e,t,n){return e.getUniformLocation(t,n)}function d_(e,t,n,s){qR(e,(()=>c_(e,t,s))),qR(e,(()=>e.uniform1i(n,s)))}function f_(e,t,n){qR(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,n))),qR(e,(()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)))}function m_(e,t){qR(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,t))),qR(e,(()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0)))}function g_(e){const t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+y_(e,t))}function y_(e,t){switch(t){case e.FRAMEBUFFER_INCOMPLETE_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT:return"FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT";case e.FRAMEBUFFER_INCOMPLETE_DIMENSIONS:return"FRAMEBUFFER_INCOMPLETE_DIMENSIONS";case e.FRAMEBUFFER_UNSUPPORTED:return"FRAMEBUFFER_UNSUPPORTED";default:return`unknown error ${t}`}}function b_(e,t,n){const s=qR(e,(()=>t()));if(null==s)throw new Error(n);return s}function x_(e,t){const n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,s=t+e.TEXTURE0;if(s<e.TEXTURE0||s>n){throw new Error(`textureUnit must be in ${`[gl.TEXTURE0, gl.TEXTURE${n}]`}.`)}}function w_(e,t=2){return d(e.slice(0,e.length-t))}function v_(e){if(0===e.length)throw Error("Cannot get rows and columns of an empty shape array.");return[e.length>1?e[e.length-2]:1,e[e.length-1]]}function k_(e){let t=[1,1,1];return 0===e.length||1===e.length&&1===e[0]||(t=[w_(e),...v_(e)]),t}function N_(e,t=!1){let n=Y().getNumber("WEBGL_MAX_TEXTURE_SIZE"),s=Y().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");if(s===1/0&&Y().getBool("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE")&&(s=n/2),t&&(n*=2,s*=2,1===(e=e.map(((t,n)=>n>=e.length-2?o(e[n]):e[n]))).length&&(e=[2,e[0]])),2!==e.length){const t=k(e);e=t.newShape}let r=d(e),a=null;e.length<=1&&r<=n?a=[1,r]:2===e.length&&e[0]<=n&&e[1]<=n?a=e:3===e.length&&e[0]*e[1]<=n&&e[2]<=n?a=[e[0]*e[1],e[2]]:3===e.length&&e[0]<=n&&e[1]*e[2]<=n?a=[e[0],e[1]*e[2]]:4===e.length&&e[0]*e[1]*e[2]<=n&&e[3]<=n?a=[e[0]*e[1]*e[2],e[3]]:4===e.length&&e[0]<=n&&e[1]*e[2]*e[3]<=n&&(a=[e[0],e[1]*e[2]*e[3]]);const i=null!=a&&Math.max(...a)>s&&Math.min(...a)<=(t?2:1)&&Math.min(...a)>0;if(null==a||i)if(t){const t=w_(e);let n=2,s=2;e.length&&([n,s]=v_(e)),r=t*(n/2)*(s/2),a=y(r).map((e=>2*e))}else a=y(r);return a}function I_(e){return e%2==0}function S_(e,t){if(m(e=e.slice(-2),t=t.slice(-2)))return!0;if(!e.length||!t.length)return!0;if(0===e[0]||0===e[1]||0===t[0]||0===t[1])return!0;if(e.length!==t.length){const n=e[e.length-1],s=t[t.length-1];if(n===s)return!0;if(I_(n)&&I_(s)&&(1===e[0]||1===t[0]))return!0}return e[1]===t[1]&&I_(e[0])&&I_(t[0])}let T_,C_;function $_(e){if(null==T_){const t=PR(e);T_=t.getParameter(t.MAX_TEXTURE_SIZE)}return T_}function E_(e){if(null==C_){const t=PR(e);C_=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,C_)}function A_(e){if(0===e)return 0;let t;const n=PR(e);return t=R_(n,"EXT_disjoint_timer_query_webgl2")&&2===e?2:R_(n,"EXT_disjoint_timer_query")?1:0,t}function R_(e,t){return null!=e.getExtension(t)}function __(e){try{if(null!=PR(e))return!0}catch(e){return console.log("Error when getting WebGL context: ",e),!1}return!1}function F_(e){if(0===e)return!1;const t=PR(e);if(1===e){if(!R_(t,"OES_texture_float"))return!1}else if(!R_(t,"EXT_color_buffer_float"))return!1;return O_(t)}function D_(e){if(0===e)return!1;const t=PR(e);if(1!==e){if(R_(t,"EXT_color_buffer_float"))return O_(t);const e="EXT_color_buffer_half_float";if(R_(t,e)){const n=t.getExtension(e);return function(e,t){const n=jR(e,t),s=e.createTexture();e.bindTexture(e.TEXTURE_2D,s);const r=1,a=1;e.texImage2D(e.TEXTURE_2D,0,n.internalFormatHalfFloat,r,a,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);const i=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,i),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,s,0);const o=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(s),e.deleteFramebuffer(i),o}(t,n)}return!1}if(!R_(t,"OES_texture_float"))return!1;if(!R_(t,"WEBGL_color_buffer_float"))return!1;return O_(t)}function O_(e){const t=jR(e),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n);e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,1,1,0,t.textureFormatFloat,t.textureTypeFloat,null);const s=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);const r=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(n),e.deleteFramebuffer(s),r}function M_(e){if(2!==e)return!1;return null!=PR(e).fenceSync}function L_(e,t){Array.isArray(e)||(e=[e]),e.forEach((e=>{null!=e&&c("complex64"!==e.dtype,(()=>`${t} does not support complex64 tensors in the WebGL backend.`))}))}var z_=Object.freeze({__proto__:null,assertNotComplex:L_,bindCanvasToFramebuffer:function(e){qR(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,null))),qR(e,(()=>e.viewport(0,0,e.canvas.width,e.canvas.height))),qR(e,(()=>e.scissor(0,0,e.canvas.width,e.canvas.height)))},bindColorTextureToFramebuffer:f_,bindTextureToProgramUniformSampler:d_,bindTextureUnit:c_,bindVertexBufferToProgramAttribute:u_,callAndCheck:qR,canBeRepresented:KR,createFragmentShader:JR,createFramebuffer:l_,createProgram:t_,createStaticIndexBuffer:a_,createStaticVertexBuffer:r_,createTexture:i_,createVertexShader:ZR,getBatchDim:w_,getExtensionOrThrow:YR,getFramebufferErrorMessage:y_,getMaxTexturesInShader:E_,getNumChannels:function(){return 2===Y().getNumber("WEBGL_VERSION")?1:4},getProgramUniformLocation:p_,getProgramUniformLocationOrThrow:h_,getRowsCols:v_,getShapeAs3D:k_,getTextureShapeFromLogicalShape:N_,getWebGLDisjointQueryTimerVersion:A_,getWebGLErrorMessage:XR,getWebGLMaxTextureSize:$_,hasExtension:R_,isCapableOfRenderingToFloatTexture:F_,isDownloadFloatTextureEnabled:D_,isReshapeFree:S_,isWebGLFenceEnabled:M_,isWebGLVersionEnabled:__,linkProgram:n_,logShaderSourceAndInfoLog:e_,resetMaxTextureSize:function(){T_=null},resetMaxTexturesInShader:function(){C_=null},unbindColorTextureFromFramebuffer:m_,unbindTextureUnit:function(e,t){x_(e,t),qR(e,(()=>e.activeTexture(e.TEXTURE0+t))),qR(e,(()=>e.bindTexture(e.TEXTURE_2D,null)))},validateFramebuffer:g_,validateProgram:s_,validateTextureSize:o_});const P_=Y();function B_(){let e,t,n,s,r,a,i,o,l,u;return 2===Y().getNumber("WEBGL_VERSION")?(e="#version 300 es",t="in",n="out",s="in",r="texture",a="outputColor",i="out vec4 outputColor;",o=Y().getBool("WEBGL2_ISNAN_CUSTOM")?"\n      bool isnan_custom(float val) {\n        uint floatToUint = floatBitsToUint(val);\n        return (floatToUint & 0x7fffffffu) > 0x7f800000u;\n      }\n\n      bvec4 isnan_custom(vec4 val) {\n        return bvec4(isnan_custom(val.x),\n          isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));\n      }\n\n      #define isnan(value) isnan_custom(value)\n    ":"",l="",u="\n      #define round(value) newRound(value)\n      int newRound(float value) {\n        return int(floor(value + 0.5));\n      }\n\n      ivec4 newRound(vec4 value) {\n        return ivec4(floor(value + vec4(0.5)));\n      }\n    "):(e="",t="attribute",n="varying",s="varying",r="texture2D",a="gl_FragColor",i="",o="\n      #define isnan(value) isnan_custom(value)\n      bool isnan_custom(float val) {\n        return (val > 0. || val < 1. || val == 0.) ? false : true;\n      }\n      bvec4 isnan_custom(vec4 val) {\n        return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));\n      }\n    ",l="\n      uniform float INFINITY;\n\n      bool isinf(float val) {\n        return abs(val) == INFINITY;\n      }\n      bvec4 isinf(vec4 val) {\n        return equal(abs(val), vec4(INFINITY));\n      }\n    ",u="\n      int round(float value) {\n        return int(floor(value + 0.5));\n      }\n\n      ivec4 round(vec4 value) {\n        return ivec4(floor(value + vec4(0.5)));\n      }\n    "),{version:e,attribute:t,varyingVs:n,varyingFs:s,texture2D:r,output:a,defineOutput:i,defineSpecialNaN:o,defineSpecialInf:l,defineRound:u}}function W_(e,t,n="index"){const s=M(t);return s.map(((t,r)=>`${`int ${e[r]} = ${n} / ${t}`}; ${r===s.length-1?`int ${e[r+1]} = ${n} - ${e[r]} * ${t}`:`index -= ${e[r]} * ${t}`};`)).join("")}function V_(e,t,n="index"){const s=M(t);return s.map(((t,r)=>`${`int ${e[r]} = ${n} / outShapeStrides[${r}]`}; ${r===s.length-1?`int ${e[r+1]} = ${n} - ${e[r]} * outShapeStrides[${r}]`:`index -= ${e[r]} * outShapeStrides[${r}]`};`)).join("")}function U_(e,t,n="index"){const s=function(e,t){const n=e.length,s=e.map((e=>`${t}[${e}]`)),r=new Array(n-1);r[n-2]=s[n-1];for(let e=n-3;e>=0;--e)r[e]=`(${r[e+1]} * ${s[e+1]})`;return r}(e.map(((e,t)=>t)),t);return s.map(((t,r)=>`${`int ${e[r]} = ${n} / ${s[r]}`}; ${r===s.length-1?`int ${e[r+1]} = ${n} - ${e[r]} * ${s[r]}`:`index -= ${e[r]} * ${s[r]}`};`)).join("")}function G_(e){const t=M(e).map((e=>e.toString()));return`\n  int getFlatIndex(ivec3 coords) {\n    return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;\n  }\n`}P_.registerFlag("HAS_WEBGL",(()=>P_.getNumber("WEBGL_VERSION")>0)),P_.registerFlag("WEBGL_VERSION",(()=>__(2)?2:__(1)?1:0)),P_.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",(()=>!1)),P_.registerFlag("WEBGL_BUFFER_SUPPORTED",(()=>2===P_.get("WEBGL_VERSION"))),P_.registerFlag("WEBGL_CPU_FORWARD",(()=>!0)),P_.registerFlag("WEBGL_FORCE_F16_TEXTURES",(()=>!1)),P_.registerFlag("WEBGL_PACK",(()=>P_.getBool("HAS_WEBGL"))),P_.registerFlag("WEBGL_PACK_NORMALIZATION",(()=>P_.getBool("WEBGL_PACK"))),P_.registerFlag("WEBGL_PACK_CLIP",(()=>P_.getBool("WEBGL_PACK"))),P_.registerFlag("WEBGL_PACK_DEPTHWISECONV",(()=>P_.getBool("WEBGL_PACK"))),P_.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",(()=>P_.getBool("WEBGL_PACK"))),P_.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",(()=>P_.getBool("WEBGL_PACK"))),P_.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",(()=>P_.getBool("WEBGL_PACK"))),P_.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",(()=>P_.getBool("WEBGL_PACK"))),P_.registerFlag("WEBGL_PACK_REDUCE",(()=>P_.getBool("WEBGL_PACK"))),P_.registerFlag("WEBGL_LAZILY_UNPACK",(()=>P_.getBool("WEBGL_PACK"))),P_.registerFlag("WEBGL_CONV_IM2COL",(()=>P_.getBool("WEBGL_PACK"))),P_.registerFlag("WEBGL_PACK_CONV2DTRANSPOSE",(()=>P_.getBool("WEBGL_PACK"))),P_.registerFlag("WEBGL_MAX_TEXTURE_SIZE",(()=>$_(P_.getNumber("WEBGL_VERSION")))),P_.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",(()=>E_(P_.getNumber("WEBGL_VERSION")))),P_.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",(()=>{const e=P_.getNumber("WEBGL_VERSION");return 0===e?0:A_(e)})),P_.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",(()=>P_.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!ra())),P_.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",(()=>F_(P_.getNumber("WEBGL_VERSION")))),P_.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",(()=>!P_.getBool("WEBGL_FORCE_F16_TEXTURES")&&P_.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))),P_.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",(()=>D_(P_.getNumber("WEBGL_VERSION")))),P_.registerFlag("WEBGL_FENCE_API_ENABLED",(()=>M_(P_.getNumber("WEBGL_VERSION")))),P_.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",(()=>P_.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0)),P_.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",(()=>-1),(e=>{if("number"!=typeof e)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be a number but got ${e}.`);if(e<0&&-1!==e)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${e}.`)})),P_.registerFlag("WEBGL_FLUSH_THRESHOLD",(()=>ra()?1:-1),(e=>{if("number"!=typeof e)throw new Error(`WEBGL_FLUSH_THRESHOLD must be a number but got ${e}.`);if(e<0&&-1!==e)throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${e}.`)})),P_.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",(()=>128)),P_.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",(()=>!1)),P_.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",(()=>1e5)),P_.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",(()=>128)),P_.registerFlag("WEBGL_EXP_CONV",(()=>!1)),P_.registerFlag("SOFTWARE_WEBGL_ENABLED",(()=>P_.getBool("IS_TEST"))),P_.registerFlag("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE",(()=>1/0)),P_.registerFlag("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE",(()=>!1)),P_.registerFlag("WEBGL2_ISNAN_CUSTOM",(()=>!1)),P_.registerFlag("ENGINE_COMPILE_ONLY",(()=>!1));const H_="\n  const float FLOAT_MAX = 1.70141184e38;\n  const float FLOAT_MIN = 1.17549435e-38;\n\n  lowp vec4 encode_float(highp float v) {\n    if (isnan(v)) {\n      return vec4(255, 255, 255, 255);\n    }\n\n    highp float av = abs(v);\n\n    if(av < FLOAT_MIN) {\n      return vec4(0.0, 0.0, 0.0, 0.0);\n    } else if(v > FLOAT_MAX) {\n      return vec4(0.0, 0.0, 128.0, 127.0) / 255.0;\n    } else if(v < -FLOAT_MAX) {\n      return vec4(0.0, 0.0,  128.0, 255.0) / 255.0;\n    }\n\n    highp vec4 c = vec4(0,0,0,0);\n\n    highp float e = floor(log2(av));\n    highp float m = exp2(fract(log2(av))) - 1.0;\n\n    c[2] = floor(128.0 * m);\n    m -= c[2] / 128.0;\n    c[1] = floor(32768.0 * m);\n    m -= c[1] / 32768.0;\n    c[0] = floor(8388608.0 * m);\n\n    highp float ebias = e + 127.0;\n    c[3] = floor(ebias / 2.0);\n    ebias -= c[3] * 2.0;\n    c[2] += floor(ebias) * 128.0;\n\n    c[3] += 128.0 * step(0.0, -v);\n\n    return c / 255.0;\n  }\n",{getBroadcastDims:j_}=am;function q_(e,t,n){const s=[];if(e.forEach((e=>{const t=d(e.shapeInfo.logicalShape);if(e.shapeInfo.isUniform?s.push(`uniform float ${e.name}${t>1?`[${t}]`:""};`):(s.push(`uniform sampler2D ${e.name};`),s.push(`uniform int offset${e.name};`)),n.enableShapeUniforms){const{uniformShape:t}=rF(n.packedInputs,e.shapeInfo.logicalShape,e.shapeInfo.texShape);switch(t.length){case 1:s.push(`uniform int ${e.name}Shape;`);break;case 2:s.push(`uniform ivec2 ${e.name}Shape;`);break;case 3:s.push(`uniform ivec3 ${e.name}Shape;`);break;case 4:s.push(`uniform ivec4 ${e.name}Shape;`)}s.push(`uniform ivec2 ${e.name}TexShape;`)}})),n.enableShapeUniforms){switch(t.logicalShape.length){case 1:s.push("uniform int outShape;");break;case 2:s.push("uniform ivec2 outShape;"),s.push("uniform int outShapeStrides;");break;case 3:s.push("uniform ivec3 outShape;"),s.push("uniform ivec2 outShapeStrides;");break;case 4:s.push("uniform ivec4 outShape;"),s.push("uniform ivec3 outShapeStrides;")}s.push("uniform ivec2 outTexShape;")}n.customUniforms&&n.customUniforms.forEach((e=>{s.push(`uniform ${e.type} ${e.name}${e.arrayIndex?`[${e.arrayIndex}]`:""};`)}));const r=s.join("\n"),a=e.map((e=>function(e,t,n=!1,s){let r="";r+=n?X_(e,s):K_(e,s);const a=e.shapeInfo.logicalShape,i=t.logicalShape;a.length<=i.length&&(r+=n?function(e,t){const n=e.name,s=n.charAt(0).toUpperCase()+n.slice(1),r="get"+s+"AtOutCoords",a=e.shapeInfo.logicalShape.length,i=t.logicalShape.length,o=j_(e.shapeInfo.logicalShape,t.logicalShape),l=sF(i),u=i-a;let c;const h=["x","y","z","w","u","v"];c=0===a?"":i<2&&o.length>=1?"coords = 0;":o.map((e=>`coords.${h[e+u]} = 0;`)).join("\n");let p="";p=i<2&&a>0?"coords":e.shapeInfo.logicalShape.map(((e,t)=>`coords.${h[t+u]}`)).join(", ");let f="return outputValue;";const m=1===d(e.shapeInfo.logicalShape),g=1===d(t.logicalShape);if(1!==a||m||g){if(m&&!g)f=1===i?"\n        return vec4(outputValue.x, outputValue.x, 0., 0.);\n      ":"\n        return vec4(outputValue.x);\n      ";else if(o.length){const e=a-2,t=a-1;o.indexOf(e)>-1&&o.indexOf(t)>-1?f="return vec4(outputValue.x);":o.indexOf(e)>-1?f="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":o.indexOf(t)>-1&&(f="return vec4(outputValue.xx, outputValue.zz);")}}else f="\n      return vec4(outputValue.xy, outputValue.xy);\n    ";return`\n    vec4 ${r}() {\n      ${l} coords = getOutputCoords();\n      ${c}\n      vec4 outputValue = get${s}(${p});\n      ${f}\n    }\n  `}(e,t):function(e,t){const n=e.name,s=n.charAt(0).toUpperCase()+n.slice(1),r="get"+s+"AtOutCoords",a=t.texShape,i=e.shapeInfo.texShape,o=e.shapeInfo.logicalShape.length,l=t.logicalShape.length;if(!e.shapeInfo.isUniform&&o===l&&null==e.shapeInfo.flatOffset&&m(i,a))return`\n      float ${r}() {\n        return sampleTexture(${n}, resultUV);\n      }\n    `;const u=sF(l),c=j_(e.shapeInfo.logicalShape,t.logicalShape),h=l-o;let p;const d=["x","y","z","w","u","v"];p=0===o?"":l<2&&c.length>=1?"coords = 0;":c.map((e=>`coords.${d[e+h]} = 0;`)).join("\n");let f="";f=l<2&&o>0?"coords":e.shapeInfo.logicalShape.map(((e,t)=>`coords.${d[t+h]}`)).join(", ");return`\n    float ${r}() {\n      ${u} coords = getOutputCoords();\n      ${p}\n      return get${s}(${f});\n    }\n  `}(e,t));return r}(e,t,n.packedInputs,n.enableShapeUniforms))).join("\n"),i=t.texShape,o=B_(),l=function(e){return`\n    float sampleTexture(sampler2D textureSampler, vec2 uv) {\n      return ${e.texture2D}(textureSampler, uv).r;\n    }\n  `}(o);let u,c,h=function(e){return`${e.version}\n    precision highp float;\n    precision highp int;\n    precision highp sampler2D;\n    ${e.varyingFs} vec2 resultUV;\n    ${e.defineOutput}\n    const vec2 halfCR = vec2(0.5, 0.5);\n\n    struct ivec5\n    {\n      int x;\n      int y;\n      int z;\n      int w;\n      int u;\n    };\n\n    struct ivec6\n    {\n      int x;\n      int y;\n      int z;\n      int w;\n      int u;\n      int v;\n    };\n\n    uniform float NAN;\n    ${e.defineSpecialNaN}\n    ${e.defineSpecialInf}\n    ${e.defineRound}\n\n    int imod(int x, int y) {\n      return x - y * (x / y);\n    }\n\n    int idiv(int a, int b, float sign) {\n      int res = a / b;\n      int mod = imod(a, b);\n      if (sign < 0. && mod != 0) {\n        res -= 1;\n      }\n      return res;\n    }\n\n    //Based on the work of Dave Hoskins\n    //https://www.shadertoy.com/view/4djSRW\n    #define HASHSCALE1 443.8975\n    float random(float seed){\n      vec2 p = resultUV * seed;\n      vec3 p3  = fract(vec3(p.xyx) * HASHSCALE1);\n      p3 += dot(p3, p3.yzx + 19.19);\n      return fract((p3.x + p3.y) * p3.z);\n    }\n\n    ${Y_}\n    ${Z_}\n    ${J_}\n  `}(o);t.isPacked?(u=function(e,t,n){switch(e.length){case 0:return eF();case 1:return function(e,t,n){const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(1===s[0])return n?"\n      int getOutputCoords() {\n        return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));\n      }\n    ":`\n      int getOutputCoords() {\n        return 2 * int(resultUV.x * ${s[1]}.0);\n      }\n    `;if(1===s[1])return n?"\n      int getOutputCoords() {\n        return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));\n      }\n    ":`\n      int getOutputCoords() {\n        return 2 * int(resultUV.y * ${s[0]}.0);\n      }\n    `;if(n)return"\n    int getOutputCoords() {\n      ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(packedTexShape[0], packedTexShape[1]));\n      return 2 * (resTexRC.x * packedTexShape[1] + resTexRC.y);\n    }\n  ";return`\n    int getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(${s[0]}, ${s[1]}));\n      return 2 * (resTexRC.x * ${s[1]} + resTexRC.y);\n    }\n  `}(0,t,n);case 2:return function(e,t,n){const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(m(e,t))return n?"\n      ivec2 getOutputCoords() {\n        ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n        return 2 * ivec2(resultUV.yx * vec2(packedTexShape[0], packedTexShape[1]));\n      }\n    ":`\n      ivec2 getOutputCoords() {\n        return 2 * ivec2(resultUV.yx * vec2(${s[0]}, ${s[1]}));\n      }\n    `;const r=Math.ceil(e[1]/2);if(n)return"\n    ivec2 getOutputCoords() {\n      ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n      int texelsInLogicalRow = int(ceil(float(outShape[1]) / 2.0));\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(packedTexShape[0], packedTexShape[1]));\n\n      int index = resTexRC.x * packedTexShape[1] + resTexRC.y;\n      int r = 2 * (index / texelsInLogicalRow);\n      int c = imod(index, texelsInLogicalRow) * 2;\n\n      return ivec2(r, c);\n    }\n  ";return`\n    ivec2 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(${s[0]}, ${s[1]}));\n\n      int index = resTexRC.x * ${s[1]} + resTexRC.y;\n      int r = 2 * (index / ${r});\n      int c = imod(index, ${r}) * 2;\n\n      return ivec2(r, c);\n    }\n  `}(e,t,n);case 3:return function(e,t,n){if(n)return"\n    ivec3 getOutputCoords() {\n      ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n      int texelsInLogicalRow = int(ceil(float(outShape[2]) / 2.0));\n      int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[1]) / 2.0));\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(packedTexShape[0], packedTexShape[1]));\n      int index = resTexRC.x * packedTexShape[1] + resTexRC.y;\n\n      int b = index / texelsInBatch;\n      index -= b * texelsInBatch;\n\n      int r = 2 * (index / texelsInLogicalRow);\n      int c = imod(index, texelsInLogicalRow) * 2;\n\n      return ivec3(b, r, c);\n    }\n  ";const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(e[2]/2),a=r*Math.ceil(e[1]/2);return`\n    ivec3 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(${s[0]}, ${s[1]}));\n      int index = resTexRC.x * ${s[1]} + resTexRC.y;\n\n      int b = index / ${a};\n      index -= b * ${a};\n\n      int r = 2 * (index / ${r});\n      int c = imod(index, ${r}) * 2;\n\n      return ivec3(b, r, c);\n    }\n  `}(e,t,n);default:return function(e,t,n){if(n)return"\n    ivec4 getOutputCoords() {\n      ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(packedTexShape[0], packedTexShape[1]));\n      int index = resTexRC.x * packedTexShape[1] + resTexRC.y;\n\n      int texelsInLogicalRow = int(ceil(float(outShape[3]) / 2.0));\n      int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[2]) / 2.0));\n      int texelsInBatchN = texelsInBatch * outShape[1];\n\n      int b2 = index / texelsInBatchN;\n      index -= b2 * texelsInBatchN;\n\n      int b = index / texelsInBatch;\n      index -= b * texelsInBatch;\n\n      int r = 2 * (index / texelsInLogicalRow);\n      int c = imod(index, texelsInLogicalRow) * 2;\n\n      return ivec4(b2, b, r, c);\n    }\n  ";const s=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],r=Math.ceil(e[e.length-1]/2),a=r*Math.ceil(e[e.length-2]/2);let i=a,o="",l="b, r, c";for(let t=2;t<e.length-1;t++)i*=e[e.length-t-1],o=`\n      int b${t} = index / ${i};\n      index -= b${t} * ${i};\n    `+o,l=`b${t}, `+l;return`\n    ivec${e.length} getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(${s[0]}, ${s[1]}));\n      int index = resTexRC.x * ${s[1]} + resTexRC.y;\n\n      ${o}\n\n      int b = index / ${a};\n      index -= b * ${a};\n\n      int r = 2 * (index / ${r});\n      int c = imod(index, ${r}) * 2;\n\n      return ivec${e.length}(${l});\n    }\n  `}(e,t,n)}}(t.logicalShape,i,n.enableShapeUniforms),c=function(e){return`\n    void setOutput(vec4 val) {\n      ${e.output} = val;\n    }\n  `}(o)):(u=function(e,t,n){switch(e.length){case 0:return eF();case 1:return function(e,t,n){if(1===t[0])return n?"\n      int getOutputCoords() {\n        return int(resultUV.x * float(outTexShape[1]));\n      }\n    ":`\n      int getOutputCoords() {\n        return int(resultUV.x * ${t[1]}.0);\n      }\n    `;if(1===t[1])return n?"\n      int getOutputCoords() {\n        return int(resultUV.y * float(outTexShape[0]));\n      }\n    ":`\n      int getOutputCoords() {\n        return int(resultUV.y * ${t[0]}.0);\n      }\n    `;if(n)return"\n    int getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(outTexShape[0], outTexShape[1]));\n      return resTexRC.x * outTexShape[1] + resTexRC.y;\n    }\n  ";return`\n    int getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(${t[0]}, ${t[1]}));\n      return resTexRC.x * ${t[1]} + resTexRC.y;\n    }\n  `}(0,t,n);case 2:return function(e,t,n){if(m(e,t))return n?"\n      ivec2 getOutputCoords() {\n        return ivec2(resultUV.yx * vec2(outTexShape[0], outTexShape[1]));\n      }\n    ":`\n      ivec2 getOutputCoords() {\n        return ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]}));\n      }\n    `;if(1===e[1])return n?"\n      ivec2 getOutputCoords() {\n        ivec2 resTexRC = ivec2(resultUV.yx *\n                               vec2(outTexShape[0], outTexShape[1]));\n        int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n        return ivec2(index, 0);\n      }\n    ":`\n      ivec2 getOutputCoords() {\n        ivec2 resTexRC = ivec2(resultUV.yx *\n                               vec2(${t[0]}, ${t[1]}));\n        int index = resTexRC.x * ${t[1]} + resTexRC.y;\n        return ivec2(index, 0);\n      }\n    `;if(1===e[0])return n?"\n      ivec2 getOutputCoords() {\n        ivec2 resTexRC = ivec2(resultUV.yx *\n                               vec2(outTexShape[0], outTexShape[1]));\n        int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n        return ivec2(0, index);\n      }\n    ":`\n      ivec2 getOutputCoords() {\n        ivec2 resTexRC = ivec2(resultUV.yx *\n                               vec2(${t[0]}, ${t[1]}));\n        int index = resTexRC.x * ${t[1]} + resTexRC.y;\n        return ivec2(0, index);\n      }\n    `;if(n)return"\n    ivec2 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(outTexShape[0], outTexShape[1]));\n      int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n      int r = index / outShape[1];\n      int c = index - r * outShape[1];\n      return ivec2(r, c);\n    }\n  ";return`\n    ivec2 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(${t[0]}, ${t[1]}));\n      int index = resTexRC.x * ${t[1]} + resTexRC.y;\n      int r = index / ${e[1]};\n      int c = index - r * ${e[1]};\n      return ivec2(r, c);\n    }\n  `}(e,t,n);case 3:return function(e,t,n){if(n){return`\n  ivec3 getOutputCoords() {\n    ivec2 resTexRC = ivec2(resultUV.yx *\n                           vec2(outTexShape[0], outTexShape[1]));\n    int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n    ${V_(["r","c","d"],e)}\n    return ivec3(r, c, d);\n  }\n`}const s=W_(["r","c","d"],e);return`\n    ivec3 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n                             vec2(${t[0]}, ${t[1]}));\n      int index = resTexRC.x * ${t[1]} + resTexRC.y;\n      ${s}\n      return ivec3(r, c, d);\n    }\n  `}(e,t,n);case 4:return function(e,t,n){if(n){return`\n    ivec4 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n        vec2(outTexShape[0], outTexShape[1]));\n      int index = resTexRC.x * outTexShape[1] + resTexRC.y;\n      ${V_(["r","c","d","d2"],e)}\n      return ivec4(r, c, d, d2);\n    }\n  `}const s=W_(["r","c","d","d2"],e);return`\n    ivec4 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n        vec2(${t[0]}, ${t[1]}));\n      int index = resTexRC.x * ${t[1]} + resTexRC.y;\n      ${s}\n      return ivec4(r, c, d, d2);\n    }\n  `}(e,t,n);case 5:return function(e,t){const n=W_(["r","c","d","d2","d3"],e);return`\n    ivec5 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]},\n                             ${t[1]}));\n\n      int index = resTexRC.x * ${t[1]} + resTexRC.y;\n\n      ${n}\n\n      ivec5 outShape = ivec5(r, c, d, d2, d3);\n      return outShape;\n    }\n  `}(e,t);case 6:return function(e,t){const n=W_(["r","c","d","d2","d3","d4"],e);return`\n    ivec6 getOutputCoords() {\n      ivec2 resTexRC = ivec2(resultUV.yx *\n        vec2(${t[0]}, ${t[1]}));\n      int index = resTexRC.x * ${t[1]} + resTexRC.y;\n\n      ${n}\n\n      ivec6 result = ivec6(r, c, d, d2, d3, d4);\n      return result;\n    }\n  `}(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}(t.logicalShape,i,n.enableShapeUniforms),c=function(e){return`\n    void setOutput(float val) {\n      ${e.output} = vec4(val, 0, 0, 0);\n    }\n  `}(o)),n.packedInputs&&(h+=Q_);return[h,l,c,r,u,a,n.userCode].join("\n")}function K_(e,t=!1){const n=e.shapeInfo.logicalShape;switch(n.length){case 0:return function(e,t){const n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`float ${s}() {return ${n};}`;const[r,a]=e.shapeInfo.texShape;if(1===r&&1===a)return`\n      float ${s}() {\n        return sampleTexture(${n}, halfCR);\n      }\n    `;const i=tF(n);if(t)return`\n    float ${s}() {\n      vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], ${i});\n      return sampleTexture(${n}, uv);\n    }\n  `;const[o,l]=e.shapeInfo.texShape;return`\n    float ${s}() {\n      vec2 uv = uvFromFlat(${o}, ${l}, ${i});\n      return sampleTexture(${n}, uv);\n    }\n  `}(e,t);case 1:return function(e,t){const n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`\n      float ${s}(int index) {\n        ${nF(e)}\n      }\n    `;const r=e.shapeInfo.texShape,a=r[0],i=r[1];if(1===i&&1===a)return`\n      float ${s}(int index) {\n        return sampleTexture(${n}, halfCR);\n      }\n    `;const o=tF(n);if(1===i)return t?`\n      float ${s}(int index) {\n        vec2 uv = vec2(0.5, (float(index + ${o}) + 0.5) / float(${n}TexShape[0]));\n        return sampleTexture(${n}, uv);\n      }\n    `:`\n      float ${s}(int index) {\n        vec2 uv = vec2(0.5, (float(index + ${o}) + 0.5) / ${a}.0);\n        return sampleTexture(${n}, uv);\n      }\n    `;if(1===a)return t?`\n      float ${s}(int index) {\n        vec2 uv = vec2((float(index + ${o}) + 0.5) / float(${n}TexShape[1]), 0.5);\n        return sampleTexture(${n}, uv);\n      }\n    `:`\n      float ${s}(int index) {\n        vec2 uv = vec2((float(index + ${o}) + 0.5) / ${i}.0, 0.5);\n        return sampleTexture(${n}, uv);\n      }\n    `;if(t)return`\n    float ${s}(int index) {\n      vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index + ${o});\n      return sampleTexture(${n}, uv);\n    }\n  `;return`\n    float ${s}(int index) {\n      vec2 uv = uvFromFlat(${a}, ${i}, index + ${o});\n      return sampleTexture(${n}, uv);\n    }\n  `}(e,t);case 2:return function(e,t){const n=e.shapeInfo.logicalShape,s=e.name,r="get"+s.charAt(0).toUpperCase()+s.slice(1),a=e.shapeInfo.texShape;if(null!=a&&m(n,a)){if(t)return`\n      float ${r}(int row, int col) {\n        vec2 uv = (vec2(col, row) + halfCR) / vec2(${s}TexShape[1], ${s}TexShape[0]);\n        return sampleTexture(${s}, uv);\n      }\n    `;const e=a[0];return`\n    float ${r}(int row, int col) {\n      vec2 uv = (vec2(col, row) + halfCR) / vec2(${a[1]}.0, ${e}.0);\n      return sampleTexture(${s}, uv);\n    }\n  `}const{newShape:i,keptDims:o}=k(n),l=i;if(l.length<n.length){const n=["row","col"];return`\n      ${K_(aF(e,l),t)}\n      float ${r}(int row, int col) {\n        return ${r}(${iF(n,o)});\n      }\n    `}if(e.shapeInfo.isUniform)return`\n      float ${r}(int row, int col) {\n        int index = round(dot(vec2(row, col), vec2(${n[1]}, 1)));\n        ${nF(e)}\n      }\n    `;const u=a[0],c=a[1],h=tF(s);if(1===c)return t?`\n      float ${r}(int row, int col) {\n        float index = dot(vec3(row, col, ${h}), vec3(${s}Shape[1], 1, 1));\n        vec2 uv = vec2(0.5, (index + 0.5) / float(${s}TexShape[0]));\n        return sampleTexture(${s}, uv);\n      }\n    `:`\n    float ${r}(int row, int col) {\n      float index = dot(vec3(row, col, ${h}), vec3(${n[1]}, 1, 1));\n      vec2 uv = vec2(0.5, (index + 0.5) / ${u}.0);\n      return sampleTexture(${s}, uv);\n    }\n  `;if(1===u)return t?`\n      float ${r}(int row, int col) {\n        float index = dot(vec3(row, col, ${h}), vec3(${s}Shape[1], 1, 1));\n        vec2 uv = vec2((index + 0.5) / float(${s}TexShape[1]), 0.5);\n        return sampleTexture(${s}, uv);\n      }\n    `:`\n    float ${r}(int row, int col) {\n      float index = dot(vec3(row, col, ${h}), vec3(${n[1]}, 1, 1));\n      vec2 uv = vec2((index + 0.5) / ${c}.0, 0.5);\n      return sampleTexture(${s}, uv);\n    }\n  `;if(t)return`\n      float ${r}(int row, int col) {\n        // Explicitly use integer operations as dot() only works on floats.\n        int index = row * ${s}Shape[1] + col + ${h};\n        vec2 uv = uvFromFlat(${s}TexShape[0], ${s}TexShape[1], index);\n        return sampleTexture(${s}, uv);\n      }\n    `;return`\n  float ${r}(int row, int col) {\n    // Explicitly use integer operations as dot() only works on floats.\n    int index = row * ${n[1]} + col + ${h};\n    vec2 uv = uvFromFlat(${u}, ${c}, index);\n    return sampleTexture(${s}, uv);\n  }\n`}(e,t);case 3:return function(e,t){const n=e.shapeInfo.logicalShape,s=e.name,r="get"+s.charAt(0).toUpperCase()+s.slice(1),a=n[1]*n[2],i=n[2],{newShape:o,keptDims:l}=k(n),u=o;if(u.length<n.length){const n=["row","col","depth"];return`\n        ${K_(aF(e,u),t)}\n        float ${r}(int row, int col, int depth) {\n          return ${r}(${iF(n,l)});\n        }\n      `}if(e.shapeInfo.isUniform)return`\n      float ${r}(int row, int col, int depth) {\n        int index = round(dot(vec3(row, col, depth),\n                          vec3(${a}, ${i}, 1)));\n        ${nF(e)}\n      }\n    `;const c=e.shapeInfo.texShape,h=c[0],p=c[1],d=e.shapeInfo.flatOffset;if(p===a&&null==d)return t?`\n      float ${r}(int row, int col, int depth) {\n        int stride1 = ${s}Shape[2];\n        float texR = float(row);\n        float texC = dot(vec2(col, depth), vec2(stride1, 1));\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                   vec2(${s}TexShape[1], ${s}TexShape[0]);\n        return sampleTexture(${s}, uv);\n      }\n    `:`\n        float ${r}(int row, int col, int depth) {\n          float texR = float(row);\n          float texC = dot(vec2(col, depth), vec2(${i}, 1));\n          vec2 uv = (vec2(texC, texR) + halfCR) /\n                     vec2(${p}.0, ${h}.0);\n          return sampleTexture(${s}, uv);\n        }\n      `;if(p===i&&null==d)return t?`\n      float ${r}(int row, int col, int depth) {\n        float texR = dot(vec2(row, col), vec2(${s}Shape[1], 1));\n        float texC = float(depth);\n        vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${s}TexShape[1], ${s}TexShape[0]);\n        return sampleTexture(${s}, uv);\n      }\n    `:`\n    float ${r}(int row, int col, int depth) {\n      float texR = dot(vec2(row, col), vec2(${n[1]}, 1));\n      float texC = float(depth);\n      vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${p}.0, ${h}.0);\n      return sampleTexture(${s}, uv);\n    }\n  `;const f=tF(s);if(t)return`\n    float ${r}(int row, int col, int depth) {\n      // Explicitly use integer operations as dot() only works on floats.\n      int stride0 = ${s}Shape[1] * ${s}Shape[2];\n      int stride1 = ${s}Shape[2];\n      int index = row * stride0 + col * stride1 + depth + ${f};\n      vec2 uv = uvFromFlat(${s}TexShape[0], ${s}TexShape[1], index);\n      return sampleTexture(${s}, uv);\n    }\n    `;return`\n      float ${r}(int row, int col, int depth) {\n        // Explicitly use integer operations as dot() only works on floats.\n        int index = row * ${a} + col * ${i} + depth + ${f};\n        vec2 uv = uvFromFlat(${h}, ${p}, index);\n        return sampleTexture(${s}, uv);\n      }\n  `}(e,t);case 4:return function(e,t){const n=e.shapeInfo.logicalShape,s=e.name,r="get"+s.charAt(0).toUpperCase()+s.slice(1),a=n[3],i=n[2]*a,o=n[1]*i,{newShape:l,keptDims:u}=k(n);if(l.length<n.length){const n=["row","col","depth","depth2"];return`\n      ${K_(aF(e,l),t)}\n      float ${r}(int row, int col, int depth, int depth2) {\n        return ${r}(${iF(n,u)});\n      }\n    `}if(e.shapeInfo.isUniform)return`\n      float ${r}(int row, int col, int depth, int depth2) {\n        int index = round(dot(vec4(row, col, depth, depth2),\n                          vec4(${o}, ${i}, ${a}, 1)));\n        ${nF(e)}\n      }\n    `;const c=e.shapeInfo.flatOffset,h=e.shapeInfo.texShape,p=h[0],d=h[1],f=`int stride2 = ${s}Shape[3];`,m=`int stride1 = ${s}Shape[2] * stride2;`,g=`int stride0 = ${s}Shape[1] * stride1;`;if(d===o&&null==c)return t?`\n      float ${r}(int row, int col, int depth, int depth2) {\n        ${f}\n        ${m}\n        float texR = float(row);\n        float texC =\n            dot(vec3(col, depth, depth2),\n                vec3(stride1, stride2, 1));\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                   vec2(${s}TexShape[1], ${s}TexShape[0]);\n        return sampleTexture(${s}, uv);\n      }\n    `:`\n      float ${r}(int row, int col, int depth, int depth2) {\n        float texR = float(row);\n        float texC =\n            dot(vec3(col, depth, depth2),\n                vec3(${i}, ${a}, 1));\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                   vec2(${d}.0, ${p}.0);\n        return sampleTexture(${s}, uv);\n      }\n    `;if(d===a&&null==c)return t?`\n      float ${r}(int row, int col, int depth, int depth2) {\n        float texR = dot(vec3(row, col, depth),\n                         vec3(${s}Shape[1] * ${s}Shape[2], ${s}Shape[2], 1));\n        float texC = float(depth2);\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                  vec2(${s}TexShape[1], ${s}TexShape[0]);\n        return sampleTexture(${s}, uv);\n      }\n    `:`\n      float ${r}(int row, int col, int depth, int depth2) {\n        float texR = dot(vec3(row, col, depth),\n                         vec3(${n[1]*n[2]}, ${n[2]}, 1));\n        float texC = float(depth2);\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                  vec2(${d}.0, ${p}.0);\n        return sampleTexture(${s}, uv);\n      }\n    `;const y=tF(s);if(t)return`\n    float ${r}(int row, int col, int depth, int depth2) {\n      // Explicitly use integer operations as dot() only works on floats.\n      ${f}\n      ${m}\n      ${g}\n      int index = row * stride0 + col * stride1 +\n          depth * stride2 + depth2;\n      vec2 uv = uvFromFlat(${s}TexShape[0], ${s}TexShape[1], index + ${y});\n      return sampleTexture(${s}, uv);\n    }\n  `;return`\n    float ${r}(int row, int col, int depth, int depth2) {\n      // Explicitly use integer operations as dot() only works on floats.\n      int index = row * ${o} + col * ${i} +\n          depth * ${a} + depth2;\n      vec2 uv = uvFromFlat(${p}, ${d}, index + ${y});\n      return sampleTexture(${s}, uv);\n    }\n  `}(e,t);case 5:return function(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),r=t[4],a=t[3]*r,i=t[2]*a,o=t[1]*i,{newShape:l,keptDims:u}=k(t);if(l.length<t.length){const t=["row","col","depth","depth2","depth3"];return`\n      ${K_(aF(e,l))}\n      float ${s}(int row, int col, int depth, int depth2, int depth3) {\n        return ${s}(${iF(t,u)});\n      }\n    `}if(e.shapeInfo.isUniform)return`\n      float ${s}(int row, int col, int depth, int depth2, int depth3) {\n        float index = dot(\n          vec4(row, col, depth, depth2),\n          vec4(${o}, ${i}, ${a}, ${r})) +\n          depth3;\n        ${nF(e)}\n      }\n    `;const c=e.shapeInfo.flatOffset,h=e.shapeInfo.texShape,p=h[0],d=h[1];if(d===o&&null==c)return`\n      float ${s}(int row, int col, int depth, int depth2, int depth3) {\n        int texR = row;\n        float texC = dot(vec4(col, depth, depth2, depth3),\n                         vec4(${i}, ${a}, ${r}, 1));\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                   vec2(${d}.0, ${p}.0);\n        return sampleTexture(${n}, uv);\n      }\n    `;if(d===r&&null==c)return`\n      float ${s}(int row, int col, int depth, int depth2, int depth3) {\n        float texR = dot(\n          vec4(row, col, depth, depth2),\n          vec4(${t[1]*t[2]*t[3]},\n               ${t[2]*t[3]}, ${t[3]}, 1));\n        int texC = depth3;\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                  vec2(${d}.0, ${p}.0);\n        return sampleTexture(${n}, uv);\n      }\n    `;const f=tF(n);return`\n    float ${s}(int row, int col, int depth, int depth2, int depth3) {\n      // Explicitly use integer operations as dot() only works on floats.\n      int index = row * ${o} + col * ${i} + depth * ${a} +\n          depth2 * ${r} + depth3 + ${f};\n      vec2 uv = uvFromFlat(${p}, ${d}, index);\n      return sampleTexture(${n}, uv);\n    }\n  `}(e);case 6:return function(e){const t=e.shapeInfo.logicalShape,n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:r,keptDims:a}=k(t);if(r.length<t.length){const t=["row","col","depth","depth2","depth3","depth4"];return`\n      ${K_(aF(e,r))}\n      float ${s}(int row, int col, int depth,\n                    int depth2, int depth3, int depth4) {\n        return ${s}(${iF(t,a)});\n      }\n    `}const i=t[5],o=t[4]*i,l=t[3]*o,u=t[2]*l,c=t[1]*u;if(e.shapeInfo.isUniform)return`\n      float ${s}(int row, int col, int depth,\n                  int depth2, int depth3, int depth4) {\n        int index = round(dot(\n          vec4(row, col, depth, depth2),\n          vec4(${c}, ${u}, ${l}, ${o})) +\n          dot(\n            vec2(depth3, depth4),\n            vec2(${i}, 1)));\n        ${nF(e)}\n      }\n    `;const h=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,d=p[0],f=p[1];if(f===c&&null==h)return`\n      float ${s}(int row, int col, int depth,\n                    int depth2, int depth3, int depth4) {\n        int texR = row;\n        float texC = dot(vec4(col, depth, depth2, depth3),\n          vec4(${u}, ${l}, ${o}, ${i})) +\n               float(depth4);\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                   vec2(${f}.0, ${d}.0);\n        return sampleTexture(${n}, uv);\n      }\n    `;if(f===i&&null==h)return`\n      float ${s}(int row, int col, int depth,\n                    int depth2, int depth3, int depth4) {\n        float texR = dot(vec4(row, col, depth, depth2),\n          vec4(${t[1]*t[2]*t[3]*t[4]},\n               ${t[2]*t[3]*t[4]},\n               ${t[3]*t[4]},\n               ${t[4]})) + float(depth3);\n        int texC = depth4;\n        vec2 uv = (vec2(texC, texR) + halfCR) /\n                  vec2(${f}.0, ${d}.0);\n        return sampleTexture(${n}, uv);\n      }\n    `;const m=tF(n);return`\n    float ${s}(int row, int col, int depth,\n                  int depth2, int depth3, int depth4) {\n      // Explicitly use integer operations as dot() only works on floats.\n      int index = row * ${c} + col * ${u} + depth * ${l} +\n          depth2 * ${o} + depth3 * ${i} + depth4 + ${m};\n      vec2 uv = uvFromFlat(${d}, ${f}, index);\n      return sampleTexture(${n}, uv);\n    }\n  `}(e);default:throw new Error(`${n.length}-D input sampling is not yet supported`)}}function X_(e,t){switch(e.shapeInfo.logicalShape.length){case 0:return function(e){const t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),s=B_();return`\n    vec4 ${n}() {\n      return ${s.texture2D}(${t}, halfCR);\n    }\n  `}(e);case 1:return function(e,t){const n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),r=e.shapeInfo.texShape,a=B_();if(t)return`\n    vec4 ${s}(int index) {\n      ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));\n      vec2 uv = packedUVfrom1D(\n        packedTexShape[0], packedTexShape[1], index);\n      return ${a.texture2D}(${n}, uv);\n    }\n  `;const i=[Math.ceil(r[0]/2),Math.ceil(r[1]/2)];return`\n    vec4 ${s}(int index) {\n      vec2 uv = packedUVfrom1D(\n        ${i[0]}, ${i[1]}, index);\n      return ${a.texture2D}(${n}, uv);\n    }\n  `}(e,t);case 2:return function(e,t){const n=e.shapeInfo.logicalShape,s=e.name,r="get"+s.charAt(0).toUpperCase()+s.slice(1),a=e.shapeInfo.texShape,i=a[0],o=a[1],l=B_();if(null!=a&&m(n,a))return t?`\n      vec4 ${r}(int row, int col) {\n        vec2 uv = (vec2(col, row) + halfCR) / vec2(${s}TexShape[1], ${s}TexShape[0]);\n\n        return ${l.texture2D}(${s}, uv);\n      }\n    `:`\n      vec4 ${r}(int row, int col) {\n        vec2 uv = (vec2(col, row) + halfCR) / vec2(${o}.0, ${i}.0);\n\n        return ${l.texture2D}(${s}, uv);\n      }\n    `;if(t)return`\n    vec4 ${r}(int row, int col) {\n      ivec2 packedTexShape = ivec2(ceil(float(${s}TexShape[0]) / 2.0), ceil(float(${s}TexShape[1]) / 2.0));\n      int valuesPerRow = int(ceil(float(${s}Shape[1]) / 2.0));\n      vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);\n      return ${l.texture2D}(${s}, uv);\n    }\n  `;const u=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],c=Math.ceil(n[1]/2);return`\n    vec4 ${r}(int row, int col) {\n      vec2 uv = packedUVfrom2D(${c}, ${u[0]}, ${u[1]}, row, col);\n      return ${l.texture2D}(${s}, uv);\n    }\n  `}(e,t);case 3:return function(e,t){const n=e.shapeInfo.logicalShape,s=e.name,r="get"+s.charAt(0).toUpperCase()+s.slice(1),a=e.shapeInfo.texShape,i=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];if(1===n[0]){const s=[1,2],a=["b","row","col"];return`\n        ${X_(aF(e,n.slice(1)),t)}\n        vec4 ${r}(int b, int row, int col) {\n          return ${r}(${iF(a,s)});\n        }\n      `}const o=B_();if(t)return`\n    vec4 ${r}(int b, int row, int col) {\n      ivec2 packedTexShape = ivec2(ceil(float(${s}TexShape[0]) / 2.0), ceil(float(${s}TexShape[1]) / 2.0));\n      int valuesPerRow = int(ceil(float(${s}Shape[2]) / 2.0));\n      int texelsInBatch = valuesPerRow * int(ceil(float(${s}Shape[1]) / 2.0));\n      vec2 uv = packedUVfrom3D(\n        packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);\n      return ${o.texture2D}(${s}, uv);\n    }\n  `;const l=i[0],u=i[1],c=Math.ceil(n[2]/2),h=c*Math.ceil(n[1]/2);return`\n    vec4 ${r}(int b, int row, int col) {\n      vec2 uv = packedUVfrom3D(\n        ${l}, ${u}, ${h}, ${c}, b, row, col);\n      return ${o.texture2D}(${s}, uv);\n    }\n  `}(e,t);default:return function(e,t){const n=e.name,s="get"+n.charAt(0).toUpperCase()+n.slice(1),r=B_();if(t)return`\n    vec4 ${s}(int b2, int b, int row, int col) {\n      int valuesPerRow = int(ceil(float(${n}Shape[3]) / 2.0));\n      int texelsInBatch = valuesPerRow * int(ceil(float(${n}Shape[2]) / 2.0));\n      int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);\n      texelsInBatch *= ${n}Shape[1];\n      index = b2 * texelsInBatch + index;\n      ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));\n      int texR = index / packedTexShape[1];\n      int texC = index - texR * packedTexShape[1];\n      vec2 uv = (vec2(texC, texR) + halfCR) / vec2(packedTexShape[1], packedTexShape[0]); return ${r.texture2D}(${n}, uv);\n    }\n  `;const a=e.shapeInfo.logicalShape,i=a.length,o=e.shapeInfo.texShape,l=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],u=l[0],c=l[1],h=Math.ceil(a[i-1]/2);let p=h*Math.ceil(a[i-2]/2),d="int b, int row, int col",f=`b * ${p} + (row / 2) * ${h} + (col / 2)`;for(let e=2;e<i-1;e++)d=`int b${e}, `+d,p*=a[i-e-1],f=`b${e} * ${p} + `+f;return`\n    vec4 ${s}(${d}) {\n      int index = ${f};\n      int texR = index / ${c};\n      int texC = index - texR * ${c};\n      vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${c}, ${u});\n      return ${r.texture2D}(${n}, uv);\n    }\n  `}(e,t)}}const Y_="\nvec2 uvFromFlat(int texNumR, int texNumC, int index) {\n  int texR = index / texNumC;\n  int texC = index - texR * texNumC;\n  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\nvec2 packedUVfrom1D(int texNumR, int texNumC, int index) {\n  int texelIndex = index / 2;\n  int texR = texelIndex / texNumC;\n  int texC = texelIndex - texR * texNumC;\n  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",Z_="\nvec2 packedUVfrom2D(int texelsInLogicalRow, int texNumR,\n  int texNumC, int row, int col) {\n  int texelIndex = (row / 2) * texelsInLogicalRow + (col / 2);\n  int texR = texelIndex / texNumC;\n  int texC = texelIndex - texR * texNumC;\n  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",J_="\nvec2 packedUVfrom3D(int texNumR, int texNumC,\n    int texelsInBatch, int texelsInLogicalRow, int b,\n    int row, int col) {\n  int index = b * texelsInBatch + (row / 2) * texelsInLogicalRow + (col / 2);\n  int texR = index / texNumC;\n  int texC = index - texR * texNumC;\n  return (vec2(texC, texR) + halfCR) / vec2(texNumC, texNumR);\n}\n",Q_="\n  float getChannel(vec4 frag, vec2 innerDims) {\n    vec2 modCoord = mod(innerDims, 2.);\n    return modCoord.x == 0. ?\n      (modCoord.y == 0. ? frag.r : frag.g) :\n      (modCoord.y == 0. ? frag.b : frag.a);\n  }\n  float getChannel(vec4 frag, int dim) {\n    float modCoord = mod(float(dim), 2.);\n    return modCoord == 0. ? frag.r : frag.g;\n  }\n";function eF(){return"\n    int getOutputCoords() {\n      return 0;\n    }\n  "}function tF(e){return`offset${e}`}function nF(e){const t=e.name,n=d(e.shapeInfo.logicalShape);return n<2?`return ${t};`:`\n    for (int i = 0; i < ${n}; i++) {\n      if (i == index) {\n        return ${t}[i];\n      }\n    }\n  `}function sF(e){if(e<=1)return"int";if(2===e)return"ivec2";if(3===e)return"ivec3";if(4===e)return"ivec4";if(5===e)return"ivec5";if(6===e)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)}function rF(e,t,n){const{newShape:s,keptDims:r}=k(t),a=t.length,i=e&&3===a&&1===t[0],o=i?t.slice(1):s,l=!e&&a>1&&!m(t,n)&&s.length<a||i;return{useSqueezeShape:l,uniformShape:l?o:t,keptDims:r}}function aF(e,t){const n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function iF(e,t){return t.map((t=>e[t])).join(", ")}function oF(e,t,n){const s=[],r=[];let a,i,o,l=null,u=null;u=e.getUniformLocation(n,"NAN",!1),1===Y().getNumber("WEBGL_VERSION")&&(l=e.getUniformLocation(n,"INFINITY",!1));const c=!1;for(const r of t.variableNames){const a={name:r,uniform:e.getUniformLocation(n,r,c),offset:e.getUniformLocation(n,`offset${r}`,c)};t.enableShapeUniforms&&(a.shape=e.getUniformLocation(n,`${r}Shape`,c),a.texShape=e.getUniformLocation(n,`${r}TexShape`,c)),s.push(a)}if(t.enableShapeUniforms&&(a=e.getUniformLocation(n,"outShape",c),o=e.getUniformLocation(n,"outShapeStrides",c),i=e.getUniformLocation(n,"outTexShape",c)),t.customUniforms)for(const s of t.customUniforms)r.push(e.getUniformLocation(n,s.name,c));return{variablesLocations:s,customUniformLocations:r,infLoc:l,nanLoc:u,outShapeLocation:a,outShapeStridesLocation:o,outTexShapeLocation:i}}function lF(e,t){if(e.length!==t.length)throw Error(`Binary was compiled with ${e.length} inputs, but was executed with ${t.length} inputs`);e.forEach(((e,n)=>{const s=e.logicalShape,r=t[n],a=r.shape;if(!m(s,a))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${s} and ${a} must match`);if(e.isUniform&&r.isUniform)return;const i=e.texShape,o=r.isUniform?null:r.texData.texShape;if(!m(i,o))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${i} and ${o} must match`)}))}function uF(e){return Y().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&e<=4}class cF{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=BR.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=B_();this.outputShape=e,this.enableShapeUniforms=uF(this.outputShape.length),this.userCode=`\n      ivec3 outCoordsFromFlatIndex(int index) {\n        ${this.enableShapeUniforms?V_(["r","c","d"],e):W_(["r","c","d"],e)}\n        return ivec3(r, c, d);\n      }\n\n      void main() {\n        ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));\n        int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);\n\n        vec4 result = vec4(0.);\n\n        for (int i=0; i<4; i++) {\n          int flatIndex = index + i;\n          ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n          result[i] = getA(rc.x, rc.y, rc.z);\n        }\n\n        ${t.output} = result;\n      }\n    `}}class hF{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=BR.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=B_();this.outputShape=e,this.enableShapeUniforms=uF(this.outputShape.length),this.userCode=`\n      ivec3 outCoordsFromFlatIndex(int index) {\n        ${this.enableShapeUniforms?V_(["r","c","d"],e):W_(["r","c","d"],e)}\n        return ivec3(r, c, d);\n      }\n\n      void main() {\n        ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));\n        int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);\n\n        vec4 result = vec4(0.);\n\n        for (int i=0; i<4; i++) {\n          int flatIndex = index + i;\n          ivec3 rc = outCoordsFromFlatIndex(flatIndex);\n          result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));\n        }\n\n        ${t.output} = result;\n      }\n    `}}class pF{constructor(e){this.variableNames=["A"],this.outTexUsage=WR.DOWNLOAD;const t=B_();this.outputShape=e,this.userCode=`\n      ${H_}\n\n      void main() {\n        float x = getAAtOutCoords();\n        ${t.output} = encode_float(x);\n      }\n    `}}class dF{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=WR.DOWNLOAD;const t=B_();this.outputShape=e,this.userCode=`\n      ${H_}\n\n      void main() {\n        ivec3 coords = getOutputCoords();\n        float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));\n        ${t.output} = encode_float(x);\n      }\n    `}}const fF={R:0,G:1,B:2,A:3};class mF{constructor(e,t=!1,n="RGBA"){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];const s=B_();this.outputShape=e,this.enableShapeUniforms=uF(this.outputShape.length);let r="result";t&&(r="floor(result * 255. + 0.5)");let a="";for(let e=0;e<n.length;e++){const t=n[e];a+=`\n          if(offset == ${e}) {\n            result = values[${fF[t]}];\n          }`}this.userCode=`\n      ${this.enableShapeUniforms?"\n  int getFlatIndex(ivec3 coords) {\n    return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;\n  }\n":G_(e)}\n\n      void main() {\n        ivec3 coords = getOutputCoords();\n        int flatIndex = getFlatIndex(coords);\n        float result = 0.;\n        int offset = imod(flatIndex, ${n.length});\n\n        flatIndex = idiv(flatIndex, ${n.length}, 1.);\n\n        int r = flatIndex / texShape[1];\n        if (r < texShape[0]) {\n          int c = imod(flatIndex, texShape[1]);\n          vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);\n          vec4 values = ${s.texture2D}(A, uv);\n          ${a}\n        }\n        ${s.output} = vec4(${r}, 0., 0., 0.);\n      }\n    `}}class gF{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];const n=B_();this.outputShape=e,this.enableShapeUniforms=uF(this.outputShape.length);let s="",r="result";t&&(r="floor(result * 255. + 0.5)");for(let t=0;t<=1;t++)for(let r=0;r<=1;r++){const a=2*t+r;s+=`\n          localCoords = coords;\n          if(localCoords[2] + ${r} < ${this.enableShapeUniforms?"outShape[2]":`${e[2]}`}) {\n          localCoords[2] += ${r};\n          if (localCoords[1] + ${t} < ${this.enableShapeUniforms?"outShape[1]":`${e[1]}`}) {\n            localCoords[1] += ${t};\n\n            flatIndex = getFlatIndex(localCoords);\n            offset = imod(flatIndex, 4);\n\n            flatIndex = idiv(flatIndex, 4, 1.);\n\n            int r = flatIndex / texShape[1];\n            int c = imod(flatIndex, texShape[1]);\n            vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);\n            values = ${n.texture2D}(A, uv);\n\n            if (offset == 0) {\n              result[${a}] = values[0];\n            } else if (offset == 1) {\n              result[${a}] = values[1];\n            } else if (offset == 2) {\n              result[${a}] = values[2];\n            } else {\n              result[${a}] = values[3];\n            }\n          }\n        }\n        `}this.userCode=`\n        ${this.enableShapeUniforms?"\n  int getFlatIndex(ivec3 coords) {\n    return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;\n  }\n":G_(e)}\n\n        void main() {\n          ivec3 coords = getOutputCoords();\n\n          vec4 result = vec4(0.);\n          int flatIndex, r, c, offset;\n          ivec3 localCoords;\n          vec2 uv;\n          vec4 values;\n\n          ${s}\n\n          ${n.output} = ${r};\n        }\n    `}}function yF(e){const t=B_();return ZR(e,`${t.version}\n    precision highp float;\n    ${t.attribute} vec3 clipSpacePos;\n    ${t.attribute} vec2 uv;\n    ${t.varyingVs} vec2 resultUV;\n\n    void main() {\n      gl_Position = vec4(clipSpacePos, 1);\n      resultUV = uv;\n    }`)}function bF(e){return r_(e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function xF(e){return a_(e,new Uint16Array([0,1,2,2,1,3]))}function wF(e,t,n,s,r,a){o_(t,n);const i=i_(e),o=e.TEXTURE_2D;return qR(e,(()=>e.bindTexture(o,i))),qR(e,(()=>e.texParameteri(o,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE))),qR(e,(()=>e.texParameteri(o,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE))),qR(e,(()=>e.texParameteri(o,e.TEXTURE_MIN_FILTER,e.NEAREST))),qR(e,(()=>e.texParameteri(o,e.TEXTURE_MAG_FILTER,e.NEAREST))),1===Y().getNumber("WEBGL_VERSION")?qR(e,(()=>e.texImage2D(o,0,s,t,n,0,r,a,null))):qR(e,(()=>e.texStorage2D(o,1,s,t,n))),qR(e,(()=>e.bindTexture(e.TEXTURE_2D,null))),{texture:i,texShape:[n,t]}}function vF(e){return e.internalFormatFloat}function kF(e,t,n,s){const[r,a]=UR(t,n);return wF(e,r,a,vF(s),s.textureFormatFloat,e.FLOAT)}function NF(e){return e.internalFormatHalfFloat}function IF(e,t,n,s){const[r,a]=UR(t,n);return wF(e,r,a,NF(s),s.textureFormatFloat,s.textureTypeHalfFloat)}function SF(e){return e.downloadTextureFormat}function TF(e,t,n,s){const[r,a]=UR(t,n);return wF(e,r,a,SF(s),e.RGBA,e.UNSIGNED_BYTE)}function CF(e){return e.internalFormatPackedFloat}function $F(e,t,n,s){const[r,a]=HR(t,n);return wF(e,r,a,CF(s),e.RGBA,e.FLOAT)}function EF(e){return e.internalFormatPackedHalfFloat}function AF(e,t,n,s){const[r,a]=HR(t,n);return wF(e,r,a,EF(s),e.RGBA,s.textureTypeHalfFloat)}function RF(e,t,n){qR(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,n)));return u_(e,t,"clipSpacePos",n,3,20,0)&&u_(e,t,"uv",n,2,20,12)}function _F(e,t,n,s,r,a){let i,o,l;qR(e,(()=>e.bindTexture(e.TEXTURE_2D,t))),r instanceof Uint8Array?(i=new Uint8Array(n*s*4),o=e.UNSIGNED_BYTE,l=e.RGBA):(i=new Float32Array(n*s*4),o=e.FLOAT,l=a.internalFormatPackedFloat),i.set(r),2===Y().getNumber("WEBGL_VERSION")?qR(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,s,e.RGBA,o,i))):qR(e,(()=>e.texImage2D(e.TEXTURE_2D,0,l,n,s,0,e.RGBA,o,i))),qR(e,(()=>e.bindTexture(e.TEXTURE_2D,null)))}function FF(e,t,n){qR(e,(()=>e.bindTexture(e.TEXTURE_2D,t))),n.data instanceof Uint8Array?2===Y().getNumber("WEBGL_VERSION")?qR(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n.width,n.height,e.RGBA,e.UNSIGNED_BYTE,n.data))):qR(e,(()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data))):2===Y().getNumber("WEBGL_VERSION")?qR(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,n))):qR(e,(()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n))),qR(e,(()=>e.bindTexture(e.TEXTURE_2D,null)))}function DF(e,t,n,s){const r=e.createBuffer();qR(e,(()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,r)));const a=16*t*n;return qR(e,(()=>e.bufferData(e.PIXEL_PACK_BUFFER,a,e.STREAM_READ))),qR(e,(()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0))),qR(e,(()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null))),r}function OF(e,t,n){const s=e,r=new Float32Array(n);return s.bindBuffer(s.PIXEL_PACK_BUFFER,t),s.getBufferSubData(s.PIXEL_PACK_BUFFER,0,r),s.bindBuffer(s.PIXEL_PACK_BUFFER,null),r}function MF(e,t,n,s){const[r,a]=UR(t,n),i=new Uint8Array(t*n*4);return qR(e,(()=>e.readPixels(0,0,r,a,s.downloadTextureFormat,e.UNSIGNED_BYTE,i))),new Float32Array(i.buffer)}function LF(e,t,n,s,r,a,i,o){const l=e,u=new Float32Array(function(e,t){const[n,s]=HR(e,t);return n*s*4}(a,i));return l.bindBuffer(l.PIXEL_PACK_BUFFER,t),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,u),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),u}function zF(e,t,n){const s=new Float32Array(t*n*4);return qR(e,(()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,s))),s}var PF=Object.freeze({__proto__:null,bindVertexProgramAttributeStreams:RF,createBufferFromOutputTexture:DF,createFloat16MatrixTexture:IF,createFloat16PackedMatrixTexture:AF,createFloat32MatrixTexture:kF,createIndexBuffer:xF,createPackedMatrixTexture:$F,createUnsignedBytesMatrixTexture:TF,createVertexBuffer:bF,createVertexShader:yF,downloadByteEncodedFloatMatrixFromOutputTexture:MF,downloadFloat32MatrixFromBuffer:OF,downloadMatrixFromPackedOutputTexture:zF,downloadPackedMatrixFromBuffer:LF,getInternalFormatForFloat16MatrixTexture:NF,getInternalFormatForFloat16PackedMatrixTexture:EF,getInternalFormatForFloat32MatrixTexture:vF,getInternalFormatForPackedMatrixTexture:CF,getInternalFormatForUnsignedBytesMatrixTexture:SF,uploadDenseMatrixToTexture:_F,uploadPixelDataToTexture:FF});class BF{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.itemsToPoll=[];const t=Y().getNumber("WEBGL_VERSION");if(null!=e?(this.gl=e,zR(t,e)):this.gl=PR(t),e=this.gl,2===Y().getNumber("WEBGL_VERSION")){const t=e;this.createVertexArray=()=>qR(t,(()=>t.createVertexArray())),this.bindVertexArray=e=>qR(t,(()=>t.bindVertexArray(e))),this.deleteVertexArray=e=>qR(t,(()=>t.deleteVertexArray(e))),this.getVertexArray=()=>qR(t,(()=>t.getParameter(t.VERTEX_ARRAY_BINDING)))}else if(null!=e){const t=e.getExtension("OES_vertex_array_object");if(null==t)throw new Error("All WebGL1 implementations are expected to offer OES_vertex_array_object.");this.createVertexArray=()=>qR(e,(()=>t.createVertexArrayOES())),this.bindVertexArray=n=>qR(e,(()=>t.bindVertexArrayOES(n))),this.deleteVertexArray=n=>qR(e,(()=>t.deleteVertexArrayOES(n))),this.getVertexArray=()=>qR(e,(()=>e.getParameter(t.VERTEX_ARRAY_BINDING_OES)))}let n="WEBGL_color_buffer_float";const s="EXT_color_buffer_half_float";if(this.parallelCompilationExtension=this.gl.getExtension("KHR_parallel_shader_compile"),1===Y().getNumber("WEBGL_VERSION")){const e="OES_texture_float",t="OES_texture_half_float";if(this.textureFloatExtension=YR(this.gl,e),R_(this.gl,t))this.textureHalfFloatExtension=YR(this.gl,t);else if(Y().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(n),R_(this.gl,s))this.colorBufferHalfFloatExtension=YR(this.gl,s);else if(Y().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(n="EXT_color_buffer_float",R_(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else{if(!R_(this.gl,s))throw new Error("GL context does not support color renderable floats");this.colorBufferHalfFloatExtension=this.gl.getExtension(s)}this.vertexBuffer=bF(this.gl),this.indexBuffer=xF(this.gl),this.framebuffer=l_(this.gl),this.textureConfig=jR(this.gl,this.textureHalfFloatExtension)}get debug(){return Y().getBool("DEBUG")}dispose(){if(this.disposed)return;null!=this.program&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),null!=this.outputTexture&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture.  This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");const e=this.gl;qR(e,(()=>e.finish())),qR(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,null))),qR(e,(()=>e.deleteFramebuffer(this.framebuffer))),qR(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,null))),qR(e,(()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null))),qR(e,(()=>e.deleteBuffer(this.indexBuffer))),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),kF(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),IF(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),TF(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),FF(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,s){this.throwIfDisposed(),_F(this.gl,e,t,n,s,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),AF(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),$F(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(m_(this.gl,this.framebuffer),this.outputTexture=null),qR(this.gl,(()=>this.gl.deleteTexture(e)))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,(()=>MF(this.gl,t,n,this.textureConfig)))}downloadPackedMatrixFromBuffer(e,t,n,s,r,a){return LF(this.gl,e,0,0,0,r,a,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return OF(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);const s=DF(this.gl,t,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),s}createAndWaitForFence(){const e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,n;if(Y().getBool("WEBGL_FENCE_API_ENABLED")){const s=e,r=s.fenceSync(s.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),n=()=>{const e=s.clientWaitSync(r,0,0);return e===s.ALREADY_SIGNALED||e===s.CONDITION_SATISFIED},t=r}else Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,(()=>zF(this.gl,t,n)))}createProgram(e){this.throwIfDisposed();const t=this.gl;null==this.vertexShader&&(this.vertexShader=yF(t));const n=t_(t);qR(t,(()=>t.attachShader(n,this.vertexShader))),qR(t,(()=>t.attachShader(n,e))),n_(t,n);const s=Object.assign(n,{vao:this.createVertexArray()});return this.debug&&s_(t,s),s}buildVao(e){this.setProgram(e),this.bindVertexArray(e.vao);const t=this.gl;qR(t,(()=>t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer))),RF(t,e,this.vertexBuffer)}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),null!=e&&(qR(this.gl,(()=>this.gl.deleteProgram(e))),this.deleteVertexArray(e.vao))}setProgram(e){this.throwIfDisposed(),this.program=e,null!=this.program&&this.debug&&s_(this.gl,this.program),qR(this.gl,(()=>this.gl.useProgram(e)))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?h_(this.gl,e,t):p_(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),qR(this.gl,(()=>this.gl.getAttribLocation(e,t)))}getUniformLocationNoThrow(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)}setInputMatrixTexture(e,t,n){this.throwIfDisposed(),this.throwIfNoProgram(),d_(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();const[s,r]=HR(t,n);this.setOutputMatrixTextureDriver(e,s,r)}setOutputMatrixWriteRegion(e,t,n,s){this.setOutputMatrixWriteRegionDriver(n,e,s,t)}setOutputPackedMatrixWriteRegion(e,t,n,s){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){null!=this.program&&s_(this.gl,this.program),g_(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();const e=this.gl;if(this.debug){const e=this.getVertexArray();console.assert(e===this.program.vao,"VAO changed between setProgram and executeProgram!"),this.debugValidate()}qR(e,(()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0)))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),qR(this.gl,(()=>this.gl.finish()))}getQueryTimerExtension(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=YR(this.gl,2===Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension}getQueryTimerExtensionWebGL2(){return this.getQueryTimerExtension()}getQueryTimerExtensionWebGL1(){return this.getQueryTimerExtension()}beginQuery(){if(2===Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){const e=this.gl,t=this.getQueryTimerExtensionWebGL2(),n=e.createQuery();return e.beginQuery(t.TIME_ELAPSED_EXT,n),n}const e=this.getQueryTimerExtensionWebGL1(),t=e.createQueryEXT();return e.beginQueryEXT(e.TIME_ELAPSED_EXT,t),t}endQuery(){if(2===Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")){const e=this.gl,t=this.getQueryTimerExtensionWebGL2();return void e.endQuery(t.TIME_ELAPSED_EXT)}const e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}async waitForQueryAndGetTime(e){return await x((()=>this.disposed||this.isQueryAvailable(e,Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")))),this.getQueryTime(e,Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(0===t)return null;if(2===t){const t=this.gl;return t.getQueryParameter(e,t.QUERY_RESULT)/1e6}{const t=this.getQueryTimerExtensionWebGL1();return t.getQueryObjectEXT(e,t.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(e,t){if(0===t)return!0;if(2===t){const t=this.gl,n=this.getQueryTimerExtensionWebGL2(),s=t.getQueryParameter(e,t.QUERY_RESULT_AVAILABLE);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),s&&!this.disjoint}{const t=this.getQueryTimerExtensionWebGL1(),n=t.getQueryObjectEXT(e,t.QUERY_RESULT_AVAILABLE_EXT);return null==this.disjoint&&(this.disjoint=this.gl.getParameter(t.GPU_DISJOINT_EXT)),n&&!this.disjoint}}pollFence(e){return new Promise((t=>{this.addItemToPoll((()=>e.isFencePassed()),(()=>t()))}))}pollItems(){const e=function(e){let t=0;for(;t<e.length;++t){if(!e[t]())break}return t-1}(this.itemsToPoll.map((e=>e.isDoneFn)));for(let t=0;t<=e;++t){const{resolveFn:e}=this.itemsToPoll[t];e()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}addItemToPoll(e,t){if(this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),this.itemsToPoll.length>1)return;let n;"setTimeoutCustom"in Y().platform&&(n=Y().platform.setTimeoutCustom.bind(Y().platform)),x((()=>(this.pollItems(),0===this.itemsToPoll.length)),(()=>0),null,n)}bindTextureToFrameBuffer(e){this.throwIfDisposed(),f_(this.gl,e,this.framebuffer),this.debug&&g_(this.gl)}unbindTextureToFrameBuffer(){null!=this.outputTexture?(f_(this.gl,this.outputTexture,this.framebuffer),this.debug&&g_(this.gl)):m_(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);const n=t();return this.unbindTextureToFrameBuffer(),n}setOutputMatrixTextureDriver(e,t,n){this.throwIfDisposed();const s=this.gl;f_(s,e,this.framebuffer),this.debug&&g_(s),this.outputTexture=e,qR(s,(()=>s.viewport(0,0,t,n))),qR(s,(()=>s.scissor(0,0,t,n)))}setOutputMatrixWriteRegionDriver(e,t,n,s){this.throwIfDisposed(),qR(this.gl,(()=>this.gl.scissor(e,t,n,s)))}throwIfDisposed(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")}throwIfNoProgram(){if(null==this.program)throw new Error("No GPU program is currently set.")}}const{addImpl:WF,bincountImpl:VF,bincountReduceImpl:UF,bitwiseAndImpl:GF,castImpl:HF,ceilImpl:jF,concatImpl:qF,equalImpl:KF,expImpl:XF,expm1Impl:YF,floorImpl:ZF,gatherNdImpl:JF,gatherV2Impl:QF,greaterImpl:eD,greaterEqualImpl:tD,lessImpl:nD,lessEqualImpl:sD,linSpaceImpl:rD,logImpl:aD,maxImpl:iD,maximumImpl:oD,minimumImpl:lD,multiplyImpl:uD,negImpl:cD,notEqualImpl:hD,prodImpl:pD,raggedGatherImpl:dD,raggedRangeImpl:fD,raggedTensorToTensorImpl:mD,rangeImpl:gD,rsqrtImpl:yD,scatterImpl:bD,sigmoidImpl:xD,simpleAbsImpl:wD,sliceImpl:vD,sparseFillEmptyRowsImpl:kD,sparseReshapeImpl:ND,sparseSegmentReductionImpl:ID,sqrtImpl:SD,staticRegexReplaceImpl:TD,stridedSliceImpl:CD,stringNGramsImpl:$D,stringSplitImpl:ED,stringToHashBucketFastImpl:AD,subImpl:RD,tileImpl:_D,topKImpl:FD,transposeImpl:DD,uniqueImpl:OD}=LC;function MD(e,t){return["x","y","z","w","u","v"].slice(0,t).map((t=>`${e}.${t}`))}function LD(e,t){return 1===t?[e]:MD(e,t)}class zD{constructor(e){if(this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.enableShapeUniforms=uF(this.outputShape.length),0===this.rank)this.userCode="\n        void main() {\n          setOutput(vec4(getA(), 0., 0., 0.));\n        }\n      ";else{const e=LD("rc",this.rank),t=sF(this.rank),n=this.getOutOfBoundsCondition(e),s=this.getSetup(e),r=this.getOutput(e);this.userCode=`\n        void main() {\n          ${t} rc = getOutputCoords();\n\n          if(${n}) {\n            setOutput(vec4(0));\n          } else {\n            ${s}\n\n            setOutput(vec4(${r}));\n          }\n        }\n      `}}getSourceCoordsArr(e){const t=[];for(let n=0;n<=1;n++)for(let s=0;s<=1;s++){let r=`${0===n?"r":"rp1"}, ${0===s?"c":"cp1"}`;for(let t=2;t<this.rank;t++)r=`${e[e.length-1-t]},`+r;t.push(r)}return t}getOutOfBoundsCondition(e){if(1===this.rank)return`rc > ${this.enableShapeUniforms?"outShape":this.outputShape[0]}`;let t="";for(let n=this.rank-2;n<this.rank;n++)t+=`${e[n]} >= ${this.enableShapeUniforms?`outShape[${n}]`:this.outputShape[n]}`,n<this.rank-1&&(t+="||");return t}getSetup(e){if(1===this.rank)return"";const t=e.slice(-2),n=this.enableShapeUniforms?`outShape[${this.rank} - 1]`:this.outputShape[this.rank-1],s=this.enableShapeUniforms?`outShape[${this.rank} - 2]`:this.outputShape[this.rank-2];return`\n      int r = ${t[0]};\n      int c = ${t[1]};\n      int rp1 = r + 1;\n      int cp1 = c + 1;\n\n      bool cEdge = cp1 >= ${n};\n      bool rEdge = rp1 >= ${s};\n    `}getOutput(e){const t=this.getSourceCoordsArr(e);if(1===this.rank){return`getA(rc), (rc + 1 >= ${this.enableShapeUniforms?"outShape":this.outputShape[0]} ? 0. : getA(rc + 1)), 0, 0`}return`getA(${t[0]}),\n            cEdge ? 0. : getA(${t[1]}),\n            rEdge ? 0. : getA(${t[2]}),\n            rEdge || cEdge ? 0. : getA(${t[3]})`}}class PD{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=uF(this.outputShape.length);let n="";for(let e=0;e<4;e++){let t="thisRC = rc;";e%2==1&&(t+="thisRC.z += 1;"),e>1&&(t+="thisRC.y += 1;"),n+=`\n        ${t}\n        ${e>0?"if(thisRC.y < rows && thisRC.z < cols){":""}\n          int flatIndex = getFlatIndex(thisRC);\n\n          ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);\n          vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));\n\n          result[${e}] =\n            getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);\n        ${e>0?"}":""}\n      `}var s,r;this.userCode=`\n      ${s=t,r=this.enableShapeUniforms,`\n    ivec3 inputCoordsFromReshapedOutCoords(int index) {\n      ${r?U_(["r","c","d"],"inputShape"):W_(["r","c","d"],s)}\n      return ivec3(r, c, d);\n    }\n  `}\n      ${this.enableShapeUniforms?"\n  int getFlatIndex(ivec3 coords) {\n    return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;\n  }\n":G_(e)}\n\n      void main() {\n        ivec3 rc = getOutputCoords();\n\n        vec4 result = vec4(0.);\n\n        ivec3 thisRC;\n        int rows = ${this.enableShapeUniforms?"outShape[1]":e[1]};\n        int cols = ${this.enableShapeUniforms?"outShape[2]":e[2]};\n\n        ${n}\n\n        setOutput(result);\n      }\n    `}}class BD{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.usedTextures={},this.logEnabled=!1}acquireTexture(e,t,n){const s=VD(t,n),r=UD(e,s,n);r in this.freeTextures||(this.freeTextures[r]=[]),r in this.usedTextures||(this.usedTextures[r]=[]);const a=WD(e,s,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[r].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=a,this.log();const e=this.freeTextures[r].pop();return this.usedTextures[r].push(e),e}let i;return s===VR.PACKED_2X2_FLOAT32?i=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):s===VR.PACKED_2X2_FLOAT16?i=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):s===VR.UNPACKED_FLOAT32?i=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):s===VR.UNPACKED_FLOAT16?i=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):s===VR.PACKED_4X1_UNSIGNED_BYTE&&(i=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[r].push(i),this.numUsedTextures++,this._numBytesAllocated+=a,this.log(),i}releaseTexture(e,t,n,s){if(null==this.freeTextures)return;const r=VD(n,s),a=UD(t,r,s);a in this.freeTextures||(this.freeTextures[a]=[]);const i=WD(t,r,this.gpgpu.gl,this.gpgpu.textureConfig,s),o=Y().getNumber("WEBGL_DELETE_TEXTURE_THRESHOLD");-1!==o&&this._numBytesAllocated>o?(this.gpgpu.deleteMatrixTexture(e.texture),this._numBytesAllocated-=i):(this.freeTextures[a].push(e),this.numFreeTextures++,this._numBytesFree+=i),this.numUsedTextures--;const l=this.usedTextures[a],u=l&&l.indexOf(e);if(null==u||u<0)throw new Error("Cannot release a texture that was never provided by this texture manager");l[u]=l[l.length-1],l.pop(),this.log()}log(){if(!this.logEnabled)return;const e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);const t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(null!=this.freeTextures){for(const e in this.freeTextures)this.freeTextures[e].forEach((e=>{this.gpgpu.deleteMatrixTexture(e.texture)}));for(const e in this.usedTextures)this.usedTextures[e].forEach((e=>{this.gpgpu.deleteMatrixTexture(e.texture)}));this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}}function WD(e,t,n,s,r){const a=function(e,t){switch(e){case VR.PACKED_2X2_FLOAT32:return CF(t);case VR.PACKED_2X2_FLOAT16:return EF(t);case VR.UNPACKED_FLOAT32:return vF(t);case VR.UNPACKED_FLOAT16:return NF(t);case VR.PACKED_4X1_UNSIGNED_BYTE:return SF(t);default:throw new Error(`Unknown physical texture type ${e}`)}}(t,s);let i;if(r){const[t,n]=HR(e[0],e[1]);i=t*n}else{const[t,n]=UR(e[0],e[1]);i=t*n}const o=function(e,t){const n=e;if(t===n.R32F)return 4;if(t===n.R16F)return 2;if(t===n.RGBA32F)return 16;if(t===e.RGBA)return 16;if(t===n.RGBA16F)return 8;if(t===n.RGBA8)return 4;throw new Error(`Unknown internal format ${t}`)}(n,a);return i*o}function VD(e,t){if(e===WR.UPLOAD)return VR.PACKED_2X2_FLOAT32;if(e===WR.RENDER||null==e)return function(e){return Y().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?VR.PACKED_2X2_FLOAT32:VR.UNPACKED_FLOAT32:e?VR.PACKED_2X2_FLOAT16:VR.UNPACKED_FLOAT16}(t);if(e===WR.DOWNLOAD||e===WR.PIXELS)return VR.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function UD(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}class GD{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=uF(this.outputShape.length),this.userCode=`\n      float unaryOperation(float x) {\n        ${t}\n      }\n\n      void main() {\n        float x = getAAtOutCoords();\n        float y = unaryOperation(x);\n\n        setOutput(y);\n      }\n    `}}const HD="return abs(x);";const jD="return x;";class qD{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=uF(this.outputShape.length),this.userCode=`\n      vec4 unaryOperation(vec4 x) {\n        ${t}\n      }\n\n      void main() {\n        vec4 x = getAAtOutCoords();\n        vec4 y = unaryOperation(x);\n\n        setOutput(y);\n      }\n    `}}class KD{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=uF(this.outputShape.length);const t=e.length,n=LD("rc",t),s=sF(t),r=function(e,t){if(1===e)return"rc";let n="";for(let s=0;s<e;s++)n+=t[s],s<e-1&&(n+=",");return n}(t,n),a=n.slice(-2),i=t<=1?"rc":`vec2(${a.join(",")})`;this.userCode=`\n      void main() {\n        ${s} rc = getOutputCoords();\n        vec4 packedInput = getA(${r});\n\n        setOutput(getChannel(packedInput, ${i}));\n      }\n    `}}const XD=bh,YD={};const ZD=Y().getNumber("CPU_HANDOFF_SIZE_THRESHOLD");class JD extends s{nextDataId(){return JD.nextDataId++}constructor(e){if(super(),this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.lastGlFlushTime=0,this.warnedAboutMemory=!1,this.pendingDeletes=0,this.disposed=!1,!Y().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");let t;if(null!=e){if(e instanceof BF)t=e;else{const n=PR(Y().getNumber("WEBGL_VERSION"),e);t=new BF(n)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{const e=PR(Y().getNumber("WEBGL_VERSION"));t=new BF(e),this.binaryCache=((s=Y().getNumber("WEBGL_VERSION"))in YD||(YD[s]={}),YD[s]),this.gpgpuCreatedLocally=!0}var s;this.gpgpu=t,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new BD(this.gpgpu),this.numMBBeforeWarning=null==Y().global.screen?1024:Y().global.screen.height*Y().global.screen.width*window.devicePixelRatio*600/1024/1024,this.texData=new n(this,va())}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}writeTexture(e,t,n,s,r,a){const i=this.makeTensorInfo(t,n),o=this.texData.get(i.dataId);o.isPacked=!1,o.texture={texture:e,texShape:[s,r]},o.texShape=[s,r];const l=k_(t),u=new mF(l,!1,a),c=this.runWebGLProgram(u,[i],n,[[s,r]]);return c.shape=t,o.texture=null,this.disposeIntermediateTensorInfo(i),c.dataId}write(e,t,n){if((Y().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||Y().getBool("DEBUG"))&&this.checkNumericalProblems(e),"complex64"===n&&null!=e)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");const s={id:this.nextDataId()};return this.texData.set(s,{shape:t,dtype:n,values:e,usage:WR.UPLOAD,refCount:1}),s}refCount(e){if(this.texData.has(e)){return this.texData.get(e).refCount}return 0}incRef(e){this.texData.get(e).refCount++}decRef(e){if(this.texData.has(e)){this.texData.get(e).refCount--}}move(e,t,n,s,r){if(Y().getBool("DEBUG")&&this.checkNumericalProblems(t),"complex64"===s)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:n,dtype:s,values:t,usage:WR.UPLOAD,refCount:r})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}readSync(e){const t=this.texData.get(e),{values:n,dtype:s,complexTensorInfos:r,slice:a,shape:i,isPacked:o}=t;if(null!=a){let t;t=o?new qD(i,jD):new GD(i,jD);const n=this.runWebGLProgram(t,[{dataId:e,shape:i,dtype:s}],s),r=this.readSync(n.dataId);return this.disposeIntermediateTensorInfo(n),r}if(null!=n)return this.convertAndCacheOnCPU(e);if("string"===s)return n;const l=null!=this.activeTimers;let u,c;if(l&&(u=dr()),"complex64"===s){c=If(this.readSync(r.real.dataId),this.readSync(r.imag.dataId))}else c=this.getValuesFromTexture(e);return l&&(this.downloadWaitMs+=dr()-u),this.convertAndCacheOnCPU(e,c)}async read(e){if(this.pendingRead.has(e)){const t=this.pendingRead.get(e);return new Promise((e=>t.push(e)))}const t=this.texData.get(e),{values:n,shape:s,slice:r,dtype:a,complexTensorInfos:i,isPacked:o}=t;if(null!=r){let t;t=o?new qD(s,jD):new GD(s,jD);const n=this.runWebGLProgram(t,[{dataId:e,shape:s,dtype:a}],a),r=this.read(n.dataId);return this.disposeIntermediateTensorInfo(n),r}if(null!=n)return this.convertAndCacheOnCPU(e);if(Y().getBool("DEBUG")&&!Y().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===Y().getNumber("WEBGL_VERSION"))throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let l,u,c=null;if("complex64"!==a&&Y().get("WEBGL_BUFFER_SUPPORTED")){l=this.decode(e);const t=this.texData.get(l.dataId);c=this.gpgpu.createBufferFromTexture(t.texture.texture,...GR(s))}if(this.pendingRead.set(e,[]),"complex64"!==a&&await this.gpgpu.createAndWaitForFence(),"complex64"===a){const e=await Promise.all([this.read(i.real.dataId),this.read(i.imag.dataId)]);u=If(e[0],e[1])}else if(null==c)u=this.getValuesFromTexture(e);else{const e=d(s);u=this.gpgpu.downloadFloat32MatrixFromBuffer(c,e)}if(null!=l&&this.disposeIntermediateTensorInfo(l),null!=c){const e=this.gpgpu.gl;qR(e,(()=>e.deleteBuffer(c)))}const h=this.convertAndCacheOnCPU(e,u),p=this.pendingRead.get(e);return this.pendingRead.delete(e),p.forEach((e=>e(h))),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&va().removeDataId(e,this),this.pendingDeletes--),h}readToGPU(e,t={}){const n=this.texData.get(e),{values:s,shape:r,slice:a,dtype:i,isPacked:o,texture:l}=n;if("complex64"===i)throw new Error("Does not support reading texture for complex64 dtype.");if(null!=a){let n;n=o?new qD(r,jD):new GD(r,jD);const s=this.runWebGLProgram(n,[{dataId:e,shape:r,dtype:i}],i),a=this.readToGPU(s,t);return this.disposeIntermediateTensorInfo(s),a}if(null==l)throw null!=s?new Error("Data is not on GPU but on CPU."):new Error("There is no data on GPU or CPU.");const u=this.decode(e,t.customTexShape),c=va().makeTensorFromTensorInfo(u),h=this.texData.get(u.dataId);return Object.assign({tensorRef:c},h.texture)}bufferSync(e){const t=this.readSync(e.dataId);if("string"===e.dtype)try{const n=t.map((e=>gr(e)));return Si(e.shape,e.dtype,n)}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return Si(e.shape,e.dtype,t)}checkNumericalProblems(e){if(null!=e)for(let t=0;t<e.length;t++){const n=e[t];if(!KR(n)){if(Y().getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))throw Error(`The value ${n} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`);throw Error(`The value ${n} cannot be represented on this device.`)}}}getValuesFromTexture(e){const{shape:t,dtype:n,isPacked:s}=this.texData.get(e),r=d(t);if(Y().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){const n=this.decode(e),s=this.texData.get(n.dataId),a=this.gpgpu.downloadMatrixFromPackedTexture(s.texture.texture,...GR(t)).subarray(0,r);return this.disposeIntermediateTensorInfo(n),a}const a=Y().getBool("WEBGL_PACK")&&!0===s,i=a?k_(t):t,o=a?new dF(i):new pF(i),l=this.runWebGLProgram(o,[{shape:i,dtype:n,dataId:e}],"float32"),u=this.texData.get(l.dataId),c=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(u.texture.texture,u.texShape[0],u.texShape[1]).subarray(0,r);return this.disposeIntermediateTensorInfo(l),c}timerAvailable(){return Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0}time(e){const t=this.activeTimers,n=[];let s=!1;null==this.programTimersStack?(this.programTimersStack=n,s=!0):this.activeTimers.push(n),this.activeTimers=n,e();const r=br(this.activeTimers.map((e=>e.query))).filter((e=>null!=e)),a=br(this.activeTimers.map((e=>e.name))).filter((e=>null!=e));this.activeTimers=t,s&&(this.programTimersStack=null);const i={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};return(async()=>{if(Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){const e=await Promise.all(r);i.kernelMs=u(e),i.getExtraProfileInfo=()=>e.map(((e,t)=>({name:a[t],ms:e}))).map((e=>`${e.name}: ${e.ms}`)).join(", ")}else i.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,i})()}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:dr(),endMs:null}}endTimer(e){return Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=dr(),e)}async getQueryTime(e){if(Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(e);const t=e;return t.endMs-t.startMs}disposeData(e,t=!1){if(this.pendingDisposal.has(e))return!1;if(!this.texData.has(e))return!0;if(t?this.texData.get(e).refCount=0:this.texData.get(e).refCount--,!t&&this.texData.get(e).refCount>0)return!1;if(this.pendingRead.has(e))return this.pendingDisposal.add(e),this.pendingDeletes++,!1;this.releaseGPUData(e);const{complexTensorInfos:n}=this.texData.get(e);return null!=n&&(this.disposeData(n.real.dataId,t),this.disposeData(n.imag.dataId,t)),this.texData.delete(e),!0}releaseGPUData(e){const{texture:t,dtype:n,texShape:s,usage:r,isPacked:a,slice:i}=this.texData.get(e),o=i&&i.origDataId||e,l=this.dataRefCount.get(o);l>1?this.dataRefCount.set(o,l-1):(this.dataRefCount.delete(o),null!=t&&(this.numBytesInGPU-=this.computeBytes(s,n),this.textureManager.releaseTexture(t,s,r,a)));const u=this.texData.get(e);u.texture=null,u.texShape=null,u.isPacked=!1,u.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture.texture}getDataInfo(e){return this.texData.get(e)}shouldExecuteOnCPU(e,t=ZD){return Y().getBool("WEBGL_CPU_FORWARD")&&e.every((e=>null==this.texData.get(e.dataId).texture&&d(e.shape)<t))}getGPGPUContext(){return this.gpgpu}where(e){fs("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");const t=e.dataSync();return XD(e.shape,t)}packedUnaryOp(e,t,n){const s=new qD(e.shape,t),r=this.compileAndRun(s,[e],n);return va().makeTensorFromTensorInfo(r)}abs(e){if(this.shouldExecuteOnCPU([e])&&"complex64"!==e.dtype){const t=wD(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,t)}if(Y().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,HD,e.dtype);const t=new GD(e.shape,HD),n=this.compileAndRun(t,[e]);return va().makeTensorFromTensorInfo(n)}makeTensorInfo(e,t,n){let s;if("string"===t&&null!=n&&n.length>0&&A(n[0])){const r=n.map((e=>mr(e)));s=this.write(r,e,t)}else s=this.write(n,e,t);return this.texData.get(s).usage=null,{dataId:s,shape:e,dtype:t}}makeOutput(e,t,n){return va().makeTensorFromTensorInfo(this.makeTensorInfo(e,t,n),this)}unpackTensor(e){const t=new KD(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){const t=new zD(e.shape);return this.runWebGLProgram(t,[e],e.dtype,null,!0)}packedReshape(e,t){const n=[w_(e.shape),...v_(e.shape)],s={dtype:e.dtype,shape:n,dataId:e.dataId},r=[w_(t),...v_(t)],a=new PD(r,n),i=[n],o=this.runWebGLProgram(a,[s],e.dtype,i,!0);return{dataId:o.dataId,shape:t,dtype:o.dtype}}decode(e,t){const n=this.texData.get(e),{isPacked:s,shape:r,dtype:a}=n;if(null!=t){c(d(r)<=t[0]*t[1]*4,(()=>"customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data."))}const i=k_(r);let o;o=s?new hF(i):new cF(i);const l=[null!=t?t:GR(i)];return{dtype:a,shape:r,dataId:this.runWebGLProgram(o,[{shape:i,dtype:a,dataId:e}],a,l,!0,t).dataId}}runWebGLProgram(e,t,n,s,r=!1,a){const i=this.makeTensorInfo(e.outputShape,n),o=this.texData.get(i.dataId);if(e.packedOutput&&(o.isPacked=!0),e.outPackingScheme===BR.DENSE){const t=null!=a?a:GR(e.outputShape);o.texShape=t.map((e=>2*e))}if(null!=e.outTexUsage&&(o.usage=e.outTexUsage),0===d(i.shape))return o.values=N(i.dtype,0),i;const l=[],u=t.map((t=>{if("complex64"===t.dtype)throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let n=this.texData.get(t.dataId);if(null==n.texture){if(!e.packedInputs&&d(t.shape)<=Y().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:t.shape,texData:null,isUniform:!0,uniformValues:n.values};e.packedInputs&&(n.isPacked=!0,n.shape=t.shape)}if(this.uploadToGPU(t.dataId),!!n.isPacked!=!!e.packedInputs)t=n.isPacked?this.unpackTensor(t):this.packTensor(t),l.push(t),n=this.texData.get(t.dataId);else if(n.isPacked&&!S_(n.shape,t.shape)){const e=t,s=t.shape;t.shape=n.shape,t=this.packedReshape(t,s),l.push(t),n=this.texData.get(t.dataId),e.shape=s}return{shape:t.shape,texData:n,isUniform:!1}}));this.uploadToGPU(i.dataId);const c={shape:i.shape,texData:o,isUniform:!1},h=function(e,t,n){let s="";t.concat(n).forEach((t=>{const r=null!=t.texData&&null!=t.texData.slice&&t.texData.slice.flatOffset>0;if(e.enableShapeUniforms&&!t.isUniform){const a=t.texData.texShape,{useSqueezeShape:i,uniformShape:o,keptDims:l}=rF(e.packedInputs,t.shape,a);let u="",c="",h="";if(1===o.length&&e.packedInputs){const e=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];u=`${e[0]>1}_${e[1]>1}`}else if(2!==o.length||e.packedInputs){if(o.length>2&&!e.packedInputs){const e=M(o);h=`${e[0]===a[1]}_${e[e.length-1]===a[1]}`}}else c=`${o[0]>1}_${o[1]>1}`;const p=t.shape.length,f=2===o.length&&m(t.shape,a),g=1===d(t.shape),y=Xo(t.shape,n.shape),b=!e.packedInputs&&p===n.shape.length&&m(a,n.texData.texShape),x=e.packedInputs||o.length>2?"":`${a[0]>1}_${a[1]>1}`;s+=`${p}_${b}_${i?l:""}_${o.length}_${g}_${y}_${f}_${u}_${c}_${h}_${x}_${r}`}else{const e=t.isUniform?"uniform":t.texData.texShape;s+=`${t.shape}_${e}_${r}`}}));const r=e.userCode;let a=e.constructor.name;return a+="_"+s+"_"+r+`${Y().getNumber("WEBGL_VERSION")}`,a}(e,u,c),p=this.getAndSaveBinary(h,(()=>function(e,t,n,s){const r=n.map(((e,n)=>{const s={logicalShape:e.shape,texShape:e.isUniform?null:e.texData.texShape,isUniform:e.isUniform,isPacked:!e.isUniform&&e.texData.isPacked,flatOffset:null};return null!=e.texData&&null!=e.texData.slice&&e.texData.slice.flatOffset>0&&(s.flatOffset=e.texData.slice.flatOffset),{name:t.variableNames[n],shapeInfo:s}})),a=r.map((e=>e.shapeInfo)),i={logicalShape:s.shape,texShape:s.texData.texShape,isUniform:!1,isPacked:s.texData.isPacked,flatOffset:null},o=q_(r,i,t),l=JR(e.gl,o),u=e.createProgram(l);return Y().get("ENGINE_COMPILE_ONLY")?{program:t,fragmentShader:l,source:o,webGLProgram:u,inShapeInfos:a,outShapeInfo:i,variablesLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}:(e.buildVao(u),Object.assign({program:t,fragmentShader:l,source:o,webGLProgram:u,inShapeInfos:a,outShapeInfo:i},oF(e,t,u)))}(this.gpgpu,e,u,c))),f=null!=this.activeTimers;let g;f&&(g=this.startTimer()),Y().get("ENGINE_COMPILE_ONLY")||function(e,t,n,s,r){t.program.enableShapeUniforms||(lF(t.inShapeInfos,n),lF([t.outShapeInfo],[s]));const a=s.texData.texture,i=s.texData.texShape;s.texData.isPacked?e.setOutputPackedMatrixTexture(a.texture,i[0],i[1]):e.setOutputMatrixTexture(a.texture,i[0],i[1]),e.setProgram(t.webGLProgram),e.bindVertexArray(t.webGLProgram.vao),1===Y().getNumber("WEBGL_VERSION")&&null!==t.infLoc&&e.gl.uniform1f(t.infLoc,1/0),null!==t.nanLoc&&e.gl.uniform1f(t.nanLoc,NaN);for(let s=0;s<n.length;++s){const r=n[s],{uniform:a,offset:i,shape:o,texShape:l}=t.variablesLocations[s];if(o){const{uniformShape:n}=rF(t.program.packedInputs,r.shape,r.texData.texShape);switch(n.length){case 1:e.gl.uniform1iv(o,new Int32Array(n));break;case 2:e.gl.uniform2iv(o,new Int32Array(n));break;case 3:e.gl.uniform3iv(o,new Int32Array(n));break;case 4:e.gl.uniform4iv(o,new Int32Array(n))}}if(l&&e.gl.uniform2i(l,r.texData.texShape[0],r.texData.texShape[1]),null!=a)if(r.isUniform)if(d(r.shape)<2)e.gl.uniform1f(a,r.uniformValues[0]);else{let t=r.uniformValues;t instanceof Float32Array||(t=new Float32Array(t)),e.gl.uniform1fv(a,t)}else null!=r.texData.slice&&null!=i&&e.gl.uniform1i(i,r.texData.slice.flatOffset),e.setInputMatrixTexture(r.texData.texture.texture,a,s)}const o=t.outShapeLocation;if(o)switch(s.shape.length){case 1:e.gl.uniform1iv(o,new Int32Array(s.shape));break;case 2:e.gl.uniform2iv(o,new Int32Array(s.shape));break;case 3:e.gl.uniform3iv(o,new Int32Array(s.shape));break;case 4:e.gl.uniform4iv(o,new Int32Array(s.shape))}if(t.outShapeStridesLocation){const n=M(s.shape);switch(s.shape.length){case 2:e.gl.uniform1iv(t.outShapeStridesLocation,new Int32Array(n));break;case 3:e.gl.uniform2iv(t.outShapeStridesLocation,new Int32Array(n));break;case 4:e.gl.uniform3iv(t.outShapeStridesLocation,new Int32Array(n))}}if(t.outTexShapeLocation&&e.gl.uniform2i(t.outTexShapeLocation,s.texData.texShape[0],s.texData.texShape[1]),t.program.customUniforms&&r)for(let n=0;n<t.program.customUniforms.length;++n){const s=t.program.customUniforms[n],a=t.customUniformLocations[n],i=r[n];if("float"===s.type)e.gl.uniform1fv(a,i);else if("vec2"===s.type)e.gl.uniform2fv(a,i);else if("vec3"===s.type)e.gl.uniform3fv(a,i);else if("vec4"===s.type)e.gl.uniform4fv(a,i);else if("int"===s.type)e.gl.uniform1iv(a,i);else if("ivec2"===s.type)e.gl.uniform2iv(a,i);else if("ivec3"===s.type)e.gl.uniform3iv(a,i);else{if("ivec4"!==s.type)throw Error(`uniform type ${s.type} is not supported yet.`);e.gl.uniform4iv(a,i)}}e.executeProgram()}(this.gpgpu,p,u,c,s),l.forEach((e=>this.disposeIntermediateTensorInfo(e))),f&&(g=this.endTimer(g),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(g)}));const y=Y().getNumber("WEBGL_FLUSH_THRESHOLD");if(y>0){const e=dr();e-this.lastGlFlushTime>y&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=e)}if(!Y().getBool("WEBGL_LAZILY_UNPACK")&&o.isPacked&&!1===r){const e=this.unpackTensor(i);return this.disposeIntermediateTensorInfo(i),e}return i}compileAndRun(e,t,n,s,r=!1){n=n||t[0].dtype;return this.runWebGLProgram(e,t,n,s,r)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){if(!this.disposed){if(!Y().getBool("IS_TEST")){Object.keys(this.binaryCache).forEach((e=>{this.gpgpu.deleteProgram(this.binaryCache[e].webGLProgram),delete this.binaryCache[e]}))}this.textureManager.dispose(),null!=this.canvas&&"undefined"!=typeof HTMLCanvasElement&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0}}floatPrecision(){return null==this.floatPrecisionValue&&(this.floatPrecisionValue=Na((()=>{if(!Y().get("WEBGL_RENDER_FLOAT32_ENABLED")){const e=Y().getBool("DEBUG");Y().set("DEBUG",!1);const t=this.abs(xl(1e-8)).dataSync()[0];if(Y().set("DEBUG",e),t>0)return 32}return 16}))),this.floatPrecisionValue}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}uploadToGPU(e){const t=this.texData.get(e),{shape:n,dtype:s,values:r,texture:a,usage:i,isPacked:o}=t;if(null!=a)return;const l=null!=this.activeTimers;let u;l&&(u=dr());let c=t.texShape;if(null==c&&(c=N_(n,o),t.texShape=c),null!=r){const e=k_(n);let a,i=c[1],h=c[0];const p=r instanceof Uint8Array||r instanceof Uint8ClampedArray;!o&&p||([i,h]=HR(c[0],c[1])),a=o?new gF(e,p):new mF(e,p);const d=p?[h,i]:c,f=this.makeTensorInfo(d,s),m=this.texData.get(f.dataId);m.usage=p?WR.PIXELS:WR.UPLOAD,m.texShape=d,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(f.dataId),i,h,r);const g=[[h,i]],y=!0,b=this.runWebGLProgram(a,[f],s,g,y),x=this.texData.get(b.dataId);t.texShape=x.texShape,t.isPacked=x.isPacked,t.usage=x.usage,Y().get("ENGINE_COMPILE_ONLY")?this.disposeData(b.dataId):(t.texture=x.texture,t.values=null,this.texData.delete(b.dataId)),this.disposeIntermediateTensorInfo(f),l&&(this.uploadWaitMs+=dr()-u)}else{const e=this.acquireTexture(c,i,s,o);t.texture=e}}convertAndCacheOnCPU(e,t){const n=this.texData.get(e),{dtype:s}=n;return null!=t&&(n.values=function(e,t){if("float32"===t||"complex64"===t)return e;if("int32"===t||"bool"===t){const n="int32"===t?new Int32Array(e.length):new Uint8Array(e.length);for(let t=0;t<n.length;++t)n[t]=Math.round(e[t]);return n}throw new Error(`Unknown dtype ${t}`)}(t,s)),n.values}acquireTexture(e,t,n,s){if(this.numBytesInGPU+=this.computeBytes(e,n),!this.warnedAboutMemory&&this.numBytesInGPU>1024*this.numMBBeforeWarning*1024){const e=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${e} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,t,s)}computeBytes(e,t){return e[0]*e[1]*$(t)}checkCompileCompletion(){for(const[,e]of Object.entries(this.binaryCache))this.checkCompletion_(e)}async checkCompileCompletionAsync(){const e=[];if(this.gpgpu.parallelCompilationExtension){for(const[,t]of Object.entries(this.binaryCache))e.push(this.checkCompletionAsync_(t));return Promise.all(e)}for(const[,t]of Object.entries(this.binaryCache)){const n=new Promise((e=>{try{this.checkCompletion_(t),e(!0)}catch(e){throw e}}));e.push(n)}return Promise.all(e)}async checkCompletionAsync_(e){return this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR)?this.checkCompletion_(e):(await ef(),this.checkCompletionAsync_(e))}checkCompletion_(e){if(!1===this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.gl.LINK_STATUS)){if(console.log(this.gpgpu.gl.getProgramInfoLog(e.webGLProgram)),!1===this.gpgpu.gl.getShaderParameter(e.fragmentShader,this.gpgpu.gl.COMPILE_STATUS))throw e_(e.source,this.gpgpu.gl.getShaderInfoLog(e.fragmentShader)),new Error("Failed to compile fragment shader.");throw new Error("Failed to link vertex and fragment shaders.")}return!0}getUniformLocations(){for(const e of Object.values(this.binaryCache)){this.gpgpu.buildVao(e.webGLProgram);const{variablesLocations:t,customUniformLocations:n,infLoc:s,nanLoc:r,outShapeLocation:a,outShapeStridesLocation:i,outTexShapeLocation:o}=oF(this.gpgpu,e.program,e.webGLProgram);e.variablesLocations=t,e.customUniformLocations=n,e.infLoc=s,e.nanLoc=r,e.outShapeLocation=a,e.outShapeStridesLocation=i,e.outTexShapeLocation=o}}createTensorFromGPUData(e,t,n){e.channels=e.channels||"RGBA";const{texture:s,height:r,width:a,channels:i}=e,o=va().backend;if(!o.gpgpu.gl.isTexture(s))throw new Error("The texture is invalid. Also, please make sure the texture and the TFJS WebGL backend are using the same canvas. If you want to use your own custom canvas, you have to create and use the custom TFJS WebGL backend created from the canvas through 'new tf.MathBackendWebGL(customCanvas)'.");const l=o.writeTexture(s,t,n,r,a,i);return va().makeTensorFromDataId(l,t,n,o)}}JD.nextDataId=0;const QD="4.15.0";function eO(){Y().set("WEBGL_FORCE_F16_TEXTURES",!0)}aa()&&$a("webgl",(()=>new JD),2);const tO={forceHalfFloat:eO};class nO{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=Zo(t,n),this.enableShapeUniforms=uF(this.outputShape.length),this.userCode=`\n      float binaryOperation(float a, float b) {\n        ${e}\n      }\n\n      void main() {\n        float a = getAAtOutCoords();\n        float b = getBAtOutCoords();\n        setOutput(binaryOperation(a, b));\n      }\n    `}}const sO="\n  result.r = isNaN.r ? NAN : result.r;\n  result.g = isNaN.g ? NAN : result.g;\n  result.b = isNaN.b ? NAN : result.b;\n  result.a = isNaN.a ? NAN : result.a;\n";class rO{constructor(e,t,n,s=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=Zo(t,n);const r=this.outputShape.length;this.enableShapeUniforms=uF(r);let a="";if(s)if(0===r||1===d(this.outputShape))a="\n          result.y = 0.;\n          result.z = 0.;\n          result.w = 0.;\n        ";else{if(a=`\n          ${sF(r)} coords = getOutputCoords();\n        `,1===r)this.enableShapeUniforms?a+="\n            result.y = (coords + 1) >= outShape ? 0. : result.y;\n            result.z = 0.;\n            result.w = 0.;\n          ":a+=`\n            result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;\n            result.z = 0.;\n            result.w = 0.;\n          `;else{const e=LD("coords",r);this.enableShapeUniforms?a+=`\n            bool nextRowOutOfBounds =\n              (${e[r-2]} + 1) >= outShape[${r} - 2];\n            bool nextColOutOfBounds =\n              (${e[r-1]} + 1) >= outShape[${r} - 1];\n            result.y = nextColOutOfBounds ? 0. : result.y;\n            result.z = nextRowOutOfBounds ? 0. : result.z;\n            result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n          `:a+=`\n            bool nextRowOutOfBounds =\n              (${e[r-2]} + 1) >= ${this.outputShape[r-2]};\n            bool nextColOutOfBounds =\n              (${e[r-1]} + 1) >= ${this.outputShape[r-1]};\n            result.y = nextColOutOfBounds ? 0. : result.y;\n            result.z = nextRowOutOfBounds ? 0. : result.z;\n            result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;\n          `}}this.userCode=`\n      vec4 binaryOperation(vec4 a, vec4 b) {\n        ${e}\n      }\n\n      void main() {\n        vec4 a = getAAtOutCoords();\n        vec4 b = getBAtOutCoords();\n\n        vec4 result = binaryOperation(a, b);\n        ${a}\n\n        setOutput(result);\n      }\n    `}}function aO(e){const{inputs:t,backend:n}=e,{x:s}=t;return n.incRef(s.dataId),{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}const iO={kernelName:gt,backendName:"webgl",kernelFunc:aO};function oO(e){const{inputs:t,backend:n}=e,{real:s,imag:r}=t,a=n.makeTensorInfo(s.shape,"complex64"),i=n.texData.get(a.dataId),o=aO({inputs:{x:s},backend:n}),l=aO({inputs:{x:r},backend:n});return i.complexTensorInfos={real:o,imag:l},a}const lO={kernelName:Ce,backendName:"webgl",kernelFunc:oO},uO="return (a < 0.) ? b * a : a;",cO="\n  vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n  return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n";const hO={kernelName:kt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{alpha:a}=s,i=n.makeTensorInfo([],"float32",hr(a,"float32")),o=Y().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new rO(cO,r.shape,i.shape):new nO(uO,r.shape,i.shape),l=n.runWebGLProgram(o,[r,i],"float32");return n.disposeIntermediateTensorInfo(i),l}},pO="return (a < 0.) ? b * a : a;",dO="\n  vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n  return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n";const fO={kernelName:rn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:s,alpha:r}=t,a=Y().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new rO(dO,s.shape,r.shape):new nO(pO,s.shape,r.shape);return n.runWebGLProgram(a,[s,r],"float32")}};function mO({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:n,dtype:s}){return({inputs:r,backend:a})=>{const{x:i}=r,o=a,l=s||i.dtype;if(o.shouldExecuteOnCPU([i])&&null!=n){const e=o.texData.get(i.dataId),t=n(e.values,l);return o.makeTensorInfo(i.shape,l,t)}let u;return u=Y().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&null!=t?new qD(i.shape,t):new GD(i.shape,e),o.runWebGLProgram(u,[i],l)}}function gO({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:s=!1,cpuKernelImpl:r,dtype:a}){return({inputs:i,backend:o})=>{const{a:l,b:u}=i,c=o;if(s&&"complex64"===l.dtype){const t=c.texData.get(l.dataId),n=c.texData.get(u.dataId),[s,r]=[[t.complexTensorInfos.real,n.complexTensorInfos.real],[t.complexTensorInfos.imag,n.complexTensorInfos.imag]].map((t=>{const[n,s]=t,r={dataId:n.dataId,dtype:n.dtype,shape:l.shape},a={dataId:s.dataId,dtype:s.dtype,shape:u.shape},i=new nO(e,l.shape,u.shape);return c.runWebGLProgram(i,[r,a],Wr(n.dtype,s.dtype))})),a=oO({inputs:{real:s,imag:r},backend:c});return c.disposeIntermediateTensorInfo(s),c.disposeIntermediateTensorInfo(r),a}const h=a||Wr(l.dtype,u.dtype);if(("string"===l.dtype||"string"===u.dtype||c.shouldExecuteOnCPU([l,u]))&&null!=r){const e=c.texData.get(l.dataId).values,t=c.texData.get(u.dataId).values,n="string"===l.dtype?sm(e):e,s="string"===l.dtype?sm(t):t,[a,i]=r(l.shape,u.shape,n,s,h),o=c.makeTensorInfo(i,h);return c.texData.get(o.dataId).values=a,o}let p;return p=Y().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&null!=t?new rO(t,l.shape,u.shape,n):new nO(e,l.shape,u.shape),c.runWebGLProgram(p,[l,u],h)}}function yO(e,t=!1){if("linear"===e)return"return x;";if("relu"===e)return t?"\n  vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n  bvec4 isNaN = isnan(x);\n\n  result.r = isNaN.r ? x.r : result.r;\n  result.g = isNaN.g ? x.g : result.g;\n  result.b = isNaN.b ? x.b : result.b;\n  result.a = isNaN.a ? x.a : result.a;\n\n  return result;\n":"if (isnan(x)) return x;\n  return (x < 0.0) ? 0.0 : x;\n";if("elu"===e)return t?"\n  vec4 result;\n\n  result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n  result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n  result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n  result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n  return result;\n":"return (x >= 0.0) ? x : (exp(x) - 1.0);";if("relu6"===e)return t?"\n  vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n  bvec4 isNaN = isnan(x);\n\n  result.r = isNaN.r ? x.r : result.r;\n  result.g = isNaN.g ? x.g : result.g;\n  result.b = isNaN.b ? x.b : result.b;\n  result.a = isNaN.a ? x.a : result.a;\n\n  return result;\n":"if (isnan(x)) return x;\n  return (x < 0.0) ? 0.0 : min(6.0, x);\n";if("prelu"===e)return t?dO:pO;if("leakyrelu"===e)return t?cO:uO;if("sigmoid"===e)return"return 1.0 / (1.0 + exp(-1.0 * x));";throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}class bO{constructor(e,t,n,s=!1,r=!1,a=!1,i=null,o=!1,l=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n,this.enableShapeUniforms=uF(this.outputShape.length);const u=s?e[1]:e[2],c=Math.ceil(u/2),h=s?"i * 2, rc.y":"rc.y, i * 2",p=r?"rc.z, i * 2":"i * 2, rc.z",d=s?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"];let m="",g="";i&&(m=o?`vec4 activation(vec4 a) {\n          vec4 b = getPreluActivationWeightsAtOutCoords();\n          ${i}\n        }`:l?`vec4 activation(vec4 a) {\n          vec4 b = getLeakyreluAlphaAtOutCoords();\n          ${i}\n        }`:`vec4 activation(vec4 x) {\n          ${i}\n        }`,g="result = activation(result);");const y=a?"result += getBiasAtOutCoords();":"";a&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),l&&this.variableNames.push("leakyreluAlpha");let b="rc.x",x="rc.x";e[0]<t[0]?b=`imod(rc.x, ${e[0]})`:t[0]<e[0]&&(x=`imod(rc.x, ${t[0]})`),this.userCode=`\n      ${m}\n      // Don't use uniform for sharedDimensionPacked for performance.\n      const float sharedDimension = ${c}.0;\n\n      vec4 dot2x2ARowBCol(ivec3 rc) {\n        vec4 result = vec4(0);\n        int batchA = ${b};\n        int batchB = ${x};\n        for (int i = 0; i < ${c}; i++) {\n          vec4 a = getMatrixA(batchA, ${h});\n          vec4 b = getMatrixB(batchB, ${p});\n\n          // These swizzled products need to be separately added.\n          // See: https://github.com/tensorflow/tfjs/issues/1735\n          result += (${d[0]} * ${f[0]});\n          result += (${d[1]} * ${f[1]});\n        }\n        return result;\n      }\n\n      void main() {\n        ivec3 rc = getOutputCoords();\n        vec4 result = dot2x2ARowBCol(rc);\n\n        ${y}\n\n        ${g}\n\n        setOutput(result);\n      }\n    `}}const xO="return areal * breal - aimag * bimag;",wO="return areal * bimag + aimag * breal;";class vO{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=Zo(t,n),this.userCode=`\n      float binaryOpComplex(\n          float areal, float aimag, float breal, float bimag) {\n        ${e}\n      }\n\n      void main() {\n        float areal = getARealAtOutCoords();\n        float aimag = getAImagAtOutCoords();\n        float breal = getBRealAtOutCoords();\n        float bimag = getBImagAtOutCoords();\n        setOutput(binaryOpComplex(areal, aimag, breal, bimag));\n      }\n    `}}const kO="return a * b;";function NO(e){const{inputs:t,backend:n}=e,{a:s,b:r}=t,a=Wr(s.dtype,r.dtype);if("complex64"===s.dtype){const e=n.texData.get(s.dataId),t=n.texData.get(r.dataId),a=new vO(xO,s.shape,r.shape),i=new vO(wO,s.shape,r.shape),o=[{dataId:e.complexTensorInfos.real.dataId,dtype:e.complexTensorInfos.real.dtype,shape:s.shape},{dataId:e.complexTensorInfos.imag.dataId,dtype:e.complexTensorInfos.imag.dtype,shape:s.shape},{dataId:t.complexTensorInfos.real.dataId,dtype:t.complexTensorInfos.real.dtype,shape:r.shape},{dataId:t.complexTensorInfos.imag.dataId,dtype:t.complexTensorInfos.imag.dtype,shape:r.shape}],l=n.runWebGLProgram(a,o,"float32"),u=n.runWebGLProgram(i,o,"float32"),c=oO({inputs:{real:l,imag:u},backend:n});return n.disposeIntermediateTensorInfo(l),n.disposeIntermediateTensorInfo(u),c}if(n.shouldExecuteOnCPU([s,r])){const e=n.texData.get(s.dataId),t=n.texData.get(r.dataId),[i,o]=uD(s.shape,r.shape,e.values,t.values,a),l=n.makeTensorInfo(o,a);return n.texData.get(l.dataId).values=i,l}let i;return i=Y().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new rO(kO,s.shape,r.shape):new nO(kO,s.shape,r.shape),n.runWebGLProgram(i,[s,r],a)}const IO={kernelName:qt,backendName:"webgl",kernelFunc:NO};function SO(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{shape:a}=s,i=n,o=d(r.shape),l=w(a,o),u=d(l);c(o===u,(()=>`The new shape (${l}) has ${u} elements and the old shape (${r.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`));const h=i.texData.get(r.dataId);return!h.isPacked||S_(r.shape,l)||null!==h.texture&&S_(h.shape,l)?(i.incRef(r.dataId),{dataId:r.dataId,shape:l,dtype:r.dtype}):function(e,t,n){const s=[w_(e.shape),...v_(e.shape)],r={dtype:e.dtype,shape:s,dataId:e.dataId},a=[w_(t),...v_(t)],i=new PD(a,s),o=[s],l=n.runWebGLProgram(i,[r],e.dtype,o,!0);return{dataId:l.dataId,shape:t,dtype:l.dtype}}(r,l,i)}const TO={kernelName:fn,backendName:"webgl",kernelFunc:SO};class CO{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:s,inSize:r,outSize:a}=e;this.outputShape=[s,a];const i=4*Math.floor(n/4),o=n%4;let l="sumValue += dot(values, ones);";if(null!=t){const e=1/t;l=`sumValue += dot(values * ${g(e)?e.toPrecision(2):e}, ones);`}let u="";r%n>0&&(u=`\n        if (inIdx < 0 || inIdx >= ${r}) {\n          return 0.0;\n        }\n      `),this.userCode=`\n      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n      float getValue(int batch, int inIdx) {\n        ${u}\n        return getX(batch, inIdx);\n      }\n\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int batch = coords[0];\n        int outIdx = coords[1];\n        int inOffset = outIdx * ${n};\n\n        float sumValue = 0.0;\n\n        for (int i = 0; i < ${i}; i += 4) {\n          int inIdx = inOffset + i;\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            getValue(batch, inIdx + 3)\n          );\n\n          ${l}\n        }\n\n        int inIdx = inOffset + ${i};\n        if (${1===o}) {\n          vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);\n\n          ${l}\n        } else if (${2===o}) {\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1), 0.0, 0.0);\n\n          ${l}\n        } else if (${3===o}) {\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2), 0.0);\n\n          ${l}\n        }\n        setOutput(sumValue);\n      }\n    `}}class $O{constructor(e,t){this.variableNames=["x"];const{windowSize:n,batchSize:s,inSize:r,outSize:a}=e;this.outputShape=[s,a];let i="0.0",o="";"prod"===t?i="1.0":"min"===t?(i="1.0 / 1e-20",o="min"):"max"===t&&(i="-1.0 / 1e-20",o="max");let l=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"sum"===t?l="sumValue":"prod"===t?l="prodValue":"all"===t?l="allValue":"any"===t&&(l="anyValue");const u=4*Math.floor(n/4),c=n%4;let h=`\n      if (${"sum"===t}) {\n        sumValue += dot(values, ones);\n      } else if (${"prod"===t}) {\n        vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);\n        prodValue *= tmp[0] * tmp[1];\n      } else {\n        minMaxValue = ${o}(values, minMaxValue);\n        if (${"min"===t} || ${"max"===t}) {\n          minMaxValue = ${o}(values, minMaxValue);\n          bvec4 isNaN = isnan(values);\n          if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {\n            minMaxValue = vec4(NAN);\n          }\n        }\n      }\n    `,p="vec4";"all"===t?(i="1.0",h="\n        bool reducedAllValue = all(values);\n        float floatedReducedAllValue = float(reducedAllValue);\n        allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);\n      ",p="bvec4"):"any"===t&&(i="0.0",h="\n        bool reducedAnyValue = any(values);\n        float floatedReducedAnyValue = float(reducedAnyValue);\n        anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);\n      ",p="bvec4");let d="";r%n>0&&(d=`\n        if (inIdx < 0 || inIdx >= ${r}) {\n          return initializationValue;\n        }\n      `),this.userCode=`\n      const float initializationValue = ${i};\n      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n      float getValue(int batch, int inIdx) {\n        ${d}\n        return getX(batch, inIdx);\n      }\n\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int batch = coords[0];\n        int outIdx = coords[1];\n        int inOffset = outIdx * ${n};\n\n        vec4 minMaxValue = vec4(${i});\n        float prodValue = 1.0;\n        float sumValue = 0.0;\n        float allValue = 1.0;\n        float anyValue = 0.0;\n\n        for (int i = 0; i < ${u}; i += 4) {\n          int inIdx = inOffset + i;\n          ${p} values = ${p}(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            getValue(batch, inIdx + 3)\n          );\n\n          ${h}\n        }\n\n        int inIdx = inOffset + ${u};\n        if (${1===c}) {\n          ${p} values = ${p}(\n            getValue(batch, inIdx),\n            initializationValue,\n            initializationValue,\n            initializationValue\n          );\n\n          ${h}\n        } else if (${2===c}) {\n          ${p} values = ${p}(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            initializationValue,\n            initializationValue\n          );\n\n          ${h}\n        } else if (${3===c}) {\n          ${p} values = ${p}(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            initializationValue\n          );\n\n          ${h}\n        }\n        setOutput(${l});\n      }\n    `}}function EO(e,t,n,s){const r=function(e){const t=[];for(;0===t.length||1!==t[t.length-1].outSize;){const n=t.length?t[t.length-1].outSize:e[1],s=uf(n);t.push({inSize:n,windowSize:s,outSize:Math.ceil(n/s)})}return t}(e.shape);let a=e;for(let i=0;i<r.length;i++){const{inSize:o,windowSize:l,outSize:u}=r[i];let c,h;c="mean"===n?0===i?new CO({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:u},o):new CO({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:u}):new $O({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:u},n),h=a,a=s.runWebGLProgram(c,[a],t),h.dataId!==e.dataId&&s.disposeIntermediateTensorInfo(h)}return a}class AO{constructor(e,t){this.variableNames=["A"];const n=new Array(e.length);for(let s=0;s<n.length;s++)n[s]=e[t[s]];this.outputShape=n,this.rank=n.length;const s=sF(this.rank),r=function(e){const t=e.length;if(t>6)throw Error(`Transpose for rank ${t} is not yet supported`);const n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],s=new Array(t);for(let t=0;t<e.length;t++)s[e[t]]=n[t];return s.join()}(t);this.userCode=`\n    void main() {\n      ${s} resRC = getOutputCoords();\n      setOutput(getA(${r}));\n    }\n    `}}class RO{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;const n=new Array(e.length);for(let s=0;s<n.length;s++)n[s]=e[t[s]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);const s=sF(this.rank),r=MD("rc",this.rank),a=new Array(this.rank);for(let e=0;e<t.length;e++)a[t[e]]=r[e];const i=`vec2(${a.slice(-2).join()})`,o=`++${r[this.rank-1]} < ${n[this.rank-1]}`,l=`getChannel(getA(${a.join()}), ${i})`;this.userCode=`\n    void main() {\n      ${s} rc = getOutputCoords();\n      vec4 result = vec4(0.);\n      result[0] = ${l};\n      if(${o}) {\n        result[1] = ${l};\n      }\n      --${r[this.rank-1]};\n      if(++${r[this.rank-2]} < ${n[this.rank-2]}) {\n        result[2] = ${l};\n        if(${o}) {\n          result[3] = ${l};\n        }\n      }\n      setOutput(result);\n    }\n    `}}function _O(e,t,n){const s=Y().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new RO(e.shape,t):new AO(e.shape,t);return n.runWebGLProgram(s,[e],e.dtype)}function FO(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s;return function(e,t,n,s){const r=t,a=e.shape.length,i=v(r,e.shape);let o=i;const l=dl(o,a),u=null!=l;let c=e;u&&(c=_O(e,l,s),o=ml(o.length,a)),pl("sum",o,a);const[h,p]=cl(c.shape,o);let f=h;n&&(f=hl(h,i));const m=d(p),g=SO({inputs:{x:c},attrs:{shape:[d(e.shape)/m,m]},backend:s}),y=EO(g,Vr(e.dtype),"sum",s),b=SO({inputs:{x:y},attrs:{shape:f},backend:s});return s.disposeIntermediateTensorInfo(g),s.disposeIntermediateTensorInfo(y),u&&s.disposeIntermediateTensorInfo(c),b}(r,a,i,n)}const DO={kernelName:On,backendName:"webgl",kernelFunc:FO};function OO(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{perm:a}=s,i=n,o=r.shape.length,l=new Array(o);for(let e=0;e<l.length;e++)l[e]=r.shape[a[e]];let u;if(i.shouldExecuteOnCPU([r])){const e=i.texData.get(r.dataId).values,t=DD(e,r.shape,r.dtype,a,l);u=i.makeTensorInfo(l,r.dtype);i.texData.get(u.dataId).values=t}else u=_O(r,a,i);return u}const MO={kernelName:ss,backendName:"webgl",kernelFunc:OO};function LO({a:e,b:t,transposeA:n,transposeB:s,backend:r,bias:a=null,preluActivationWeights:i=null,leakyreluAlpha:o=0,activation:l=null}){const u=e.shape.length,h=t.shape.length,p=n?e.shape[u-2]:e.shape[u-1],f=s?t.shape[h-1]:t.shape[h-2],m=n?e.shape[u-1]:e.shape[u-2],g=s?t.shape[h-2]:t.shape[h-1],y=e.shape.slice(0,-2),b=t.shape.slice(0,-2),x=d(y),w=d(b),v=Zo(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([m,g]);c(p===f,(()=>`Error in matMul: inner shapes (${p}) and (${f}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${s} must match.`));const k=n?[x,p,m]:[x,m,p],N=s?[w,g,f]:[w,f,g],I=SO({inputs:{x:e},backend:r,attrs:{shape:k}}),S=SO({inputs:{x:t},backend:r,attrs:{shape:N}}),T=[I,S],C=Math.max(x,w),$=n?I.shape[1]:I.shape[2],E=null!=a,A=null!=i,R="leakyrelu"===l,_=null!=l?yO(l,!0):null;let F;if((1===m||1===g)&&$>1e3&&!1===(E||A||R||null!=_)){let e=I,t=S;n&&(e=OO({inputs:{x:I},backend:r,attrs:{perm:[0,2,1]}}),T.push(e)),s&&(t=OO({inputs:{x:S},backend:r,attrs:{perm:[0,2,1]}}),T.push(t));const a=1===g;let i=e;1!==g&&(i=SO({inputs:{x:e},backend:r,attrs:{shape:[C,$,1]}}),T.push(i));const o=1===g?2:1;let l=t;a&&(l=SO({inputs:{x:t},backend:r,attrs:{shape:[C,1,$]}}),T.push(l));const u=NO({inputs:{a:i,b:l},backend:r});F=FO({inputs:{x:u},backend:r,attrs:{axis:o,keepDims:!0}}),T.push(u)}else{const l=Wr(e.dtype,t.dtype),u=new bO(k,N,[C,m,g],n,s,E,_,A,R),c=[I,S];if(null!=a&&c.push(a),A&&c.push(i),R){const e=r.makeTensorInfo([],"float32",hr(o,"float32"));c.push(e),T.push(e)}F=r.runWebGLProgram(u,c,l)}const D=SO({inputs:{x:F},backend:r,attrs:{shape:v}});T.push(F);for(const e of T)r.disposeIntermediateTensorInfo(e);return D}const zO={kernelName:hs,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{a:r,b:a,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:u,activation:c,leakyreluAlpha:h}=s;return LO({a:r,b:a,transposeA:l,transposeB:u,backend:n,bias:i,preluActivationWeights:o,leakyreluAlpha:h,activation:c})}},PO="return abs(x);";const BO={kernelName:ee,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:s}=t;if(n.shouldExecuteOnCPU([s])&&"complex64"!==s.dtype){const e=n.texData.get(s.dataId),t=wD(e.values);return n.makeTensorInfo(s.shape,s.dtype,t)}let r;return r=Y().getBool("WEBGL_PACK_UNARY_OPERATIONS")?new qD(s.shape,PO):new GD(s.shape,PO),n.runWebGLProgram(r,[s],s.dtype)}},WO=mO({opSnippet:"if (isnan(x)) return x;\n  if (abs(x) > 1.) {\n    return NAN;\n  }\n  return acos(x);\n"}),VO={kernelName:te,backendName:"webgl",kernelFunc:WO},UO=mO({opSnippet:"if (isnan(x)) return x;\n  if (x < 1.0) return NAN;\nreturn log(x + sqrt(x * x - 1.0));"}),GO={kernelName:ne,backendName:"webgl",kernelFunc:UO},HO="return a + b;",jO=gO({opSnippet:HO,packedOpSnippet:HO,supportsComplex:!0,cpuKernelImpl:WF}),qO={kernelName:se,backendName:"webgl",kernelFunc:jO};class KO{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map(((e,t)=>`T${t}`));const n=[];this.variableNames.forEach((e=>{n.push(`float v${e} = get${e}AtOutCoords();`)}));const s=this.variableNames.map((e=>`v${e}`)).join(" + ");this.userCode=`\n      void main() {\n        ${n.join("\n        ")}\n\n        float result = ${s};\n        setOutput(result);\n      }\n    `}}class XO{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map(((e,t)=>`T${t}`));const n=[];this.variableNames.forEach((e=>{n.push(`vec4 v${e} = get${e}AtOutCoords();`)}));const s=this.variableNames.map((e=>`v${e}`)).join(" + ");this.userCode=`\n      void main() {\n        ${n.join("\n        ")}\n\n        vec4 result = ${s};\n        setOutput(result);\n      }\n    `}}const YO={kernelName:re,backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:s}=t,r=n;if(1===r.length)return aO({inputs:{x:r[0]},backend:s});if(r.length>Y().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){const t=Math.floor(r.length/2),n=e({inputs:r.slice(0,t),backend:s}),a=e({inputs:r.slice(t),backend:s});return e({inputs:[n,a],backend:s})}const a=r.map((e=>e.dtype)).reduce(((e,t)=>Wr(e,t))),i=r.map((e=>e.shape)),o=Y().getBool("WEBGL_PACK")?new XO(r[0].shape,i):new KO(r[0].shape,i);return s.runWebGLProgram(o,r,a)}};const ZO={kernelName:ae,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s,o=r.shape.length,l=v(a,r.shape);let u=l;const c=dl(u,o);let h=r;null!=c&&(h=OO({inputs:{x:r},backend:n,attrs:{perm:c}}),u=ml(u.length,o)),pl("all",u,o);const[p,f]=cl(h.shape,u),m=SO({inputs:{x:h},backend:n,attrs:{shape:[-1,d(f)]}}),g=EO(m,m.dtype,"all",n);let y;if(i){y=SO({inputs:{x:g},backend:n,attrs:{shape:hl(p,l)}})}else y=SO({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),null!=c&&n.disposeIntermediateTensorInfo(h),y}};const JO={kernelName:ie,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s,o=r.shape.length,l=v(a,r.shape);let u=l;const c=dl(u,o);let h=r;null!=c&&(h=OO({inputs:{x:r},backend:n,attrs:{perm:c}}),u=ml(u.length,o)),pl("any",u,o);const[p,f]=cl(h.shape,u),m=SO({inputs:{x:h},backend:n,attrs:{shape:[-1,d(f)]}}),g=EO(m,m.dtype,"any",n);let y;if(i){y=SO({inputs:{x:g},backend:n,attrs:{shape:hl(p,l)}})}else y=SO({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),null!=c&&n.disposeIntermediateTensorInfo(h),y}};class QO{constructor(e,t,n){this.variableNames=["A"];const{windowSize:s,batchSize:r,outSize:a}=e;n||this.variableNames.push("bestIndicesA"),this.outputShape=[r,a];const i="max"===t?">":"<",o=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int batch = coords[0];\n        int outIdx = coords[1];\n        int inOffset = outIdx * ${s};\n\n        int bestIndex = inOffset;\n        float bestValue = getA(batch, bestIndex);\n\n        for (int i = 0; i < ${s}; i++) {\n          int inIdx = ${o};\n          float candidate = getA(batch, inIdx);\n          if (candidate ${i} bestValue) {\n            bestValue = candidate;\n            bestIndex = inIdx;\n          }\n        }\n        setOutput(float(bestIndex));\n      }\n    `}}class eM{constructor(e,t,n,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,c(e.length>2,(()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`));const r=e[e.length-1],a=Math.ceil(r/t);this.outputShape=e.slice(0,-1),a>1&&this.outputShape.push(a),s||this.variableNames.push("bestIndicesA");const i=this.outputShape,o=i.length,l=sF(o),u=LD("coords",o);let h,p;if(1===a){p=o+1;const e=sF(p);h=`\n        ${e} sourceLocR = ${e}(${u.join()}, 0);\n        ++${u[o-1]};\n        ${e} sourceLocG = ${e}(${u.join()}, 0);\n        ++${u[o-2]};\n        ${e} sourceLocA = ${e}(${u.join()}, 0);\n        --${u[o-1]};\n        ${e} sourceLocB = ${e}(${u.join()}, 0);\n        --${u[o-2]};`}else p=o,h=`\n        ${l} sourceLocR = coords;\n        ++${u[o-1]};\n        ${l} sourceLocG = coords;\n        ++${u[o-2]};\n        ${l} sourceLocA = coords;\n        --${u[o-1]};\n        ${l} sourceLocB = coords;\n        --${u[o-2]};`;const d=["x","y","z","w","u","v"].slice(0,p),f="."+d[p-1],m=d.map((e=>"int "+e)),g=LD("sourceLocR",p-1).concat("inIdx.r"),y=LD("sourceLocG",p-1).concat("inIdx.g"),b=LD("sourceLocB",p-1).concat("inIdx.b"),x=LD("sourceLocA",p-1).concat("inIdx.a"),w="max"===n?"greaterThan":"lessThan",v=s?"":`\n          inIdx = round(vec4(getBestIndicesAChannel(${g.join()}),\n                             getBestIndicesAChannel(${y.join()}),\n                             getBestIndicesAChannel(${b.join()}),\n                             getBestIndicesAChannel(${x.join()})));`,k=`vec4(\n            getAChannel(${g.join()}),\n            hasNextCol ? getAChannel(${y.join()}) : 0.,\n            hasNextRow ? getAChannel(${b.join()}) : 0.,\n            hasNextRow && hasNextCol ? getAChannel(${x.join()}) : 0.)`,N=s?"":`\n      float getBestIndicesAChannel(${m.join()}) {\n        return getChannel(getBestIndicesA(${d.join()}),\n                                          vec2(${d.slice(-2).join()}));\n      }`;this.userCode=`\n      float getAChannel(${m.join()}) {\n        return getChannel(getA(${d.join()}),\n                               vec2(${d.slice(-2).join()}));\n      }\n      ${N}\n      void main() {\n        ${l} coords = getOutputCoords();\n        bool hasNextCol = ${u[o-1]} < ${i[o-1]-1};\n        bool hasNextRow = ${u[o-2]} < ${i[o-2]-1};\n        ${h}\n        ivec4 srcIdx = ivec4(sourceLocR${f}, sourceLocG${f},\n          sourceLocB${f}, sourceLocA${f}) * ${t};\n        ivec4 inIdx = srcIdx;\n        vec4 bestIndex = vec4(inIdx);\n        vec4 bestValue = ${k};\n\n        for (int i = 0; i < ${t}; i++) {\n          inIdx = srcIdx;\n          ${v}\n          vec4 candidate = ${k};\n          bvec4 nan = isnan(candidate);\n          bvec4 replace = bvec4(\n            vec4(${w}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));\n\n          bestValue = vec4(replace.x  ? candidate.x : bestValue.x,\n                           replace.y  ? candidate.y : bestValue.y,\n                           replace.z  ? candidate.z : bestValue.z,\n                           replace.w  ? candidate.w : bestValue.w);\n          bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));\n          srcIdx++;\n        }\n        setOutput(bestIndex);\n      }\n    `}}function tM(e,t,n,s=null){let r=t.shape[0],a=t.shape[1];null!=s&&(r=s.shape[0],a=s.shape[1]);const i=uf(a),o={windowSize:i,inSize:a,batchSize:r,outSize:Math.ceil(a/i)},l=new QO(o,n,null==s),u=[t];null!=s&&u.push(s);const c=e.runWebGLProgram(l,u,"int32");if(1===c.shape[1])return c;const h=tM(e,t,n,c);return e.disposeIntermediateTensorInfo(c),h}function nM(e,t,n,s=null){const r=null!=s?s.shape:t.shape,a=uf(r[r.length-1]),i=new eM(r,a,n,null==s),o=null==s?[t]:[t,s],l=e.runWebGLProgram(i,o,"int32");if(l.shape.length===t.shape.length){const s=nM(e,t,n,l);return e.disposeIntermediateTensorInfo(l),s}return l}function sM(e,t,n,s){const r=[n];if(pl("arg"+s.charAt(0).toUpperCase()+s.slice(1),r,t.shape.length),!Y().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){const n=[],a=e.texData.get(t.dataId);let i=t;null!==a&&a.isPacked&&(i=e.unpackTensor(t),n.push(i));const[o,l]=cl(i.shape,r),u=d(l),c=SO({inputs:{x:i},backend:e,attrs:{shape:[-1,u]}});n.push(c);const h=tM(e,c,s);n.push(h);const p=SO({inputs:{x:h},backend:e,attrs:{shape:o}});return n.forEach((t=>e.disposeIntermediateTensorInfo(t))),p}return nM(e,t,s)}const rM={kernelName:oe,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s;let i=v(a,r.shape);const o=dl(i,r.shape.length);let l=r;const u=[];null!=o&&(l=OO({inputs:{x:r},backend:n,attrs:{perm:o}}),u.push(l),i=ml(i.length,l.shape.length)),pl("argMax",[i[0]],l.shape.length);const c=sM(n,l,i[0],"max");return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),c}};const aM={kernelName:le,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s;let i=v(a,r.shape);const o=dl(i,r.shape.length);let l=r;const u=[];null!=o&&(l=OO({inputs:{x:r},backend:n,attrs:{perm:o}}),u.push(l),i=ml(i.length,l.shape.length)),pl("argMin",[i[0]],l.shape.length);const c=sM(n,l,i[0],"min");return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),c}},iM=mO({opSnippet:"if (isnan(x)) return x;\n  if (abs(x) > 1.) {\n    return NAN;\n  }\n  return asin(x);\n"}),oM={kernelName:ue,backendName:"webgl",kernelFunc:iM},lM=mO({opSnippet:"if (isnan(x)) return x;return log(x + sqrt(x * x + 1.0));"}),uM={kernelName:ce,backendName:"webgl",kernelFunc:lM},cM=mO({opSnippet:"if (isnan(x)) return x;\n  return atan(x);\n"}),hM={kernelName:he,backendName:"webgl",kernelFunc:cM},pM=gO({opSnippet:"\n  if (isnan(a)) return a;\n  if (isnan(b)) return b;\n\n  return atan(a, b);\n",packedOpSnippet:"\n  vec4 result = atan(a, b);\n  bvec4 isNaNA = isnan(a);\n  bvec4 isNaNB = isnan(b);\n  bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);\n  \n  result.r = isNaN.r ? NAN : result.r;\n  result.g = isNaN.g ? NAN : result.g;\n  result.b = isNaN.b ? NAN : result.b;\n  result.a = isNaN.a ? NAN : result.a;\n\n  return result;\n"}),dM={kernelName:de,backendName:"webgl",kernelFunc:pM},fM=mO({opSnippet:"if (isnan(x)) return x;\n  if ((x < -1.0) || (x > 1.0)) return NAN;\nreturn (log(1.0 + x) - log(1.0 - x)) / 2.0;"}),mM={kernelName:pe,backendName:"webgl",kernelFunc:fM};class gM{constructor(e,t,n,s=!1,r=!1){if(this.variableNames=["x"],"avg"===t&&n)throw new Error("Cannot compute positions for average pool.");const a=e.filterWidth,i=e.strideHeight,o=e.strideWidth,l=e.dilationHeight,u=e.dilationWidth,c=e.effectiveFilterHeight,h=e.effectiveFilterWidth,p=e.padInfo.top,d=e.padInfo.left;this.outputShape=e.outShape;const f="avg"===t,m=`((batch  * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,g=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`;let y="0.0";if(f||(y="-1.0 / 1e-20"),n){const t=">=";return void(this.userCode=`\n        const ivec2 strides = ivec2(${i}, ${o});\n        const ivec2 pads = ivec2(${p}, ${d});\n\n        void main() {\n          ivec4 coords = getOutputCoords();\n          int batch = coords[0];\n          int d = coords[3];\n\n          ivec2 xRCCorner = coords.yz * strides - pads;\n          int xRCorner = xRCCorner.x;\n          int xCCorner = xRCCorner.y;\n\n          // max/min x(?, ?, d) to get y(yR, yC, d).\n          // ? = to be determined\n          float minMaxValue = 0.0;\n          float minMaxValueFound = 0.0;\n          int minMaxPosition = 0;\n          float avgValue = 0.0;\n\n          for (int wR = 0; wR < ${c};\n              wR += ${l}) {\n            int xR = xRCorner + wR;\n\n            if (xR < 0 || xR >= ${e.inHeight}) {\n              continue;\n            }\n\n            for (int wC = 0; wC < ${h};\n                wC += ${u}) {\n              int xC = xCCorner + wC;\n\n              if (xC < 0 || xC >= ${e.inWidth}) {\n                continue;\n              }\n\n              float value = getX(batch, xR, xC, d);\n\n              // If a min / max value has already been found, use it. If not,\n              // use the current value.\n              float currMinMaxValue = mix(\n                  value, minMaxValue, minMaxValueFound);\n              if (value ${t} currMinMaxValue) {\n                minMaxValue = value;\n                minMaxValueFound = 1.0;\n                minMaxPosition = ${s?r?m:g:`wR * ${h} + wC`};\n              }\n            }\n          }\n          setOutput(float(minMaxPosition));\n        }\n      `)}let b=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"avg"===t&&(b="avgValue / max(count, 1.0)");const x=4*Math.floor(a/4),w=a%4,v=`\n      if (${f}) {\n        avgValue += dot(values, ones);\n      } else {\n        minMaxValue = max(values, minMaxValue);\n      }\n    `;this.userCode=`\n      const ivec2 strides = ivec2(${i}, ${o});\n      const ivec2 pads = ivec2(${p}, ${d});\n      const float initializationValue = ${y};\n      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n      float count = 0.0;\n\n      float getValue(int batch, int xR, int xC, int d) {\n        if (xC < 0 || xC >= ${e.inWidth}) {\n          return initializationValue;\n        }\n        count += 1.0;\n        return getX(batch, xR, xC, d);\n      }\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d = coords[3];\n\n        ivec2 xRCCorner = coords.yz * strides - pads;\n        int xRCorner = xRCCorner.x;\n        int xCCorner = xRCCorner.y;\n\n        // max/min x(?, ?, d) to get y(yR, yC, d).\n        // ? = to be determined\n        vec4 minMaxValue = vec4(${y});\n        float avgValue = 0.0;\n        count = 0.0;\n\n        for (int wR = 0; wR < ${c};\n            wR += ${l}) {\n          int xR = xRCorner + wR;\n\n          if (xR < 0 || xR >= ${e.inHeight}) {\n            continue;\n          }\n\n          for (int wC = 0; wC < ${x}; wC += 4) {\n            int xC = xCCorner + wC * ${u};\n\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              getValue(batch, xR, xC + ${u}, d),\n              getValue(batch, xR, xC + 2 * ${u}, d),\n              getValue(batch, xR, xC + 3 * ${u}, d)\n            );\n\n            ${v}\n          }\n\n          int xC = xCCorner + ${x};\n          if (${1===w}) {\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              initializationValue,\n              initializationValue,\n              initializationValue\n            );\n\n            ${v}\n          } else if (${2===w}) {\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              getValue(batch, xR, xC + ${u}, d),\n              initializationValue,\n              initializationValue\n            );\n\n            ${v}\n          } else if (${3===w}) {\n            vec4 values = vec4(\n              getValue(batch, xR, xC, d),\n              getValue(batch, xR, xC + ${u}, d),\n              getValue(batch, xR, xC + 2 * ${u}, d),\n              initializationValue\n            );\n\n            ${v}\n          }\n        }\n        setOutput(${b});\n      }\n    `}}class yM{constructor(e,t,n,s=!1,r=!1){if(this.variableNames=["x"],"avg"===t&&n)throw new Error("Cannot compute positions for average pool.");const a=e.filterWidth,i=e.strideDepth,o=e.strideHeight,l=e.strideWidth,u=e.dilationDepth,c=e.dilationHeight,h=e.dilationWidth,p=e.effectiveFilterDepth,d=e.effectiveFilterHeight,f=e.effectiveFilterWidth,m=e.padInfo.front,g=e.padInfo.top,y=e.padInfo.left;this.outputShape=e.outShape;const b="avg"===t;let x="0.0";if(b||(x="-1.0 / 1e-20"),n){const t=">=";return void(this.userCode=`\n        const ivec3 strides =\n            ivec3(${i}, ${o}, ${l});\n        const ivec3 pads = ivec3(${m}, ${g}, ${y});\n\n        void main() {\n          ivec5 coords = getOutputCoords();\n          int batch = coords.x;\n          int ch = coords.u;\n\n          ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n          int xDCorner = xCorner.x;\n          int xRCorner = xCorner.y;\n          int xCCorner = xCorner.z;\n\n          // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).\n          // ? = to be determined\n          float minMaxValue = 0.0;\n          float minMaxValueFound = 0.0;\n          int minMaxPosition = 0;\n\n          for (int wD = 0; wD < ${p};\n              wD += ${u}) {\n            int xD = xDCorner + wD;\n\n            if (xD < 0 || xD >= ${e.inDepth}) {\n              continue;\n            }\n\n            for (int wR = 0; wR < ${d};\n                wR += ${c}) {\n              int xR = xRCorner + wR;\n\n              if (xR < 0 || xR >= ${e.inHeight}) {\n                continue;\n              }\n\n              for (int wC = 0; wC < ${f};\n                  wC += ${h}) {\n                int xC = xCCorner + wC;\n\n                if (xC < 0 || xC >= ${e.inWidth}) {\n                  continue;\n                }\n\n                float value = getX(batch, xD, xR, xC, ch);\n\n                // If a min / max value has already been found, use it. If not,\n                // use the current value.\n                float currMinMaxValue = mix(\n                    value, minMaxValue, minMaxValueFound);\n                if (value ${t} currMinMaxValue) {\n                  minMaxValue = value;\n                  minMaxValueFound = 1.0;\n                  minMaxPosition = ${s?r?`(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`wD * ${d} * ${f} +\n                      wR * ${f} + wC`};\n                }\n              }\n            }\n          }\n          setOutput(float(minMaxPosition));\n        }\n      `)}let w=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;"avg"===t&&(w="avgValue / max(count, 1.0)");const v=4*Math.floor(a/4),k=a%4,N=`\n      if (${b}) {\n        avgValue += dot(values, ones);\n      } else {\n        minMaxValue = max(values, minMaxValue);\n      }\n    `;this.userCode=`\n      const ivec3 strides =\n        ivec3(${i}, ${o}, ${l});\n      const ivec3 pads = ivec3(${m}, ${g}, ${y});\n      const float initializationValue = ${x};\n      const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);\n\n      float count = 0.0;\n\n      float getValue(int batch, int xD, int xR, int xC, int ch) {\n        if (xC < 0 || xC >= ${e.inWidth}) {\n          return initializationValue;\n        }\n        count += 1.0;\n        return getX(batch, xD, xR, xC, ch);\n      }\n\n      void main() {\n        ivec5 coords = getOutputCoords();\n        int batch = coords.x;\n        int ch = coords.u;\n\n        ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n        int xDCorner = xCorner.x;\n        int xRCorner = xCorner.y;\n        int xCCorner = xCorner.z;\n\n        // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).\n        // ? = to be determined\n        vec4 minMaxValue = vec4(${x});\n        float avgValue = 0.0;\n        count = 0.0;\n\n        for (int wD = 0; wD < ${p};\n            wD += ${u}) {\n          int xD = xDCorner + wD;\n\n          if (xD < 0 || xD >= ${e.inDepth}) {\n            continue;\n          }\n\n          for (int wR = 0; wR < ${d};\n            wR += ${c}) {\n            int xR = xRCorner + wR;\n\n            if (xR < 0 || xR >= ${e.inHeight}) {\n              continue;\n            }\n\n            for (int wC = 0; wC < ${v}; wC += 4) {\n              int xC = xCCorner + wC * ${h};\n\n              vec4 values = vec4(\n                getValue(batch, xD, xR, xC, ch),\n                getValue(batch, xD, xR, xC + ${h}, ch),\n                getValue(batch, xD, xR, xC + 2 * ${h}, ch),\n                getValue(batch, xD, xR, xC + 3 * ${h}, ch)\n              );\n\n              ${N}\n            }\n\n            int xC = xCCorner + ${v};\n            if (${1===k}) {\n              vec4 values = vec4(\n                getValue(batch, xD, xR, xC, ch),\n                initializationValue,\n                initializationValue,\n                initializationValue\n              );\n\n              ${N}\n            } else if (${2===k}) {\n              vec4 values = vec4(\n                getValue(batch, xD, xR, xC, ch),\n                getValue(batch, xD, xR, xC + ${h}, ch),\n                initializationValue,\n                initializationValue\n              );\n\n              ${N}\n            } else if (${3===k}) {\n              vec4 values = vec4(\n                getValue(batch, xD, xR, xC, ch),\n                getValue(batch, xD, xR, xC + ${h}, ch),\n                getValue(batch, xD, xR, xC + 2 * ${h}, ch),\n                initializationValue\n              );\n\n              ${N}\n            }\n          }\n        }\n        setOutput(${w});\n      }\n    `}}const bM={kernelName:fe,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t;L_(r,"avgPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:l}=s;c(so(i,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const u=qi(r.shape,a,i,1,o,l);if(1===u.filterWidth&&1===u.filterHeight&&m(u.inShape,u.outShape))return aO({inputs:{x:r},backend:n});const h=new gM(u,"avg",!1);return n.runWebGLProgram(h,[r],"float32")}};const xM={kernelName:ge,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=s,c=Ki(r.shape,a,i,[1,1,1],o,l,u),h=new yM(c,"avg",!1);return n.runWebGLProgram(h,[r],"float32")}};class wM{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,r=e.strideWidth,a=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterHeight,l=e.effectiveFilterWidth,u=o-1-e.padInfo.top,c=l-1-e.padInfo.left,h=1/(t*n);this.userCode=`\n      const ivec2 pads = ivec2(${u}, ${c});\n      const float avgMultiplier = float(${h});\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n\n        ivec2 dyRCCorner = coords.yz - pads;\n        int dyRCorner = dyRCCorner.x;\n        int dyCCorner = dyRCCorner.y;\n\n        // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        for (int wR = 0; wR < ${o};\n            wR += ${a}) {\n          float dyR = float(dyRCorner + wR) / ${s}.0;\n\n          if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          for (int wC = 0; wC < ${l};\n            wC+= ${i}) {\n            float dyC = float(dyCCorner + wC) / ${r}.0;\n\n            if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n                fract(dyC) > 0.0) {\n              continue;\n            }\n            int idyC = int(dyC);\n\n            float dyValue = getDy(b, idyR, idyC, d);\n\n            dotProd += dyValue * avgMultiplier;\n          }\n        }\n        setOutput(dotProd);\n      }\n    `}}class vM{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;const t=e.filterDepth,n=e.filterHeight,s=e.filterWidth,r=e.strideDepth,a=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,l=e.dilationHeight,u=e.dilationWidth,c=e.effectiveFilterDepth,h=e.effectiveFilterHeight,p=e.effectiveFilterWidth,d=c-1-e.padInfo.front,f=h-1-e.padInfo.top,m=p-1-e.padInfo.left,g=1/(t*n*s);this.userCode=`\n      const ivec3 pads = ivec3(${d}, ${f}, ${m});\n      const float avgMultiplier = float(${g});\n\n      void main() {\n        ivec5 coords = getOutputCoords();\n        int batch = coords.x;\n        int ch = coords.u;\n\n        ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n        int dyDCorner = dyCorner.x;\n        int dyRCorner = dyCorner.y;\n        int dyCCorner = dyCorner.z;\n\n        // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get\n        // dx(xD, xR, xC, ch).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n\n        for (int wD = 0; wD < ${c};\n            wD += ${o}) {\n          float dyD = float(dyDCorner + wD) / ${r}.0;\n\n          if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {\n            continue;\n          }\n          int idyD = int(dyD);\n\n          for (int wR = 0; wR < ${h};\n              wR += ${l}) {\n            float dyR = float(dyRCorner + wR) / ${a}.0;\n\n            if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||\n                fract(dyR) > 0.0) {\n              continue;\n            }\n            int idyR = int(dyR);\n\n            for (int wC = 0; wC < ${p};\n                wC += ${u}) {\n              float dyC = float(dyCCorner + wC) / ${i}.0;\n\n              if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n                  fract(dyC) > 0.0) {\n                continue;\n              }\n              int idyC = int(dyC);\n\n              float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n\n              dotProd += dyValue * avgMultiplier;\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    `}}const kM={kernelName:ye,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,i=a,{filterSize:o,strides:l,pad:u,dimRoundingMode:c}=s,h=Ki(i.shape,o,l,[1,1,1],u,c),p=new vM(h);return n.runWebGLProgram(p,[r],i.dtype)}};const NM={kernelName:me,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,i=a;L_([r,a],"avgPoolGrad");const{filterSize:o,strides:l,pad:u}=s,c=qi(i.shape,o,l,1,u),h=new wM(c);return n.runWebGLProgram(h,[r],i.dtype)}};const IM={kernelName:be,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{a:r,b:a}=t,{transposeA:i,transposeB:o}=s;return LO({a:r,b:a,transposeA:i,transposeB:o,backend:n})}};class SM{constructor(e,t,n,s,r,a){this.outputShape=[],this.variableNames=["x","mean","variance"],Zo(e,t),Zo(e,n);let i="0.0";null!=s&&(Zo(e,s),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="1.0";null!=r&&(Zo(e,r),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`\n      void main() {\n        float x = getXAtOutCoords();\n        float mean = getMeanAtOutCoords();\n        float variance = getVarianceAtOutCoords();\n        float offset = ${i};\n        float scale = ${o};\n        float inv = scale * inversesqrt(variance + float(${a}));\n        setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));\n      }\n    `}}class TM{constructor(e,t,n,s,r,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],Zo(e,t),Zo(e,n);let i="vec4(0.0)";null!=s&&(Zo(e,s),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="vec4(1.0)";null!=r&&(Zo(e,r),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`\n      void main() {\n        vec4 offset = ${i};\n        vec4 scale = ${o};\n\n        vec4 x = getXAtOutCoords();\n        vec4 mean = getMeanAtOutCoords();\n        vec4 variance = getVarianceAtOutCoords();\n\n        vec4 inv = scale * inversesqrt(variance + vec4(${a}));\n\n        setOutput((x - mean) * inv + offset);\n      }\n    `}}const CM={kernelName:ht,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s,mean:r,variance:a,offset:i,scale:o}=e;c(r.shape.length===a.shape.length,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),c(null==i||r.shape.length===i.shape.length,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),c(null==o||r.shape.length===o.shape.length,(()=>"Batch normalization gradient requires mean and scale to have equal ranks."));let{varianceEpsilon:l}=n;null==l&&(l=.001);const u=[s,r,a];let h=null;null!=i&&(h=i.shape,u.push(i));let p=null;null!=o&&(p=o.shape,u.push(o));const d=Y().getBool("WEBGL_PACK_NORMALIZATION")?new TM(s.shape,r.shape,a.shape,h,p,l):new SM(s.shape,r.shape,a.shape,h,p,l);return t.runWebGLProgram(d,u,u[0].dtype)}};class $M{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=sF(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const n=function(e){if(1===e)return"sourceLoc";if(e<=6)return EM.slice(0,e).map((e=>"sourceLoc."+e)).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}(this.rank);let s;s=`\n        ${t} sourceLoc;\n        ${t} coords = getOutputCoords();\n        ${e.map(((e,t)=>`sourceLoc.${EM[t]} = start[${t}] + coords.${EM[t]};`)).join("\n")}\n      `,this.userCode=`\n      void main() {\n        ${s}\n        setOutput(getSource(${n}));\n      }\n    `}}const EM=["x","y","z","w","u","v"];class AM{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const t=sF(this.rank),n=LD("coords",this.rank),s=LD("sourceLoc",this.rank),r=1===this.rank?"sourceLoc":`vec2(${s.slice(-2).join()})`,a=`getChannel(getSource(${s.join()}), ${r})`,i=`\n      result.x = ${a};\n      if (++${n[this.rank-1]} < ${e[this.rank-1]}) {\n        ++${s[this.rank-1]};\n        result.y = ${a};\n        --${s[this.rank-1]};\n      }\n    `,o=1===this.rank?"":`\n      --${n[this.rank-1]};\n      if (++${n[this.rank-2]} < ${e[this.rank-2]}) {\n        ++${s[this.rank-2]};\n        result.z = ${a};\n        if (++${n[this.rank-1]} < ${e[this.rank-1]}) {\n          ++${s[this.rank-1]};\n          result.w = ${a};\n        }\n      }\n    `,l=this.rank<=4?`sourceLoc = coords +\n            ${t}(${e.map(((e,t)=>`start[${t}]`)).join()});`:e.map(((e,t)=>`${s[t]} = ${n[t]} + start[${t}];`)).join("\n");this.userCode=`\n      void main() {\n        ${t} coords = getOutputCoords();\n        ${t} sourceLoc;\n        ${l}\n        vec4 result = vec4(0.);\n        ${i}\n        ${o}\n        setOutput(result);\n      }\n    `}}function RM(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,size:i}=s,[o,l]=jd(r,a,i);if(Dd(r,o,l),0===d(l))return n.makeTensorInfo(l,r.dtype,[]);if(n.shouldExecuteOnCPU([r])||"string"===r.dtype){const e=n.texData.get(r.dataId),t=vD(e.values,o,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,t)}const{isPacked:u}=n.texData.get(r.dataId),c=Gd(r.shape,o,l);if(u||!c){const e=Y().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new AM(l):new $M(l),t=[o];return n.runWebGLProgram(e,[r],r.dtype,t)}return n.uploadToGPU(r.dataId),function(e,t,n,s){const r=s.texData.get(e.dataId),a=s.makeTensorInfo(n,e.dtype),i=s.texData.get(a.dataId);Object.assign(i,r),i.refCount=1,i.shape=n,i.dtype=e.dtype;let o=Hd(t,M(e.shape));r.slice&&(o+=r.slice.flatOffset),i.slice={flatOffset:o,origDataId:r.slice&&r.slice.origDataId||e.dataId};const l=s.dataRefCount.get(i.slice.origDataId)||1;return s.dataRefCount.set(i.slice.origDataId,l+1),a}(r,o,l,n)}const _M={kernelName:$n,backendName:"webgl",kernelFunc:RM},FM={kernelName:xe,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,crops:i}=s;c(r.shape.length<=4,(()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"));const o=a.reduce(((e,t)=>e*t)),l=hf(r.shape,a,o),u=pf(l.length,a.length),h=df(r.shape,a,o),p=ff(i,a.length),d=mf(h,i,a.length),f=[],m=SO({inputs:{x:r},backend:n,attrs:{shape:l}}),g=OO({inputs:{x:m},backend:n,attrs:{perm:u}}),y=SO({inputs:{x:g},backend:n,attrs:{shape:h}}),b=RM({inputs:{x:y},backend:n,attrs:{begin:p,size:d}});return f.push(m),f.push(g),f.push(y),f.forEach((e=>n.disposeIntermediateTensorInfo(e))),b}};const DM={kernelName:we,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,weights:a}=t,{size:i}=s,o=n.readSync(r.dataId),l=n.readSync(a.dataId),u=VF(o,l,a.dtype,a.shape,i);return n.makeTensorInfo([i],a.dtype,u)}};const OM={kernelName:ve,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{a:s,b:r}=t,a=Y().getBool("WEBGL_PACK_BINARY_OPERATIONS"),i=Y().getNumber("WEBGL_VERSION");if(n.shouldExecuteOnCPU([s,r])||1===i){const e=n.texData.get(s.dataId).values,t=n.texData.get(r.dataId).values,[a,i]=GF(s.shape,r.shape,e,t,s.dtype),o=n.makeTensorInfo(i,s.dtype);return n.texData.get(o.dataId).values=a,o}let o;return o=a?new rO("\n  int r = int(a.r) & int(b.r);\n  int g = int(a.g) & int(b.g);\n  int rb = int(a.b) & int(b.b);\n  int ra = int(a.a) & int(b.a);\n  return vec4(r, g, rb, ra);\n",s.shape,r.shape,!1):new nO("\n  return float(int(a.r) & int(b.r));\n",s.shape,r.shape),n.runWebGLProgram(o,[s,r],s.dtype)}};const MM={kernelName:Ne,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{s0:s,s1:r}=t,a=n.readSync(s.dataId),i=n.readSync(r.dataId),o=Zo(Array.from(a),Array.from(i));return n.makeTensorInfo([o.length],"int32",Int32Array.from(o))}},LM=gO({opSnippet:"return float(a != b);",cpuKernelImpl:hD,dtype:"bool"}),zM={kernelName:Xt,backendName:"webgl",kernelFunc:LM};function PM(e){const{inputs:t,backend:n}=e,{input:s}=t;return aO({inputs:{x:n.texData.get(s.dataId).complexTensorInfos.real},backend:n})}const BM={kernelName:hn,backendName:"webgl",kernelFunc:PM};const WM={kernelName:Ie,backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:s,attrs:r}=t,{x:a}=n,{dtype:i}=r;if("complex64"===i){if("complex64"===a.dtype)return aO({inputs:{x:a},backend:s});const t=du(a.shape),n=e({inputs:{x:a},backend:s,attrs:{dtype:"float32"}}),r=oO({inputs:{real:n,imag:t},backend:s});return t.dispose(),s.disposeIntermediateTensorInfo(n),r}if("complex64"===a.dtype){const t=PM({inputs:{input:a},backend:s}),n=e({inputs:{x:t},backend:s,attrs:{dtype:i}});return s.disposeIntermediateTensorInfo(t),n}if(!C(a.dtype,i)){const e=aO({inputs:{x:a},backend:s});return{dataId:e.dataId,shape:e.shape,dtype:i}}if(s.shouldExecuteOnCPU([a])){const e=s.texData.get(a.dataId).values,[t,n,r]=HF(e,a.shape,a.dtype,i);return s.makeTensorInfo(t,n,r)}if("int32"===i)return function(e,t){const n=new GD(e.shape,"return float(int(x));"),s=t.runWebGLProgram(n,[e],"int32");return{dataId:s.dataId,shape:s.shape,dtype:s.dtype}}(a,s);if("bool"===i){const e=s.makeTensorInfo([],"bool",N("bool",1)),t=LM({inputs:{a:a,b:e},backend:s});return s.disposeIntermediateTensorInfo(e),t}throw new Error(`Error in Cast: failed to cast ${a.dtype} to ${i}`)}},VM="return ceil(x);",UM=mO({opSnippet:VM,packedOpSnippet:VM,cpuKernelImpl:jF}),GM={kernelName:Se,backendName:"webgl",kernelFunc:UM};class HM{constructor(e){this.variableNames=["A"],this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode="\n\n      void main() {\n        float value = getAAtOutCoords();\n        if (isnan(value)) {\n          setOutput(value);\n          return;\n        }\n\n        setOutput(clamp(value, minVal, maxVal));\n      }\n    "}}class jM{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"minVal",type:"float"},{name:"maxVal",type:"float"}],this.outputShape=e,this.userCode="\n      void main() {\n        vec4 value = getAAtOutCoords();\n\n        if (any(isnan(value))) {\n          setOutput(value);\n          return;\n        }\n\n        setOutput(clamp(value, vec4(minVal), vec4(maxVal)));\n      }\n    "}}const qM={kernelName:Te,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{clipValueMin:a,clipValueMax:i}=s;let o;o=Y().getBool("WEBGL_PACK_CLIP")?new jM(r.shape):new HM(r.shape);const l=[[a],[i]];return n.runWebGLProgram(o,[r],r.dtype,l)}};class KM{constructor(e){this.variableNames=["real","imag"],this.outputShape=e,this.userCode="\n      void main() {\n        float re = abs(getRealAtOutCoords());\n        float im = abs(getImagAtOutCoords());\n        float mx = max(re, im);\n\n        // sadly the length function in glsl is not underflow-safe\n        // (at least not on Intel GPUs). So the safe solution is\n        // to ensure underflow-safety in all cases.\n        setOutput(\n          mx == 0.0 ? 0.0 : mx * length(vec2(1, min(re, im)/mx))\n        );\n      }\n    "}}function XM(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}const YM={kernelName:$e,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:s}=t,r=n.texData.get(s.dataId),a=new KM(s.shape),i=[XM(s,r.complexTensorInfos.real),XM(s,r.complexTensorInfos.imag)];return n.runWebGLProgram(a,i,i[0].dtype)}};class ZM{constructor(e){this.outputShape=[],this.outputShape=nf(e,1),this.variableNames=e.map(((e,t)=>`T${t}`));const t=new Array(e.length-1);t[0]=e[0][1];for(let n=1;n<t.length;n++)t[n]=t[n-1]+e[n][1];const n=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let e=1;e<t.length;e++){const s=t[e-1];n.push(`else if (yC < ${t[e]}) setOutput(getT${e}(yR, yC-${s}));`)}const s=t.length,r=t[t.length-1];n.push(`else setOutput(getT${s}(yR, yC-${r}));`),this.userCode=`\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int yR = coords.x;\n        int yC = coords.y;\n\n        ${n.join("\n        ")}\n      }\n    `}}class JM{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=nf(e,t);const n=this.outputShape,s=n.length,r=sF(s),a=LD("coords",s),i=["x","y","z","w","u","v"].slice(0,s);this.variableNames=e.map(((e,t)=>`T${t}`));const o=new Array(e.length-1);o[0]=e[0][t];for(let n=1;n<o.length;n++)o[n]=o[n-1]+e[n][t];const l=i[t],u=i.slice(-2),c=i.join();let h=`if (${l} < ${o[0]}) {\n        return getChannel(\n            getT0(${c}), vec2(${u.join()}));\n        }`;for(let e=1;e<o.length;e++){const t=o[e-1];h+=`\n        if (${l} < ${o[e]}  && ${l} >= ${o[e-1]}) {\n          return getChannel(\n            getT${e}(${QM(i,l,t)}),\n            vec2(${QM(u,l,t)}));\n        }`}const p=o.length,d=o[o.length-1];h+=`\n        return getChannel(\n          getT${p}(${QM(i,l,d)}),\n          vec2(${QM(u,l,d)}));`,this.userCode=`\n      float getValue(${i.map((e=>"int "+e))}) {\n        ${h}\n      }\n\n      void main() {\n        ${r} coords = getOutputCoords();\n        vec4 result = vec4(getValue(${a}), 0., 0., 0.);\n\n        ${a[s-1]} = ${a[s-1]} + 1;\n        if (${a[s-1]} < ${n[s-1]}) {\n          result.g = getValue(${a});\n        }\n\n        ${a[s-2]} = ${a[s-2]} + 1;\n        if (${a[s-2]} < ${n[s-2]}) {\n          result.a = getValue(${a});\n        }\n\n        ${a[s-1]} = ${a[s-1]} - 1;\n        if (${a[s-2]} < ${n[s-2]} &&\n            ${a[s-1]} < ${n[s-1]}) {\n          result.b = getValue(${a});\n        }\n        setOutput(result);\n      }\n    `}}function QM(e,t,n){const s=e.indexOf(t);return e.map(((e,t)=>t===s?`${e} - ${n}`:e)).join()}function eL(e){const{inputs:t,backend:n}=e,{input:s}=t;return aO({inputs:{x:n.texData.get(s.dataId).complexTensorInfos.imag},backend:n})}const tL={kernelName:bt,backendName:"webgl",kernelFunc:eL};function nL(e,t,n){const s=e[0].dtype;if("complex64"===s){const s=e.map((e=>PM({inputs:{input:e},backend:n}))),r=e.map((e=>eL({inputs:{input:e},backend:n}))),a=nL(s,t,n),i=nL(r,t,n),o=oO({inputs:{real:a,imag:i},backend:n});return s.forEach((e=>n.disposeIntermediateTensorInfo(e))),r.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(i),o}let r=n.shouldExecuteOnCPU(e);if("string"===s&&(r=!0),r){const r=e.map((e=>{const s=d(e.shape.slice(t));return SO({inputs:{x:e},backend:n,attrs:{shape:[-1,s]}})})),a=r.map((e=>({vals:n.readSync(e.dataId),shape:e.shape}))),i=nf(r.map((e=>e.shape)),1),o=1===r[0].shape[0],l=qF(a,i,s,o),u=nf(e.map((e=>e.shape)),t),c=n.makeTensorInfo(u,s,l);return r.forEach((e=>n.disposeIntermediateTensorInfo(e))),c}const a=e.filter((e=>d(e.shape)>0)),i=Y().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&a[0].shape.length>1;if(1===a.length){const t=i?new GD(e[0].shape,jD):new qD(e[0].shape,jD);return n.runWebGLProgram(t,e,s)}const o=Y().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER");if(a.length>o){const e=[];for(let s=0;s<a.length;s+=o){const r=a.slice(s,s+o);e.push(nL(r,t,n))}const s=nL(e,t,n);for(const t of e)n.disposeIntermediateTensorInfo(t);return s}if(i){const e=new JM(a.map((e=>e.shape)),t);return n.runWebGLProgram(e,a,s)}const{tensors2D:l,outShape:u}=function(e,t,n){const s=nf(e.map((e=>e.shape)),t);return{tensors2D:e.map((e=>SO({inputs:{x:e},attrs:{shape:[-1,d(e.shape.slice(t))]},backend:n}))),outShape:s}}(a,t,n),c=new ZM(l.map((e=>e.shape))),h=n.runWebGLProgram(c,l,s);l.forEach((e=>n.disposeIntermediateTensorInfo(e)));const p=SO({inputs:{x:h},attrs:{shape:u},backend:n});return n.disposeIntermediateTensorInfo(h),p}function sL(e){const{inputs:t,backend:n,attrs:s}=e,{axis:r}=s,a=v(r,t[0].shape)[0];tf(t.map((e=>e.shape)),a);const i=nf(t.map((e=>e.shape)),a);if(0===d(i))return n.makeTensorInfo(i,t[0].dtype,[]);const o=t.filter((e=>d(e.shape)>0));return 1===o.length?aO({inputs:{x:o[0]},backend:n}):nL(o,a,n)}const rL={kernelName:Ee,backendName:"webgl",kernelFunc:sL};class aL{constructor(e,t=!1,n=null,s=!1,r=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;const a=e.padInfo.top,i=e.padInfo.left,o=e.strideHeight,l=e.strideWidth,u=e.dilationHeight,c=e.dilationWidth,h=e.filterHeight,p=e.filterWidth,d=4*Math.floor(e.inChannels/4),f=e.inChannels%4,m="channelsLast"===e.dataFormat,g=m?1:2,y=m?2:3,b=m?3:1;let x="",w="";n&&(x=s?`float activation(float a) {\n          float b = getPreluActivationWeightsAtOutCoords();\n          ${n}\n        }`:r?`float activation(float a) {\n          float b = getLeakyreluAlphaAtOutCoords();\n          ${n}\n        }`:`\n          float activation(float x) {\n            ${n}\n          }\n        `,w="result = activation(result);");const v=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n      ${x}\n\n      const ivec2 strides = ivec2(${o}, ${l});\n      const ivec2 pads = ivec2(${a}, ${i});\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d2 = coords[${b}];\n\n        ivec2 xRCCorner =\n            ivec2(coords[${g}], coords[${y}]) * strides - pads;\n        int xRCorner = xRCCorner.x;\n        int xCCorner = xRCCorner.y;\n\n        // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        for (int wR = 0; wR < ${h}; wR++) {\n          int xR = xRCorner + wR * ${u};\n\n          if (xR < 0 || xR >= ${e.inHeight}) {\n            continue;\n          }\n\n          for (int wC = 0; wC < ${p}; wC++) {\n            int xC = xCCorner + wC * ${c};\n\n            if (xC < 0 || xC >= ${e.inWidth}) {\n              continue;\n            }\n\n            for (int d1 = 0; d1 < ${d}; d1 += 4) {\n              vec4 wValues = vec4(\n                getW(wR, wC, d1, d2),\n                getW(wR, wC, d1 + 1, d2),\n                getW(wR, wC, d1 + 2, d2),\n                getW(wR, wC, d1 + 3, d2)\n              );\n\n              if (${m}) {\n                vec4 xValues = vec4(\n                  getX(batch, xR, xC, d1),\n                  getX(batch, xR, xC, d1 + 1),\n                  getX(batch, xR, xC, d1 + 2),\n                  getX(batch, xR, xC, d1 + 3)\n                );\n                dotProd += dot(xValues, wValues);\n              } else {\n                vec4 xValues = vec4(\n                  getX(batch, d1, xR, xC),\n                  getX(batch, d1 + 1, xR, xC),\n                  getX(batch, d1 + 2, xR, xC),\n                  getX(batch, d1 + 3, xR, xC)\n                );\n                dotProd += dot(xValues, wValues);\n              }\n            }\n\n            if (${1===f}) {\n\n              if (${m}) {\n                dotProd +=\n                    getX(batch, xR, xC, ${d}) *\n                    getW(wR, wC, ${d}, d2);\n              } else {\n                dotProd +=\n                    getX(batch, ${d}, xR, xC) *\n                    getW(wR, wC, ${d}, d2);\n              }\n\n            } else if (${2===f}) {\n              vec2 wValues = vec2(\n                getW(wR, wC, ${d}, d2),\n                getW(wR, wC, ${d} + 1, d2)\n              );\n\n              if (${m}) {\n                vec2 xValues = vec2(\n                  getX(batch, xR, xC, ${d}),\n                  getX(batch, xR, xC, ${d} + 1)\n                );\n                dotProd += dot(xValues, wValues);\n              } else {\n                vec2 xValues = vec2(\n                  getX(batch, ${d}, xR, xC),\n                  getX(batch, ${d} + 1, xR, xC)\n                );\n                dotProd += dot(xValues, wValues);\n              }\n\n            } else if (${3===f}) {\n              vec3 wValues = vec3(\n                getW(wR, wC, ${d}, d2),\n                getW(wR, wC, ${d} + 1, d2),\n                getW(wR, wC, ${d} + 2, d2)\n              );\n\n              if (${m}) {\n                vec3 xValues = vec3(\n                  getX(batch, xR, xC, ${d}),\n                  getX(batch, xR, xC, ${d} + 1),\n                  getX(batch, xR, xC, ${d} + 2)\n                );\n                dotProd += dot(xValues, wValues);\n              } else {\n                vec3 xValues = vec3(\n                  getX(batch, ${d}, xR, xC),\n                  getX(batch, ${d} + 1, xR, xC),\n                  getX(batch, ${d} + 2, xR, xC)\n                );\n                dotProd += dot(xValues, wValues);\n              }\n\n            }\n          }\n        }\n\n        float result = dotProd;\n        ${v}\n        ${w}\n        setOutput(result);\n      }\n    `}}class iL{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const t=e.padInfo.front,n=e.padInfo.top,s=e.padInfo.left,r=e.strideDepth,a=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,l=e.dilationHeight,u=e.dilationWidth,c=e.filterDepth,h=e.filterHeight,p=e.filterWidth,d=4*Math.floor(e.inChannels/4),f=e.inChannels%4;this.userCode=`\n      const ivec3 strides = ivec3(${r}, ${a}, ${i});\n      const ivec3 pads = ivec3(${t}, ${n}, ${s});\n\n      void main() {\n        ivec5 coords = getOutputCoords();\n        int batch = coords.x;\n        int d2 = coords.u;\n\n        ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;\n        int xFCorner = xFRCCorner.x;\n        int xRCorner = xFRCCorner.y;\n        int xCCorner = xFRCCorner.z;\n\n        // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get\n        // y(yF, yR, yC, d2). ? = to be determined. : = across all\n        // values in that axis.\n        float dotProd = 0.0;\n        for (int wF = 0; wF < ${c}; wF++) {\n          int xF = xFCorner + wF * ${o};\n\n          if (xF < 0 || xF >= ${e.inDepth}) {\n            continue;\n          }\n\n          for (int wR = 0; wR < ${h}; wR++) {\n            int xR = xRCorner + wR * ${l};\n\n            if (xR < 0 || xR >= ${e.inHeight}) {\n              continue;\n            }\n\n            for (int wC = 0; wC < ${p}; wC++) {\n              int xC = xCCorner + wC * ${u};\n\n              if (xC < 0 || xC >= ${e.inWidth}) {\n                continue;\n              }\n\n              for (int d1 = 0; d1 < ${d}; d1 += 4) {\n                vec4 xValues = vec4(\n                  getX(batch, xF, xR, xC, d1),\n                  getX(batch, xF, xR, xC, d1 + 1),\n                  getX(batch, xF, xR, xC, d1 + 2),\n                  getX(batch, xF, xR, xC, d1 + 3)\n                );\n                vec4 wValues = vec4(\n                  getW(wF, wR, wC, d1, d2),\n                  getW(wF, wR, wC, d1 + 1, d2),\n                  getW(wF, wR, wC, d1 + 2, d2),\n                  getW(wF, wR, wC, d1 + 3, d2)\n                );\n\n                dotProd += dot(xValues, wValues);\n              }\n\n              if (${1===f}) {\n                dotProd +=\n                  getX(batch, xF, xR, xC, ${d}) *\n                  getW(wF, wR, wC, ${d}, d2);\n              } else if (${2===f}) {\n                vec2 xValues = vec2(\n                  getX(batch, xF, xR, xC, ${d}),\n                  getX(batch, xF, xR, xC, ${d} + 1)\n                );\n                vec2 wValues = vec2(\n                  getW(wF, wR, wC, ${d}, d2),\n                  getW(wF, wR, wC, ${d} + 1, d2)\n                );\n                dotProd += dot(xValues, wValues);\n              } else if (${3===f}) {\n                vec3 xValues = vec3(\n                  getX(batch, xF, xR, xC, ${d}),\n                  getX(batch, xF, xR, xC, ${d} + 1),\n                  getX(batch, xF, xR, xC, ${d} + 2)\n                );\n                vec3 wValues = vec3(\n                  getW(wF, wR, wC, ${d}, d2),\n                  getW(wF, wR, wC, ${d} + 1, d2),\n                  getW(wF, wR, wC, ${d} + 2, d2)\n                );\n                dotProd += dot(xValues, wValues);\n              }\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    `}}class oL{constructor(e,t=!1,n=null,s=!1,r=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=uF(this.outputShape.length);const a=e.padInfo.left,i=e.strideWidth,l=e.dilationWidth,u=e.filterHeight,c=e.filterWidth,h=c;let p="\n       int xR; int xC; int xCOffset;\n       vec4 wTexel; vec4 previous; vec4 final;";for(let e=0;e<c;e++)p+=`\n           vec4 xTexelC${2*e};\n           int xTexelC${2*e}Ready;\n           vec4 xTexelC${2*e+1};\n           int xTexelC${2*e+1}Ready;\n           vec4 xC${e};`;p+=`\n     for (int r = 0; r < ${u}; r++) {\n      for (int d1 = 0; d1 < ${e.inChannels}; d1 += 2) {\n       `;for(let e=0;e<c;e++)p+=`\n           xTexelC${2*e} = vec4(0.0);\n           xTexelC${2*e}Ready = 0;\n           xTexelC${2*e+1} = vec4(0.0);\n           xTexelC${2*e+1}Ready = 0;\n           xC${e} = vec4(0.0);`;p+="\n         xR = xRCorner + r * dilations[0];\n         if (xR >=0 && xR < inDims[0]) {\n       ";for(let t=0;t<(h+1)/2;t++){const n=2*t;if(p+=`\n           xC = xCCorner + ${n*l};\n           `,1===i){if(n<c&&(a%2==1?(p+=`\n                 xCOffset = xC + 1;\n                 if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n}Ready == 0) {\n                   xTexelC${n} = getX(batch, xR, xCOffset, d1);\n\n                   // Need to manually clear unused channels in case\n                   // we're reading from recycled texture.\n                   if (xCOffset + 1 >= inDims[1]) {\n                     xTexelC${n}.zw = vec2(0.0);\n                   }\n                   xTexelC${n}Ready = 1;\n                 }\n               `,p+=1===l&&n>0?`\n                 xC${n} = vec4(xTexelC${n-2}.zw, xTexelC${n}.xy);\n                 `:`\n                   xCOffset = xC + 1 - 2;\n\n                   if (xCOffset >= 0 && xCOffset < inDims[1]) {\n                     previous = getX(batch, xR, xCOffset, d1);\n\n                     // Need to manually clear unused channels in case\n                     // we're reading from recycled texture.\n                     if (xCOffset + 1 >= inDims[1]) {\n                       previous.zw = vec2(0.0);\n                     }\n\n                     xC${n} = vec4(previous.zw, xTexelC${n}.xy);\n                   } else {\n                     xC${n} = vec4(0.0, 0.0, xTexelC${n}.xy);\n                   }\n                   `):p+=`\n                 if (xC >= 0 && xC < inDims[1] && xTexelC${n}Ready == 0) {\n                   xTexelC${n} = getX(batch, xR, xC, d1);\n                   if (xC + 1 >= inDims[1]) {\n                     xTexelC${n}.zw = vec2(0.0);\n                   }\n                   xTexelC${n}Ready = 1;\n                 }\n\n                 xC${n} = xTexelC${n};\n                 `,n+1<c)){const e=a%2==0?o(l):l;l%2==0&&a%2==1||l%2!=0&&a%2!=1?(p+=`\n                   xCOffset = xC + imod(pads[1], 2) + ${e};\n\n                   if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n+1}Ready == 0) {\n                     xTexelC${n+1} = getX(batch, xR, xCOffset, d1);\n\n                     // Need to manually clear unused channels in case\n                     // we're reading from recycled texture.\n                     if (xCOffset + 1 >= inDims[1]) {\n                       xTexelC${n+1}.zw = vec2(0.0);\n                     }\n                     xTexelC${n+1}Ready = 1;\n                   }\n                   `,p+=l>1?`\n                     xCOffset -= 2;\n                     if (xCOffset >= 0 && xCOffset < inDims[1]) {\n                      previous = getX(batch, xR, xCOffset, d1);\n                      xC${n+1} = vec4(previous.zw, xTexelC${n+1}.xy);\n                     } else {\n                      xC${n+1} = vec4(0.0, 0.0, xTexelC${n+1}.xy);\n                     }\n                     `:`\n                     xC${n+1} = vec4(xTexelC${n}.zw, xTexelC${n+1}.xy);\n                     `):p+=1===e?`\n                     xC${n+1} = xTexelC${n};\n                     `:`\n                     xCOffset = xC + ${e};\n\n                     if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n+1}Ready == 0) {\n                       xTexelC${n+1} = getX(batch, xR, xCOffset, d1);\n                       if (xCOffset + 1 >= inDims[1]) {\n                         xTexelC${n+1}.zw = vec2(0.0);\n                       }\n                       xTexelC${n+1}Ready = 1;\n                     }\n\n                     xC${n+1} = xTexelC${n+1};\n                     `}}else n<c&&(a%2==1?(p+=`\n                 xCOffset = xC + 1 - strides[1];\n                 if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n}Ready == 0) {\n                   xTexelC${n} = getX(batch, xR, xCOffset, d1);\n                   // Need to manually clear unused channels in case\n                   // we're reading from recycled texture.\n                   if (xCOffset + 1 >= inDims[1]) {\n                     xTexelC${n}.zw = vec2(0.0);\n                   }\n                   xTexelC${n}Ready = 1;\n                 }\n\n                 if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${n+1}Ready == 0) {\n                   xTexelC${n+1} = getX(batch, xR, xC + 1, d1);\n                   // Need to manually clear unused channels in case\n                   // we're reading from recycled texture.\n                   if (xC + 2 >= inDims[1]) {\n                     xTexelC${n+1}.zw = vec2(0.0);\n                   }\n                   xTexelC${n+1}Ready = 1;\n                 }\n\n                 xC${n} = vec4(xTexelC${n}.zw, xTexelC${n+1}.zw);\n               `,n+1<c&&(p+=`\n                   final = vec4(0.0);\n                   xCOffset = xC + 1 + strides[1];\n                   if(xCOffset >= 0 && xCOffset < inDims[1]) {\n                     final = getX(batch, xR, xCOffset, d1);\n                   }\n                   xC${n+1} = vec4(xTexelC${n+1}.xy, final.xy);\n                 `)):(p+=`\n                 if(xC >= 0 && xC < inDims[1] && xTexelC${n}Ready == 0) {\n                   xTexelC${n} = getX(batch, xR, xC, d1);\n                   if (xC + 1 >= inDims[1]) {\n                     xTexelC${n}.zw = vec2(0.0);\n                   }\n                   xTexelC${n}Ready = 1;\n                 }\n\n                 xCOffset = xC + strides[1];\n                 if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${n+1}Ready == 0) {\n                   xTexelC${n+1} = getX(batch, xR, xCOffset, d1);\n                   if (xCOffset + 1 >= inDims[1]) {\n                     xTexelC${n+1}.zw = vec2(0.);\n                   }\n                   xTexelC${n+1}Ready = 1;\n                 }\n\n                 xC${n} = vec4(\n                   xTexelC${n}.xy, xTexelC${n+1}.xy);\n               `,n+1<c&&(p+=`\n                   xC${n+1} = vec4(xTexelC${n}.zw, xTexelC${n+1}.zw);\n                 `)));n<c&&(p+=`\n             wTexel = getW(r, ${n}, d1, d2);\n             dotProd += xC${n}.xxzz * vec4(wTexel.xy, wTexel.xy);\n             if(d1 + 1 < ${e.inChannels}) {\n               dotProd += xC${n}.yyww * vec4(wTexel.zw, wTexel.zw);\n             }\n           `,n+1<c&&(p+=`\n               wTexel = getW(r, ${n+1}, d1, d2);\n               dotProd += xC${n+1}.xxzz * vec4(wTexel.xy, wTexel.xy);\n               if(d1 + 1 < ${e.inChannels}) {\n                 dotProd += xC${n+1}.yyww * vec4(wTexel.zw, wTexel.zw);\n               }\n             `))}p+="\n     }\n   ",p+="\n     }\n   ",p+="\n     }\n   ";let d="",f="";n&&(d=s?`vec4 activation(vec4 a) {\n           vec4 b = getPreluActivationWeightsAtOutCoords();\n           ${n}\n         }`:r?`vec4 activation(vec4 a) {\n           vec4 b = getLeakyreluAlphaAtOutCoords();\n           ${n}\n         }`:`vec4 activation(vec4 x) {\n           ${n}\n         }`,f="result = activation(result);");const m=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n       ${d}\n\n       void main() {\n         ivec4 coords = getOutputCoords();\n         int batch = coords.x;\n         ivec2 xRCCorner = coords.yz * strides - pads;\n         int d2 = coords.w;\n         int xRCorner = xRCCorner.x;\n         int xCCorner = xRCCorner.y;\n\n         //intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.\n         vec4 dotProd = vec4(0.000000000000001);\n\n         ${p}\n\n         vec4 result = dotProd - vec4(0.000000000000001);\n         ${m}\n         ${f}\n         setOutput(result);\n       }\n     `}}class lL{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec4"},{name:"pad",type:"ivec2"},{name:"stride",type:"ivec2"},{name:"dilation",type:"ivec2"},{name:"inChannels",type:"int"},{name:"itemsPerBlockRow",type:"int"},{name:"outWidth",type:"int"}],this.outputShape=e,this.enableShapeUniforms=uF(this.outputShape.length);const{dataFormat:n}=t,s=B_(),r="channelsLast"===n,a=r?1:2,i=r?2:3,o=this.enableShapeUniforms?"if(blockIndex < outShape[2] && pos < outShape[1]) {":`if(blockIndex < ${e[2]} && pos < ${e[1]}) {`;let l="";for(let e=0;e<=1;e++)for(let t=0;t<=1;t++)l+=`\n          blockIndex = rc.z + ${t};\n          pos = rc.y + ${e};\n\n          ${o}\n            offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];\n            d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);\n\n            if(d0 < inputShape[${a}] && d0 >= 0) {\n              // Use custom imod instead mod. On Intel GPU, mod may generate\n              // unexpected value.\n              // https://github.com/tensorflow/tfjs/issues/5447\n              offsetX = imod(blockIndex, outWidth) * stride[1] - pad[1];\n              d1 = offsetX + dilation[1] * (imod(pos, itemsPerBlockRow) /\n                  inChannels);\n\n              if(d1 < inputShape[${i}] && d1 >= 0) {\n\n                ch = imod(pos, inChannels);\n\n                if (${r}) {\n                  innerDims = vec2(d1, ch);\n                  result[${2*e+t}] = getChannel(\n                    getA(rc.x, d0, int(innerDims.x),\n                    int(innerDims.y)), innerDims);\n                } else {\n                  innerDims = vec2(d0, d1);\n                  result[${2*e+t}] = getChannel(\n                    getA(rc.x, ch, int(innerDims.x),\n                    int(innerDims.y)), innerDims);\n                }\n              }\n            }\n          }\n        `;this.userCode=`\n      void main() {\n        ivec3 rc = getOutputCoords();\n\n        vec4 result = vec4(0);\n\n        int blockIndex, pos, offsetY, d0, offsetX, d1, ch;\n        vec2 innerDims;\n\n        ${l}\n\n        ${s.output} = result;\n      }\n    `}}function uL(e,t){const n=e.length;return n>=3?t?[...e.slice(0,-3),e[n-3]*e[n-2],e[n-1]]:[...e.slice(0,-3),e[n-3],e[n-2]*e[n-1]]:!t&&1===n&&e[0]>1?[e[0],1]:null}function cL({x:e,filter:t,convInfo:n,backend:s,bias:r=null,preluActivationWeights:a=null,leakyreluAlpha:i=0,activation:o=null}){const l=e.shape,u=s.texData.get(e.dataId),h=n.inChannels,p=l[0]*l[1]*l[2],d=n.outChannels,f="channelsLast"===n.dataFormat;let g;const y=[];if(null!=a){const e=uL(a.shape,f);null!=e&&(a=SO({inputs:{x:a},backend:s,attrs:{shape:e}}),y.push(a))}if(null!=r){const e=uL(r.shape,f);null!=e&&(r=SO({inputs:{x:r},backend:s,attrs:{shape:e}}),y.push(r))}if(!((1===p||1===d)&&h>1e3)&&u.isPacked&&f&&null!=u.texture&&l[2]%2!=0&&m(u.shape.slice(-3),l.slice(-3))){const h=l[0]*l[1]*(l[2]+1),p={dataId:e.dataId,shape:[1,h,n.inChannels],dtype:e.dtype},d=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,c(S_(u.shape,p.shape),(()=>`packed reshape ${u.shape} to ${p.shape} isn't free`));const f=SO({inputs:{x:t},backend:s,attrs:{shape:[1,n.inChannels,n.outChannels]}});y.push(f);const m=LO({a:p,b:f,backend:s,transposeA:false,transposeB:false,bias:r,activation:o,preluActivationWeights:a,leakyreluAlpha:i}),b=s.texData.get(m.dataId);c(b.isPacked,(()=>"batchMatMul result is expected to be packed")),u.shape=d,b.shape=n.outShape,g=aO({inputs:{x:m},backend:s}),g.shape=n.outShape,y.push(m)}else{const l=n.outHeight*n.outWidth,u=SO({inputs:{x:e},backend:s,attrs:{shape:f?[n.batchSize,l,n.inChannels]:[n.batchSize,n.inChannels,l]}}),c=SO({inputs:{x:t},backend:s,attrs:{shape:[1,n.inChannels,n.outChannels]}}),h=LO({a:f?u:c,b:f?c:u,transposeA:!f,transposeB:false,backend:s,bias:r,activation:o,preluActivationWeights:a,leakyreluAlpha:i});g=SO({inputs:{x:h},backend:s,attrs:{shape:n.outShape}}),y.push(u),y.push(c),y.push(h)}for(const e of y)s.disposeIntermediateTensorInfo(e);return g}function hL({x:e,filter:t,convInfo:n,backend:s,bias:r=null,preluActivationWeights:a=null,leakyreluAlpha:i=0,activation:o=null}){const{filterWidth:l,filterHeight:u,inChannels:c,outWidth:h,outHeight:p,dataFormat:f}=n,m="channelsLast"===f,g=l*u*c,y=p*h,b=[n.batchSize,g,y],x=[];if(null!=a){const e=uL(a.shape,m);null!=e&&(a=SO({inputs:{x:a},backend:s,attrs:{shape:e}}),x.push(a))}if(null!=r){const e=uL(r.shape,m);null!=e&&(r=SO({inputs:{x:r},backend:s,attrs:{shape:e}}),x.push(r))}const w=SO({inputs:{x:t},backend:s,attrs:{shape:[1,g,d(t.shape)/g]}});x.push(w);const v=new lL(b,n),k=[e.shape,[n.padInfo.top,n.padInfo.left],[n.strideHeight,n.strideWidth],[n.dilationHeight,n.dilationWidth],[n.inChannels],[n.filterWidth*n.inChannels],[n.outWidth]],N=s.runWebGLProgram(v,[e],"float32",k),I=SO({inputs:{x:N},backend:s,attrs:{shape:b}});x.push(N),x.push(I);const S=null!=r,T=null!=a,C="leakyrelu"===o,$=o?yO(o,!0):null,E=new bO(m?I.shape:w.shape,m?w.shape:I.shape,m?[n.batchSize,y,n.outChannels]:[n.batchSize,n.outChannels,y],!0,!1,S,$,T,C),A=m?[I,w]:[w,I];if(r&&A.push(r),T&&A.push(a),C){const e=s.makeTensorInfo([],"float32",hr(i,"float32"));A.push(e),x.push(e)}const R=s.runWebGLProgram(E,A,"float32"),_=SO({inputs:{x:R},backend:s,attrs:{shape:n.outShape}});x.push(R);for(const e of x)s.disposeIntermediateTensorInfo(e);return _}const pL={kernelName:Ae,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:c}=s,h=ao(l),p=Xi(r.shape,a.shape,i,u,o,c,!1,h);let d;if(1!==p.filterHeight||1!==p.filterWidth||1!==p.dilationHeight||1!==p.dilationWidth||1!==p.strideHeight||1!==p.strideWidth||"SAME"!==p.padInfo.type&&"VALID"!==p.padInfo.type)if(p.strideWidth<=2&&"channelsLast"===h&&Y().getBool("WEBGL_EXP_CONV")){const e=new oL(p),t=[[p.padInfo.top,p.padInfo.left],[p.strideHeight,p.strideWidth],[p.dilationHeight,p.dilationWidth],[p.inHeight,p.inWidth]];d=n.runWebGLProgram(e,[r,a],"float32",t)}else if(Y().getBool("WEBGL_CONV_IM2COL"))d=hL({x:r,filter:a,convInfo:p,backend:n});else{const e=new aL(p);d=n.runWebGLProgram(e,[r,a],"float32")}else d=cL({x:r,filter:a,convInfo:p,backend:n});const f=SO({inputs:{x:d},backend:n,attrs:{shape:p.outShape}});return n.disposeIntermediateTensorInfo(d),f}};class dL{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,n=e.strideWidth,s=e.padInfo.top,r=e.padInfo.left,a="channelsLast"===e.dataFormat;this.userCode=`\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int wR = coords.x;\n        int wC = coords.y;\n        int d1 = coords.z;\n        int d2 = coords.w;\n\n        // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n\n        for (int b = 0; b < ${e.batchSize}; b++) {\n          for (int yR = 0; yR < ${e.outHeight}; yR++) {\n            int xR = wR + yR * ${t} - ${s};\n\n            if (xR < 0 || xR >= ${e.inHeight}) {\n              continue;\n            }\n\n            for (int yC = 0; yC < ${e.outWidth}; yC++) {\n              int xC = wC + yC * ${n} - ${r};\n\n              if (xC < 0 || xC >= ${e.inWidth}) {\n                continue;\n              }\n\n              ${a?"float dyValue = getDy(b, yR, yC, d2);\n              float xValue = getX(b, xR, xC, d1);\n              dotProd += (xValue * dyValue);":"float dyValue = getDy(b, d2, yR, yC);\n              float xValue = getX(b, d1, xR, xC);\n              dotProd += (xValue * dyValue);"}\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    `}}class fL{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,r=e.strideWidth,a="channelsLast"===e.dataFormat,i=t-1-e.padInfo.top,o=n-1-e.padInfo.left,l=a?1:2,u=a?2:3,c=a?3:1;this.userCode=`\n      const ivec2 pads = ivec2(${i}, ${o});\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d1 = coords[${c}];\n\n        ivec2 dyCorner = ivec2(coords[${l}], coords[${u}]) - pads;\n        int dyRCorner = dyCorner.x;\n        int dyCCorner = dyCorner.y;\n\n        // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        for (int wR = 0; wR < ${t}; wR++) {\n          float dyR = float(dyRCorner + wR) / ${s}.0;\n\n          if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          int wRPerm = ${t} - 1 - wR;\n\n          for (int wC = 0; wC < ${n}; wC++) {\n            float dyC = float(dyCCorner + wC) / ${r}.0;\n\n            if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n                fract(dyC) > 0.0) {\n              continue;\n            }\n            int idyC = int(dyC);\n\n            int wCPerm = ${n} - 1 - wC;\n\n            for (int d2 = 0; d2 < ${e.outChannels}; d2++) {\n\n              if (${a}) {\n                float xValue = getDy(batch, idyR, idyC, d2);\n                float wValue = getW(wRPerm, wCPerm, d1, d2);\n                dotProd += xValue * wValue;\n              } else {\n                float xValue = getDy(batch, d2, idyR, idyC);\n                float wValue = getW(wRPerm, wCPerm, d1, d2);\n                dotProd += xValue * wValue;\n              }\n\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    `}}class mL{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideDepth,n=e.strideHeight,s=e.strideWidth,r=e.padInfo.front,a=e.padInfo.top,i=e.padInfo.left;this.userCode=`\n      void main() {\n        ivec5 coords = getOutputCoords();\n        int wF = coords.x;\n        int wR = coords.y;\n        int wC = coords.z;\n        int d1 = coords.w;\n        int d2 = coords.u;\n\n        float dotProd = 0.0;\n\n        for (int b = 0; b < ${e.batchSize}; b++) {\n          for (int yF = 0; yF < ${e.outDepth}; yF++) {\n            int xF = wF + yF * ${t} - ${r};\n\n            if (xF < 0 || xF >= ${e.inDepth}) {\n              continue;\n            }\n\n            for (int yR = 0; yR < ${e.outHeight}; yR++) {\n              int xR = wR + yR * ${n} - ${a};\n\n              if (xR < 0 || xR >= ${e.inHeight}) {\n                continue;\n              }\n\n              for (int yC = 0; yC < ${e.outWidth}; yC++) {\n                int xC = wC + yC * ${s} - ${i};\n\n                if (xC < 0 || xC >= ${e.inWidth}) {\n                  continue;\n                }\n\n                float dyValue = getDy(b, yF, yR, yC, d2);\n                float xValue = getX(b, xF, xR, xC, d1);\n                dotProd += (xValue * dyValue);\n              }\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    `}}class gL{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterDepth,n=e.filterHeight,s=e.filterWidth,r=e.strideDepth,a=e.strideHeight,i=e.strideWidth,o=t-1-e.padInfo.front,l=n-1-e.padInfo.top,u=s-1-e.padInfo.left;this.userCode=`\n      const ivec3 pads = ivec3(${o}, ${l}, ${u});\n\n      void main() {\n        ivec5 coords = getOutputCoords();\n        int batch = coords.x;\n        int d1 = coords.u;\n\n\n        ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n        int dyFCorner = dyCorner.x;\n        int dyRCorner = dyCorner.y;\n        int dyCCorner = dyCorner.z;\n\n        float dotProd = 0.0;\n        for (int wF = 0; wF < ${t}; wF++) {\n          float dyF = float(dyFCorner + wF) / ${r}.0;\n\n          if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) {\n            continue;\n          }\n          int idyF = int(dyF);\n\n          int wFPerm = ${t} - 1 - wF;\n\n          for (int wR = 0; wR < ${n}; wR++) {\n            float dyR = float(dyRCorner + wR) / ${a}.0;\n\n            if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||\n              fract(dyR) > 0.0) {\n              continue;\n            }\n            int idyR = int(dyR);\n\n            int wRPerm = ${n} - 1 - wR;\n\n            for (int wC = 0; wC < ${s}; wC++) {\n              float dyC = float(dyCCorner + wC) / ${i}.0;\n\n              if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n                  fract(dyC) > 0.0) {\n                continue;\n              }\n              int idyC = int(dyC);\n\n              int wCPerm = ${s} - 1 - wC;\n\n              for (int d2 = 0; d2 < ${e.outChannels}; d2++) {\n                float xValue = getDy(batch, idyF, idyR, idyC, d2);\n                float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);\n                dotProd += xValue * wValue;\n              }\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    `}}const yL={kernelName:Re,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,dy:a}=t,{strides:i,pad:o,dataFormat:l,dimRoundingMode:u,filterShape:c}=s,h=ao(l),p=Xi(r.shape,c,i,1,o,u,!1,h),d=new dL(p);return n.runWebGLProgram(d,[r,a],"float32")}};class bL{constructor(e){this.variableNames=["dy","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"strides",type:"vec2"}],this.outputShape=e.inShape,this.enableShapeUniforms=uF(this.outputShape.length);const t=e.filterHeight,n=e.filterWidth,s=t-1-e.padInfo.top,r=n-1-e.padInfo.left;this.userCode=`\n      const ivec2 pads = ivec2(${s}, ${r});\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d1 = coords[3];\n\n        ivec2 dyCorner = ivec2(coords[1], coords[2]) - pads;\n        int dyRCorner = dyCorner.x;\n        int dyCCorner = dyCorner.y;\n\n        vec4 result = vec4(0.);\n        for (int wR = 0; wR < ${t}; wR++) {\n          float dyR = float(dyRCorner + wR) / strides[0];\n          if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n          int wRPerm = ${t} - 1 - wR;\n\n          for (int wC = 0; wC < ${n}; wC++) {\n            int wCPerm = ${n} - 1 - wC;\n\n            float dyC = float(dyCCorner + wC) / strides[1];\n            bool idyCVal = (dyC >= 0.0) && (dyC < ${e.outWidth}.0)\n              && (fract(dyC) == 0.0);\n            int idyC = int(dyC);\n\n            float dyC2 = float(dyCCorner + wC + 1) / strides[1];\n            bool idyCVal2 = (dyC2 >= 0.0) && (dyC2 < ${e.outWidth}.0)\n              && (fract(dyC2) == 0.0);\n            int idyC2 = int(dyC2);\n\n            if (idyCVal && idyCVal2) {\n              for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {\n                vec4 wValue = getW(wRPerm, wCPerm, d1, d2);\n                vec4 dySample = getDy(batch, idyR, idyC, d2);\n                vec4 dySample2 = (idyC / 2 == idyC2 / 2) ?\n                  dySample : getDy(batch, idyR, idyC2, d2);\n\n                vec2 dyValue = mod(float(idyC), 2.) == 0. ?\n                  dySample.xy : dySample.zw;\n                result.xy += vec2(dot(dyValue, wValue.xy),\n                  dot(dyValue, wValue.zw));\n\n                dyValue = mod(float(idyC2), 2.) == 0. ?\n                  dySample2.xy : dySample2.zw;\n                result.zw += vec2(dot(dyValue, wValue.xy),\n                  dot(dyValue, wValue.zw));\n              }\n            } else if (idyCVal) {\n              for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {\n                vec4 wValue = getW(wRPerm, wCPerm, d1, d2);\n                vec4 dySample = getDy(batch, idyR, idyC, d2);\n                vec2 dyValue = mod(float(idyC), 2.) == 0. ?\n                  dySample.xy : dySample.zw;\n                result.xy += vec2(dot(dyValue, wValue.xy),\n                  dot(dyValue, wValue.zw));\n              }\n            } else if (idyCVal2) {\n              for (int d2 = 0; d2 < ${e.outChannels}; d2 += 2) {\n                vec4 wValue = getW(wRPerm, wCPerm, d1, d2);\n                vec4 dySample = getDy(batch, idyR, idyC2, d2);\n                vec2 dyValue = mod(float(idyC2), 2.) == 0. ?\n                  dySample.xy : dySample.zw;\n                result.zw += vec2(dot(dyValue, wValue.xy),\n                  dot(dyValue, wValue.zw));\n              }\n            }\n          }\n        }\n        setOutput(result);\n      }\n    `}}const xL={kernelName:_e,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,filter:a}=t,{inputShape:i,strides:o,pad:l,dataFormat:u,dimRoundingMode:c}=s,h=ao(u),p=Xi(i,a.shape,o,1,l,c,!1,h);if(Y().getBool("WEBGL_PACK_CONV2DTRANSPOSE")&&"channelsLast"===h){const e=[[p.strideHeight,p.strideWidth]],t=new bL(p);return n.runWebGLProgram(t,[r,a],"float32",e)}{const e=new fL(p);return n.runWebGLProgram(e,[r,a],"float32")}}};const wL={kernelName:Fe,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:i,pad:o,dilations:l}=s,u=Yi(r.shape,a.shape,i,l,o),c=new iL(u);return n.runWebGLProgram(c,[r,a],"float32")}};const vL={kernelName:De,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,dy:a}=t,{strides:i,pad:o,filterShape:l}=s,u=Yi(r.shape,l,i,1,o),c=new mL(u);return n.runWebGLProgram(c,[r,a],"float32")}};const kL={kernelName:Oe,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,filter:a}=t,{pad:i,strides:o,inputShape:l}=s,u=Yi(l,a.shape,o,1,i),c=new gL(u);return n.runWebGLProgram(c,[r,a],"float32")}},NL=mO({opSnippet:"if (isnan(x)) return x;\n  return cos(x);\n",packedOpSnippet:`\n  vec4 result = cos(x);\n  bvec4 isNaN = isnan(x);\n  ${sO}\n  return result;\n`}),IL={kernelName:Me,backendName:"webgl",kernelFunc:NL},SL=mO({opSnippet:"\n  float e2x = exp(-x);\n  return (e2x + 1.0 / e2x) / 2.0;\n"}),TL={kernelName:Le,backendName:"webgl",kernelFunc:SL};class CL{constructor(e,t,n,s,r){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];const[a,i,o,l]=e,[u]=t,[c,h]=n;this.outputShape=[u,c,h,l];const p="bilinear"===s?1:0,[d,f]=[i-1+".0",o-1+".0"],[m,g,y]=c>1?[""+(i-1)/(c-1),"(y2-y1) * height_ratio",`y1*${d} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${d}`],[b,x,w]=h>1?[""+(o-1)/(h-1),"(x2-x1) * width_ratio",`x1*${f} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${f}`];this.userCode=`\n      const float height_ratio = float(${m});\n      const float width_ratio = float(${b});\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int y = coords[1];\n        int x = coords[2];\n        int d = coords[3];\n\n        // get box vals\n        float y1 = getBoxes(b,0);\n        float x1 = getBoxes(b,1);\n        float y2 = getBoxes(b,2);\n        float x2 = getBoxes(b,3);\n\n        // get image in batch index\n        int bInd = round(getBoxInd(b));\n        if(bInd < 0 || bInd >= ${a}) {\n          return;\n        }\n\n        float height_scale = ${g};\n        float width_scale = ${x};\n\n        float in_y = ${y};\n        if( in_y < 0.0 || in_y > ${d} ) {\n          setOutput(float(${r}));\n          return;\n        }\n        float in_x = ${w};\n        if( in_x < 0.0 || in_x > ${f} ) {\n          setOutput(float(${r}));\n          return;\n        }\n\n        vec2 sourceFracIndexCR = vec2(in_x,in_y);\n        if(${p} == 1) {\n          // Compute the four integer indices.\n          ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);\n          ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));\n\n          float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);\n          float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);\n          float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);\n          float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);\n\n          vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);\n\n          float top = topLeft + (topRight - topLeft) * fracCR.x;\n          float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;\n          float newValue = top + (bottom - top) * fracCR.y;\n          setOutput(newValue);\n        } else {\n          // Compute the coordinators of nearest neighbor point.\n          ivec2 sourceNearestCR = ivec2(floor(\n            sourceFracIndexCR + vec2(0.5,0.5)));\n          float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);\n          setOutput(newValue);\n        }\n      }\n    `}}const $L={kernelName:Be,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:s}=e,{image:r,boxes:a,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:u}=s,c=new CL(r.shape,a.shape,o,l,u);return n.runWebGLProgram(c,[r,a,i],"float32")}};var EL;!function(e){e.Prod="*",e.Sum="+"}(EL||(EL={}));class AL{constructor(e,t,n,s){this.op=e,this.outputShape=t,this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}];const r=this.outputShape.length,a=this.op===EL.Prod?"1.0":"0.0",i=n?a:`getX(${RL(r,"coords",this.op)})`,o=this.outputShape[this.outputShape.length-1];let l="",u="";n?(l=s?"end != "+(o-1):"end != 0",u=s?"end + 1":"end - 1"):(l=s?`end + pow2 < ${o}`:"end >= pow2",u=s?"end + pow2":"end - pow2"),this.userCode=`\n      void main() {\n        ${sF(r)} coords = getOutputCoords();\n        int end = ${_L(r,"coords",this.op)};\n        float val = ${i};\n        int pow2 = int(pow(2.0, index));\n        if (${l}) {\n          int idx = ${u};\n          ${_L(r,"coords",this.op)} = idx;\n          val ${this.op}= getX(${RL(r,"coords",this.op)});\n        }\n        setOutput(val);\n      }\n    `}}function RL(e,t,n){if(1===e)return`${t}`;if(2===e)return`${t}.x, ${t}.y`;if(3===e)return`${t}.x, ${t}.y, ${t}.z`;if(4===e)return`${t}.x, ${t}.y, ${t}.z, ${t}.w`;throw new Error(`Cumulative ${n} for rank ${e} is not yet supported`)}function _L(e,t,n){if(1===e)return`${t}`;if(2===e)return`${t}.y`;if(3===e)return`${t}.z`;if(4===e)return`${t}.w`;throw new Error(`Cumulative ${n} for rank ${e} is not yet supported`)}function FL(e,t,n,s,r,a){const i=t.shape.length,o=dl([s],i);let l=t;null!=o&&(l=OO({inputs:{x:t},backend:n,attrs:{perm:o}}));const u=ml(1,i)[0];if(u!==i-1)throw new Error(`WebGL cumprod shader expects an inner-most axis=${t.shape.length-1} but got axis=${s}`);const c=l.shape[u];let h=aO({inputs:{x:l},backend:n});for(let t=0;t<=Math.ceil(Math.log2(c))-1;t++){const s=new AL(e,l.shape,!1,a),r=[[t]],i=h;h=n.runWebGLProgram(s,[h],h.dtype,r),n.disposeIntermediateTensorInfo(i)}if(r){const t=new AL(e,l.shape,r,a),s=h;h=n.runWebGLProgram(t,[h],h.dtype),n.disposeIntermediateTensorInfo(s)}if(null!=o){const e=OO({inputs:{x:h},backend:n,attrs:{perm:fl(o)}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(l),e}return h}const DL={kernelName:ze,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,exclusive:i,reverse:o}=s;return FL(EL.Prod,r,n,a,i,o)}};const OL={kernelName:Pe,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,exclusive:i,reverse:o}=s;return FL(EL.Sum,r,n,a,i,o)}};const ML={kernelName:We,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,weights:a}=t,{size:i,binaryOutput:o}=s;if(1===r.shape.length){const e=n.readSync(r.dataId),t=n.readSync(a.dataId),s=VF(e,t,a.dtype,a.shape,i);return n.makeTensorInfo([i],a.dtype,s)}if(2===r.shape.length){const e=n.bufferSync(r),t=n.bufferSync(a),s=UF(e,t,i,o);return n.makeTensorInfo(s.shape,a.dtype,s.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${r.shape.length}.`)}};class LL{constructor(e,t,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=n,this.userCode=`\n    void main() {\n      ivec4 coords = getOutputCoords();\n      int b = coords[0];\n      int h = ${this.getHeightCoordString()};\n      int w = ${this.getWidthCoordString()};\n      int d = ${this.getDepthCoordString()};\n\n      int in_h = h / ${t};\n      int offset_h = imod(h, ${t});\n      int in_w = w / ${t};\n      int offset_w = imod(w, ${t});\n      int offset_d = (offset_h * ${t} + offset_w) *\n        ${this.getOutputDepthSize()};\n      int in_d = d + offset_d;\n\n      float result = ${this.getInputSamplingString()};\n      setOutput(result);\n    }\n  `}getHeightCoordString(){return"NHWC"===this.dataFormat?"coords[1]":"coords[2]"}getWidthCoordString(){return"NHWC"===this.dataFormat?"coords[2]":"coords[3]"}getDepthCoordString(){return"NHWC"===this.dataFormat?"coords[3]":"coords[1]"}getOutputDepthSize(){return"NHWC"===this.dataFormat?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return"NHWC"===this.dataFormat?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}}const zL={kernelName:Ve,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockSize:a,dataFormat:i}=s,o=r.shape[0],l=("NHWC"===i?r.shape[1]:r.shape[2])*a,u=("NHWC"===i?r.shape[2]:r.shape[3])*a,c=("NHWC"===i?r.shape[3]:r.shape[1])/(a*a),h=new LL("NHWC"===i?[o,l,u,c]:[o,c,l,u],a,i);return n.runWebGLProgram(h,[r],r.dtype)}};class PL{constructor(e,t=!1,n=null,s=!1,r=!1){this.variableNames=["x","W"],this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=uF(this.outputShape.length);const a=e.filterHeight,i=e.filterWidth,o=e.outChannels/e.inChannels;let l="",u="";n&&(l=s?`float activation(float a) {\n          float b = getPreluActivationWeightsAtOutCoords();\n          ${n}\n        }`:r?`float activation(float a) {\n          float b = getLeakyreluAlphaAtOutCoords();\n          ${n}\n        }`:`\n          float activation(float x) {\n            ${n}\n          }\n        `,u="result = activation(result);");const c=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n      ${l}\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords.x;\n        ivec2 xRCCorner = coords.yz * strides - pads;\n        int d2 = coords.w;\n        int d1 = d2 / ${o};\n        int q = d2 - d1 * ${o};\n\n        int xRCorner = xRCCorner.x;\n        int xCCorner = xRCCorner.y;\n\n        // Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        // TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.\n        for (int wR = 0; wR < ${a}; wR++) {\n          int xR = xRCorner + wR * dilations[0];\n\n          if (xR < 0 || xR >= inDims[0]) {\n            continue;\n          }\n\n          for (int wC = 0; wC < ${i}; wC++) {\n            int xC = xCCorner + wC * dilations[1];\n\n            if (xC < 0 || xC >= inDims[1]) {\n              continue;\n            }\n\n            float xVal = getX(batch, xR, xC, d1);\n            float wVal = getW(wR, wC, d1, q);\n            dotProd += xVal * wVal;\n          }\n        }\n\n        float result = dotProd;\n        ${c}\n        ${u}\n        setOutput(result);\n      }\n    `}}class BL{constructor(e,t=!1,n=null,s=!1,r=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"pads",type:"ivec2"},{name:"strides",type:"ivec2"},{name:"dilations",type:"ivec2"},{name:"inDims",type:"ivec2"}],this.outputShape=e.outShape,this.enableShapeUniforms=uF(this.outputShape.length);const a=e.outChannels/e.inChannels,i=e.padInfo.left,l=e.strideWidth,u=e.dilationWidth,c=e.filterHeight,h=e.filterWidth,p=h;let d="\n      int xR; int xC; int xCOffset;\n      vec4 wTexel; vec4 previous; vec4 final;";for(let e=0;e<h;e++)d+=`\n          vec4 xTexelC${2*e};\n          int xTexelC${2*e}Ready;\n          vec4 xTexelC${2*e+1};\n          int xTexelC${2*e+1}Ready;\n          vec4 xC${e};`;d+=`\n    for (int r = 0; r < ${c}; r++) {\n      `;for(let e=0;e<h;e++)d+=`\n          xTexelC${2*e} = vec4(0.0);\n          xTexelC${2*e}Ready = 0;\n          xTexelC${2*e+1} = vec4(0.0);\n          xTexelC${2*e+1}Ready = 0;\n          xC${e} = vec4(0.0);`;d+="\n        xR = xRCorner + r * dilations[0];\n        if (xR >=0 && xR < inDims[0]) {\n      ";for(let e=0;e<(p+1)/2;e++){const t=2*e;if(d+=`\n          xC = xCCorner + ${t*u};\n          `,1===l){if(t<h&&(i%2==1?(d+=`\n                xCOffset = xC + 1;\n                if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t}Ready == 0) {\n                  xTexelC${t} = getX(batch, xR, xCOffset, d1);\n\n                  // Need to manually clear unused channels in case\n                  // we're reading from recycled texture.\n                  if (xCOffset + 1 >= inDims[1]) {\n                    xTexelC${t}.zw = vec2(0.0);\n                  }\n                  xTexelC${t}Ready = 1;\n                }\n              `,d+=1===u&&t>0?`\n                xC${t} = vec4(xTexelC${t-2}.zw, xTexelC${t}.xy);\n                `:`\n                  xCOffset = xC + 1 - 2;\n\n                  if (xCOffset >= 0 && xCOffset < inDims[1]) {\n                    previous = getX(batch, xR, xCOffset, d1);\n\n                    // Need to manually clear unused channels in case\n                    // we're reading from recycled texture.\n                    if (xCOffset + 1 >= inDims[1]) {\n                      previous.zw = vec2(0.0);\n                    }\n\n                    xC${t} = vec4(previous.zw, xTexelC${t}.xy);\n                  } else {\n                    xC${t} = vec4(0.0, 0.0, xTexelC${t}.xy);\n                  }\n                  `):d+=`\n                if (xC >= 0 && xC < inDims[1] && xTexelC${t}Ready == 0) {\n                  xTexelC${t} = getX(batch, xR, xC, d1);\n                  if (xC + 1 >= inDims[1]) {\n                    xTexelC${t}.zw = vec2(0.0);\n                  }\n                  xTexelC${t}Ready = 1;\n                }\n\n                xC${t} = xTexelC${t};\n                `,t+1<h)){const e=i%2==0?o(u):u;u%2==0&&i%2==1||u%2!=0&&i%2!=1?(d+=`\n                  xCOffset = xC + imod(pads[1], 2) + ${e};\n\n                  if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t+1}Ready == 0) {\n                    xTexelC${t+1} = getX(batch, xR, xCOffset, d1);\n\n                    // Need to manually clear unused channels in case\n                    // we're reading from recycled texture.\n                    if (xCOffset + 1 >= inDims[1]) {\n                      xTexelC${t+1}.zw = vec2(0.0);\n                    }\n                    xTexelC${t+1}Ready = 1;\n                  }\n                  `,d+=u>1?`\n                    xCOffset -= 2;\n                    if (xCOffset >= 0 && xCOffset < inDims[1]) {\n                     previous = getX(batch, xR, xCOffset, d1);\n                     xC${t+1} = vec4(previous.zw, xTexelC${t+1}.xy);\n                    } else {\n                     xC${t+1} = vec4(0.0, 0.0, xTexelC${t+1}.xy);\n                    }\n                    `:`\n                    xC${t+1} = vec4(xTexelC${t}.zw, xTexelC${t+1}.xy);\n                    `):d+=1===e?`\n                    xC${t+1} = xTexelC${t};\n                    `:`\n                    xCOffset = xC + ${e};\n\n                    if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t+1}Ready == 0) {\n                      xTexelC${t+1} = getX(batch, xR, xCOffset, d1);\n                      if (xCOffset + 1 >= inDims[1]) {\n                        xTexelC${t+1}.zw = vec2(0.0);\n                      }\n                      xTexelC${t+1}Ready = 1;\n                    }\n\n                    xC${t+1} = xTexelC${t+1};\n                    `}}else t<h&&(i%2==1?(d+=`\n                xCOffset = xC + 1 - strides[1];\n                if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t}Ready == 0) {\n                  xTexelC${t} = getX(batch, xR, xCOffset, d1);\n                  // Need to manually clear unused channels in case\n                  // we're reading from recycled texture.\n                  if (xCOffset + 1 >= inDims[1]) {\n                    xTexelC${t}.zw = vec2(0.0);\n                  }\n                  xTexelC${t}Ready = 1;\n                }\n\n                if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${t+1}Ready == 0) {\n                  xTexelC${t+1} = getX(batch, xR, xC + 1, d1);\n                  // Need to manually clear unused channels in case\n                  // we're reading from recycled texture.\n                  if (xC + 2 >= inDims[1]) {\n                    xTexelC${t+1}.zw = vec2(0.0);\n                  }\n                  xTexelC${t+1}Ready = 1;\n                }\n\n                xC${t} = vec4(xTexelC${t}.zw, xTexelC${t+1}.zw);\n              `,t+1<h&&(d+=`\n                  final = vec4(0.0);\n                  xCOffset = xC + 1 + strides[1];\n                  if(xCOffset >= 0 && xCOffset < inDims[1]) {\n                    final = getX(batch, xR, xCOffset, d1);\n                  }\n                  xC${t+1} = vec4(xTexelC${t+1}.xy, final.xy);\n                `)):(d+=`\n                if(xC >= 0 && xC < inDims[1] && xTexelC${t}Ready == 0) {\n                  xTexelC${t} = getX(batch, xR, xC, d1);\n                  if (xC + 1 >= inDims[1]) {\n                    xTexelC${t}.zw = vec2(0.0);\n                  }\n                  xTexelC${t}Ready = 1;\n                }\n\n                xCOffset = xC + strides[1];\n                if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${t+1}Ready == 0) {\n                  xTexelC${t+1} = getX(batch, xR, xCOffset, d1);\n                  if (xCOffset + 1 >= inDims[1]) {\n                    xTexelC${t+1}.zw = vec2(0.);\n                  }\n                  xTexelC${t+1}Ready = 1;\n                }\n\n                xC${t} = vec4(\n                  xTexelC${t}.xy, xTexelC${t+1}.xy);\n              `,t+1<h&&(d+=`\n                  xC${t+1} = vec4(xTexelC${t}.zw, xTexelC${t+1}.zw);\n                `)));t<h&&(d+=`\n            wTexel = getW(r, ${t}, d1, q);\n            dotProd += xC${t} * vec4(wTexel.xz, wTexel.xz);\n          `,t+1<h&&(d+=`\n              wTexel = getW(r, ${t+1}, d1, q);\n              dotProd += xC${t+1} * vec4(wTexel.xz, wTexel.xz);\n            `))}d+="\n    }\n  ",d+="\n      }\n    ";let f="",m="";n&&(f=s?`vec4 activation(vec4 a) {\n          vec4 b = getPreluActivationWeightsAtOutCoords();\n          ${n}\n        }`:r?`vec4 activation(vec4 a) {\n          vec4 b = getLeakyreluAlphaAtOutCoords();\n          ${n}\n        }`:`vec4 activation(vec4 x) {\n          ${n}\n        }`,m="result = activation(result);");const g=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),s&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=`\n      ${f}\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords.x;\n        ivec2 xRCCorner = coords.yz * strides - pads;\n        int d2 = coords.w;\n        int d1 = d2 / ${a};\n        int q = d2 - d1 * ${a};\n        int xRCorner = xRCCorner.x;\n        int xCCorner = xRCCorner.y;\n\n        //intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.\n        vec4 dotProd = vec4(0.000000000000001);\n\n        ${d}\n\n        vec4 result = dotProd - vec4(0.000000000000001);\n        ${g}\n        ${m}\n        setOutput(result);\n      }\n    `}}const WL={kernelName:Ue,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:i,pad:o,dilations:l,dimRoundingMode:u}=s;let h=l;null==h&&(h=[1,1]),c(so(i,h),(()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${h}'`));const p=Xi(r.shape,a.shape,i,h,o,u,!0);let d;d=Y().getBool("WEBGL_PACK_DEPTHWISECONV")&&p.strideWidth<=2&&p.outChannels/p.inChannels==1?new BL(p):new PL(p);const f=[[p.padInfo.top,p.padInfo.left],[p.strideHeight,p.strideWidth],[p.dilationHeight,p.dilationWidth],[p.inHeight,p.inWidth]];return n.runWebGLProgram(d,[r,a],"float32",f)}};class VL{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;const t=e.strideHeight,n=e.strideWidth,s=e.padInfo.top,r=e.padInfo.left,a=e.outChannels/e.inChannels;this.userCode=`\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int wR = coords.x;\n        int wC = coords.y;\n        int d1 = coords.z;\n        int dm = coords.w;\n        int d2 = d1 * ${a} + dm;\n\n        float dotProd = 0.0;\n\n        // TO DO: Vec4 over the batch size\n        for (int b = 0; b < ${e.batchSize}; b++) {\n          for (int yR = 0; yR < ${e.outHeight}; yR++) {\n            int xR = wR + yR * ${t} - ${s};\n\n            if (xR < 0 || xR >= ${e.inHeight}) {\n              continue;\n            }\n\n            for (int yC = 0; yC < ${e.outWidth}; yC++) {\n              int xC = wC + yC * ${n} - ${r};\n\n              if (xC < 0 || xC >= ${e.inWidth}) {\n                continue;\n              }\n\n              float dyValue = getDy(b, yR, yC, d2);\n              float xValue = getX(b, xR, xC, d1);\n              dotProd += (xValue * dyValue);\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    `}}class UL{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;const t=e.filterHeight,n=e.filterWidth,s=e.strideHeight,r=e.strideWidth,a=t-1-e.padInfo.top,i=n-1-e.padInfo.left,o=e.outChannels/e.inChannels;this.userCode=`\n      const ivec2 pads = ivec2(${a}, ${i});\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords[0];\n        int d1 = coords[3];\n        ivec2 dyCorner = coords.yz - pads;\n        int dyRCorner = dyCorner.x;\n        int dyCCorner = dyCorner.y;\n\n        float dotProd = 0.0;\n\n        for (int wR = 0; wR < ${t}; wR++) {\n          float dyR = float(dyRCorner + wR) / ${s}.0;\n\n          if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          int wRPerm = ${t} - 1 - wR;\n\n          for (int wC = 0; wC < ${n}; wC++) {\n            float dyC = float(dyCCorner + wC) / ${r}.0;\n\n            if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n                fract(dyC) > 0.0) {\n              continue;\n            }\n            int idyC = int(dyC);\n\n            int wCPerm = ${n} - 1 - wC;\n\n            // TO DO: Vec4 over the channelMul\n            for (int dm = 0; dm < ${o}; dm++) {\n              int d2 = d1 * ${o} + dm;\n              float xValue = getDy(batch, idyR, idyC, d2);\n              float wValue = getW(wRPerm, wCPerm, d1, dm);\n              dotProd += xValue * wValue;\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    `}}const GL={kernelName:Ge,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,dy:a}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,filterShape:c}=s,h=Xi(r.shape,c,i,o,l,u,!0),p=new VL(h);return n.runWebGLProgram(p,[r,a],"float32")}};const HL={kernelName:He,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,filter:a}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,inputShape:c}=s,h=Xi(c,a.shape,i,o,l,u,!0),p=new UL(h);return n.runWebGLProgram(p,[r,a],"float32")}};class jL{constructor(e){this.variableNames=["X"],this.outputShape=[e,e],this.userCode="\n      void main() {\n          ivec2 coords = getOutputCoords();\n          float val = coords[0] == coords[1] ? getX(coords[0]) : 0.0;\n          setOutput(val);\n      }\n    "}}const qL={kernelName:je,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:s}=t,r=[...s.shape,...s.shape],a=d(s.shape),i=SO({inputs:{x:s},backend:n,attrs:{shape:[a]}}),o=new jL(a),l=n.runWebGLProgram(o,[i],i.dtype),u=SO({inputs:{x:l},backend:n,attrs:{shape:r}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),u}};class KL{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;const{inHeight:t,inWidth:n,padInfo:s,strideHeight:r,strideWidth:a,filterHeight:i,filterWidth:o,dilationHeight:l,dilationWidth:u}=e,{top:c,left:h}=s;this.userCode=`\n      const ivec2 strides = ivec2(${r}, ${a});\n      const ivec2 pads = ivec2(${c}, ${h});\n      const float neg_infinity = -3.4e38;\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int batch = coords.x;\n        int d1 = coords.w;\n        ivec2 outTopLeftCorner =\n            coords.yz * strides - pads;\n        int hBeg = outTopLeftCorner.x;\n        int wBeg = outTopLeftCorner.y;\n\n        float curVal = neg_infinity;\n        for (int h = 0; h < ${i}; h++) {\n          int hIn = hBeg + h * ${l};\n\n          if (hIn >= 0 && hIn < ${t}) {\n            for (int w = 0; w < ${o}; w++) {\n              int wIn = wBeg + w * ${u};\n\n              if (wIn >= 0 && wIn < ${n}) {\n                float xVal = getX(batch, hIn, wIn, d1);\n                float wVal = getW(h, w, d1);\n\n                float val = xVal + wVal;\n                if (val > curVal) {\n                  curVal = val;\n                }\n              }\n            }\n          }\n        }\n\n        float result = curVal;\n        setOutput(result);\n      }\n    `}}const XL={kernelName:qe,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:i,pad:o,dilations:l}=s,u=ji(r.shape,a.shape,i,o,"NHWC",l);let c;const h=new KL(u);c=n.runWebGLProgram(h,[r,a],"float32");const p=SO({inputs:{x:c},backend:n,attrs:{shape:u.outShape}});return n.disposeIntermediateTensorInfo(c),p}};const YL={kernelName:Je,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{equation:r}=s,a=t,{allDims:i,summedDims:o,idDims:l}=Df(r,a.length);Mf(i.length,l,a);const{path:u,steps:c}=Lf(o,l),h=c.length;let p=null,d=i.length;const f=[];for(let e=0;e<h;++e){for(const t of c[e]){const{permutationIndices:e,expandDims:s}=Of(d,l[t]);let r;zf(e)?r=a[t]:(r=OO({inputs:{x:a[t]},backend:n,attrs:{perm:e}}),f.push(r));const i=r.shape.slice();for(let e=0;e<s.length;++e)i.splice(s[e],0,1);m(r.shape,i)||(r=SO({inputs:{x:r},backend:n,attrs:{shape:i}}),f.push(r)),null===p?p=r:(p=NO({inputs:{a:r,b:p},backend:n}),f.push(p))}e<h-1&&(u[e]>=0&&(p=FO({inputs:{x:p},backend:n,attrs:{axis:u[e]-(i.length-d),keepDims:!1}}),f.push(p)),d--)}for(const e of f)e!==p&&n.disposeIntermediateTensorInfo(e);return p}},ZL=mO({opSnippet:"return (x >= 0.0) ? x : (exp(x) - 1.0);",packedOpSnippet:"\n  vec4 result;\n\n  result.r = (x.r >= 0.0) ? x.r : (exp(x.r) - 1.0);\n  result.g = (x.g >= 0.0) ? x.g : (exp(x.g) - 1.0);\n  result.b = (x.b >= 0.0) ? x.b : (exp(x.b) - 1.0);\n  result.a = (x.a >= 0.0) ? x.a : (exp(x.a) - 1.0);\n\n  return result;\n"}),JL={kernelName:Qe,backendName:"webgl",kernelFunc:ZL},QL={kernelName:et,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n}=e,{dy:s,y:r}=t,a=Y().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new rO("\n  vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));\n  return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));\n",s.shape,r.shape):new nO("return (b >= 0.0) ? a : a * (b + 1.0);",s.shape,r.shape);return n.runWebGLProgram(a,[s,r],s.dtype)}},ez=gO({opSnippet:"return float(a == b);",packedOpSnippet:"\n  return vec4(equal(a, b));\n",dtype:"bool",cpuKernelImpl:KF}),tz={kernelName:nt,backendName:"webgl",kernelFunc:ez},nz=mO({opSnippet:`\n  // Error function is calculated approximately with elementary function.\n  // See "Handbook of Mathematical Functions with Formulas,\n  // Graphs, and Mathematical Tables", Abramowitz and Stegun.\n  float p = ${bf};\n  float a1 = ${xf};\n  float a2 = ${wf};\n  float a3 = ${vf};\n  float a4 = ${kf};\n  float a5 = ${Nf};\n\n  float sign = sign(x);\n  x = abs(x);\n  float t = 1.0 / (1.0 + p * x);\n  return sign * (1.0 - (((((a5*t + a4)*t) + a3)*t + a2)*t + a1)*t*exp(-x*x));\n`}),sz={kernelName:tt,backendName:"webgl",kernelFunc:nz},rz=mO({opSnippet:"if (isnan(x)) return x;\n  return exp(x);\n",packedOpSnippet:"\n  vec4 result = exp(x);\n  bvec4 isNaN = isnan(x);\n  result.r = isNaN.r ? x.r : result.r;\n  result.g = isNaN.g ? x.g : result.g;\n  result.b = isNaN.b ? x.b : result.b;\n  result.a = isNaN.a ? x.a : result.a;\n\n  return result;\n",cpuKernelImpl:XF,dtype:"float32"}),az={kernelName:st,backendName:"webgl",kernelFunc:rz};function iz(e){const{inputs:t,attrs:n,backend:s}=e,{dim:r}=n,{input:a}=t,i=a.shape.length,o=a.shape.slice();let l=r;return r<0&&(c(-(i+1)<=r,(()=>`Axis must be in the interval [${-(i+1)}, ${i}]`)),l=i+r+1),o.splice(l,0,1),SO({inputs:{x:a},backend:s,attrs:{shape:o}})}const oz={kernelName:rt,backendName:"webgl",kernelFunc:iz},lz="return exp(x) - 1.0;",uz=mO({opSnippet:lz,packedOpSnippet:lz,cpuKernelImpl:YF}),cz={kernelName:at,backendName:"webgl",kernelFunc:uz};class hz{constructor(e,t,n){this.variableNames=["real","imag"];const s=t[1];this.outputShape=t;const r=n?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,a=n?`${s}.0`:"1.0";let i;if("real"===e)i="return real * expR - imag * expI;";else{if("imag"!==e)throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);i="return real * expI + imag * expR;"}this.userCode=`\n      const float exponentMultiplier = ${r};\n\n      float unaryOpComplex(float real, float expR, float imag, float expI) {\n        ${i}\n      }\n\n      float mulMatDFT(int batch, int index) {\n        float indexRatio = float(index) / float(${s});\n        float exponentMultiplierTimesIndexRatio =\n            exponentMultiplier * indexRatio;\n\n        float result = 0.0;\n\n        for (int i = 0; i < ${s}; i++) {\n          // x = (-2|2 * PI / N) * index * i;\n          float x = exponentMultiplierTimesIndexRatio * float(i);\n          float expR = cos(x);\n          float expI = sin(x);\n          float real = getReal(batch, i);\n          float imag = getImag(batch, i);\n\n          result +=\n              unaryOpComplex(real, expR, imag, expI) / ${a};\n        }\n\n        return result;\n      }\n\n      void main() {\n        ivec2 coords = getOutputCoords();\n        setOutput(mulMatDFT(coords[0], coords[1]));\n      }\n    `}}function pz(e,t,n){const s=n.texData.get(e.dataId),r=d(e.shape),a=e.shape[e.shape.length-1],i=SO({inputs:{x:e},backend:n,attrs:{shape:[r/a,a]}}),o=i.shape,l=new hz("real",o,t),u=new hz("imag",o,t),c=[{dataId:s.complexTensorInfos.real.dataId,dtype:s.complexTensorInfos.real.dtype,shape:o},{dataId:s.complexTensorInfos.imag.dataId,dtype:s.complexTensorInfos.imag.dtype,shape:o}],h=n.runWebGLProgram(l,c,"float32"),p=n.runWebGLProgram(u,c,"float32"),f=oO({inputs:{real:h,imag:p},backend:n});n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(p);const m=SO({inputs:{x:f},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(f),m}const dz={kernelName:it,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:s}=t;return pz(s,!1,n)}};class fz{constructor(e,t){this.outputShape=[],this.customUniforms=[{name:"value",type:"float"}],this.variableNames=["x"],this.outputShape=e,this.userCode="\n      void main() {\n        // Input can be obtained from uniform value.\n        setOutput(value);\n      }\n    "}}function mz(e){const{backend:t,attrs:n}=e,{shape:s,value:r}=n;let{dtype:a}=n;if(a=a||F(r),"string"===a){const e=I(a,d(s));return e.fill(r),t.makeTensorInfo(s,a,e)}{const e=new fz(s,r),n=[[r]];return t.runWebGLProgram(e,[],a,n)}}const gz={kernelName:ot,backendName:"webgl",kernelFunc:mz};class yz{constructor(e){this.variableNames=["Image"],this.outputShape=[];const t=e[2];this.outputShape=e,this.userCode=`\n        void main() {\n          ivec4 coords = getOutputCoords();\n          int x = coords[2];\n\n          int coordX = ${t} - x - 1;\n          float outputValue;\n          if(coordX >= 0 && coordX < ${t}) {\n            outputValue = getImage(coords[0], coords[1], coordX, coords[3]);\n          } else {\n            outputValue = getImage(coords[0], coords[1], coords[2], coords[3]);\n          }\n          setOutput(outputValue);\n        }\n    `}}const bz={kernelName:lt,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{const{image:n}=e,s=t,r=new yz(n.shape);return s.runWebGLProgram(r,[n],n.dtype)}},xz="return floor(x);",wz=mO({opSnippet:xz,packedOpSnippet:xz,cpuKernelImpl:ZF}),vz={kernelName:ut,backendName:"webgl",kernelFunc:wz},kz=gO({opSnippet:"\n  float s = sign(a) * sign(b);\n  int ia = round(a);\n  int ib = round(b);\n  if (ib != 0) {\n    // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n    return float(idiv(ia, ib, s));\n  } else {\n    return NAN;\n  }\n",packedOpSnippet:"\n  ivec4 ia = round(a);\n  ivec4 ib = round(b);\n  bvec4 cond = notEqual(ib, ivec4(0));\n  ivec4 result = ivec4(0);\n  vec4 s = sign(a) * sign(b);\n\n  // Windows (D3D) wants guaranteed non-zero int division at compile-time.\n  if (cond[0]) {\n    result[0] = idiv(ia[0], ib[0], s[0]);\n  }\n  if (cond[1]) {\n    result[1] = idiv(ia[1], ib[1], s[1]);\n  }\n  if (cond[2]) {\n    result[2] = idiv(ia[2], ib[2], s[2]);\n  }\n  if (cond[3]) {\n    result[3] = idiv(ia[3], ib[3], s[3]);\n  }\n  return vec4(result);\n",dtype:"int32"}),Nz={kernelName:ct,backendName:"webgl",kernelFunc:kz};class Iz{constructor(e){this.variableNames=["A"];const t=B_(),[n,s]=e;this.outputShape=e,this.userCode=`\n      void main() {\n        ivec3 coords = getOutputCoords();\n        int texR = coords[0];\n        int texC = coords[1];\n        int depth = coords[2];\n        vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${s}.0, ${n}.0);\n\n        vec4 values = ${t.texture2D}(A, uv);\n        float value;\n        if (depth == 0) {\n          value = values.r;\n        } else if (depth == 1) {\n          value = values.g;\n        } else if (depth == 2) {\n          value = values.b;\n        } else if (depth == 3) {\n          value = values.a;\n        }\n\n        setOutput(floor(value * 255.0 + 0.5));\n      }\n    `}}class Sz{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=B_(),[n,s]=e;this.outputShape=e,this.userCode=`\n      void main() {\n        ivec3 coords = getOutputCoords();\n        int texR = coords[0];\n        int texC = coords[1];\n        int depth = coords[2];\n\n        vec4 result = vec4(0.);\n\n        for(int row=0; row<=1; row++) {\n          for(int col=0; col<=1; col++) {\n            texC = coords[1] + row;\n            depth = coords[2] + col;\n\n            vec2 uv = (vec2(texC, texR) + halfCR) /\n                       vec2(${s}.0, ${n}.0);\n            vec4 values = ${t.texture2D}(A, uv);\n            float value;\n            if (depth == 0) {\n              value = values.r;\n            } else if (depth == 1) {\n              value = values.g;\n            } else if (depth == 2) {\n              value = values.b;\n            } else if (depth == 3) {\n              value = values.a;\n            }\n\n            result[row * 2 + col] = floor(value * 255.0 + 0.5);\n          }\n        }\n\n        ${t.output} = result;\n      }\n    `}}const Tz={kernelName:us,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e;let{pixels:r}=t;const{numChannels:a}=s,i="undefined"!=typeof HTMLVideoElement&&r instanceof HTMLVideoElement,o="undefined"!=typeof HTMLImageElement&&r instanceof HTMLImageElement,[l,u]=i?[r.videoWidth,r.videoHeight]:[r.width,r.height],c=[u,l],h=[u,l,a];if(o||i){const e=Y().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");null!=Cz&&e===$z||($z=e,Cz=document.createElement("canvas").getContext("2d",{willReadFrequently:$z})),Cz.canvas.width=l,Cz.canvas.height=u,Cz.drawImage(r,0,0,l,u),r=Cz.canvas}const p=n.makeTensorInfo(c,"int32");n.texData.get(p.dataId).usage=WR.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(p.dataId),r);const d=Y().getBool("WEBGL_PACK")?new Sz(h):new Iz(h),f=n.runWebGLProgram(d,[p],"int32");return n.disposeData(p.dataId),f}};let Cz,$z=Y().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");const Ez={kernelName:ps,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:p,activation:d,leakyreluAlpha:f}=s,m=ao(c),g=Xi(r.shape,a.shape,l,h,u,p,!1,m);let y;const b=[],x=null!=i,w=null!=o,v="leakyrelu"===d,k=()=>{const e=[r,a],t=(e,t)=>{if("NCHW"===t&&1===e.shape.length&&1!==e.shape[0]){const t=SO({inputs:{x:e},backend:n,attrs:{shape:[e.shape[0],1,1]}});return b.push(t),t}return e};if(x&&e.push(t(i,c)),w&&e.push(t(o,c)),v){const t=n.makeTensorInfo([],"float32",hr(f,"float32"));e.push(t),b.push(t)}return e};if(1!==g.filterHeight||1!==g.filterWidth||1!==g.dilationHeight||1!==g.dilationWidth||1!==g.strideHeight||1!==g.strideWidth||"SAME"!==g.padInfo.type&&"VALID"!==g.padInfo.type)if(g.strideWidth<=2&&"channelsLast"===m&&Y().getBool("WEBGL_EXP_CONV")){const e=d?yO(d,!0):null,t=new oL(g,x,e,w,v),s=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],r=k();y=n.runWebGLProgram(t,r,"float32",s)}else if(Y().getBool("WEBGL_CONV_IM2COL"))y=hL({x:r,filter:a,convInfo:g,backend:n,bias:i,activation:d,preluActivationWeights:o,leakyreluAlpha:f});else{const e=d?yO(d,!1):null,t=new aL(g,x,e,w,v),s=k();y=n.runWebGLProgram(t,s,"float32")}else y=cL({x:r,filter:a,convInfo:g,backend:n,bias:i,activation:d,preluActivationWeights:o,leakyreluAlpha:f});const N=SO({inputs:{x:y},backend:n,attrs:{shape:g.outShape}});return b.push(y),b.forEach((e=>n.disposeIntermediateTensorInfo(e))),N}};const Az={kernelName:ds,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:h,dimRoundingMode:p,activation:d,leakyreluAlpha:f}=s,m=[];let g=h;null==g&&(g=[1,1]),c(so(l,g),(()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${g}'`));const y=Xi(r.shape,a.shape,l,g,u,p,!0),b=Y().getBool("WEBGL_PACK_DEPTHWISECONV")&&y.strideWidth<=2&&y.outChannels/y.inChannels==1,x=d?yO(d,b):null,w=[r,a],v=null!=i,k=null!=o,N="leakyrelu"===d;if(v&&w.push(i),k&&w.push(o),N){const e=n.makeTensorInfo([],"float32",hr(f,"float32"));w.push(e),m.push(e)}let I;I=b?new BL(y,v,x,k,N):new PL(y,v,x,k,N);const S=[[y.padInfo.top,y.padInfo.left],[y.strideHeight,y.strideWidth],[y.dilationHeight,y.dilationWidth],[y.inHeight,y.inWidth]],T=n.runWebGLProgram(I,w,"float32",S);return m.forEach((e=>n.disposeIntermediateTensorInfo(e))),T}};class Rz{constructor(e,t,n,s){this.sliceDim=e,this.strides=t,this.paramsShape=s,this.variableNames=["x","indices"],this.outputShape=n;const r=sF(n.length);let a="\n    int index;";for(let e=0;e<this.sliceDim;e++)a+=`\n          index = round(getIndices(coords[0], ${e}));\n          out_of_bounds = out_of_bounds || index < 0;\n          out_of_bounds = out_of_bounds || index >= ${this.paramsShape[e]};\n          flattenIndex += index * ${this.strides[e]};`;this.userCode=`\n         void main() {\n          ${r} coords = getOutputCoords();\n          int flattenIndex = 0;\n          bool out_of_bounds = false;\n\n          ${a}\n\n          setOutput(out_of_bounds ? 0.0 : getX(flattenIndex, coords[1]));\n        }\n      `}}const _z={kernelName:dt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{params:s,indices:r}=t,a=r.shape,i=a[a.length-1],o=d(s.shape),[l,u,c,h]=_d(s,r),p=SO({inputs:{x:r},backend:n,attrs:{shape:[u,i]}}),f=SO({inputs:{x:s},backend:n,attrs:{shape:[d(s.shape)/c,c]}});if(n.shouldExecuteOnCPU([s,r])||"string"===s.dtype){const e=n.readSync(r.dataId),t=n.bufferSync(s),a=JF(e,t,s.dtype,u,i,c,h,s.shape,o);return n.makeTensorInfo(l,s.dtype,a.values)}const m=new Rz(i,h,[u,c],s.shape),g=n.runWebGLProgram(m,[f,p],f.dtype),y=SO({inputs:{x:g},backend:n,attrs:{shape:l}});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(g),y}};class Fz{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;const n=sF(this.rank),s=function(e,t){const n=["resRC.x","resRC.y","resRC.z","resRC.w"],s=[];for(let t=0;t<e.length;t++)2===t?s.push("index"):s.push(`${n[t]}`);return s.join()}(e);this.userCode=`\n      void main() {\n        ${n} resRC = getOutputCoords();\n        int index = int(getIndices(resRC.x, resRC.z));\n        float inBounds = (index >= 0) && (index < ${e[2]}) ? 1.0 : 0.0;\n        setOutput(inBounds * getA(${s}));\n      }\n    `}}function Dz(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,indices:a}=t,{axis:i,batchDims:o}=s,l=v(i,r.shape)[0];if(Y().get("DEBUG")){const e=n.readSync(a.dataId),t=r.shape[l];for(let n=0;n<e.length;++n){const s=e[n];c(s<=t-1&&s>=0,(()=>`GatherV2: the index value ${s} is not in [0, ${t-1}]`))}}const u=tm(r,a,l,o),h=d(a.shape),p=[],f=SO({inputs:{x:r},backend:n,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),m=SO({inputs:{x:a},backend:n,attrs:{shape:[u.batchSize,h/u.batchSize]}});p.push(f),p.push(m);const g=[u.batchSize,u.outerSize,h/u.batchSize,u.sliceSize];if(n.shouldExecuteOnCPU([r,a])||"string"===r.dtype){const e=n.bufferSync(m),t=n.bufferSync(f),s=QF(t,e,g);return p.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(u.outputShape,s.dtype,s.values)}const y=new Fz(f.shape,g),b=n.runWebGLProgram(y,[f,m],f.dtype);p.push(b);const x=SO({inputs:{x:b},backend:n,attrs:{shape:u.outputShape}});return p.forEach((e=>n.disposeIntermediateTensorInfo(e))),x}const Oz={kernelName:pt,backendName:"webgl",kernelFunc:Dz},Mz=gO({opSnippet:"return float(a > b);",packedOpSnippet:"\n  return vec4(greaterThan(a, b));\n",cpuKernelImpl:eD,dtype:"bool"}),Lz={kernelName:ft,backendName:"webgl",kernelFunc:Mz},zz=gO({opSnippet:"return float(a >= b);",packedOpSnippet:"\n  return vec4(greaterThanEqual(a, b));\n",dtype:"bool",cpuKernelImpl:tD}),Pz={kernelName:mt,backendName:"webgl",kernelFunc:zz};const Bz={kernelName:yt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:s}=t;return pz(s,!0,n)}},Wz=mO({opSnippet:"return float(!isnan(x) && !isinf(x));",dtype:"bool"}),Vz={kernelName:xt,backendName:"webgl",kernelFunc:Wz},Uz=mO({opSnippet:"return float(isinf(x));",dtype:"bool"}),Gz={kernelName:wt,backendName:"webgl",kernelFunc:Uz},Hz=mO({opSnippet:"return float(isnan(x));",dtype:"bool"}),jz={kernelName:vt,backendName:"webgl",kernelFunc:Hz},qz=gO({opSnippet:"return float(a < b);",packedOpSnippet:"\n  return vec4(lessThan(a, b));\n",cpuKernelImpl:nD,dtype:"bool"}),Kz={kernelName:Nt,backendName:"webgl",kernelFunc:qz},Xz=gO({opSnippet:"return float(a <= b);",packedOpSnippet:"\n  return vec4(lessThanEqual(a, b));\n",cpuKernelImpl:sD,dtype:"bool"}),Yz={kernelName:It,backendName:"webgl",kernelFunc:Xz};const Zz={kernelName:St,backendName:"webgl",kernelFunc:function(e){const{backend:t,attrs:n}=e,{start:s,stop:r,num:a}=n,i=rD(s,r,a);return t.makeTensorInfo([i.length],"float32",i)}},Jz=mO({opSnippet:"if (isnan(x)) return x;\n  return x < 0.0 ? 0./0. : log(x);\n",packedOpSnippet:"\n  vec4 result = log(x);\n  bvec4 isNaN = isnan(x);\n  result.r = isNaN.r ? x.r : (x.r < 0.0 ? 0./0. : result.r);\n  result.g = isNaN.g ? x.g : (x.g < 0.0 ? 0./0. : result.g);\n  result.b = isNaN.b ? x.b : (x.b < 0.0 ? 0./0. : result.b);\n  result.a = isNaN.a ? x.a : (x.a < 0.0 ? 0./0. : result.a);\n  return result;\n",cpuKernelImpl:aD}),Qz={kernelName:Tt,backendName:"webgl",kernelFunc:Jz},eP=mO({opSnippet:"if (isnan(x)) return x;\n  return log(1.0 + x);\n"}),tP={kernelName:Ct,backendName:"webgl",kernelFunc:eP},nP=gO({opSnippet:"return float(a >= 1.0 && b >= 1.0);",packedOpSnippet:"\n  return vec4(\n    vec4(greaterThanEqual(a, vec4(1.0))) *\n    vec4(greaterThanEqual(b, vec4(1.0))));\n",dtype:"bool"}),sP={kernelName:$t,backendName:"webgl",kernelFunc:nP},rP=mO({opSnippet:"return float(!(x >= 1.0));"}),aP={kernelName:Et,backendName:"webgl",kernelFunc:rP},iP=gO({opSnippet:"return float(a >= 1.0 || b >= 1.0);",packedOpSnippet:"\n  return min(\n    vec4(greaterThanEqual(a, vec4(1.0))) +\n    vec4(greaterThanEqual(b, vec4(1.0))),\n    vec4(1.0));\n",dtype:"bool"}),oP={kernelName:At,backendName:"webgl",kernelFunc:iP};class lP{constructor(e,t,n,s,r){this.variableNames=["x"],this.outputShape=[];const a=t,i=e[3]-1;let o;this.outputShape=e;const l=`float(${n}) + float(${s}) * sum`;o=.5===r?`inversesqrt(${l})`:1===r?`1.0/(${l})`:`exp(log(${l}) * float(-${r}));`,this.userCode=`\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int r = coords[1];\n        int c = coords[2];\n        int d = coords[3];\n        float x = getX(b, r, c, d);\n        float sum = 0.0;\n        for (int j = -${a}; j <= ${a}; j++) {\n          int idx = d + j;\n          if (idx >= 0 && idx <=  ${i}) {\n            float z = getX(b, r, c, idx);\n            sum += z * z;\n          }\n        }\n        float val = x * ${o};\n        setOutput(val);\n      }\n    `}}class uP{constructor(e,t,n,s,r){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;const a=t,i=e[3]-1;let o;this.outputShape=e;const l=`float(${n}) + float(${s}) * sum`;o=.5===r?`inversesqrt(${l})`:1===r?`1.0/(${l})`:`exp(log(${l}) * float(-${r}));`,this.userCode=`\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords.x;\n        int r = coords.y;\n        int c = coords.z;\n        int d = coords.w;\n\n        bool hasNextCol = d < ${this.outputShape[3]};\n        bool hasNextRow = c < ${this.outputShape[2]};\n\n        vec4 sum = vec4(0.);\n        vec4 xFragAtOutputCoords = getX(b, r, c, d);\n\n        vec4 xAtOutputCoords = vec4(\n          getChannel(xFragAtOutputCoords, vec2(c, d)),\n          hasNextCol ?\n            getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,\n          hasNextRow ?\n            getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0\n        );\n\n        int firstChannel = d - ${a};\n        vec2 cache = vec2(0.);\n        if(firstChannel >= 0){\n          vec4 firstChannelFrag = getX(b, r, c, firstChannel);\n          cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));\n            if(hasNextRow){\n              cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));\n            }\n        }\n\n        ivec2 depth = ivec2(d, d + 1);\n        for (int j = - ${a}; j <= ${a}; j++) {\n          ivec2 idx = depth + j;\n          bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));\n          bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${i}));\n\n          bool depthInRange = aboveLowerBound.x && belowUpperBound.x;\n          bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;\n\n          if(depthInRange || depthPlusOneInRange){\n            vec4 z = vec4(0.);\n            vec4 xFragAtCurrentDepth;\n            z.xz = cache.xy;\n            if(depthPlusOneInRange && hasNextCol){\n              xFragAtCurrentDepth = idx.y != d ?\n                getX(b, r, c, idx.y) : xFragAtOutputCoords;\n              z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));\n              if(hasNextRow){\n                z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));\n              }\n            }\n            cache.xy = z.yw;\n            sum += z * z;\n          }\n        }\n        vec4 result = xAtOutputCoords * ${o};\n        setOutput(result);\n      }\n    `}}const cP={kernelName:_t,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{depthRadius:a,bias:i,alpha:o,beta:l}=s,u=Y().getBool("WEBGL_PACK_NORMALIZATION")?new uP(r.shape,a,i,o,l):new lP(r.shape,a,i,o,l);return n.runWebGLProgram(u,[r],r.dtype)}};class hP{constructor(e,t,n,s,r){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=n,this.alpha=s,this.beta=r,this.userCode=`\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int r = coords[1];\n        int c = coords[2];\n\n        float result = 0.0;\n        for (int d = 0; d < ${this.depth}; ++d) {\n          int depthBegin = int(max(0.0, float(d - ${t})));\n          int depthEnd = int(min(float(${this.depth}),\n              float(d + ${t} + 1)));\n\n          const int MIN_DEPTH_BEGIN = 0;\n          const int MAX_DEPTH_END = ${this.depth};\n\n          float norm = 0.0;\n          for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {\n            if (k < depthBegin){\n              continue;\n            }\n            else if (k >= depthBegin && k < depthEnd) {\n              norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);\n            }\n            else {\n              break;\n            }\n          }\n\n          norm = float(${s}) * norm + float(${n});\n\n          for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){\n            if (k < depthBegin){\n              continue;\n            }\n            else if (k >= depthBegin && k < depthEnd){\n              float dyi = -2.0 * float(${s})\n                * float(${r})\n                * getInputImage(b, r, c, k) * getOutputImage(b, r, c, d)\n                / norm;\n              if (k == d) {\n                dyi += pow(norm, -1.0 * ${r});\n              }\n              if (k == coords[3]) {\n                dyi *= getDy(b, r, c, d);\n                result += dyi;\n              }\n            }\n            else {\n              break;\n            }\n          }\n      }\n      setOutput(result);\n      }\n    `}}const pP={kernelName:Ft,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:s}=e,{x:r,y:a,dy:i}=t,{depthRadius:o,bias:l,alpha:u,beta:c}=s,h=new hP(r.shape,o,l,u,c);return n.runWebGLProgram(h,[r,a,i],r.dtype)}};function dP(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{reductionIndices:a,keepDims:i}=s,o=r.shape.length,l=v(a,r.shape);let u=l;const c=dl(u,o),h=null!=c,p=n.shouldExecuteOnCPU([r]);let f=r;if(h){if(p){const e=n.texData.get(f.dataId).values,t=new Array(o);for(let e=0;e<t.length;e++)t[e]=r.shape[c[e]];const s=DD(e,r.shape,r.dtype,c,t);f=n.makeTensorInfo(t,r.dtype);n.texData.get(f.dataId).values=s}else f=_O(r,c,n);u=ml(u.length,o)}pl("max",u,o);const[m,g]=cl(f.shape,u);let y,b=m;if(i&&(b=hl(m,l)),p){const e=n.texData.get(f.dataId).values,t=iD(e,d(g),b,r.dtype);y=n.makeTensorInfo(b,r.dtype);n.texData.get(y.dataId).values=t}else y=function(e,t,n,s){const r=d(t),a=SO({inputs:{x:e},attrs:{shape:[d(e.shape)/r,r]},backend:s}),i=EO(a,e.dtype,"max",s),o=SO({inputs:{x:i},attrs:{shape:n},backend:s});return s.disposeIntermediateTensorInfo(a),s.disposeIntermediateTensorInfo(i),o}(f,g,b,n);return h&&n.disposeIntermediateTensorInfo(f),y}const fP={kernelName:Dt,backendName:"webgl",kernelFunc:dP},mP=gO({opSnippet:"\n  if (isnan(a)) return a;\n  if (isnan(b)) return b;\n\n  return max(a, b);\n",packedOpSnippet:"\n  vec4 result = vec4(max(a, b));\n  bvec4 isNaNA = isnan(a);\n  bvec4 isNaNB = isnan(b);\n  bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);\n  \n  result.r = isNaN.r ? NAN : result.r;\n  result.g = isNaN.g ? NAN : result.g;\n  result.b = isNaN.b ? NAN : result.b;\n  result.a = isNaN.a ? NAN : result.a;\n\n  return result;\n",cpuKernelImpl:oD}),gP={kernelName:Ot,backendName:"webgl",kernelFunc:mP};const yP={kernelName:Mt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t;L_(r,"maxPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:l}=s;c(so(i,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const u=qi(r.shape,a,i,1,o,l);if(1===u.filterWidth&&1===u.filterHeight&&m(u.inShape,u.outShape))return aO({inputs:{x:r},backend:n});const h=new gM(u,"max",!1);return n.runWebGLProgram(h,[r],r.dtype)}};const bP={kernelName:zt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{filterSize:a,strides:i,pad:o,dataFormat:l,dimRoundingMode:u}=s,c=Ki(r.shape,a,i,[1,1,1],o,u,l),h=new yM(c,"max",!1);return n.runWebGLProgram(h,[r],r.dtype)}};class xP{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideHeight,n=e.strideWidth,s=e.dilationHeight,r=e.effectiveFilterHeight,a=e.effectiveFilterWidth,i=r-1-e.padInfo.top,o=a-1-e.padInfo.left,l=r*a-1;this.userCode=`\n      const ivec2 pads = ivec2(${i}, ${o});\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n\n        ivec2 dyRCCorner = coords.yz - pads;\n        int dyRCorner = dyRCCorner.x;\n        int dyCCorner = dyRCCorner.y;\n\n        // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n        for (int wR = 0; wR < ${r};\n          wR += ${s}) {\n          float dyR = float(dyRCorner + wR) / ${t}.0;\n\n          if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {\n            continue;\n          }\n          int idyR = int(dyR);\n\n          for (int wC = 0; wC < ${a}; wC++) {\n            float dyC = float(dyCCorner + wC) / ${n}.0;\n\n            if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n                fract(dyC) > 0.0) {\n              continue;\n            }\n            int idyC = int(dyC);\n\n            float dyValue = getDy(b, idyR, idyC, d);\n            int maxPosValue = ${l} - int(getMaxPos(b, idyR, idyC, d));\n\n            // Get the current value, check it against the value from the\n            // position matrix.\n            int curPosValue = wR * ${a} + wC;\n            float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n            dotProd += dyValue * mask;\n          }\n        }\n        setOutput(dotProd);\n      }\n    `}}class wP{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;const t=e.strideDepth,n=e.strideHeight,s=e.strideWidth,r=e.dilationDepth,a=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterDepth,l=e.effectiveFilterHeight,u=e.effectiveFilterWidth,c=o-1-e.padInfo.front,h=l-1-e.padInfo.top,p=u-1-e.padInfo.left,d=o*l*u-1;this.userCode=`\n      const ivec3 pads = ivec3(${c}, ${h}, ${p});\n\n      void main() {\n        ivec5 coords = getOutputCoords();\n        int batch = coords.x;\n        int ch = coords.u;\n\n        ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;\n        int dyDCorner = dyCorner.x;\n        int dyRCorner = dyCorner.y;\n        int dyCCorner = dyCorner.z;\n\n        // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get\n        // dx(xD, xR, xC, ch).\n        // ? = to be determined. : = across all values in that axis.\n        float dotProd = 0.0;\n\n        for (int wD = 0; wD < ${o};\n           wD += ${r}) {\n          float dyD = float(dyDCorner + wD) / ${t}.0;\n\n          if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {\n            continue;\n          }\n          int idyD = int(dyD);\n\n          for (int wR = 0; wR < ${l};\n              wR += ${a}) {\n            float dyR = float(dyRCorner + wR) / ${n}.0;\n\n            if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||\n                fract(dyR) > 0.0) {\n              continue;\n            }\n            int idyR = int(dyR);\n\n            for (int wC = 0; wC < ${u};\n                wC += ${i}) {\n              float dyC = float(dyCCorner + wC) / ${s}.0;\n\n              if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||\n                  fract(dyC) > 0.0) {\n                continue;\n              }\n              int idyC = int(dyC);\n\n              float dyValue = getDy(batch, idyD, idyR, idyC, ch);\n              int maxPosValue = ${d} -\n                  int(getMaxPos(batch, idyD, idyR, idyC, ch));\n\n              // Get the current value, check it against the value from the\n              // position matrix.\n              int curPosValue =\n                  wD * ${l} * ${u} +\n                  wR * ${u} + wC;\n              float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);\n\n              dotProd += dyValue * mask;\n            }\n          }\n        }\n        setOutput(dotProd);\n      }\n    `}}const vP={kernelName:Pt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,i=a,{filterSize:o,strides:l,pad:u,dimRoundingMode:c}=s,h=Ki(i.shape,o,l,[1,1,1],u,c),p=new yM(h,"max",!0),d=n.runWebGLProgram(p,[i],i.dtype),f=new wP(h),m=n.runWebGLProgram(f,[r,d],i.dtype);return n.disposeIntermediateTensorInfo(d),m}};const kP={kernelName:Lt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a,output:i}=t,o=a;L_([a,i],"maxPoolGrad");const{filterSize:l,strides:u,pad:c,dimRoundingMode:h}=s,p=qi(o.shape,l,u,1,c,h),d=new gM(p,"max",!0),f=n.runWebGLProgram(d,[o],o.dtype),m=new xP(p),g=n.runWebGLProgram(m,[r,f],o.dtype);return n.disposeIntermediateTensorInfo(f),g}};const NP={kernelName:Bt,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{filterSize:r,strides:a,pad:i,includeBatchInIndex:o}=t,l=n;c(4===s.shape.length,(()=>`Error in maxPool: input must be rank 4 but got rank ${s.shape.length}.`));const u=[1,1];c(so(a,u),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`));const h=qi(s.shape,r,a,u,i),[p,d]=function(e,t,n,s){let r=new gM(n,"max",!1);const a=s.runWebGLProgram(r,[e],"float32");return r=new gM(n,"max",!0,!0,t),[a,s.runWebGLProgram(r,[e],"float32")]}(s,o,h,l);return[p,d]}};const IP={kernelName:Wt,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{keepDims:r,axis:a}=t,i=n,o=s.shape.length,l=v(a,s.shape);let u=l;const c=dl(u,o),h=null!=c,p=i.shouldExecuteOnCPU([s]),f=[];let m=s;if(h){if(p){const e=i.texData.get(m.dataId).values,t=new Array(o);for(let e=0;e<t.length;e++)t[e]=s.shape[c[e]];const n=DD(e,s.shape,s.dtype,c,t);m=i.makeTensorInfo(t,s.dtype);i.texData.get(m.dataId).values=n}else m=_O(s,c,i);f.push(m),u=ml(u.length,o)}pl("sum",u,o);const[g,y]=cl(m.shape,u);let b=g;r&&(b=hl(g,l));const x=function(e,t,n,s){const r=d(t),a=SO({inputs:{x:e},attrs:{shape:[d(e.shape)/r,r]},backend:s}),i=EO(a,"float32","mean",s),o=SO({inputs:{x:i},attrs:{shape:n},backend:s});return s.disposeIntermediateTensorInfo(a),s.disposeIntermediateTensorInfo(i),o}(m,y,b,i);for(const e of f)i.disposeIntermediateTensorInfo(e);return x}};const SP={kernelName:Vt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s,o=r.shape.length,l=v(a,r.shape);let u=l;const c=dl(u,o);let h=r;null!=c&&(h=OO({inputs:{x:r},backend:n,attrs:{perm:c}}),u=ml(u.length,r.shape.length)),pl("min",u,o);const[p,f]=cl(h.shape,u),m=SO({inputs:{x:h},backend:n,attrs:{shape:[-1,d(f)]}}),g=EO(m,m.dtype,"min",n);let y;if(i){y=SO({inputs:{x:g},backend:n,attrs:{shape:hl(p,l)}})}else y=SO({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),null!=c&&n.disposeIntermediateTensorInfo(h),y}},TP=gO({opSnippet:"\n  if (isnan(a)) return a;\n  if (isnan(b)) return b;\n\n  return min(a, b);\n",packedOpSnippet:"\n  vec4 result = vec4(min(a, b));\n  bvec4 isNaNA = isnan(a);\n  bvec4 isNaNB = isnan(b);\n  bvec4 isNaN = bvec4(isNaNA.x || isNaNB.x, isNaNA.y || isNaNB.y, isNaNA.z || isNaNB.z, isNaNA.w || isNaNB.w);\n  \n  result.r = isNaN.r ? NAN : result.r;\n  result.g = isNaN.g ? NAN : result.g;\n  result.b = isNaN.b ? NAN : result.b;\n  result.a = isNaN.a ? NAN : result.a;\n\n  return result;\n",cpuKernelImpl:lD}),CP={kernelName:Ut,backendName:"webgl",kernelFunc:TP};class $P{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1]));const s=e.length,r=sF(s),a=t.map((e=>e[0])).join(","),i=t.map(((t,n)=>t[0]+e[n])).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,s),l="reflect"===n?0:1;this.userCode=1!==s?`\n      ${r} start = ${r}(${a});\n      ${r} end = ${r}(${i});\n\n      void main() {\n        ${r} outC = getOutputCoords();\n        for (int i = 0; i < ${s}; i++) {\n          if (outC[i] < start[i]) {\n            outC[i] = start[i] * 2 - outC[i] - ${l};\n          } else if(outC[i] >= end[i]) {\n            outC[i] = (end[i] - 1) * 2 - outC[i] + ${l};\n          }\n        }\n        ${r} coords = outC - start;\n        setOutput(getX(${o}));\n      }\n    `:`\n        int start = ${a};\n        int end = ${i};\n\n        void main() {\n          int outC = getOutputCoords();\n          if (outC < start) {\n            outC = start * 2 - outC - ${l};\n          } else if(outC >= end) {\n            outC = (end - 1) * 2 - outC + ${l};\n          }\n          setOutput(getX(outC - start));\n        }\n      `}}class EP{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1]));const s=e.length,r=sF(s),a=t.map((e=>e[0])).join(","),i=t.map(((t,n)=>t[0]+e[n])).join(","),o=LD("rc",s),l=LD("source",s),u=`${o[s-1]} < ${this.outputShape[s-1]}`,c=1===s?"source":`vec2(${l.slice(-2).join()})`,h="reflect"===n?0:1;let p="";if(1===s){const e=`\n        ${r} source = rc;\n        if (source < start) {\n          source = start * 2 - source - ${h};\n        } else if (source >= end) {\n          source = (end - 1) * 2 - source + ${h};\n        }\n        source -= start;\n      `;p=`\n        ${r} rc = outputLoc;\n        ${e}\n        result[0] = getChannel(getX(${l.join()}), ${c});\n        ${o[s-1]} += 1;\n        if(${u}) {\n          ${e}\n          result[1] = getChannel(getX(${l.join()}), ${c});\n        }\n      `}else{const e=`\n        ${r} source = rc;\n        ${r} lt = ${r}(lessThan(source, start));\n        ${r} gte = ${r}(greaterThanEqual(source, end));\n        ${r} orig = 1 - (lt + gte);\n        source = orig * source +\n                lt * (start * 2 - source - ${h}) +\n                gte * ((end - 1) * 2 - source + ${h});\n        source -= start;\n      `;p=`\n        ${r} rc = outputLoc;\n        ${e}\n        result[0] = getChannel(getX(${l.join()}), ${c});\n        ${o[s-1]} += 1;\n        if(${u}) {\n          ${e}\n          result[1] = getChannel(getX(${l.join()}), ${c});\n        }\n        rc = outputLoc;\n        ${o[s-2]} += 1;\n        if(${o[s-2]} < ${this.outputShape[s-2]}) {\n          ${e}\n          result[2] = getChannel(getX(${l.join()}), ${c});\n          ${o[s-1]} += 1;\n          if(${u}) {\n            ${e}\n            result[3] = getChannel(getX(${l.join()}), ${c});\n          }\n        }\n      `}this.userCode=`\n      const ${r} start = ${r}(${a});\n      const ${r} end = ${r}(${i});\n\n      void main() {\n        ${r} outputLoc = getOutputCoords();\n        vec4 result = vec4(0.);\n        ${p}\n        setOutput(result);\n      }\n    `}}const AP={kernelName:Gt,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s}=e,{paddings:r,mode:a}=n,i=Y().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new EP(s.shape,r,a):new $P(s.shape,r,a);return t.runWebGLProgram(i,[s],s.dtype)}},RP=gO({opSnippet:"if (b == 0.0) return NAN;\n  return mod(a, b);",packedOpSnippet:"\n  vec4 result = mod(a, b);\n  bvec4 isNaN = equal(b, vec4(0.0));\n  \n  result.r = isNaN.r ? NAN : result.r;\n  result.g = isNaN.g ? NAN : result.g;\n  result.b = isNaN.b ? NAN : result.b;\n  result.a = isNaN.a ? NAN : result.a;\n\n  return result;\n"}),_P={kernelName:Ht,backendName:"webgl",kernelFunc:RP};class FP{constructor(e,t,n){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[e,n],this.userCode=`\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int batch = coords[0];\n\n        float r = random(seed);\n        float cdf = 0.0;\n\n        for (int i = 0; i < ${t-1}; i++) {\n          cdf += getProbs(batch, i);\n\n          if (r < cdf) {\n            setOutput(float(i));\n            return;\n          }\n        }\n\n        // If no other event happened, last event happened.\n        setOutput(float(${t-1}));\n      }\n    `}}const DP=gO({opSnippet:"\nif (a == b) {\n  return 1.0;\n};\nreturn a / b;",packedOpSnippet:"\n  // vec4 one = vec4(equal(a, b));\n  // return one + (vec4(1.0) - one) * a / b;\n  vec4 result = a / b;\n  if(a.x == b.x) {\n    result.x = 1.;\n  }\n  if(a.y == b.y) {\n    result.y = 1.;\n  }\n  if(a.z == b.z) {\n    result.z = 1.;\n  }\n  if(a.w == b.w) {\n    result.w = 1.;\n  }\n\n  return result;\n",checkOutOfBounds:!0}),OP={kernelName:Ze,backendName:"webgl",kernelFunc:DP},MP="return a - b;",LP=gO({opSnippet:MP,packedOpSnippet:MP,supportsComplex:!0,cpuKernelImpl:RD}),zP={kernelName:Zn,backendName:"webgl",kernelFunc:LP};function PP(e){const{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{dim:a}=s,i=v([a],r.shape),o=dP({inputs:{x:r},backend:n,attrs:{reductionIndices:i,keepDims:!1}}),l=hl(o.shape,i),u=SO({inputs:{x:o},backend:n,attrs:{shape:l}}),c=LP({inputs:{a:r,b:u},backend:n}),h=rz({inputs:{x:c},backend:n}),p=FO({inputs:{x:h},backend:n,attrs:{axis:i,keepDims:!1}}),d=SO({inputs:{x:p},backend:n,attrs:{shape:l}}),f=DP({inputs:{a:h,b:d},backend:n});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),f}const BP={kernelName:zn,backendName:"webgl",kernelFunc:PP};const WP={kernelName:jt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{numSamples:a,seed:i,normalized:o}=s,l=o?r:PP({inputs:{logits:r},backend:n,attrs:{dim:r.shape.length-1}}),u=l.shape[0],c=l.shape[1],h=new FP(u,c,a),p=[[i]],d=n.runWebGLProgram(h,[l],"int32",p);return o||n.disposeIntermediateTensorInfo(l),d}};const VP={kernelName:Kt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:s}=t;if(n.shouldExecuteOnCPU([s])){const e=n.texData.get(s.dataId),[t,r]=cD(e.values,s.shape,s.dtype);return n.makeTensorInfo(r,s.dtype,t)}let r;return r=Y().getBool("WEBGL_PACK_UNARY_OPERATIONS")?new qD(s.shape,"\n  vec4 result = -x;\n  bvec4 isNaN = isnan(x);\n\n  result.r = isNaN.r ? x.r : result.r;\n  result.g = isNaN.g ? x.g : result.g;\n  result.b = isNaN.b ? x.b : result.b;\n  result.a = isNaN.a ? x.a : result.a;\n\n  return result;\n"):new GD(s.shape,"if (isnan(x)) return x;\n  return -x;\n"),n.runWebGLProgram(r,[s],s.dtype)}},UP=ep;const GP={kernelName:Yt,backendName:"webgl",kernelFunc:function(e){fs("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:s}=e,{boxes:r,scores:a}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=s,u=n.readSync(r.dataId),c=n.readSync(a.dataId),{selectedIndices:h}=UP(u,c,i,o,l);return n.makeTensorInfo([h.length],"int32",new Int32Array(h))}},HP=tp;const jP={kernelName:Zt,backendName:"webgl",kernelFunc:function(e){fs("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:s}=e,{boxes:r,scores:a}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:u}=s,c=n.readSync(r.dataId),h=n.readSync(a.dataId),{selectedIndices:p,validOutputs:d}=HP(c,h,i,o,l,u);return[n.makeTensorInfo([p.length],"int32",new Int32Array(p)),n.makeTensorInfo([],"int32",new Int32Array([d]))]}},qP=np;const KP={kernelName:Jt,backendName:"webgl",kernelFunc:function(e){fs("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");const{inputs:t,backend:n,attrs:s}=e,{boxes:r,scores:a}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:u}=s,c=n.readSync(r.dataId),h=n.readSync(a.dataId),p=i,d=o,f=l,m=u,{selectedIndices:g,selectedScores:y}=qP(c,h,p,d,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}};class XP{constructor(e,t,n,s){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int index = round(getIndices(coords.x));\n        setOutput(mix(float(${s}), float(${n}),\n                      float(index == coords.y)));\n      }\n    `}}const YP={kernelName:en,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:s}=e,{indices:r}=t,{dtype:a,depth:i,onValue:o,offValue:l}=s,u=d(r.shape),c=new XP(u,i,o,l),h=SO({inputs:{x:r},backend:n,attrs:{shape:[u]}}),p=n.runWebGLProgram(c,[h],a);n.disposeIntermediateTensorInfo(h);const f=SO({inputs:{x:p},backend:n,attrs:{shape:[...r.shape,i]}});return n.disposeIntermediateTensorInfo(p),f}};function ZP(e){const{inputs:t,backend:n}=e,{x:s}=t;if("complex64"===s.dtype){const e=PM({inputs:{input:s},backend:n}),t=ZP({inputs:{x:e},backend:n}),r=eL({inputs:{input:s},backend:n}),a=ZP({inputs:{x:r},backend:n}),i=oO({inputs:{real:t,imag:a},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(a),i}return mz({attrs:{shape:s.shape,dtype:s.dtype,value:"string"===s.dtype?"":0},backend:n})}const JP={kernelName:os,backendName:"webgl",kernelFunc:ZP};const QP={kernelName:Qt,backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:s}=t,{x:r}=n;if("string"===r.dtype)throw new Error("onesLike is not supported under string dtype");if("complex64"===r.dtype){const t=PM({inputs:{input:r},backend:s}),n=e({inputs:{x:t},backend:s}),a=eL({inputs:{input:r},backend:s}),i=ZP({inputs:{x:a},backend:s}),o=oO({inputs:{real:n,imag:i},backend:s});return s.disposeIntermediateTensorInfo(t),s.disposeIntermediateTensorInfo(n),s.disposeIntermediateTensorInfo(a),s.disposeIntermediateTensorInfo(i),o}return mz({attrs:{shape:r.shape,dtype:r.dtype,value:1},backend:s})}};const eB={kernelName:tn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{axis:r}=s;if(1===t.length)return iz({inputs:{input:t[0]},backend:n,attrs:{dim:r}});const a=t[0].shape,i=t[0].dtype;t.forEach((e=>{h(a,e.shape,"All tensors passed to stack must have matching shapes"),c(i===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const o=[],l=sL({inputs:t.map((e=>{const t=iz({inputs:{input:e},backend:n,attrs:{dim:r}});return o.push(t),t})),backend:n,attrs:{axis:r}});return o.forEach((e=>n.disposeIntermediateTensorInfo(e))),l}};class tB{constructor(e,t,n){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1]));const s=e.length,r=sF(s),a=t.map((e=>e[0])).join(","),i=t.map(((t,n)=>t[0]+e[n])).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,s);this.userCode=1!==s?`\n      ${r} start = ${r}(${a});\n      ${r} end = ${r}(${i});\n\n      void main() {\n        ${r} outC = getOutputCoords();\n        if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {\n          setOutput(value);\n        } else {\n          ${r} coords = outC - start;\n          setOutput(getX(${o}));\n        }\n      }\n    `:`\n        int start = ${a};\n        int end = ${i};\n\n        void main() {\n          int outC = getOutputCoords();\n          if (outC < start || outC >= end) {\n            setOutput(value);\n          } else {\n            setOutput(getX(outC - start));\n          }\n        }\n      `}}class nB{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1]));const s=e.length,r=sF(s),a=t.map((e=>e[0])).join(","),i=t.map(((t,n)=>t[0]+e[n])).join(","),o=LD("rc",s),l=LD("source",s),u=`${o[s-1]} < ${this.outputShape[s-1]}`,c=1===s?"source":`vec2(${l.slice(-2).join()})`,h=[`${r} rc = outputLoc;`,`${o[s-1]} += 1;\n       if(${u}) {\n      `,1===s?"":`}\n       rc = outputLoc;\n       ${o[s-2]} += 1;\n       if(${o[s-2]} < ${this.outputShape[s-2]}) {`,1===s?"":`  ${o[s-1]} += 1;\n         if(${u}) {`],p=1===s?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))";let d="";for(let e=0,t=1===s?2:4;e<t;e++)d+=`\n        ${h[e]}\n        if (${p}) {\n          result[${e}] = float(value);\n        } else {\n          ${r} source = rc - start;\n          result[${e}] = getChannel(getX(${l.join()}), ${c});\n        }\n      `;d+=1===s?"} ":"}}",this.userCode=`\n      const ${r} start = ${r}(${a});\n      const ${r} end = ${r}(${i});\n\n      void main() {\n        ${r} outputLoc = getOutputCoords();\n        vec4 result = vec4(0.);\n        ${d}\n        setOutput(result);\n      }\n    `}}const sB=e=>{const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{paddings:a,constantValue:i}=s;if(0===d(r.shape)){const e=a.map(((e,t)=>e[0]+r.shape[t]+e[1]));return mz({backend:n,attrs:{shape:e,value:i,dtype:r.dtype}})}const o=Y().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new nB(r.shape,a,i):new tB(r.shape,a,i),l=[[i]];return n.runWebGLProgram(o,[r],r.dtype,l)},rB={kernelName:nn,backendName:"webgl",kernelFunc:sB},aB=gO({opSnippet:"\n  if(a < 0.0 && floor(b) < b){\n    return NAN;\n  }\n  if (b == 0.0) {\n    return 1.0;\n  }\n  return (round(mod(b, 2.0)) != 1) ?\n      pow(abs(a), b) : sign(a) * pow(abs(a), b);\n",packedOpSnippet:"\n  // isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.\n  vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));\n  vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);\n  vec4 result = multiplier * pow(abs(a), b);\n\n  // Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS\n  bvec4 isExpZero = equal(b, vec4(0.0));\n  result.r = isExpZero.r ? 1.0 : result.r;\n  result.g = isExpZero.g ? 1.0 : result.g;\n  result.b = isExpZero.b ? 1.0 : result.b;\n  result.a = isExpZero.a ? 1.0 : result.a;\n\n  bvec4 isNaN1 = lessThan(a, vec4(0.0));\n  bvec4 isNaN2 = lessThan(floor(b), b);\n  bvec4 isNaN = bvec4(isNaN1.x && isNaN2.x, isNaN1.y && isNaN2.y, isNaN1.z && isNaN2.z, isNaN1.w && isNaN2.w);\n  \n  result.r = isNaN.r ? NAN : result.r;\n  result.g = isNaN.g ? NAN : result.g;\n  result.b = isNaN.b ? NAN : result.b;\n  result.a = isNaN.a ? NAN : result.a;\n\n  return result;\n"}),iB={kernelName:sn,backendName:"webgl",kernelFunc:aB};const oB={kernelName:an,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s,o=r.shape.length,l=[],u=v(a,r.shape);let c=u;const h=dl(c,o);let p,f=r;if(null!=h&&(f=OO({inputs:{x:r},backend:n,attrs:{perm:h}}),c=ml(c.length,o),l.push(f)),pl("prod",c,o),n.shouldExecuteOnCPU([f])){const e=n.texData.get(f.dataId).values,{outVals:t,outShape:s,outDtype:r}=pD(f.shape,f.dtype,e,c);p=n.makeTensorInfo(s,r,t)}else{const[e,t]=cl(f.shape,c),s=d(t),a=SO({inputs:{x:f},backend:n,attrs:{shape:[-1,s]}}),i=EO(a,Vr(r.dtype),"prod",n);p=SO({inputs:{x:i},backend:n,attrs:{shape:e}}),l.push(a),l.push(i)}if(i){l.push(p);const e=hl(p.shape,u);p=SO({inputs:{x:p},backend:n,attrs:{shape:e}})}return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),p}};const lB={kernelName:on,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{paramsNestedSplits:r,paramsDenseValues:a,indices:i}=t,{outputRaggedRank:o}=s,l=r.map((e=>n.readSync(e.dataId))),u=r.map((e=>e.shape)),c=n.readSync(a.dataId),h=n.readSync(i.dataId),[p,d,f]=dD(l,u,c,a.shape,a.dtype,h,i.shape,o),m=p.map((e=>n.makeTensorInfo([e.length],"int32",e))),g=n.makeTensorInfo(f,a.dtype,d);return m.concat([g])}};const uB={kernelName:ln,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{starts:s,limits:r,deltas:a}=t,i=n.readSync(s.dataId),o=n.readSync(r.dataId),l=n.readSync(a.dataId),[u,c]=fD(i,s.shape,s.dtype,o,r.shape,l,a.shape);return[n.makeTensorInfo([u.length],"int32",u),n.makeTensorInfo([c.length],s.dtype,c)]}};const cB={kernelName:un,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{shape:r,values:a,defaultValue:i,rowPartitionTensors:o}=t,{rowPartitionTypes:l}=s,u=n.readSync(r.dataId),c=n.readSync(a.dataId),h=n.readSync(i.dataId),p=o.map((e=>n.readSync(e.dataId))),d=o.map((e=>e.shape)),[f,m]=mD(u,r.shape,c,a.shape,a.dtype,h,i.shape,p,d,l);return n.makeTensorInfo(f,a.dtype,m)}},hB=e=>{const{backend:t,attrs:n}=e,{start:s,stop:r,step:a,dtype:i}=n,o=gD(s,r,a,i);return t.makeTensorInfo([o.length],i,o)},pB={kernelName:cn,backendName:"webgl",kernelFunc:hB},dB=mO({opSnippet:"return 1.0 / x;"}),fB={kernelName:pn,backendName:"webgl",kernelFunc:dB},mB=mO({opSnippet:"if (isnan(x)) return x;\n  return (x < 0.0) ? 0.0 : x;\n",packedOpSnippet:"\n  vec4 result = x * vec4(greaterThanEqual(x, vec4(0.0)));\n  bvec4 isNaN = isnan(x);\n\n  result.r = isNaN.r ? x.r : result.r;\n  result.g = isNaN.g ? x.g : result.g;\n  result.b = isNaN.b ? x.b : result.b;\n  result.a = isNaN.a ? x.a : result.a;\n\n  return result;\n"}),gB={kernelName:dn,backendName:"webgl",kernelFunc:mB},yB=mO({opSnippet:"if (isnan(x)) return x;\n  return (x < 0.0) ? 0.0 : min(6.0, x);\n",packedOpSnippet:"\n  vec4 result = min(x, vec4(6.)) * vec4(greaterThanEqual(x, vec4(0.0)));\n  bvec4 isNaN = isnan(x);\n\n  result.r = isNaN.r ? x.r : result.r;\n  result.g = isNaN.g ? x.g : result.g;\n  result.b = isNaN.b ? x.b : result.b;\n  result.a = isNaN.a ? x.a : result.a;\n\n  return result;\n"}),bB={kernelName:xn,backendName:"webgl",kernelFunc:yB};class xB{constructor(e,t,n,s,r){this.variableNames=["A"],this.outputShape=[];const[a,i,o,l]=e;this.outputShape=[a,t,n,l];const u=[s&&t>1?i-1:i,s&&n>1?o-1:o],c=[s&&t>1?t-1:t,s&&n>1?n-1:n];let h;h=r?"(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":"vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n      const vec2 effectiveInputOverOutputRatioRC = vec2(\n          ${u[0]/c[0]},\n          ${u[1]/c[1]});\n      const vec2 inputShapeRC = vec2(${i}.0, ${o}.0);\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n        ivec2 yRC = coords.yz;\n\n        // Fractional source index.\n        vec2 sourceFracIndexRC = ${h};\n\n        // Compute the four integer indices.\n        ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0)));\n        ivec2 sourceCeilRC = ivec2(\n          min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n        float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);\n        float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);\n        float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);\n        float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);\n\n        vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);\n\n        float top = topLeft + (topRight - topLeft) * fracRC.y;\n        float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;\n        float newValue = top + (bottom - top) * fracRC.x;\n\n        setOutput(newValue);\n      }\n    `}}class wB{constructor(e,t,n,s,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[a,i,o,l]=e;this.outputShape=[a,t,n,l];const u=[s&&t>1?i-1:i,s&&n>1?o-1:o],c=[s&&t>1?t-1:t,s&&n>1?n-1:n];let h;h=r?"(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":"vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n      const vec3 effectiveInputOverOutputRatioRC = vec3(\n          ${u[0]/c[0]},\n          ${u[1]/c[1]},\n          ${u[1]/c[1]});\n      const vec3 inputShapeRC = vec3(${i}.0, ${o}.0,\n                                     ${o}.0);\n\n      float getAValue(int b, int r, int c, int d) {\n        return getChannel(getA(b, r, c, d), vec2(c, d));\n      }\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n        // Calculate values for next column in yRC.z.\n        ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n        // Fractional source index.\n        vec3 sourceFracIndexRC = ${h};\n\n        // Compute the four integer indices.\n        ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0)));\n        ivec3 sourceCeilRC = ivec3(\n          min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));\n\n        // Should we calculate next column and row elements in 2x2 packed cell.\n        bool hasNextCol = d < ${l-1};\n        bool hasNextRow = coords.z < ${n-1};\n\n        // In parallel, construct four corners for all four components in\n        // packed 2x2 cell.\n        vec4 topLeft = vec4(\n          getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),\n          hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)\n                     : 0.0,\n          hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)\n                     : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n        vec4 bottomLeft = vec4(\n          getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),\n          hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)\n                     : 0.0,\n          hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)\n                     : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);\n\n        vec4 topRight = vec4(\n          getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),\n          hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)\n                     : 0.0,\n          hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)\n                     : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n        vec4 bottomRight = vec4(\n          getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),\n          hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)\n                     : 0.0,\n          hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)\n                     : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);\n\n        vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);\n\n        vec4 top = mix(topLeft, topRight, fracRC.yyzz);\n        vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);\n        vec4 newValue = mix(top, bottom, fracRC.x);\n\n        setOutput(newValue);\n      }\n    `}}const vB={kernelName:yn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,halfPixelCenters:i,size:o}=s,[l,u]=o,c=Y().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new wB(r.shape,l,u,a,i):new xB(r.shape,l,u,a,i);return n.runWebGLProgram(c,[r],"float32")}};class kB{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;const[,s,r]=t,[,a,i]=e,o=[n&&a>1?s-1:s,n&&i>1?r-1:r],l=[n&&a>1?a-1:a,n&&i>1?i-1:i],u=o[0]/l[0],c=o[1]/l[1],h=1/u,p=1/c,d=2*Math.ceil(h)+2,f=2*Math.ceil(p)+2;this.userCode=`\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n        int r = coords[1];\n        int c = coords[2];\n\n        float accumulator = 0.0;\n\n        const float heightScale = float(${u});\n        const float widthScale = float(${c});\n\n        const float invHeightScale = float(${h});\n        const float invWidthScale = float(${p});\n\n        const int winHeight = int(${d});\n        const int winWidth = int(${f});\n\n        // Compute bounds for where in dy we will look\n        float startRLerp = floor(float(r) * invHeightScale);\n        int startDyR = int(startRLerp - float(winHeight / 2));\n\n        float startCLerp = floor(float(c) * invWidthScale);\n        int startDyC = int(startCLerp - float(winWidth / 2));\n\n        // Loop over dy\n        for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n          int dyR = dyROffset + startDyR;\n\n          // Guard against the window exceeding the bounds of dy\n          if (dyR < 0 || dyR >= ${a}) {\n            continue;\n          }\n\n          for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n            int dyC = dyCOffset + startDyC;\n\n            // Guard against the window exceeding the bounds of dy\n            if (dyC < 0 || dyC >= ${i}) {\n              continue;\n            }\n\n            float dxR = float(dyR) * heightScale;\n            int topDxRIndex = int(floor(dxR));\n            int bottomDxRIndex = int(min(ceil(dxR), ${s-1}.0));\n            float dxRLerp = dxR - float(topDxRIndex);\n            float inverseDxRLerp = 1.0 - dxRLerp;\n\n            float dxC = float(dyC) * widthScale;\n            int leftDxCIndex = int(floor(dxC));\n            int rightDxCIndex = int(min(ceil(dxC), ${r-1}.0));\n            float dxCLerp = dxC - float(leftDxCIndex);\n            float inverseDxCLerp = 1.0 - dxCLerp;\n\n            if (r == topDxRIndex && c == leftDxCIndex) {\n              // topLeft\n              accumulator +=\n                getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp;\n            }\n\n            if (r == topDxRIndex && c == rightDxCIndex) {\n              // topRight\n              accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp;\n            }\n\n            if (r == bottomDxRIndex && c == leftDxCIndex) {\n              // bottomLeft\n              accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp;\n            }\n\n            if (r == bottomDxRIndex && c == rightDxCIndex) {\n              // bottomRight\n              accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp;\n            }\n          }\n        }\n        // End loop over dy\n\n        setOutput(accumulator);\n      }\n    `}}const NB={kernelName:bn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{images:r,dy:a}=t,{alignCorners:i}=s,o=new kB(a.shape,r.shape,i);return n.runWebGLProgram(o,[a],a.dtype)}};class IB{constructor(e,t,n,s,r){this.variableNames=["A"],this.outputShape=[];const[a,i,o,l]=e;this.outputShape=[a,t,n,l];const u=[s&&t>1?i-1:i,s&&n>1?o-1:o],c=[s&&t>1?t-1:t,s&&n>1?n-1:n],h=s?"0.5":"0.0";let p;p=r?"max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":"vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n      const vec2 effectiveInputOverOutputRatioRC = vec2(\n          ${u[0]/c[0]},\n          ${u[1]/c[1]});\n      const vec2 inputShapeRC = vec2(${i}.0, ${o}.0);\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n        ivec2 yRC = coords.yz;\n\n        // Fractional source index.\n        vec2 sourceFracIndexRC = ${p};\n\n        // Compute the coordinators of nearest neighbor point.\n        ivec2 sourceNearestRC = ivec2(\n          min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${h})));\n        float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);\n\n        setOutput(newValue);\n      }\n    `}}class SB{constructor(e,t,n,s,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];const[a,i,o,l]=e;this.outputShape=[a,t,n,l];const u=[s&&t>1?i-1:i,s&&n>1?o-1:o],c=[s&&t>1?t-1:t,s&&n>1?n-1:n],h=s?"0.5":"0.0";let p;p=r?"max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":"vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`\n      const vec3 effectiveInputOverOutputRatioRC = vec3(\n          ${u[0]/c[0]},\n          ${u[1]/c[1]},\n          ${u[1]/c[1]});\n      const vec3 inputShapeRC = vec3(${i}.0, ${o}.0,\n                                     ${o}.0);\n\n      float getAValue(int b, int r, int c, int d) {\n        return getChannel(getA(b, r, c, d), vec2(c, d));\n      }\n\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n        // Calculate values for next column in yRC.z.\n        ivec3 yRC = coords.yzz + ivec3(0, 0, 1);\n\n        // Fractional source index.\n        vec3 sourceFracIndexRC = ${p};\n\n        // Compute the coordinators of nearest neighbor point.\n        ivec3 sourceNearestRC = ivec3(\n          min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${h})));\n\n        // Should we calculate next column and row elements in 2x2 packed cell.\n        bool hasNextCol = d < ${l-1};\n        bool hasNextRow = coords.z < ${n-1};\n\n        vec4 newValue = vec4(\n          getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d),\n          hasNextCol ? getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d + 1)\n                     : 0.0,\n          hasNextRow ? getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d)\n                     : 0.0,\n          (hasNextRow && hasNextCol) ?\n            getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d + 1) : 0.0);\n\n        setOutput(newValue);\n      }\n    `}}const TB={kernelName:mn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,halfPixelCenters:i,size:o}=s,[l,u]=o,c=Y().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new SB(r.shape,l,u,a,i):new IB(r.shape,l,u,a,i);return n.runWebGLProgram(c,[r],r.dtype)}};class CB{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;const[,s,r]=t,[,a,i]=e,o=[n&&a>1?s-1:s,n&&i>1?r-1:r],l=[n&&a>1?a-1:a,n&&i>1?i-1:i],u=o[0]/l[0],c=o[1]/l[1],h=1/u,p=1/c,d=2*Math.ceil(h)+2,f=2*Math.ceil(p)+2;this.userCode=`\n      void main() {\n        ivec4 coords = getOutputCoords();\n        int b = coords[0];\n        int d = coords[3];\n        int r = coords[1];\n        int c = coords[2];\n\n        float accumulator = 0.0;\n\n        const float heightScale = float(${u});\n        const float widthScale = float(${c});\n\n        const float invHeightScale = float(${h});\n        const float invWidthScale = float(${p});\n\n        const int winHeight = int(${d});\n        const int winWidth = int(${f});\n\n        // Compute bounds for where in dy we will look\n        float startRLerp = floor(float(r) * invHeightScale);\n        int startDyR = int(floor(startRLerp - float(winHeight / 2)));\n\n        float startCLerp = floor(float(c) * invWidthScale);\n        int startDyC = int(floor(startCLerp - float(winWidth / 2)));\n\n        // Loop over dy\n        for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {\n          int dyR = dyROffset + startDyR;\n\n          // Guard against the window exceeding the bounds of dy\n          if (dyR < 0 || dyR >= ${a}) {\n            continue;\n          }\n\n          for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {\n            int dyC = dyCOffset + startDyC;\n\n            // Guard against the window exceeding the bounds of dy\n            if (dyC < 0 || dyC >= ${i}) {\n              continue;\n            }\n\n            float sourceFracRow =\n              float(${o[0]}) *\n                (float(dyR) / float(${l[0]}));\n\n            float sourceFracCol =\n                float(${o[1]}) *\n                  (float(dyC) / float(${l[1]}));\n\n            int sourceNearestRow = int(min(\n                float(int(${s}) - 1),\n                ${n} ? float(round(sourceFracRow)) :\n                                  float(floor(sourceFracRow))));\n\n            int sourceNearestCol = int(min(\n                float(int(${r}) - 1),\n                ${n} ? float(round(sourceFracCol)) :\n                                  float(floor(sourceFracCol))));\n\n            if (r == sourceNearestRow && c == sourceNearestCol) {\n              accumulator += getDy(b, dyR, dyC, d);\n            }\n          }\n        }\n        // End loop over dy\n\n        setOutput(accumulator);\n      }\n    `}}const $B={kernelName:gn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{images:r,dy:a}=t,{alignCorners:i}=s,o=new CB(a.shape,r.shape,i);return n.runWebGLProgram(o,[a],a.dtype)}};class EB{constructor(e,t){this.variableNames=["x"];const n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);if(this.outputShape=e,1===n)return void(this.userCode=`\n        void main() {\n          int coord = getOutputCoords();\n          setOutput(getX(${e[0]} - coord - 1));\n        }\n      `);const s=e.map(((n,s)=>(n=>-1!==t.indexOf(n)&&1!==e[n]?`${e[n]} - coords[${n}] - 1`:`coords[${n}]`)(s))).join(","),r=sF(n);this.userCode=`\n      void main() {\n        ${r} coords = getOutputCoords();\n        setOutput(getX(${s}));\n      }\n    `}}class AB{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;const n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);this.outputShape=e;const s=LD("rc",n),r=`${s[n-1]} + 1 < ${this.outputShape[n-1]}`,a=`${s[n-2]} + 1 < ${this.outputShape[n-2]}`,i=sF(n);function o(n){const s=e.map(((s,r)=>function(n,s){return-1!==t.indexOf(n)&&1!==e[n]?`${e[n]} - ${s[n]} - 1`:`${s[n]}`}(r,n)));return`getChannel(getX(${s.join(",")}), vec2(${s.slice(-2).join(",")}))`}this.userCode=1===n?`\n        void main(){\n          int rc = getOutputCoords();\n          vec4 result = vec4(0.);\n          result.r = getChannel(getX(${e[0]} - rc - 1),\n            ${e[0]} - rc - 1);\n          if(${r}){\n              result.g = getChannel(getX(${e[0]} - (rc  + 1) - 1),\n                ${e[0]} - (rc  + 1) - 1);\n          }\n          setOutput(result);\n        }\n      `:`\n        void main() {\n          ${i} rc = getOutputCoords();\n          vec4 result = vec4(0.);\n          result.r = ${function(e){return o(e)}(s.slice())};\n          if(${r}){\n            result.g = ${function(e){return e[n-1]="("+e[n-1]+" + 1)",o(e)}(s.slice())};\n          }\n          if(${a}) {\n            result.b = ${function(e){return e[n-2]="("+e[n-2]+" + 1)",o(e)}(s.slice())};\n            if(${r}) {\n              result.a = ${function(e){return e[n-1]="("+e[n-1]+" + 1)",e[n-2]="("+e[n-2]+" + 1)",o(e)}(s.slice())};\n            }\n          }\n          setOutput(result);\n        }\n    `}}const RB={kernelName:wn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dims:a}=s,i=r.shape.length,o=v(a,r.shape);if(0===i)return aO({inputs:{x:r},backend:n});const l=Y().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new AB(r.shape,o):new EB(r.shape,o);return n.runWebGLProgram(l,[r],r.dtype)}};class _B{constructor(e,t){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];const n=e[1],s=e[2];this.outputShape=e;let r="";r="number"==typeof t?`float outputValue = ${t.toFixed(2)};`:`\n        vec3 fill = vec3(${t.join(",")});\n        float outputValue = fill[coords[3]];`,this.userCode=`\n        void main() {\n          ivec4 coords = getOutputCoords();\n          int x = coords[2];\n          int y = coords[1];\n          float coordXFloat = (float(x) - params[0]) * params[3] -\n            (float(y) - params[1]) * params[2];\n          float coordYFloat = (float(x) - params[0]) * params[2] +\n            (float(y) - params[1]) * params[3];\n          int coordX = int(round(coordXFloat + params[0]));\n          int coordY = int(round(coordYFloat + params[1]));\n          ${r}\n          if(coordX >= 0 && coordX < ${s} && coordY >= 0 && coordY < ${n}) {\n            outputValue = getImage(coords[0], coordY, coordX, coords[3]);\n          }\n          setOutput(outputValue);\n        }\n    `}}const FB={kernelName:cs,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:s}=e,{radians:r,fillValue:a,center:i}=t,o=n,l=new _B(s.shape,a),[u,c]=cf(i,s.shape[1],s.shape[2]),h=[[u,c,Math.sin(r),Math.cos(r)]];return o.runWebGLProgram(l,[s],s.dtype,h)}},DB=mO({opSnippet:"\n  // OpenGL ES does not support round function.\n  // The algorithm is based on banker's rounding.\n  float base = floor(x);\n  if ((x - base) < 0.5) {\n    return floor(x);\n  } else if ((x - base) > 0.5) {\n    return ceil(x);\n  } else {\n    if (mod(base, 2.0) == 0.0) {\n      return base;\n    } else {\n      return base + 1.0;\n    }\n  }\n"}),OB={kernelName:vn,backendName:"webgl",kernelFunc:DB},MB=mO({opSnippet:"return inversesqrt(x);",cpuKernelImpl:yD}),LB={kernelName:kn,backendName:"webgl",kernelFunc:MB};class zB{constructor(e,t,n,s,r,a,i=!0,o=!1){this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;const l=sF(r.length),u=sF(a.length);let c="";1===n?c="i":2===n&&(c="i, j");const h=`getIndices(${c})`;let p="";1===s?p="i":2===s&&(p="i, coords[1]");const d=`getUpdates(${p})`;let f="";o&&(f="coords[0], coords[1]");const m=`getDefaultValue(${f})`,g=t>1?"strides[j]":"strides";this.userCode=`\n        ${l} strides = ${l}(${r});\n\n        void main() {\n          ${u} coords = getOutputCoords();\n          float sum = 0.0;\n          bool found = false;\n          for (int i = 0; i < ${e}; i++) {\n            int flattenedIndex = 0;\n            for (int j = 0; j < ${t}; j++) {\n              int index = round(${h});\n              flattenedIndex += index * ${g};\n            }\n            if (flattenedIndex == coords[0]) {\n              sum += ${d};\n              found = true;\n            }\n          }\n          setOutput(mix(${m}, sum, float(found)));\n        }\n      `}}class PB{constructor(e,t,n,s,r,a,i=!0,o=!1){this.variableNames=["updates","indices","defaultValue"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=a;const l=sF(r.length),u=sF(a.length);let c="";1===n?c="i":2===n&&(c="i, j");const h=`getIndices(${c})`;let p="";1===s?p="i":2===s&&(p="i, coords[1]");const d=`getUpdates(${p})`;let f="";o&&(f="coords[0], coords[1]");const m=`getDefaultValue(${f})`,g=t>1?"strides[j]":"strides",y=t>1?"strides[j + 1]":"strides";this.userCode=`\n        ${l} strides = ${l}(${r});\n\n        void main() {\n          ${u} coords = getOutputCoords();\n          vec4 sum = vec4(0.);\n          vec4 found = vec4(0.);\n          for (int i = 0; i < ${e}; i+=2) {\n            ivec2 flattenedIndex = ivec2(0);\n            for (int j = 0; j < ${t}; j+=2) {\n              ivec4 index = round(${h});\n              flattenedIndex += index.xz * ${g};\n              if (j + 1 < ${t}) {\n                flattenedIndex += index.yw * ${y};\n              }\n            }\n            if (flattenedIndex[0] == coords[0] || flattenedIndex[1] == coords[0] ||\n                flattenedIndex[0] == coords[0] + 1 || flattenedIndex[1] == coords[0] + 1) {\n              vec4 updVals = ${d};\n              if (flattenedIndex[0] == coords[0]) {\n                sum.xy += updVals.xy;\n                found.xy = vec2(1.);\n              } else if (flattenedIndex[0] == coords[0] + 1) {\n                sum.zw += updVals.xy;\n                found.zw = vec2(1.);\n              }\n              if (flattenedIndex[1] == coords[0]) {\n                sum.xy += updVals.zw;\n                found.xy = vec2(1.);\n              } else if (flattenedIndex[1] == coords[0] + 1) {\n                sum.zw += updVals.zw;\n                found.zw = vec2(1.);\n              }\n            }\n          }\n          setOutput(mix(${m}, sum, found));\n        }\n      `}}const BB={kernelName:Nn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{indices:r,updates:a}=t,{shape:i}=s,{sliceRank:o,numUpdates:l,sliceSize:u,strides:c,outputSize:h}=lh(0,r,i),p=[h/u,u];if(0===h)return n.makeTensorInfo(i,r.dtype);const d=SO({inputs:{x:r},backend:n,attrs:{shape:[l,o]}}),f=SO({inputs:{x:a},backend:n,attrs:{shape:[l,u]}}),m=n.makeTensorInfo([],"float32",new Float32Array([0]));let g;g=Y().getBool("WEBGL_PACK")?new PB(l,o,d.shape.length,f.shape.length,c,p):new zB(l,o,d.shape.length,f.shape.length,c,p);const y=n.runWebGLProgram(g,[f,d,m],f.dtype),b=SO({inputs:{x:y},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(m),b}};class WB{constructor(e,t,n,s){this.variableNames=["sortedSequence","values"],this.customUniforms=[{name:"numInputs",type:"int"}],this.outputShape=[e,n];const r=`for (int i = 0; i < ${Math.ceil(Math.log2(t+1))}; ++i) { if (left >= right) break;`,a=2===Y().getNumber("WEBGL_VERSION")?"while (left < right) {":r,i="left"===s?"<":"<=";this.userCode=`\n       int findBound(int batch, float value) {\n         int left = 0;\n         int right = numInputs;\n         int mid;\n         ${a}\n           mid = (left + right) / 2;\n           if (getSortedSequence(batch, mid) ${i} value) {\n             left = mid + 1;\n           } else {\n             right = mid;\n           }\n         }\n         return right;\n       }\n\n       void main() {\n         ivec2 coords = getOutputCoords();\n         int batch = coords[0];\n         int valueIndex = coords[1];\n\n         float value = getValues(batch, valueIndex);\n\n         setOutput(float(findBound(batch, value)));\n       }\n     `}}const VB={kernelName:Sn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{sortedSequence:r,values:a}=t,{side:i}=s,o=new WB(r.shape[0],r.shape[1],a.shape[1],i),l=[[r.shape[1]]];return n.runWebGLProgram(o,[r,a],"int32",l)}};class UB{constructor(e,t,n){let s,r;if(this.variableNames=["c","a","b"],this.outputShape=t,n>4)throw Error(`Where for rank ${n} is not yet supported`);if(1===n)r="resRC",s="resRC";else{const n=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[],i=[];for(let s=0;s<t.length;s++)i.push(`${n[s]}`),s<e&&a.push(`${n[s]}`);s=a.join(),r=i.join()}const a=sF(n);this.userCode=`\n      void main() {\n        ${a} resRC = getOutputCoords();\n        float cVal = getC(${s});\n        if (cVal >= 1.0) {\n          setOutput(getA(${r}));\n        } else {\n          setOutput(getB(${r}));\n        }\n      }\n    `}}const GB={kernelName:Tn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{condition:s,t:r,e:a}=t,i=new UB(s.shape.length,r.shape,r.shape.length);return n.runWebGLProgram(i,[s,r,a],Wr(r.dtype,a.dtype))}},HB=mO({opSnippet:`\n  // Stable and Attracting Fixed Point (0, 1) for Normalized Weights.\n  // see: https://arxiv.org/abs/1706.02515\n  float scaleAlpha = 1.7580993408473768;\n  float scale = ${yf};\n  return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n`}),jB={kernelName:Cn,backendName:"webgl",kernelFunc:HB},qB=mO({opSnippet:"if (isnan(x)) return x;\n  return 1.0 / (1.0 + exp(-1.0 * x));\n",packedOpSnippet:"\n  vec4 result = 1.0 / (1.0 + exp(-1.0 * x));\n  bvec4 isNaN = isnan(x);\n\n  result.r = isNaN.r ? x.r : result.r;\n  result.g = isNaN.g ? x.g : result.g;\n  result.b = isNaN.b ? x.b : result.b;\n  result.a = isNaN.a ? x.a : result.a;\n\n  return result;\n",cpuKernelImpl:xD}),KB={kernelName:_n,backendName:"webgl",kernelFunc:qB},XB=mO({opSnippet:"\n  if (isnan(x)) { return 0.0; }\n  return sign(x);\n"}),YB={kernelName:Rn,backendName:"webgl",kernelFunc:XB},ZB=mO({opSnippet:"if (isnan(x)) return x;\n  return sin(x);\n",packedOpSnippet:`\n  vec4 result = sin(x);\n  bvec4 isNaN = isnan(x);\n  ${sO}\n  return result;\n`}),JB={kernelName:En,backendName:"webgl",kernelFunc:ZB},QB=mO({opSnippet:"\n  float e2x = exp(x);\n  return (e2x - 1.0 / e2x) / 2.0;\n"}),eW={kernelName:An,backendName:"webgl",kernelFunc:QB},tW=mO({opSnippet:"\n  float epsilon = 1.1920928955078125e-7;\n  float threshold = log(epsilon) + 2.0;\n\n  bool too_large = x > -threshold;\n  bool too_small = x < threshold;\n\n  float result;\n  float exp_x = exp(x);\n\n  if (too_large){\n    result = x;\n  }\n  else if (too_small){\n    result = exp_x;\n  }\n  else{\n    result = log(exp_x + 1.0);\n  }\n  return result;\n"}),nW={kernelName:Fn,backendName:"webgl",kernelFunc:tW},sW={kernelName:Mn,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,paddings:i}=s;c(r.shape.length<=4,(()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet"));const o=a.reduce(((e,t)=>e*t)),l=[[0,0]];l.push(...i);for(let e=1+a.length;e<r.shape.length;++e)l.push([0,0]);const u=[],h=sB({inputs:{x:r},backend:n,attrs:{paddings:l,constantValue:0}}),p=hf(h.shape,a,o,!1),d=pf(p.length,a.length,!1),f=df(h.shape,a,o,!1),m=SO({inputs:{x:h},backend:n,attrs:{shape:p}}),g=OO({inputs:{x:m},backend:n,attrs:{perm:d}}),y=SO({inputs:{x:g},backend:n,attrs:{shape:f}});return u.push(h),u.push(m),u.push(g),u.forEach((e=>n.disposeIntermediateTensorInfo(e))),y}};const rW={kernelName:Pn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{indices:s,values:r,denseShape:a,defaultValue:i}=t;if(1!==a.shape.length)throw new Error(`Dense shape must be a vector, saw:\n         ${a.shape}`);if(2!==s.shape.length)throw new Error(`Indices must be a matrix, saw:\n         ${s.shape}`);if(1!==r.shape.length)throw new Error(`Values must be a vector, saw:\n         ${r.shape}`);if(0!==i.shape.length)throw new Error(`Default value must be a scalar, saw:\n        ${i.shape}`);const o=n.readSync(s.dataId),l=n.readSync(r.dataId),u=n.readSync(a.dataId),c=n.readSync(i.dataId)[0],[h,p,d,f,m]=kD(o,s.shape,s.dtype,l,r.dtype,u,c);return[n.makeTensorInfo(p,s.dtype,h),n.makeTensorInfo([p[0]],r.dtype,d),n.makeTensorInfo([f.length],"bool",new Uint8Array(f.map((e=>Number(e))))),n.makeTensorInfo([m.length],s.dtype,new Int32Array(m))]}};const aW={kernelName:Bn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{inputIndices:s,inputShape:r,newShape:a}=t;if(2!==s.shape.length)throw new Error(`Input indices should be a matrix but received shape ${s.shape}`);if(1!==r.shape.length)throw new Error(`Input shape should be a vector but received shape ${r.shape}`);if(1!==a.shape.length)throw new Error(`Target shape should be a vector but received shape ${a.shape}`);const i=Array.from(n.readSync(r.dataId)),o=n.readSync(s.dataId),l=Array.from(n.readSync(a.dataId)),[u,c,h]=ND(o,s.shape,s.dtype,i,l);return[n.makeTensorInfo(c,s.dtype,u),n.makeTensorInfo([h.length],a.dtype,new Int32Array(h))]}};const iW={kernelName:Wn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{data:s,indices:r,segmentIds:a}=t;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==r.shape.length)throw new Error(`Indices should be a vector but received shape\n              ${r.shape}`);if(1!==a.shape.length)throw new Error(`Segment ids should be a vector but received shape\n              ${a.shape}`);const i=n.readSync(s.dataId),o=n.readSync(r.dataId),l=n.readSync(a.dataId),[u,c]=ID(i,s.shape,s.dtype,o,l,!0);return n.makeTensorInfo(c,s.dtype,u)}};const oW={kernelName:Vn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{data:s,indices:r,segmentIds:a}=t;if(s.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(1!==r.shape.length)throw new Error(`Indices should be a vector but received shape\n             ${r.shape}`);if(1!==a.shape.length)throw new Error(`Segment ids should be a vector but received shape\n             ${a.shape}`);const i=n.readSync(s.dataId),o=n.readSync(r.dataId),l=n.readSync(a.dataId),[u,c]=ID(i,s.shape,s.dtype,o,l);return n.makeTensorInfo(c,s.dtype,u)}};const lW={kernelName:Un,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{sparseIndices:r,sparseValues:a,defaultValue:i}=t,{outputShape:o}=s,{sliceRank:l,numUpdates:u,sliceSize:c,strides:h,outputSize:p}=lh(0,r,o);if("string"===a.dtype){const e=n.bufferSync(r),t=n.bufferSync(a),s=gr(n.readSync(i.dataId)[0]),d=bD(e,t,o,p,c,u,l,h,s,false);return n.makeTensorInfo(o,d.dtype,d.values)}const d=new zB(u,l,r.shape.length,a.shape.length,h,[p,1],false),f=n.runWebGLProgram(d,[a,r,i],a.dtype),m=SO({inputs:{x:f},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(f),m}};const uW={kernelName:Ln,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{numOrSizeSplits:a,axis:i}=s,o=v(i,r.shape)[0],l=Bf(r,a,o),u=r.shape.length,c=new Array(u).fill(0),h=r.shape.slice();return l.map((e=>{const t=[...h];t[o]=e;const s=RM({inputs:{x:r},backend:n,attrs:{begin:c,size:t}});return c[o]+=e,s}))}},cW="return sqrt(x);",hW=mO({opSnippet:cW,packedOpSnippet:cW,cpuKernelImpl:SD}),pW={kernelName:Dn,backendName:"webgl",kernelFunc:hW},dW={kernelName:Hn,backendName:"webgl",kernelFunc:mO({opSnippet:"return x * x;"})},fW="return (a - b) * (a - b);",mW=gO({opSnippet:fW,packedOpSnippet:fW}),gW={kernelName:Gn,backendName:"webgl",kernelFunc:mW};const yW={kernelName:jn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t;if("string"!==r.dtype)throw new Error("Input must be of datatype string");const a=sm(n.readSync(r.dataId)),i=TD(a,"string",s);return n.makeTensorInfo(r.shape,"string",i)}};const bW={kernelName:ls,backendName:"webgl",kernelFunc:function({inputs:e,attrs:t,backend:n}){const{x:s}=e,r=`if (isnan(x)) return x;\n    return x > 0.0 ? 1.0 : float(${t.alpha});\n  `,a=new GD(s.shape,r);return n.runWebGLProgram(a,[s],s.dtype)}};class xW{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;const s=n.length,r=sF(n.length),a=sF(n.length);let i="";if(1===s)i="coords * strides + begin";else{let e=0;i=n.map(((t,s)=>(e++,1===n.length?`coords * strides[${s}] + begin[${s}]`:`coords[${e-1}] * strides[${s}] + begin[${s}]`))).join(",")}this.userCode=`\n      ${r} begin = ${r}(${e});\n      ${r} strides = ${r}(${t});\n\n      void main() {\n        ${a} coords = getOutputCoords();\n        setOutput(getX(${i}));\n      }\n    `}}const wW={kernelName:qn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:h,newAxisMask:p,shrinkAxisMask:d}=s,{finalShapeSparse:f,finalShape:m,isIdentity:g,sliceDim0:y,isSimpleSlice:b,begin:x,end:w,strides:v}=qd(r.shape,a,i,o,l,u,h,p,d);let k;if(g)k=SO({inputs:{x:r},backend:n,attrs:{shape:m}});else if(y||b){c(r.shape.length>=1,(()=>`Input must have rank at least 1, got: ${r.shape.length}`));const e=Od(x,w,v),t=RM({inputs:{x:r},backend:n,attrs:{begin:x,size:e}});k=SO({inputs:{x:t},backend:n,attrs:{shape:m}}),n.disposeIntermediateTensorInfo(t)}else{if(n.shouldExecuteOnCPU([r])){const e=n.readSync(r.dataId),t=Si(r.shape,r.dtype,e),s=CD(f,t,v,x);k=n.makeTensorInfo(m,r.dtype,s.values)}else{const e=new xW(x,v,f);k=n.runWebGLProgram(e,[r],r.dtype)}}const N=SO({inputs:{x:k},backend:n,attrs:{shape:m}});return n.disposeIntermediateTensorInfo(k),N}};const vW={kernelName:Kn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{separator:r,nGramWidths:a,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:u}=s,{data:c,dataSplits:h}=t,p=n.readSync(c.dataId),d=n.readSync(h.dataId),[f,m]=$D(p,d,r,a,i,o,l,u);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(h.shape,"int32",m)]}};const kW={kernelName:Xn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{skipEmpty:r}=s,{input:a,delimiter:i}=t;if("string"!==a.dtype)throw new Error("Input must be of datatype string");if(1!==a.shape.length)throw new Error(`Input must be a vector, got shape: ${a.shape}`);if(0!==i.shape.length)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);const o=n.readSync(a.dataId),l=n.readSync(i.dataId)[0],[u,c,h]=ED(o,l,r),p=c.length;return[n.makeTensorInfo([p,2],"int32",u),n.makeTensorInfo([p],"string",c),n.makeTensorInfo([2],"int32",new Int32Array(h))]}};const NW={kernelName:Yn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{numBuckets:r}=s,{input:a}=t;if("string"!==a.dtype)throw new Error("Input must be of datatype string");if(r<=0)throw new Error("Number of buckets must be at least 1");const i=n.readSync(a.dataId),o=AD(i,r);return n.makeTensorInfo(a.shape,"int32",o)}},IW=mO({opSnippet:"return tan(x);"}),SW={kernelName:Jn,backendName:"webgl",kernelFunc:IW},TW=mO({opSnippet:"\n  float e2x = exp(-2.0 * abs(x));\n  return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n"}),CW={kernelName:Qn,backendName:"webgl",kernelFunc:TW};const $W={kernelName:In,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{tensor:r,indices:a,updates:i}=t,{}=s,{sliceRank:o,numUpdates:l,sliceSize:u,strides:c,outputSize:h}=lh(0,a,r.shape),p=[h/u,u];if(0===h)return n.makeTensorInfo(r.shape,a.dtype);const d=SO({inputs:{x:a},backend:n,attrs:{shape:[l,o]}}),f=SO({inputs:{x:i},backend:n,attrs:{shape:[l,u]}}),m=SO({inputs:{x:r},backend:n,attrs:{shape:p}}),g=new zB(l,o,d.shape.length,f.shape.length,c,p,!1,!0),y=n.runWebGLProgram(g,[f,d,m],m.dtype),b=SO({inputs:{x:y},backend:n,attrs:{shape:r.shape}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(y),b}};class EW{constructor(e,t){this.variableNames=["A"];const n=new Array(e.length);for(let s=0;s<n.length;s++)n[s]=e[s]*t[s];this.outputShape=n,this.rank=n.length;const s=sF(this.rank),r=function(e){const t=e.length;if(t>5)throw Error(`Tile for rank ${t} is not yet supported`);if(1===t)return`imod(resRC, ${e[0]})`;const n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],s=[];for(let t=0;t<e.length;t++)s.push(`imod(${n[t]}, ${e[t]})`);return s.join()}(e);this.userCode=`\n      void main() {\n        ${s} resRC = getOutputCoords();\n        setOutput(getA(${r}));\n      }\n    `}}function AW(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{reps:a}=s;if("string"===r.dtype||r.shape.length>5){const e=n.readSync(r.dataId),t="string"===r.dtype?e.map((e=>gr(e))):e,s=Si(r.shape,r.dtype,t),i=_D(s,a);return n.makeTensorInfo(i.shape,i.dtype,i.values)}const i=new EW(r.shape,a);return n.runWebGLProgram(i,[r],r.dtype)}const RW={kernelName:es,backendName:"webgl",kernelFunc:AW};class _W{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"negativeInf",type:"float"},{name:"dir",type:"int"},{name:"inc",type:"int"}],this.outputShape=e,this.userCode="\n       void main() {\n         ivec2 coords = getOutputCoords();\n         int batch = coords[0];\n         int elemIdx = coords[1];\n\n         // We compare elements pair-wise within a group of size 2 * inc.\n         // The comparing rule for each group alternates between ascending\n         // and descending. Within each group, we compare each pair at\n         // positions i and i+inc. To decide whether an element at position i\n         // is x0 or x1, we mod it by 2 * inc, if the result is smaller than\n         // inc, it is in the first half of the group, we denote it as x0,\n         // otherwise we denote it as x1.\n         // For example, as shown in the Bitonic top K paper referenced above,\n         // Figure5(a) shows that element[1] is in the\n         // second half of the group when group size is 2, but it is in the\n         // first half of the group when group size is 4.\n\n         bool isFirstInPair = imod(elemIdx, 2 * inc) < inc;\n         int i = isFirstInPair ? elemIdx : elemIdx - inc;\n\n         int i0 = firstPass == 1 ? i : int(getIndices(batch, i));\n         int i1 = firstPass == 1 ? i + inc : int(getIndices(batch, i + inc));\n         float x0 = i0 < n ? getX(batch, i0) : negativeInf;\n         float x1 = i1 < n ? getX(batch, i1) : negativeInf;\n\n         // Denotes which direction indices are in (ascending or descending).\n         bool reverse = imod(elemIdx, 2 * dir) >= dir;\n         bool isGreater = x0 > x1 || (x0 == x1 && i1 > i0);\n         if (reverse == isGreater) { // Elements in opposite order of direction\n           int iTemp = i0;\n           i0 = i1;\n           i1 = iTemp;\n         }\n         if (isFirstInPair) {\n            setOutput(float(i0));\n         } else {\n            setOutput(float(i1));\n         }\n       }\n     "}}class FW{constructor(e){this.variableNames=["x","indices"],this.customUniforms=[{name:"n",type:"int"},{name:"firstPass",type:"int"},{name:"k",type:"int"}],this.outputShape=e,this.userCode="\n    void main() {\n         // Takes max of indices (0, k), (1, k + 1), (2, k + 2) ...\n         ivec2 coords = getOutputCoords();\n         int batch = coords[0];\n         int elemIdx = coords[1];\n\n         // The output size is half of the previous size.\n         // If the previous sequence is | | | | _ _ _ _  | | | |  _ _ _ _ (k=4),\n         // we only need to output the indices at positions |, the indices at\n         // positions _ can be thrown away, see Figure5(b) After Phase 2\n         // (Merge phase) in the Bitonic Top K paper referenced above.\n         // For example, the paper shows we only need to output the orange bars.\n         // The output sequence should look like this | | | | | | | |.\n         // Because the sequence is halved, to map the output index back\n         // to the previous sequence to find the corresponding value,\n         // we need to double the index. When we double the index,\n         // we basically interpolate a position, so 2i looks like\n         // | _ | _ | _ | _ | _ | _ | _. We move the | to the first k position\n         // of each 2k positions by - elemIdx % k. E.g. for output at\n         // index 4,5,6,7, we want to get the corresponding element at\n         // original index 8,9,10,11, for output at index 8,9,10,11,\n         // we want to get the corresponding element at original index\n         // 16,17,18,19, so on and so forth.\n\n         int i = elemIdx < k ? elemIdx : (elemIdx * 2 - imod(elemIdx, k));\n         int i0 = firstPass == 1 ? i : int(getIndices(batch, i));\n         int i1 = firstPass == 1 ? i + k : int(getIndices(batch, i + k));\n\n         float x0 = getX(batch, i0);\n         float x1 = i1 < n ? getX(batch, i1) : x0;\n\n         setOutput(x0 >= x1 ? float(i0) : float(i1));\n       }\n     "}}function DW(e,t){null!==t&&e.disposeIntermediateTensorInfo(t)}function OW(e){let t=1;for(;t<e;)t*=2;return t}const MW={kernelName:ts,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{k:a,sorted:i}=s,o=Y().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"),l=Y().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"),u=r.shape,c=u[u.length-1];if(n.shouldExecuteOnCPU([r])||c<o||a>l){const e=n.readSync(r.dataId),[t,s]=FD(e,u,r.dtype,a,i);return[n.makeTensorInfo(t.shape,t.dtype,t.values),n.makeTensorInfo(s.shape,s.dtype,s.values)]}if(0===a)return u[u.length-1]=0,[n.makeTensorInfo(u,r.dtype,[]),n.makeTensorInfo(u,"int32",[])];if(1===c)return[r,mz({attrs:{shape:u,dtype:"int32",value:0},backend:n})];const h=n.texData.get(r.dataId),p=null!==h&&h.isPacked,f=p?n.unpackTensor(r):r,m=d(u)/c,g=SO({inputs:{x:f},attrs:{shape:[m,c]},backend:n});p&&DW(n,f);const y=OW(a),b=OW(c);let x=null;const w=()=>null===x?[g,g]:[g,x],v=(e,t,s)=>{const r=w(),a=new _W(s),i=[[c],[null===x?1:0],[Number.NEGATIVE_INFINITY],[e],[t]],o=x;x=n.runWebGLProgram(a,r,"int32",i),DW(n,o)};for(let e=1;e<y;e*=2){const t=2*e;for(let n=e;n>=1;n/=2)v(t,n,[m,b])}for(let e=b;e>y;e/=2){const t=w(),s=new FW([m,e/2]),r=[[c],[null===x?1:0],[y]],a=x;x=n.runWebGLProgram(s,t,"int32",r),DW(n,a);const i=y/2,o=2*i;for(let e=i;e>=1;e/=2)v(o,e,x.shape)}let k=x;x=RM({inputs:{x:x},backend:n,attrs:{begin:0,size:[m,a]}}),DW(n,k);let N=Dz({inputs:{x:g,indices:x},backend:n,attrs:{axis:1,batchDims:1}});DW(n,g);const I=u.slice(0,-1);I.push(a),k=x,x=SO({inputs:{x:x},attrs:{shape:I},backend:n}),DW(n,k);const S=N;return N=SO({inputs:{x:N},attrs:{shape:I},backend:n}),DW(n,S),[N,x]}};class LW{constructor(e,t,n,s,r,a){this.variableNames=["Image","Transforms"],this.outputShape=a;const i="nearest"===n?1:2;let o;switch(s){case"constant":default:o=1;break;case"reflect":o=2;break;case"wrap":o=3;break;case"nearest":o=4}this.userCode=`\n            float mapCoord(float outCoord, float len) {\n              float inCoord = outCoord;\n              if(${o} == 2) {\n                if (inCoord < 0.0) {\n                  if (len <= 1.0) {\n                    inCoord = 0.0;\n                  } else {\n                    float sz2 = 2.0 * len;\n                    if (inCoord < sz2) {\n                      inCoord = sz2 * float(int(float(-inCoord / sz2))) +\n                      inCoord;\n                    }\n                    inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0;\n                  }\n                } else if (inCoord > len - 1.0) {\n                  if (len <= 1.0) {\n                    inCoord = 0.0;\n                  } else {\n                    float sz2 = 2.0 * len;\n                    inCoord -= sz2 * float(int(float(inCoord / sz2)));\n                    if (inCoord >= len) {\n                      inCoord = sz2 - inCoord - 1.0;\n                    }\n                  }\n                }\n                return clamp(inCoord, 0.0, len - 1.0);\n              } else if (${o} == 3) {\n                if (inCoord < 0.0) {\n                  if (len <= 1.0) {\n                    inCoord = 0.0;\n                  } else {\n                    float sz = len - 1.0;\n                    inCoord += len * (float(int(float(-inCoord / sz))) + 1.0);\n                  }\n                } else if (inCoord > len - 1.0) {\n                  if (len <= 1.0) {\n                    inCoord = 0.0;\n                  } else {\n                    float sz = len - 1.0;\n                    inCoord -= len * float(int(float(inCoord / sz)));\n                  }\n                }\n                return clamp(inCoord, 0.0, len - 1.0);\n              } else if (${o} == 4) {\n                return clamp(outCoord, 0.0, len - 1.0);\n              } else {\n                return outCoord;\n              }\n            }\n\n            float readWithFillValue(int batch, int coordY, int coordX,\n              int channel) {\n              float outputValue;\n              if (0 <= coordY && coordY < ${e} && 0 <= coordX && coordX < ${t}) {\n                  outputValue = getImage(batch, coordY, coordX, channel);\n              } else {\n                outputValue = float(${r});\n              }\n              return outputValue;\n            }\n\n            void main() {\n              ivec4 coords = getOutputCoords();\n              float outputValue;\n              int batch = coords[0];\n              int x = coords[2];\n              int y = coords[1];\n              int channel = coords[3];\n              float xf = float(x);\n              float yf = float(y);\n              float a1 = getTransforms(batch, 0);\n              float a2 = getTransforms(batch, 1);\n              float a3 = getTransforms(batch, 2);\n              float b1 = getTransforms(batch, 3);\n              float b2 = getTransforms(batch, 4);\n              float b3 = getTransforms(batch, 5);\n              float c1 = getTransforms(batch, 6);\n              float c2 = getTransforms(batch, 7);\n              float projection = c1 * xf + c2 * yf + 1.0;\n              if (projection == 0.0) {\n                outputValue = float(${r});\n              } else {\n                float inX = (a1 * xf + a2 * yf + a3) / projection;\n                float inY = (b1 * xf + b2 * yf + b3) / projection;\n                float mapX = mapCoord(inX, float(${t}));\n                float mapY = mapCoord(inY, float(${e}));\n\n                if (${i} == 1) {\n                  int coordY = int(round(mapY));\n                  int coordX = int(round(mapX));\n                  outputValue = readWithFillValue(batch, coordY, coordX,\n                    channel);\n                } else {\n                  float yFloor = floor(mapY);\n                  float xFloor = floor(mapX);\n                  float yCeil = yFloor + 1.0;\n                  float xCeil = xFloor + 1.0;\n                  float valueYFloor = (xCeil - mapX) *\n                  readWithFillValue(batch, int(yFloor), int(xFloor), channel) +\n                  (mapX - xFloor) *\n                  readWithFillValue(batch, int(yFloor), int(xCeil), channel);\n                  float valueYCeil = (xCeil - mapX) *\n                  readWithFillValue(batch, int(yCeil), int(xFloor), channel) +\n                  (mapX - xFloor) *\n                  readWithFillValue(batch, int(yCeil), int(xCeil), channel);\n                  outputValue = (yCeil - mapY) * valueYFloor +\n                  (mapY - yFloor) * valueYCeil;\n                }\n              }\n              setOutput(outputValue);\n            }\n        `}}const zW={kernelName:ns,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{image:r,transforms:a}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=s,[c,h,p,d]=r.shape,[f,m]=null!=u?u:[h,p],g=new LW(h,p,i,o,l,[c,f,m,d]);return n.runWebGLProgram(g,[r,a],"float32")}};const PW={kernelName:rs,backendName:"webgl",kernelFunc:function(e){const{inputs:t,attrs:n,backend:s}=e,{axis:r}=n,{x:a}=t;L_(a,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");const i=s.readSync(a.dataId),{outputValues:o,outputShape:l,indices:u}=OD(i,r,a.shape,a.dtype);return[s.makeTensorInfo(l,a.dtype,o),s.makeTensorInfo([u.length],"int32",u)]}};const BW={kernelName:as,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{value:r}=t;let{axis:a}=s;a<0&&(a+=r.shape.length);const i=r,o=i.shape.length,l=r.shape[a],u=new Array(o-1);let c=0;for(let e=0;e<o;e++)e!==a&&(u[c++]=i.shape[e]);const h=[],p=new Array(o).fill(0),d=i.shape.slice();d[a]=1;const f=new Array(l);for(let e=0;e<f.length;e++){p[a]=e;const t=RM({inputs:{x:i},backend:n,attrs:{begin:p,size:d}}),s=SO({inputs:{x:t},backend:n,attrs:{shape:u}});f[e]=s,h.push(t)}return h.forEach((e=>n.disposeIntermediateTensorInfo(e))),f}};class WW{constructor(e,t){this.variableNames=["x","segmentIds"];const n=e.windowSize,s=e.batchSize,r=e.inSize,a=e.numSegments,i=a*Math.ceil(r/n);this.outputShape=[s,i];const o=4*Math.floor(n/4),l=n%4,u="\n        sumValue += dot(values, segFilter);\n    ";let c="";r%n>0&&(c=`\n        if (inIdx < 0 || inIdx >= ${r}) {\n          return initializationValue;\n        }\n      `);let h="";r%n>0&&(h=`\n        if (inIdx < 0 || inIdx >= ${r}) {\n          return -1.0;\n        }\n      `),this.userCode=`\n      const float initializationValue = 0.0;\n\n      float getValue(int batch, int inIdx) {\n        ${c}\n        return getX(batch, inIdx);\n      }\n\n      float getSegmentIdAtIndex(int inIdx) {\n        ${h}\n        return getSegmentIds(inIdx);\n      }\n\n      void main() {\n        ivec2 coords = getOutputCoords();\n        int batch = coords[0];\n        int outIdx = coords[1];\n        int inOffset = int(floor(float(outIdx) / float(\n          ${a})) * float(${n}));\n        int currentSeg = int(mod(float(outIdx), float(${a})));\n\n        float sumValue = 0.0;\n\n        for (int i = 0; i < ${o}; i += 4) {\n          int inIdx = inOffset + i;\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            getValue(batch, inIdx + 3)\n          );\n\n          vec4 segFilter = vec4(\n            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n            int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n            int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n            int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0\n          );\n\n          ${u}\n        }\n\n        int inIdx = inOffset + ${o};\n        if (${1===l}) {\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            initializationValue,\n            initializationValue,\n            initializationValue\n          );\n\n          int inIdxSeg = int(getSegmentIdAtIndex(inIdx));\n\n          vec4 segFilter = vec4(\n            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n            0,\n            0,\n            0\n          );\n\n          ${u}\n        } else if (${2===l}) {\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            initializationValue,\n            initializationValue\n          );\n\n          vec4 segFilter = vec4(\n            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n            int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n              0,\n              0\n          );\n\n          ${u}\n        } else if (${3===l}) {\n          vec4 values = vec4(\n            getValue(batch, inIdx),\n            getValue(batch, inIdx + 1),\n            getValue(batch, inIdx + 2),\n            initializationValue\n          );\n\n          vec4 segFilter = vec4(\n            int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,\n            int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,\n            int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,\n            0\n          );\n\n          ${u}\n        }\n        setOutput(sumValue);\n      }\n    `}}const VW={kernelName:is,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,segmentIds:a}=t,{numSegments:i}=s,o=r.shape.length,l=[];let u=0;const c=dl([u],o);let h=r;null!=c&&(h=OO({inputs:{x:r},backend:n,attrs:{perm:c}}),l.push(h),u=ml(1,o)[0]);const p=em(h.shape,u,i),f=d([h.shape[u]]),m=SO({inputs:{x:h},backend:n,attrs:{shape:[-1,f]}});l.push(m);const g=Vr(r.dtype),y=(e,t,s,r,a)=>{const i=e.shape[0],o=e.shape[1],u=Qf(o,a),c=new WW({windowSize:u,inSize:o,batchSize:i,numSegments:a},t),h=n.compileAndRun(c,[e,s],r);if(l.push(h),h.shape[1]===a)return h;const p=hB({backend:n,attrs:{start:0,stop:a,step:1,dtype:"float32"}}),d=AW({inputs:{x:p},backend:n,attrs:{reps:[o/u]}});l.push(p),l.push(d);return y(h,t,d,r,a)},b=SO({inputs:{x:y(m,"unsortedSegmentSum",a,g,i)},backend:n,attrs:{shape:p}});let x=b;if(null!=c){l.push(b);const e=fl(c);x=OO({inputs:{x:x},backend:n,attrs:{perm:e}})}return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),x}},UW=[zO,BO,VO,GO,qO,YO,ZO,JO,rM,aM,oM,uM,hM,dM,mM,bM,xM,kM,NM,IM,CM,FM,DM,OM,MM,WM,GM,qM,lO,YM,rL,pL,yL,xL,wL,vL,kL,IL,TL,$L,DL,OL,ML,zL,WL,GL,HL,qL,XL,YL,JL,QL,tz,sz,az,oz,cz,dz,gz,bz,vz,Nz,Tz,Ez,Az,_z,Oz,Lz,Pz,iO,Bz,tL,Vz,Gz,jz,hO,Kz,Yz,Zz,Qz,tP,sP,aP,oP,cP,pP,fP,gP,yP,bP,vP,kP,NP,IP,SP,CP,AP,_P,WP,IO,VP,GP,jP,KP,zM,YP,QP,eB,rB,iB,fO,oB,lB,uB,cB,pB,BM,OP,fB,gB,bB,TO,vB,NB,TB,$B,RB,FB,OB,LB,BB,VB,GB,jB,KB,YB,JB,eW,_M,BP,nW,sW,rW,aW,iW,oW,lW,uW,pW,dW,gW,yW,bW,wW,vW,kW,NW,zP,DO,SW,CW,$W,RW,MW,zW,MO,PW,BW,VW,JP];for(const e of UW)ws(e);const GW={"tfjs-core":Yd,"tfjs-backend-cpu":zC,"tfjs-backend-webgl":QD,"tfjs-data":iS,"tfjs-layers":_x,"tfjs-converter":sI,tfjs:"4.15.0"};e.Abs=ee,e.Acos=te,e.Acosh=ne,e.AdadeltaOptimizer=Jp,e.AdagradOptimizer=Qp,e.AdamOptimizer=ed,e.AdamaxOptimizer=td,e.Add=se,e.AddN=re,e.All=ae,e.Any=ie,e.ArgMax=oe,e.ArgMin=le,e.Asin=ue,e.Asinh=ce,e.Atan=he,e.Atan2=de,e.Atanh=pe,e.AvgPool=fe,e.AvgPool3D=ge,e.AvgPool3DGrad=ye,e.AvgPoolGrad=me,e.BatchMatMul=be,e.BatchToSpaceND=xe,e.Bincount=we,e.BitwiseAnd=ve,e.BroadcastArgs=Ne,e.BroadcastTo=ke,e.Callback=Dk,e.CallbackList=Gb,e.Cast=Ie,e.Ceil=Se,e.ClipByValue=Te,e.Complex=Ce,e.ComplexAbs=$e,e.Concat=Ee,e.Conv2D=Ae,e.Conv2DBackpropFilter=Re,e.Conv2DBackpropInput=_e,e.Conv3D=Fe,e.Conv3DBackpropFilterV2=De,e.Conv3DBackpropInputV2=Oe,e.Cos=Me,e.Cosh=Le,e.CropAndResize=Be,e.Cumprod=ze,e.Cumsum=Pe,e.CustomCallback=qb,e.DataStorage=n,e.DenseBincount=We,e.DepthToSpace=Ve,e.DepthwiseConv2dNative=Ue,e.DepthwiseConv2dNativeBackpropFilter=Ge,e.DepthwiseConv2dNativeBackpropInput=He,e.Diag=je,e.Dilation2D=qe,e.Dilation2DBackpropFilter=Xe,e.Dilation2DBackpropInput=Ke,e.Draw=Ye,e.EarlyStopping=Lk,e.Einsum=Je,e.Elu=Qe,e.EluGrad=et,e.Environment=K,e.Equal=nt,e.Erf=tt,e.Exp=st,e.ExpandDims=rt,e.Expm1=at,e.FFT=it,e.Fill=ot,e.FlipLeftRight=lt,e.Floor=ut,e.FloorDiv=ct,e.FromPixels=us,e.FusedBatchNorm=ht,e.FusedConv2D=ps,e.FusedDepthwiseConv2D=ds,e.GPGPUContext=BF,e.GatherNd=dt,e.GatherV2=pt,e.GraphModel=nI,e.Greater=ft,e.GreaterEqual=mt,e.History=jb,e.IFFT=yt,e.Identity=gt,e.Imag=bt,e.InputSpec=pb,e.IsFinite=xt,e.IsInf=wt,e.IsNan=vt,e.KernelBackend=s,e.LRN=_t,e.LRNGrad=Ft,e.LayerVariable=ub,e.LayersModel=Jx,e.LeakyRelu=kt,e.Less=Nt,e.LessEqual=It,e.LinSpace=St,e.Log=Tt,e.Log1p=Ct,e.LogSoftmax=Rt,e.LogicalAnd=$t,e.LogicalNot=Et,e.LogicalOr=At,e.LogicalXor="LogicalXor",e.LowerBound="LowerBound",e.MathBackendCPU=cS,e.MathBackendWebGL=JD,e.MatrixBandPart="MatrixBandPart",e.Max=Dt,e.MaxPool=Mt,e.MaxPool3D=zt,e.MaxPool3DGrad=Pt,e.MaxPoolGrad=Lt,e.MaxPoolWithArgmax=Bt,e.Maximum=Ot,e.Mean=Wt,e.Min=Vt,e.Minimum=Ut,e.MirrorPad=Gt,e.Mod=Ht,e.MomentumOptimizer=sd,e.Multinomial=jt,e.Multiply=qt,e.Neg=Kt,e.NonMaxSuppressionV3=Yt,e.NonMaxSuppressionV4=Zt,e.NonMaxSuppressionV5=Jt,e.NotEqual=Xt,e.OP_SCOPE_SUFFIX=da,e.OneHot=en,e.OnesLike=Qt,e.Optimizer=Zp,e.OptimizerConstructors=Zd,e.Pack=tn,e.PadV2=nn,e.Pool="Pool",e.Pow=sn,e.Prelu=rn,e.Prod=an,e.RMSPropOptimizer=rd,e.RNN=tv,e.RaggedGather=on,e.RaggedRange=ln,e.RaggedTensorToTensor=un,e.Range=cn,e.Real=hn,e.RealDiv=Ze,e.Reciprocal=pn,e.Relu=dn,e.Relu6=xn,e.Reshape=fn,e.ResizeBilinear=yn,e.ResizeBilinearGrad=bn,e.ResizeNearestNeighbor=mn,e.ResizeNearestNeighborGrad=gn,e.Reverse=wn,e.RotateWithOffset=cs,e.Round=vn,e.Rsqrt=kn,e.SGDOptimizer=nd,e.ScatterNd=Nn,e.SearchSorted=Sn,e.Select=Tn,e.Selu=Cn,e.Sequential=ew,e.Sigmoid=_n,e.Sign=Rn,e.Sin=En,e.Sinh=An,e.Slice=$n,e.Softmax=zn,e.Softplus=Fn,e.SpaceToBatchND=Mn,e.SparseFillEmptyRows=Pn,e.SparseReshape=Bn,e.SparseSegmentMean=Wn,e.SparseSegmentSum=Vn,e.SparseToDense=Un,e.SplitV=Ln,e.Sqrt=Dn,e.Square=Hn,e.SquaredDifference=Gn,e.StaticRegexReplace=jn,e.Step=ls,e.StridedSlice=qn,e.StringNGrams=Kn,e.StringSplit=Xn,e.StringToHashBucketFast=Yn,e.Sub=Zn,e.Sum=On,e.SymbolicTensor=db,e.Tan=Jn,e.Tanh=Qn,e.Tensor=_r,e.TensorBuffer=$r,e.TensorScatterUpdate=In,e.Tile=es,e.TopK=ts,e.Transform=ns,e.Transpose=ss,e.Unique=rs,e.Unpack=as,e.UnsortedSegmentSum=is,e.UpperBound="UpperBound",e.Variable=Dr,e.ZerosLike=os,e._FusedMatMul=hs,e.abs=Fi,e.acos=Di,e.acosh=Oi,e.add=Ei,e.addN=Mi,e.all=Li,e.any=zi,e.argMax=Pi,e.argMin=Bi,e.asin=Wi,e.asinh=Vi,e.atan=Ui,e.atan2=Gi,e.atanh=Hi,e.avgPool=lo,e.avgPool3d=uo,e.backend=Ea,e.backend_util=am,e.basicLSTMCell=go,e.batchNorm=bo,e.batchNorm2d=xo,e.batchNorm3d=wo,e.batchNorm4d=vo,e.batchToSpaceND=yo,e.bincount=ko,e.bitwiseAnd=No,e.booleanMaskAsync=wh,e.broadcastArgs=Io,e.broadcastTo=So,e.broadcast_util=Jo,e.browser=Rd,e.buffer=Si,e.callbacks=zk,e.cast=Ti,e.ceil=To,e.clipByValue=$o,e.clone=Ci,e.complex=ma,e.concat=co,e.concat1d=Eo,e.concat2d=Ao,e.concat3d=Ro,e.concat4d=_o,e.constraints=zb,e.conv1d=Do,e.conv2d=Fo,e.conv2dTranspose=Mo,e.conv3d=Lo,e.conv3dTranspose=Po,e.copyRegisteredKernels=function(e,t){xs(e).forEach((e=>{ws(Object.assign({},e,{backendName:t}))}))},e.cos=Bo,e.cosh=Wo,e.cosineWindow=$h,e.cumprod=Vo,e.cumsum=Uo,e.customGrad=ql,e.data=oS,e.denseBincount=Go,e.deprecationWarn=wa,e.depthToSpace=Ho,e.depthwiseConv2d=jo,e.deregisterOp=function(e){delete Wk[e]},e.device_util=ia,e.diag=qo,e.dilation2d=Ko,e.disableDeprecationWarnings=function(){Y().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")},e.dispose=Ia,e.disposeVariables=function(){ta.disposeVariables()},e.div=Ri,e.divNoNan=nl,e.dot=sl,e.dropout=Th,e.einsum=rl,e.elu=al,e.enableDebugMode=function(){Y().set("DEBUG",!0)},e.enableProdMode=function(){Y().set("PROD",!0)},e.enclosingPowerOfTwo=Ch,e.engine=va,e.ensureShape=il,e.env=Y,e.equal=Qo,e.erf=ol,e.euclideanNorm=Sl,e.exp=Tl,e.expandDims=Cl,e.expm1=$l,e.eye=Al,e.fft=Uc,e.fill=Co,e.findBackend=function(e){return ta.findBackend(e)},e.findBackendFactory=function(e){return ta.findBackendFactory(e)},e.floor=Rl,e.floorDiv=Ai,e.forceHalfFloat=eO,e.fused=Bh,e.gather=_l,e.gatherND=Sh,e.gather_util=Fd,e.getBackend=Ca,e.getGradient=bs,e.getKernel=ys,e.getKernelsForBackend=xs,e.gpgpu_util=PF,e.grad=function(e){return c(D(e),(()=>"The f passed in grad(f) must be a function")),(t,n)=>{const s=ha(t,"x","tf.grad","string_or_numeric"),r=null!=n?ha(n,"dy","tf.grad"):null;return ta.tidy((()=>{const{value:t,grads:n}=ta.gradients((()=>e(s)),[s],r);return null!=r&&h(t.shape,r.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Kl(n),n[0]}))}},e.grads=function(e){return c(D(e),(()=>"The f passed in grads(f) must be a function")),(t,n)=>{c(Array.isArray(t),(()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s"));const s=pa(t,"args","tf.grads","string_or_numeric"),r=null!=n?ha(n,"dy","tf.grads"):null;return ta.tidy((()=>{const{value:t,grads:n}=ta.gradients((()=>e(...s)),s,r);return null!=r&&h(t.shape,r.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Kl(n),n}))}},e.greater=Fl,e.greaterEqual=Dl,e.ifft=Gc,e.imag=Ol,e.image=Bp,e.inTopKAsync=Eh,e.initializers=Bb,e.input=tw,e.io=kd,e.irfft=Hc,e.isFinite=Ml,e.isInf=Ll,e.isNaN=zl,e.keep=Sa,e.kernel_impls=im,e.layers=Ak,e.leakyRelu=Pl,e.less=Bl,e.lessEqual=Wl,e.linalg=Wp,e.linspace=Vl,e.loadGraphModel=async function(e,t={},n=kd){if(null==e)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");null==t&&(t={}),t.fromTFHub&&"string"==typeof e&&(e=function(e){e.endsWith("/")||(e+="/");return`${e}model.json?tfjs-format=file`}(e));const s=new nI(e,t,n);return await s.load(),s},e.loadGraphModelSync=function(e){if(null==e)throw new Error("modelUrl in loadGraphModelSync() cannot be null. Please provide model artifacts or an IOHandler that loads the model");let t;if(e instanceof Array){const[n,s]=e;if(!n)throw new Error("modelJSON must be the first element of the array");if(!(s&&s instanceof ArrayBuffer))throw new Error("An ArrayBuffer of weights must be the second element of the array");if(!("modelTopology"in n))throw new Error("Model JSON is missing 'modelTopology'");if(!("weightsManifest"in n))throw new Error("Model JSON is missing 'weightsManifest'");t=vd(Ua(n,ja(n.weightsManifest),s))}else if("load"in e)t=e;else{if(!("modelTopology"in e&&"weightSpecs"in e&&"weightData"in e))throw new Error("Unknown model format");t=vd(e)}const n=new nI(t);return n.load(),n},e.loadLayersModel=async function(e,t){if(null==t&&(t={}),"string"==typeof e){const n=Xa(e,t);if(0===n.length)n.push(yd(e,t));else if(n.length>1)throw new Sg(`Found more than one (${n.length}) load handlers for URL '${e}'`);e=n[0]}return async function(e,t,n){null==n&&(n={});if(null==e.load)throw new Sg("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");const s=await e.load();let r=s.modelTopology;null!=r.model_config&&(r=r.model_config);const a=null==n.strict||n.strict,i=null!=s.weightData&&null!=s.weightSpecs&&a,o=Zb(Ax(r),t,i),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 Sg("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");const{modelWeights:e,optimizerWeights:t}=function(e,t){const n=Ra(e,t),s={},r=[];return t.forEach((e=>{"optimizer"===e.group?r.push({name:e.name,tensor:n[e.name]}):s[e.name]=n[e.name]})),{modelWeights:s,optimizerWeights:r}}(s.weightData,s.weightSpecs);o.loadWeights(e,a),null!=o.optimizer&&t.length>0&&await o.optimizer.setWeights(t),Ia(e),Ia(t.map((e=>e.tensor)))}return o}(e,void 0,t)},e.localResponseNormalization=Ul,e.log=Gl,e.log1p=Hl,e.logSigmoid=Zl,e.logSoftmax=Ql,e.logSumExp=eu,e.logicalAnd=tu,e.logicalNot=nu,e.logicalOr=su,e.logicalXor=ru,e.losses=Vp,e.lowerBound=ou,e.matMul=ho,e.math=Id,e.max=gl,e.maxPool=lu,e.maxPool3d=uu,e.maxPoolWithArgmax=cu,e.maximum=hu,e.mean=pu,e.memory=ka,e.meshgrid=mu,e.metrics=Rk,e.min=yl,e.minimum=gu,e.mirrorPad=yu,e.mod=bu,e.model=function(e){return new Jx(e)},e.models=_k,e.moments=xu,e.movingAverage=kh,e.mul=_i,e.multiRNNCell=wu,e.multinomial=vu,e.neg=Xl,e.nextFrame=ef,e.norm=Il,e.notEqual=ku,e.oneHot=Nu,e.ones=fu,e.onesLike=Iu,e.op=fa,e.outerProduct=Su,e.pad=Tu,e.pad1d=Cu,e.pad2d=$u,e.pad3d=Eu,e.pad4d=Au,e.pool=_u,e.pow=bl,e.prelu=Fu,e.print=$i,e.prod=Du,e.profile=function(e){return ta.profile(e)},e.raggedGather=Ou,e.raggedRange=Mu,e.raggedTensorToTensor=Lu,e.rand=zu,e.randomGamma=mc,e.randomNormal=gc,e.randomStandardNormal=yc,e.randomUniform=bc,e.randomUniformInt=xc,e.range=wc,e.ready=function(){return ta.ready()},e.real=vc,e.reciprocal=kc,e.registerBackend=$a,e.registerCallbackConstructor=function(e,t){Xb.registerCallbackConstructor(e,t)},e.registerGradient=vs,e.registerKernel=ws,e.registerOp=function(e,t){const n={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};Wk[e]=n},e.regularizers=Fk,e.relu=Nc,e.relu6=Ic,e.removeBackend=function(e){ta.removeBackend(e)},e.reshape=oo,e.reverse=Sc,e.reverse1d=Tc,e.reverse2d=Cc,e.reverse3d=$c,e.reverse4d=Ec,e.rfft=qc,e.round=Ac,e.rsqrt=Rc,e.scalar=xl,e.scatterND=Nh,e.scatter_util=uh,e.searchSorted=iu,e.selu=_c,e.separableConv2d=Fc,e.sequential=function(e){return new ew(e)},e.serialization=Yp,e.setBackend=Ta,e.setPlatform=function(e,t){Y().setPlatform(e,t)},e.setWebGLContext=zR,e.setdiff1dAsync=Dc,e.shared=LC,e.sigmoid=po,e.sign=Oc,e.signal=Pp,e.sin=Mc,e.sinh=Lc,e.slice=fo,e.slice1d=zc,e.slice2d=Pc,e.slice3d=Bc,e.slice4d=Wc,e.slice_util=Xd,e.softmax=Vc,e.softplus=Yl,e.spaceToBatchND=Ru,e.sparse=Up,e.sparseToDense=Ih,e.spectral=zp,e.split=jc,e.sqrt=wl,e.square=vl,e.squaredDifference=Kc,e.squeeze=Xc,e.stack=Yc,e.step=Zc,e.stridedSlice=Jc,e.string=Gp,e.sub=Jl,e.sum=kl,e.sumOutType=Vr,e.tan=Qc,e.tanh=mo,e.tensor=ya,e.tensor1d=eh,e.tensor2d=th,e.tensor3d=nh,e.tensor4d=sh,e.tensor5d=rh,e.tensor6d=ah,e.tensorScatterUpdate=ch,e.tensor_util=Yr,e.test_util=hc,e.tidy=Na,e.tile=El,e.time=function(e){return ta.time(e)},e.topk=hh,e.train=Jd,e.transpose=vh,e.truncatedNormal=ph,e.unique=dh,e.unregisterGradient=function(e){if(!gs.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);gs.delete(e)},e.unregisterKernel=function(e,t){const n=ks(e,t);if(!ms.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);ms.delete(n)},e.unsortedSegmentSum=fh,e.unstack=mh,e.upcastType=Wr,e.upperBound=gh,e.util=xr,e.valueAndGrad=function(e){return c(D(e),(()=>"The f passed in valueAndGrad(f) must be a function")),(t,n)=>{c(t instanceof _r,(()=>"The x passed in valueAndGrad(f)(x) must be a tensor")),c(null==n||n instanceof _r,(()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor"));const{grads:s,value:r}=ta.gradients((()=>e(t)),[t],n);return Kl(s),{grad:s[0],value:r}}},e.valueAndGrads=function(e){return c(D(e),(()=>"The f passed in valueAndGrads(f) must be a function")),(t,n)=>{c(Array.isArray(t)&&t.every((e=>e instanceof _r)),(()=>"The args passed in valueAndGrads(f)(args) must be array of tensors")),c(null==n||n instanceof _r,(()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor"));const s=ta.gradients((()=>e(...t)),t,n);return null!=n&&h(s.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Kl(s.grads),s}},e.variable=yh,e.variableGrads=jl,e.version=GW,e.version_converter=sI,e.version_core=Yd,e.version_cpu=zC,e.version_layers=_x,e.version_webgl=QD,e.webgl=tO,e.webgl_util=z_,e.where=el,e.whereAsync=xh,e.zeros=du,e.zerosLike=tl}));
//# sourceMappingURL=tf.es2017.min.js.map