UNPKG

1.08 MBJavaScriptView Raw
1/**
2 * @license
3 * Copyright 2022 Google LLC. All Rights Reserved.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 * =============================================================================
16 */
17!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e=e||self).tf=e.tf||{})}(this,(function(e){"use strict";class t{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 n{refCount(e){return s("refCount")}incRef(e){return s("incRef")}timerAvailable(){return!0}time(e){return s("time")}read(e){return s("read")}readSync(e){return s("readSync")}readToGPU(e,t){return s("readToGPU")}numDataIds(){return s("numDataIds")}disposeData(e,t){return s("disposeData")}write(e,t,n){return s("write")}move(e,t,n,r,a){return s("move")}createTensorFromTexture(e,t,n){return s("createTensorFromTexture")}memory(){return s("memory")}floatPrecision(){return s("floatPrecision")}epsilon(){return 32===this.floatPrecision()?1e-7:1e-4}dispose(){return s("dispose")}}function s(e){throw new Error(`'${e}' not yet implemented or not found in the registry. This kernel may not be supported by the tfjs backend you have chosen`)}function r(e){let t=e.length,n=0;for(;t>0;)n=Math.random()*t|0,t--,o(e,t,n)}function a(e,t,n){return Math.max(e,Math.min(t,n))}function i(e){return e%2==0?e:e+1}function o(e,t,n){const s=e[t];e[t]=e[n],e[n]=s}function l(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}function u(e,t){if(!e)throw new Error("string"==typeof t?t:t())}function c(e,t,n=""){u(f(e,t),(()=>n+` Shapes ${e} and ${t} must match`))}function h(e){u(null!=e,(()=>"The input to the tensor constructor must be a non-null value."))}function p(e,t=[],n=!1){if(null==t&&(t=[]),Array.isArray(e)||C(e)&&!n)for(let s=0;s<e.length;++s)p(e[s],t,n);else t.push(e);return t}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(e[n]!==t[n])return!1;return!0}function m(e){return e%1==0}function g(e){const t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function y(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function b(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 x(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 w(e,t){const n=t.length;return u((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}`)),u(e.every((e=>m(e))),(()=>`All values in axis param must be integers but got axis ${e}`)),e.map((e=>e<0?n+e:e))}function v(e,t){const n=[],s=[],r=null!=t&&Array.isArray(t)&&0===t.length,a=null==t||r?null:w(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 k(e,t){let n=null;if(null==e||"float32"===e)n=new Float32Array(t);else if("int32"===e)n=new Int32Array(t);else{if("bool"!==e)throw new Error(`Unknown data type ${e}`);n=new Uint8Array(t)}return n}function N(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 I(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 S(e){return"bool"===e||"complex64"===e||"float32"===e||"int32"===e||"string"===e}function T(e,t){return"complex64"!==t&&(("float32"!==t||"complex64"===e)&&(("int32"!==t||"float32"===e||"complex64"===e)&&("bool"!==t||"bool"!==e)))}function C(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}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){const n=B(e,t);for(let e=0;e<n.length;e++)n[e]=1;return n}function B(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 W(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 V(e){e.forEach((t=>{u(Number.isInteger(t)&&t>=0,(()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`))}))}function U(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 G(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 H(e){return e&&e.then&&"function"==typeof e.then}const j="tfjsflags";class q{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=K,this.populateURLFlags()}setPlatform(e,t){null!=this.platform&&(X().getBool("IS_TEST")||X().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];X().getBool("IS_TEST")||X().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(H(t))throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(null==this.flagRegistry[e])throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,null!=this.flagRegistry[e].setHook&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(null==this.flagRegistry[e])throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(void 0===this.global||void 0===this.global.location||void 0===this.global.location.search)return;const e=this.getQueryParams(this.global.location.search);if(j in e){e.tfjsflags.split(",").forEach((e=>{const[t,n]=e.split(":");this.urlFlags[t]=function(e,t){if("true"===(t=t.toLowerCase())||"false"===t)return"true"===t;if(""+ +t===t)return+t;throw new Error(`Could not parse value flag value ${t} for flag ${e}.`)}(t,n)}))}}}function K(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 X(){return e.ENV}let Y;function Z(){if(null==Y){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}Y=e}return Y}function J(e,t){const n=function(){const e=Z();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 Q="Abs",ee="Acos",te="Acosh",ne="Add",se="AddN",re="All",ae="Any",ie="ArgMax",oe="ArgMin",le="Asin",ue="Asinh",ce="Atan",he="Atanh",pe="Atan2",de="AvgPool",fe="AvgPoolGrad",me="AvgPool3D",ge="AvgPool3DGrad",ye="BatchMatMul",be="BatchToSpaceND",xe="Bincount",we="BroadcastTo",ve="BroadcastArgs",ke="Cast",Ne="Ceil",Ie="ClipByValue",Se="Complex",Te="ComplexAbs",Ce="Concat",$e="Conv2D",Ee="Conv2DBackpropFilter",Ae="Conv2DBackpropInput",Re="Conv3D",_e="Conv3DBackpropFilterV2",Fe="Conv3DBackpropInputV2",De="Cos",Oe="Cosh",Me="Cumprod",Le="Cumsum",ze="CropAndResize",Pe="DenseBincount",Be="DepthToSpace",We="DepthwiseConv2dNative",Ve="DepthwiseConv2dNativeBackpropFilter",Ue="DepthwiseConv2dNativeBackpropInput",Ge="Diag",He="Dilation2D",je="Dilation2DBackpropInput",qe="Dilation2DBackpropFilter",Ke="RealDiv",Xe="Einsum",Ye="Elu",Ze="EluGrad",Je="Erf",Qe="Equal",et="Exp",tt="ExpandDims",nt="Expm1",st="FFT",rt="Fill",at="FlipLeftRight",it="Floor",ot="FloorDiv",lt="FusedBatchNorm",ut="GatherV2",ct="GatherNd",ht="Greater",pt="GreaterEqual",dt="Identity",ft="IFFT",mt="Imag",gt="IsFinite",yt="IsInf",bt="IsNan",xt="LeakyRelu",wt="Less",vt="LessEqual",kt="LinSpace",Nt="Log",It="Log1p",St="LogicalAnd",Tt="LogicalNot",Ct="LogicalOr",$t="LogSoftmax",Et="LRN",At="LRNGrad",Rt="Max",_t="Maximum",Ft="MaxPool",Dt="MaxPoolGrad",Ot="MaxPool3D",Mt="MaxPool3DGrad",Lt="MaxPoolWithArgmax",zt="Mean",Pt="Min",Bt="Minimum",Wt="MirrorPad",Vt="Mod",Ut="Multinomial",Gt="Multiply",Ht="Neg",jt="NotEqual",qt="NonMaxSuppressionV3",Kt="NonMaxSuppressionV4",Xt="NonMaxSuppressionV5",Yt="OnesLike",Zt="OneHot",Jt="Pack",Qt="PadV2",en="Pow",tn="Prelu",nn="Prod",sn="RaggedGather",rn="RaggedRange",an="RaggedTensorToTensor",on="Range",ln="Real",un="Reciprocal",cn="Relu",hn="Reshape",pn="ResizeNearestNeighbor",dn="ResizeNearestNeighborGrad",fn="ResizeBilinear",mn="ResizeBilinearGrad",gn="Relu6",yn="Reverse",bn="Round",xn="Rsqrt",wn="ScatterNd",vn="SearchSorted",kn="Select",Nn="Selu",In="Slice",Sn="Sin",Tn="Sinh",Cn="Sign",$n="Sigmoid",En="Softplus",An="Sqrt",Rn="Sum",_n="SpaceToBatchND",Fn="SplitV",Dn="Softmax",On="SparseFillEmptyRows",Mn="SparseReshape",Ln="SparseSegmentMean",zn="SparseSegmentSum",Pn="SparseToDense",Bn="SquaredDifference",Wn="Square",Vn="StridedSlice",Un="StringNGrams",Gn="StringSplit",Hn="StringToHashBucketFast",jn="Sub",qn="Tan",Kn="Tanh",Xn="Tile",Yn="TopK",Zn="Transform",Jn="Transpose",Qn="Unique",es="Unpack",ts="UnsortedSegmentSum",ns="ZerosLike",ss="Step",rs="FromPixels",as="RotateWithOffset",is="_FusedMatMul",os="FusedConv2D",ls="FusedDepthwiseConv2D";function us(...e){X().getBool("IS_TEST")||X().getBool("PROD")||console.warn(...e)}const cs=J("kernelRegistry",(()=>new Map)),hs=J("gradRegistry",(()=>new Map));function ps(e,t){const n=ys(e,t);return cs.get(n)}function ds(e){return hs.get(e)}function fs(e){const t=cs.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 ms(e){const{kernelName:t,backendName:n}=e,s=ys(t,n);cs.has(s)&&us(`The kernel '${t}' for backend '${n}' is already registered`),cs.set(s,e)}function gs(e){const{kernelName:t}=e;hs.has(t)&&X().getBool("DEBUG")&&us(`Overriding the gradient for '${t}'`),hs.set(t,e)}function ys(e,t){return`${t}_${e}`}var bs=ws,xs=null;try{xs=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 ws(e,t,n){this.low=0|e,this.high=0|t,this.unsigned=!!n}function vs(e){return!0===(e&&e.__isLong__)}ws.prototype.__isLong__,Object.defineProperty(ws.prototype,"__isLong__",{value:!0}),ws.isLong=vs;var ks={},Ns={};function Is(e,t){var n,s,r;return t?(r=0<=(e>>>=0)&&e<256)&&(s=Ns[e])?s:(n=Ts(e,(0|e)<0?-1:0,!0),r&&(Ns[e]=n),n):(r=-128<=(e|=0)&&e<128)&&(s=ks[e])?s:(n=Ts(e,e<0?-1:0,!1),r&&(ks[e]=n),n)}function Ss(e,t){if(isNaN(e))return t?Os:Ds;if(t){if(e<0)return Os;if(e>=Rs)return Bs}else{if(e<=-_s)return Ws;if(e+1>=_s)return Ps}return e<0?Ss(-e,t).neg():Ts(e%As|0,e/As|0,t)}function Ts(e,t,n){return new ws(e,t,n)}ws.fromInt=Is,ws.fromNumber=Ss,ws.fromBits=Ts;var Cs=Math.pow;function $s(e,t,n){if(0===e.length)throw Error("empty string");if("NaN"===e||"Infinity"===e||"+Infinity"===e||"-Infinity"===e)return Ds;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 $s(e.substring(1),t,n).neg();for(var r=Ss(Cs(n,8)),a=Ds,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=Ss(Cs(n,o));a=a.mul(u).add(Ss(l))}else a=(a=a.mul(r)).add(Ss(l))}return a.unsigned=t,a}function Es(e,t){return"number"==typeof e?Ss(e,t):"string"==typeof e?$s(e,t):Ts(e.low,e.high,"boolean"==typeof t?t:e.unsigned)}ws.fromString=$s,ws.fromValue=Es;var As=4294967296,Rs=As*As,_s=Rs/2,Fs=Is(1<<24),Ds=Is(0);ws.ZERO=Ds;var Os=Is(0,!0);ws.UZERO=Os;var Ms=Is(1);ws.ONE=Ms;var Ls=Is(1,!0);ws.UONE=Ls;var zs=Is(-1);ws.NEG_ONE=zs;var Ps=Ts(-1,2147483647,!1);ws.MAX_VALUE=Ps;var Bs=Ts(-1,-1,!0);ws.MAX_UNSIGNED_VALUE=Bs;var Ws=Ts(0,-2147483648,!1);ws.MIN_VALUE=Ws;var Vs=ws.prototype;Vs.toInt=function(){return this.unsigned?this.low>>>0:this.low},Vs.toNumber=function(){return this.unsigned?(this.high>>>0)*As+(this.low>>>0):this.high*As+(this.low>>>0)},Vs.toString=function(e){if((e=e||10)<2||36<e)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative()){if(this.eq(Ws)){var t=Ss(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=Ss(Cs(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}},Vs.getHighBits=function(){return this.high},Vs.getHighBitsUnsigned=function(){return this.high>>>0},Vs.getLowBits=function(){return this.low},Vs.getLowBitsUnsigned=function(){return this.low>>>0},Vs.getNumBitsAbs=function(){if(this.isNegative())return this.eq(Ws)?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},Vs.isZero=function(){return 0===this.high&&0===this.low},Vs.eqz=Vs.isZero,Vs.isNegative=function(){return!this.unsigned&&this.high<0},Vs.isPositive=function(){return this.unsigned||this.high>=0},Vs.isOdd=function(){return 1==(1&this.low)},Vs.isEven=function(){return 0==(1&this.low)},Vs.equals=function(e){return vs(e)||(e=Es(e)),(this.unsigned===e.unsigned||this.high>>>31!=1||e.high>>>31!=1)&&(this.high===e.high&&this.low===e.low)},Vs.eq=Vs.equals,Vs.notEquals=function(e){return!this.eq(e)},Vs.neq=Vs.notEquals,Vs.ne=Vs.notEquals,Vs.lessThan=function(e){return this.comp(e)<0},Vs.lt=Vs.lessThan,Vs.lessThanOrEqual=function(e){return this.comp(e)<=0},Vs.lte=Vs.lessThanOrEqual,Vs.le=Vs.lessThanOrEqual,Vs.greaterThan=function(e){return this.comp(e)>0},Vs.gt=Vs.greaterThan,Vs.greaterThanOrEqual=function(e){return this.comp(e)>=0},Vs.gte=Vs.greaterThanOrEqual,Vs.ge=Vs.greaterThanOrEqual,Vs.compare=function(e){if(vs(e)||(e=Es(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},Vs.comp=Vs.compare,Vs.negate=function(){return!this.unsigned&&this.eq(Ws)?Ws:this.not().add(Ms)},Vs.neg=Vs.negate,Vs.add=function(e){vs(e)||(e=Es(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,Ts((c&=65535)<<16|(h&=65535),(l&=65535)<<16|(u&=65535),this.unsigned)},Vs.subtract=function(e){return vs(e)||(e=Es(e)),this.add(e.neg())},Vs.sub=Vs.subtract,Vs.multiply=function(e){if(this.isZero())return Ds;if(vs(e)||(e=Es(e)),xs)return Ts(xs.mul(this.low,this.high,e.low,e.high),xs.get_high(),this.unsigned);if(e.isZero())return Ds;if(this.eq(Ws))return e.isOdd()?Ws:Ds;if(e.eq(Ws))return this.isOdd()?Ws:Ds;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(Fs)&&e.lt(Fs))return Ss(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,Ts((h&=65535)<<16|(p&=65535),(u&=65535)<<16|(c&=65535),this.unsigned)},Vs.mul=Vs.multiply,Vs.divide=function(e){if(vs(e)||(e=Es(e)),e.isZero())throw Error("division by zero");var t,n,s;if(xs)return this.unsigned||-2147483648!==this.high||-1!==e.low||-1!==e.high?Ts((this.unsigned?xs.div_u:xs.div_s)(this.low,this.high,e.low,e.high),xs.get_high(),this.unsigned):this;if(this.isZero())return this.unsigned?Os:Ds;if(this.unsigned){if(e.unsigned||(e=e.toUnsigned()),e.gt(this))return Os;if(e.gt(this.shru(1)))return Ls;s=Os}else{if(this.eq(Ws))return e.eq(Ms)||e.eq(zs)?Ws:e.eq(Ws)?Ms:(t=this.shr(1).div(e).shl(1)).eq(Ds)?e.isNegative()?Ms:zs:(n=this.sub(e.mul(t)),s=t.add(n.div(e)));if(e.eq(Ws))return this.unsigned?Os:Ds;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=Ds}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:Cs(2,r-48),i=Ss(t),o=i.mul(e);o.isNegative()||o.gt(n);)o=(i=Ss(t-=a,this.unsigned)).mul(e);i.isZero()&&(i=Ms),s=s.add(i),n=n.sub(o)}return s},Vs.div=Vs.divide,Vs.modulo=function(e){return vs(e)||(e=Es(e)),xs?Ts((this.unsigned?xs.rem_u:xs.rem_s)(this.low,this.high,e.low,e.high),xs.get_high(),this.unsigned):this.sub(this.div(e).mul(e))},Vs.mod=Vs.modulo,Vs.rem=Vs.modulo,Vs.not=function(){return Ts(~this.low,~this.high,this.unsigned)},Vs.and=function(e){return vs(e)||(e=Es(e)),Ts(this.low&e.low,this.high&e.high,this.unsigned)},Vs.or=function(e){return vs(e)||(e=Es(e)),Ts(this.low|e.low,this.high|e.high,this.unsigned)},Vs.xor=function(e){return vs(e)||(e=Es(e)),Ts(this.low^e.low,this.high^e.high,this.unsigned)},Vs.shiftLeft=function(e){return vs(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?Ts(this.low<<e,this.high<<e|this.low>>>32-e,this.unsigned):Ts(0,this.low<<e-32,this.unsigned)},Vs.shl=Vs.shiftLeft,Vs.shiftRight=function(e){return vs(e)&&(e=e.toInt()),0==(e&=63)?this:e<32?Ts(this.low>>>e|this.high<<32-e,this.high>>e,this.unsigned):Ts(this.high>>e-32,this.high>=0?0:-1,this.unsigned)},Vs.shr=Vs.shiftRight,Vs.shiftRightUnsigned=function(e){if(vs(e)&&(e=e.toInt()),0===(e&=63))return this;var t=this.high;return e<32?Ts(this.low>>>e|t<<32-e,t>>>e,this.unsigned):Ts(32===e?t:t>>>e-32,0,this.unsigned)},Vs.shru=Vs.shiftRightUnsigned,Vs.shr_u=Vs.shiftRightUnsigned,Vs.toSigned=function(){return this.unsigned?Ts(this.low,this.high,!1):this},Vs.toUnsigned=function(){return this.unsigned?this:Ts(this.low,this.high,!0)},Vs.toBytes=function(e){return e?this.toBytesLE():this.toBytesBE()},Vs.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]},Vs.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]},ws.fromBytes=function(e,t,n){return n?ws.fromBytesLE(e,t):ws.fromBytesBE(e,t)},ws.fromBytesLE=function(e,t){return new ws(e[0]|e[1]<<8|e[2]<<16|e[3]<<24,e[4]|e[5]<<8|e[6]<<16|e[7]<<24,t)},ws.fromBytesBE=function(e,t){return new ws(e[4]<<24|e[5]<<16|e[6]<<8|e[7],e[0]<<24|e[1]<<16|e[2]<<8|e[3],t)};const Us=bs||Object.freeze({__proto__:null,default:bs,__moduleExports:bs});function Gs(e){return Us.fromString(e,!0,16)}const Hs=Gs("c3a5c85c97cb3127"),js=Gs("b492b66fbe98f273"),qs=Gs("9ae16a3b2f90404f");function Ks(e){return e.xor(e.shru(47))}function Xs(e,t,n){const s=e.slice(t,t+n);return Us.fromBytes(Array.from(s),!0,!0)}function Ys(e,t){return Xs(e,t,8)}function Zs(e,t){return Xs(e,t,4)}function Js(e,t){return 0===t?e:e.shru(t).or(e.shl(64-t))}function Qs(e,t,n=Gs("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 er(e,t,n,s){return function(e,t,n,s,r,a){r=r.add(e),a=Js(a.add(r).add(s),21);const i=r;return r=(r=r.add(t)).add(n),a=a.add(Js(r,44)),[r.add(s),a.add(i)]}(Ys(e,t),Ys(e,t+8),Ys(e,t+16),Ys(e,t+24),n,s)}function tr(e,t=e.length){const n=Us.fromNumber(81,!0);if(t<=32)return t<=16?function(e,t=e.length){if(t>=8){const n=qs.add(2*t),s=Ys(e,0).add(qs),r=Ys(e,t-8);return Qs(Js(r,37).mul(n).add(s),Js(s,25).add(r).mul(n),n)}if(t>=4){const n=qs.add(2*t);return Qs(Zs(e,0).shl(3).add(t),Zs(e,t-4),n)}if(t>0){const n=e[0]+(e[t>>1]<<8),s=t+(e[t-1]<<2);return Ks(qs.mul(n).xor(Hs.mul(s))).mul(qs)}return qs}(e,t):function(e,t=e.length){const n=qs.add(2*t),s=Ys(e,0).mul(js),r=Ys(e,8),a=Ys(e,t-8).mul(n),i=Ys(e,t-16).mul(qs);return Qs(Js(s.add(r),43).add(Js(a,30)).add(i),s.add(Js(r.add(qs),18)).add(a),n)}(e,t);if(t<=64)return function(e,t=e.length){const n=qs.add(2*t),s=Ys(e,0).mul(qs),r=Ys(e,8),a=Ys(e,t-8).mul(n),i=Ys(e,t-16).mul(qs),o=Js(s.add(r),43).add(Js(a,30)).add(i),l=Qs(o,s.add(Js(r.add(qs),18)).add(a),n),u=Ys(e,16).mul(n),c=Ys(e,24),h=o.add(Ys(e,t-32)).mul(n),p=l.add(Ys(e,t-24)).mul(n);return Qs(Js(u.add(c),43).add(Js(h,30)).add(p),u.add(Js(c.add(s),18)).add(h),n)}(e,t);let s=n,r=n.mul(js).add(113),a=Ks(r.mul(qs).add(113)).mul(qs),i=[Us.UZERO,Us.UZERO],o=[Us.UZERO,Us.UZERO];s=s.mul(qs).add(Ys(e,0));let l=0;const u=64*(t-1>>6),c=u+(t-1&63)-63;do{s=Js(s.add(r).add(i[0]).add(Ys(e,l+8)),37).mul(js),r=Js(r.add(i[1]).add(Ys(e,l+48)),42).mul(js),s=s.xor(o[1]),r=r.add(i[0]).add(Ys(e,l+40)),a=Js(a.add(o[0]),33).mul(js),i=er(e,l,i[1].mul(js),s.add(o[0])),o=er(e,l+32,a.add(o[1]),r.add(Ys(e,l+16))),[a,s]=[s,a],l+=64}while(l!==u);const h=js.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=Js(s.add(r).add(i[0]).add(Ys(e,l+8)),37).mul(h),r=Js(r.add(i[1]).add(Ys(e,l+48)),42).mul(h),s=s.xor(o[1].mul(9)),r=r.add(i[0].mul(9).add(Ys(e,l+40))),a=Js(a.add(o[0]),33).mul(h),i=er(e,l,i[1].mul(h),s.add(o[0])),o=er(e,l+32,a.add(o[1]),r.add(Ys(e,l+16))),[a,s]=[s,a],Qs(Qs(i[0],o[0],h).add(Ks(r).mul(Hs)).add(a),Qs(i[1],o[1],h).add(s),h)}function nr(e,t){return"string"===t?ir(e):sr([e],t)}function sr(e,t){if("string"===t)throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=p(e)),X().getBool("DEBUG")&&I(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 rr(){return X().platform.now()}function ar(e,t){return X().platform.fetch(e,t)}function ir(e,t="utf-8"){return t=t||"utf-8",X().platform.encode(e,t)}function or(e,t="utf-8"){return t=t||"utf-8",X().platform.decode(e,t)}var lr=Object.freeze({__proto__:null,createScalarValue:nr,toTypedArray:sr,now:rr,fetch:ar,encodeString:ir,decodeString:or,shuffle:r,shuffleCombo:function(e,t){if(e.length!==t.length)throw new Error(`Array sizes must match to be shuffled together First array length was ${e.length}Second array length was ${t.length}`);let n=e.length,s=0;for(;n>0;)s=Math.random()*n|0,n--,o(e,n,s),o(t,n,s)},clamp:a,nearestLargerEven:i,swap:o,sum:l,randUniform:function(e,t){const n=Math.random();return t*n+(1-n)*e},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},assert:u,assertShapesMatch:c,assertNonNull:h,flatten:p,sizeFromShape:d,isScalarShape:function(e){return 0===e.length},arraysEqual:f,isInt:m,tanh:function(e){if(null!=Math.tanh)return Math.tanh(e);if(e===1/0)return 1;if(e===-1/0)return-1;{const t=Math.exp(2*e);return(t-1)/(t+1)}},sizeToSquarishShape:g,createShuffledIndices:function(e){const t=new Uint32Array(e);for(let n=0;n<e;++n)t[n]=n;return r(t),t},rightPad:y,repeatedTry:b,inferFromImplicitShape:x,parseAxisParam:w,squeezeShape:v,getTypedArrayFromDType:k,getArrayFromDType:N,checkConversionForErrors:I,isValidDtype:S,hasEncodingLoss:T,isTypedArray:C,bytesPerElement:$,bytesFromStringArray:E,isString:A,isBoolean:R,isNumber:_,inferDtype:F,isFunction:D,nearestDivisor:O,computeStrides:M,toNestedArray:z,makeOnesTypedArray:P,makeZerosTypedArray:B,makeZerosNestedTypedArray:W,assertNonNegativeIntegerDimensions:V,locToIndex:U,indexToLoc:G,isPromise:H,hexToLong:Gs,fingerPrint64:tr});class ur{constructor(e,t){this.backendTimer=e,this.logger=t,null==t&&(this.logger=new hr)}profileKernel(e,t,n){let s;const r=()=>{s=n()};let a;const i=rr();if(this.backendTimer.timerAvailable())a=this.backendTimer.time(r);else{r();for(const e of s)e.dataSync();a=Promise.resolve({kernelMs:rr()-i})}if(X().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let t=0;t<s.length;t++){const n=s[t];n.data().then((t=>{cr(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 cr(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 hr{logKernelProfile(e,t,n,s,r,a){const i="number"==typeof s?y(`${s}ms`,9):s.error,o=y(e,25),l=t.rank,u=t.size,c=y(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 pr(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?gr(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],dr(l[t+e],0,n).length)}return i}(e,t,n,r),i=t.length,o=mr(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 dr(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?fr(e):parseFloat(e.toFixed(7)).toString(),y(s,t)}function fr(e){return 0===e?"false":"true"}function mr(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[dr(gr(e)[0],0,n)]}return"bool"===n?[fr(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=gr(s),a=gr(a)),["["+s.map(((e,t)=>dr(e,r[t],n))).join(", ")+", ..., "+a.map(((e,t)=>dr(e,r[o-3+t],n))).join(", ")+"]"]}return["["+("complex64"===n?gr(e):Array.from(e)).map(((e,t)=>dr(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(...mr(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(...mr(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(...mr(e.slice(s,a),u,n,c,r,t===o-1))}const d=2===l?",":"";p[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 gr(e){const t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}class yr{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=d(e),null!=n){const e=n.length;u(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||N(t,this.size),this.strides=M(e)}set(e,...t){0===t.length&&(t=[0]),u(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 br().makeTensor(this.values,this.shape,this.dtype)}}let br=null,xr=null,wr=null;class vr{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 xr.buffer(this.shape,this.dtype,e)}bufferSync(){return xr.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=br().read(this.dataId);if("string"===this.dtype){const t=await e;try{return t.map((e=>or(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(),br().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();const e=br().readSync(this.dataId);if("string"===this.dtype)try{return e.map((e=>or(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 br().read(this.dataId);return"string"===this.dtype?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(br().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return xr.print(this,e)}clone(){return this.throwIfDisposed(),xr.clone(this)}toString(e=!1){return pr(this.dataSync(),this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),xr.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),br().makeVariable(this,e,t,n)}}function kr(){return J("Tensor",(()=>vr))}Object.defineProperty(vr,Symbol.hasInstance,{value:e=>!!e&&null!=e.data&&null!=e.dataSync&&null!=e.throwIfDisposed}),kr();class Nr extends vr{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(!f(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);br().disposeTensor(this),this.dataId=e.dataId,br().incRef(this,null)}dispose(){br().disposeVariable(this),this.isDisposedInternal=!0}}var Ir,Sr,Tr,Cr,$r;Object.defineProperty(Nr,Symbol.hasInstance,{value:e=>e instanceof vr&&null!=e.assign&&e.assign instanceof Function}),(Ir=e.Rank||(e.Rank={})).R0="R0",Ir.R1="R1",Ir.R2="R2",Ir.R3="R3",Ir.R4="R4",Ir.R5="R5",Ir.R6="R6",function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"}(Sr||(Sr={})),function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"}(Tr||(Tr={})),function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"}(Cr||(Cr={})),function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"}($r||($r={}));const Er={float32:Cr,int32:Sr,bool:Tr,complex64:$r};function Ar(e,t){if("string"===e||"string"===t){if("string"===e&&"string"===t)return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return Er[e][t]}function Rr(e){return Ar(e,"int32")}function _r(e,t){if(e.dtype===t.dtype)return[e,t];const n=Ar(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function Fr(e,t){u(e.dtype===t.dtype,(()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`))}function Dr(e,t){return t.some((t=>t.id===e.id))}function Or(e){const t=[];return Mr(e,t,new Set),t}function Mr(e,t,n){if(null==e)return;if(e instanceof vr)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),Mr(s,t,n))}}var Lr=Object.freeze({__proto__:null,makeTypesMatch:_r,assertTypesMatch:Fr,isTensorInList:Dr,getTensorsInContainer:Or});function zr(e){return null!=e.kernelName}class Pr{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 Br{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Pr}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?(us(`${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 ur(this.backendInstance),!0}setupRegisteredKernels(){fs(this.backendName).forEach((e=>{null!=e.setupFunc&&e.setupFunc(this.backendInstance)}))}disposeRegisteredKernels(e){fs(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 s=t.factory();if(!s||s instanceof n||"function"!=typeof s.then)return this.registry[e]=s,{success:!0,asyncInit:!1};{const t=++this.pendingBackendInitId,n=s.then((n=>!(t<this.pendingBackendInitId)&&(this.registry[e]=n,this.pendingBackendInit=null,!0))).catch((n=>(t<this.pendingBackendInitId||(this.pendingBackendInit=null,us(`Initialization of backend ${e} failed`),us(n.stack||n.message)),!1)));return this.pendingBackendInit=n,{success:n,asyncInit:!0}}}catch(t){return us(`Initialization of backend ${e} failed`),us(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 Br.nextTensorId++}nextVariableId(){return Br.nextVariableId++}clone(e){const t=Vr.runKernel(dt,{x:e}),n={x:e};return this.addTapeNode(this.state.activeScope.name,n,[t],(e=>({x:()=>{const t={x:e},n={dtype:"float32"};return Vr.runKernel(ke,t,n)}})),[],{}),t}runKernel(e,t,n){null==this.backendName&&this.backend;if(!(null!=ps(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=ps(t,this.backendName);u(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:c,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,c,(()=>i())),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(d),t=d.outputs):t=i()})),s&&this.addTapeNode(l,c,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(c).map((e=>null!=c[e]?c[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=ds(e);if(null!=s){const e=s.inputsToSave||[],r=s.outputsToSave||[];let a;s.saveAllInputs?(u(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=>ir(e))));const a=s.write(r,t,n),i=new vr(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 vr(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 Nr(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 Nr||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=ds(e);null!=o&&(s=o.gradFunc),null!=s&&(i.gradient=e=>(e=e.map(((e,t)=>{if(null==e){const e=n[t],s=B(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=Or(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(u(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)));u(r instanceof vr,(()=>"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=P(d(e),"float32");return Vr.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(!f(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)),Ur);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 u(D(e),(()=>"The f passed in customGrad(f) must be a function.")),(...t)=>{let n;u(t.every((e=>e instanceof vr)),(()=>"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),u(n.value instanceof vr,(()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor")),u(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];u(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(...).")),u(a.every((e=>e instanceof vr)),(()=>"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=rr(),n=await this.backend.time(e);return n.wallMs=rr()-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 Pr;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 Wr(){const t=Z();if(null==t._tfengine){const e=new q(t);t._tfengine=new Br(e)}var n;return n=t._tfengine.ENV,e.ENV=n,br=()=>t._tfengine,t._tfengine}Br.nextTensorId=0,Br.nextVariableId=0;const Vr=Wr();function Ur(e,t){const n={a:e,b:t};return Vr.runKernel(ne,n)}let Gr;function Hr(e){if(void 0!==Gr)return Gr;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 jr(){return"undefined"!=typeof window&&null!=window.document||"undefined"!=typeof WorkerGlobalScope}var qr=Object.freeze({__proto__:null,mockIsMobile:function(e){Gr=e},isMobile:Hr,isBrowser:jr});const Kr=X();function Xr(e,t){let n=e;if(C(e))return"string"===t?[]:[e.length];if("object"==typeof e&&"texture"in e){const t=e.channels||"RGBA";return[e.height,e.width*t.length]}if(!Array.isArray(e))return[];const s=[];for(;Array.isArray(n)||C(n)&&"string"!==t;)s.push(n.length),n=n[0];return Array.isArray(e)&&X().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&Yr(e,s,[]),s}function Yr(e,t,n){if(n=n||[],!Array.isArray(e)&&!C(e))return void u(0===t.length,(()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`));u(t.length>0,(()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`)),u(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)Yr(e[t],s,n.concat(t))}function Zr(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 Jr(e,t,n,s="numeric"){if(e instanceof vr)return Zr(s,e.dtype,t,n),e;let r=F(e);if("string"!==r&&["bool","int32","float32"].indexOf(s)>=0&&(r=s),Zr(s,r,t,n),null==e||!C(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=Xr(e,r);C(e)||Array.isArray(e)||(e=[e]);const i="string"!==r?sr(e,r):p(e,[],!0);return Vr.makeTensor(i,a,r)}function Qr(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)=>Jr(e,`${t}[${r}]`,n,s)))}Kr.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.")})),Kr.registerFlag("IS_BROWSER",(()=>jr())),Kr.registerFlag("IS_NODE",(()=>"undefined"!=typeof process&&void 0!==process.versions&&void 0!==process.versions.node)),Kr.registerFlag("IS_CHROME",(()=>"undefined"!=typeof navigator&&null!=navigator&&null!=navigator.userAgent&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor))),Kr.registerFlag("PROD",(()=>!1)),Kr.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",(()=>Kr.getBool("DEBUG"))),Kr.registerFlag("DEPRECATION_WARNINGS_ENABLED",(()=>!0)),Kr.registerFlag("IS_TEST",(()=>!1)),Kr.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",(()=>!0)),Kr.registerFlag("WRAP_TO_IMAGEBITMAP",(()=>!1)),Kr.registerFlag("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU",(()=>!1)),Kr.registerFlag("USE_SETTIMEOUTCUSTOM",(()=>!1));const ea="__op";function ta(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+=ea;const r=(...e)=>{Vr.startScope(n);try{const t=s(...e);return H(t)&&console.error("Cannot return a Promise inside of tidy."),Vr.endScope(t),t}catch(e){throw Vr.endScope(null),e}};return Object.defineProperty(r,"name",{value:n,configurable:!0}),r}const na=ta({complex_:function(e,t){const n=Jr(e,"real","complex"),s=Jr(t,"imag","complex");c(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 Vr.runKernel(Se,r)}});function sa(e,t,n,s){if(null==s&&(s=F(e)),"complex64"===s)throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if("object"==typeof e&&"texture"in e){if("float32"!==s&&"int32"!==s)throw new Error(`Creating tensor from texture only supports 'float32'|'int32' dtype, while the dtype is ${s}.`);return e.channels=e.channels||"RGBA",Vr.backend.createTensorFromTexture(e,t||n,s)}if(!C(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){V(t);const e=d(t),s=d(n);u(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));u(n[e]===t[e]||!r,(()=>`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `))}}return C(e)||Array.isArray(e)||(e=[e]),t=t||n,e="string"!==s?sr(e,s):p(e,[],!0),Vr.makeTensor(e,t,s)}function ra(e,t,n){return sa(e,t,Xr(e,n),n)}const aa={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8};async function ia(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 oa(e,t){const n={};let s,r=0;for(const a of t){const t=a.name,i=a.dtype,o=a.shape,l=d(o);let u;if("quantization"in a){const n=a.quantization;if("uint8"===n.dtype||"uint16"===n.dtype){if(!("min"in n)||!("scale"in n))throw new Error(`Weight ${a.name} with quantization ${n.dtype} doesn't have corresponding metadata min and scale.`)}else{if("float16"!==n.dtype)throw new Error(`Weight ${a.name} has unknown quantization dtype ${n.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);if("float32"!==i)throw new Error(`Weight ${a.name} is quantized with ${n.dtype} which only supports weights of type float32 not ${i}.`)}const o=aa[n.dtype],c=e.slice(r,r+l*o),h="uint8"===n.dtype?new Uint8Array(c):new Uint16Array(c);if("float32"===i)if("uint8"===n.dtype||"uint16"===n.dtype){u=new Float32Array(h.length);for(let e=0;e<h.length;e++){const t=h[e];u[e]=t*n.scale+n.min}}else{if("float16"!==n.dtype)throw new Error(`Unsupported quantization type ${n.dtype} for weight type float32.`);void 0===s&&(s=ba()),u=s(h)}else{if("int32"!==i)throw new Error(`Unsupported dtype in weight '${t}': ${i}`);if("uint8"!==n.dtype&&"uint16"!==n.dtype)throw new Error(`Unsupported quantization type ${n.dtype} for weight type int32.`);u=new Int32Array(h.length);for(let e=0;e<h.length;e++){const t=h[e];u[e]=Math.round(t*n.scale+n.min)}}r+=l*o}else if("string"===i){const t=d(a.shape);u=[];for(let n=0;n<t;n++){const t=new Uint32Array(e.slice(r,r+4))[0];r+=4;const n=new Uint8Array(e.slice(r,r+t));u.push(n),r+=t}}else{const s=aa[i],a=e.slice(r,r+l*s);if("float32"===i)u=new Float32Array(a);else if("int32"===i)u=new Int32Array(a);else if("bool"===i)u=new Uint8Array(a);else{if("complex64"!==i)throw new Error(`Unsupported dtype in weight '${t}': ${i}`);{u=new Float32Array(a);const e=new Float32Array(u.length/2),s=new Float32Array(u.length/2);for(let t=0;t<e.length;t++)e[t]=u[2*t],s[t]=u[2*t+1];const r=ra(e,o,"float32"),i=ra(s,o,"float32");n[t]=na(r,i),r.dispose(),i.dispose()}}r+=l*s}"complex64"!==i&&(n[t]=ra(u,o,i))}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 ua="undefined"!=typeof Buffer&&("undefined"==typeof Blob||"undefined"==typeof atob||"undefined"==typeof btoa);function ca(e){return ua?Buffer.byteLength(e):new Blob([e]).size}function ha(e){if(1===e.length)return e[0];let t=0;e.forEach((e=>{t+=e.byteLength}));const n=new Uint8Array(t);let s=0;return e.forEach((e=>{n.set(new Uint8Array(e),s),s+=e.byteLength})),n.buffer}function pa(e){for(e=e.trim();e.endsWith("/");)e=e.slice(0,e.length-1);const t=e.split("/");return t[t.length-1]}function da(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 fa(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 ma(e,t){let n,s;return null!=e.weightsManifest&&([n,s]=await t(e.weightsManifest)),fa(e,n,s)}function ga(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:ca(JSON.stringify(e.modelTopology)),weightSpecsBytes:null==e.weightSpecs?0:ca(JSON.stringify(e.weightSpecs)),weightDataBytes:null==e.weightData?0:e.weightData.byteLength}}function ya(e){const t=[];for(const n of e)t.push(...n.weights);return t}function ba(){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)}}class xa{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return null==xa.instance&&(xa.instance=new xa),xa.instance}static registerSaveRouter(e){xa.getInstance().saveRouters.push(e)}static registerLoadRouter(e){xa.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return xa.getHandlers(e,"save")}static getLoadHandlers(e,t){return xa.getHandlers(e,"load",t)}static getHandlers(e,t,n){const s=[];return("load"===t?xa.getInstance().loadRouters:xa.getInstance().saveRouters).forEach((t=>{const r=t(e,n);null!==r&&s.push(r)})),s}}const wa=e=>xa.getSaveHandlers(e),va=(e,t)=>xa.getLoadHandlers(e,t),ka="tensorflowjs",Na="models_store",Ia="model_info_store";function Sa(){if(!X().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 Ta(e){const t=e.result;t.createObjectStore(Na,{keyPath:"modelPath"}),t.createObjectStore(Ia,{keyPath:"modelPath"})}class Ca{constructor(e){if(this.indexedDB=Sa(),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(ka,1);s.onupgradeneeded=()=>Ta(s),s.onsuccess=()=>{const r=s.result;if(null==t){const t=r.transaction(Na,"readonly"),s=t.objectStore(Na).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{const s=ga(t),a=r.transaction(Ia,"readwrite");let i=a.objectStore(Ia);const o=i.put({modelPath:this.modelPath,modelArtifactsInfo:s});let l;o.onsuccess=()=>{l=r.transaction(Na,"readwrite");const o=l.objectStore(Na).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:s});o.onsuccess=()=>e({modelArtifactsInfo:s}),o.onerror=e=>{i=a.objectStore(Ia);const t=i.delete(this.modelPath);t.onsuccess=()=>(r.close(),n(o.error)),t.onerror=e=>(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)}))}}Ca.URL_SCHEME="indexeddb://";const $a=e=>{return X().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Ca.URL_SCHEME)?(t=e.slice(Ca.URL_SCHEME.length),new Ca(t)):null;var t};xa.registerSaveRouter($a),xa.registerLoadRouter($a);class Ea{constructor(){this.indexedDB=Sa()}async listModels(){return new Promise(((e,t)=>{const n=this.indexedDB.open(ka,1);n.onupgradeneeded=()=>Ta(n),n.onsuccess=()=>{const s=n.result,r=s.transaction(Ia,"readonly"),a=r.objectStore(Ia).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(Ca.URL_SCHEME)?t.slice(Ca.URL_SCHEME.length):t,new Promise(((t,n)=>{const s=this.indexedDB.open(ka,1);s.onupgradeneeded=()=>Ta(s),s.onsuccess=()=>{const r=s.result,a=r.transaction(Ia,"readwrite"),i=a.objectStore(Ia),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(Na,"readwrite");const s=l.objectStore(Na).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 Aa="/",Ra="tensorflowjs_models",_a="info",Fa="model_topology",Da="weight_specs",Oa="weight_data",Ma="model_metadata";function La(e){return{info:[Ra,e,_a].join(Aa),topology:[Ra,e,Fa].join(Aa),weightSpecs:[Ra,e,Da].join(Aa),weightData:[Ra,e,Oa].join(Aa),modelMetadata:[Ra,e,Ma].join(Aa)}}function za(e){for(const t of Object.values(e))window.localStorage.removeItem(t)}function Pa(e){const t=e.split(Aa);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(Aa)}class Ba{constructor(e){if(!X().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=La(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=ga(e);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(ua)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)}(e.weightData));const r={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(r)),{modelArtifactsInfo:s}}catch(e){throw za(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(ua){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}}Ba.URL_SCHEME="localstorage://";const Wa=e=>{return X().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Ba.URL_SCHEME)?(t=e.slice(Ba.URL_SCHEME.length),new Ba(t)):null;var t};xa.registerSaveRouter(Wa),xa.registerLoadRouter(Wa);class Va{constructor(){u(X().getBool("IS_BROWSER"),(()=>"Current environment is not a web browser")),u("undefined"==typeof window||void 0!==window.localStorage,(()=>"Current browser does not appear to support localStorage")),this.LS=window.localStorage}async listModels(){const e={},t=Ra+Aa,n=Aa+_a;for(let s=0;s<this.LS.length;++s){const r=this.LS.key(s);if(r.startsWith(t)&&r.endsWith(n)){e[Pa(r)]=JSON.parse(this.LS.getItem(r))}}return e}async removeModel(e){var t;const n=La(e=(t=e).startsWith(Ba.URL_SCHEME)?t.slice(Ba.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 za(n),s}}const Ua="://";class Ga{constructor(){this.managers={}}static getInstance(){return null==Ga.instance&&(Ga.instance=new Ga),Ga.instance}static registerManager(e,t){u(null!=e,(()=>"scheme must not be undefined or null.")),e.endsWith(Ua)&&(e=e.slice(0,e.indexOf(Ua))),u(e.length>0,(()=>"scheme must not be an empty string."));const n=Ga.getInstance();u(null==n.managers[e],(()=>`A model store manager is already registered for scheme '${e}'.`)),n.managers[e]=t}static getManager(e){const t=Ga.getInstance().managers[e];if(null==t)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(Ga.getInstance().managers)}}function Ha(e){if(-1===e.indexOf(Ua))throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Ga.getSchemes().join(",")}`);return{scheme:e.split(Ua)[0],path:e.split(Ua)[1]}}async function ja(e,t,n=!1){u(e!==t,(()=>`Old path and new path are the same: '${e}'`));const s=xa.getLoadHandlers(e);u(s.length>0,(()=>`Copying failed because no load handler is found for source URL ${e}.`)),u(s.length<2,(()=>`Copying failed because more than one (${s.length}) load handlers for source URL ${e}.`));const r=s[0],a=xa.getSaveHandlers(t);u(a.length>0,(()=>`Copying failed because no save handler is found for destination URL ${t}.`)),u(a.length<2,(()=>`Copying failed because more than one (${s.length}) save handlers for destination URL ${t}.`));const i=a[0],o=Ha(e).scheme,l=Ha(e).path,c=o===Ha(e).scheme,h=await r.load();n&&c&&await Ga.getManager(o).removeModel(l);const p=await i.save(h);return n&&!c&&await Ga.getManager(o).removeModel(l),p.modelArtifactsInfo}class qa{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&&X().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)}}if(X().get("IS_BROWSER")){X().setPlatform("browser",new qa);try{Ga.registerManager(Ba.URL_SCHEME,new Va)}catch(e){}try{Ga.registerManager(Ca.URL_SCHEME,new Ea)}catch(e){}}const Ka=()=>require("node-fetch");let Xa;class Ya{constructor(){this.util=require("util"),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return null!=X().global.fetch?X().global.fetch(e,t):(null==Xa&&(Xa=Ka()),Xa(e,t))}now(){const e=process.hrtime();return 1e3*e[0]+e[1]/1e6}encode(e,t){if("utf-8"!==t&&"utf8"!==t)throw new Error(`Node built-in encoder only supports utf-8, but got ${t}`);return this.textEncoder.encode(e)}decode(e,t){return 0===e.length?"":new this.util.TextDecoder(t).decode(e)}}function Za(e,t="float32",n){return t=t||"float32",V(e),new yr(e,t,n)}X().get("IS_NODE")&&!X().get("IS_BROWSER")&&X().setPlatform("node",new Ya);const Ja=ta({cast_:function(e,t){const n=Jr(e,"x","cast");if(!S(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 Vr.runKernel(ke,s,r)}});const Qa=ta({clone_:function(e){const t={x:Jr(e,"x","clone","string_or_numeric")};return Vr.runKernel(dt,t)}});function ei(e,t=!1){console.log(e.toString(t))}Wr();xr={buffer:Za,cast:Ja,clone:Qa,print:ei};function ti(e){return new Promise((e=>setTimeout(e))).then(e)}class ni{constructor(e){if(!X().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(ni.URL_SCHEME)&&(e=e.slice(ni.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=window.URL.createObjectURL(new Blob([e.weightData],{type:"application/octet-stream"}));if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{const n=da(e,[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}]),s=window.URL.createObjectURL(new Blob([JSON.stringify(n)],{type:"application/json"})),r=null==this.modelJsonAnchor?document.createElement("a"):this.modelJsonAnchor;if(r.download=this.modelJsonFileName,r.href=s,await ti((()=>r.dispatchEvent(new MouseEvent("click")))),null!=e.weightData){const e=null==this.weightDataAnchor?document.createElement("a"):this.weightDataAnchor;e.download=this.weightDataFileName,e.href=t,await ti((()=>e.dispatchEvent(new MouseEvent("click"))))}return{modelArtifactsInfo:ga(e)}}}}ni.URL_SCHEME="downloads://";class si{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=ma(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,ha(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=>pa(e.name))),s={};for(const r of e)r.paths.forEach((e=>{const r=pa(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 ri(e,t,n,s){!function(e){u(null!=e&&Array.isArray(e)&&e.length>0,(()=>"promises must be a none empty array"))}(e),function(e,t){u(e>=0&&e<=1,(()=>`Progress fraction must be in range [0, 1], but got startFraction ${e}`)),u(t>=0&&t<=1,(()=>`Progress fraction must be in range [0, 1], but got endFraction ${t}`)),u(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 ai(e,t){null==t&&(t={});const n=null==t.fetchFunc?X().platform.fetch:t.fetchFunc,s=e.map((e=>n(e,t.requestInit,{isBinary:!0}))),r=(null==t.onProgress?await Promise.all(s):await ri(s,t.onProgress,0,.5)).map((e=>e.arrayBuffer()));return null==t.onProgress?await Promise.all(r):await ri(r,t.onProgress,.5,1)}async function ii(e,t="",n,s){return oi((e=>ai(e,{requestInit:s})))(e,t,n)}function oi(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=aa[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;let s=0;for(let e=0;e<n;e++)s+=c[p+e].byteLength;const r=new ArrayBuffer(s),i=new Uint8Array(r);let o=0;for(let e=0;e<n;e++){const t=new Uint8Array(c[p+e]);i.set(t,o),o+=t.byteLength}a[e].forEach((e=>{const t=oa(r.slice(e.groupOffset,e.groupOffset+e.sizeBytes),[e.manifestEntry]);for(const e in t)h[e]=t[e]})),p+=n})),h}}xa.registerSaveRouter((e=>X().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(ni.URL_SCHEME)?function(e="model"){return new ni(e)}(e.slice(ni.URL_SCHEME.length)):null));class li{constructor(e,t){if(this.DEFAULT_METHOD="POST",null==t&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,null!=t.fetchFunc?(u("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=X().platform.fetch,u(null!=e&&e.length>0,(()=>"URL path for http must not be null, undefined or empty.")),Array.isArray(e)&&u(2===e.length,(()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`)),this.path=e,null!=t.requestInit&&null!=t.requestInit.body)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");const t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;const n=da(e,[{paths:["./model.weights.bin"],weights:e.weightSpecs}]);t.body.append("model.json",new Blob([JSON.stringify(n)],{type:"application/json"}),"model.json"),null!=e.weightData&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:"application/octet-stream"}),"model.weights.bin");const s=await this.fetch(this.path,t);if(s.ok)return{modelArtifactsInfo:ga(e),responses:[s]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${s.status}.`)}async load(){const e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch(e){let t=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?t+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":t+=" Please make sure the server is serving valid JSON for this request.",new Error(t)}const n=t.modelTopology,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 ma(t,(e=>this.loadWeights(e)))}async loadWeights(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=ya(e),i=[],o=[];for(const t of e)for(const e of t.paths)null!=this.weightUrlConverter?o.push(this.weightUrlConverter(e)):i.push(r+e+s);this.weightUrlConverter&&i.push(...await Promise.all(o));return[a,ha(await ai(i,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress}))]}}function ui(e){return null!=e.match(li.URL_SCHEME_REGEX)}li.URL_SCHEME_REGEX=/^https?:\/\//;const ci=(e,t)=>{if("undefined"==typeof fetch&&(null==t||null==t.fetchFunc))return null;{let n=!0;if(n=Array.isArray(e)?e.every((e=>ui(e))):ui(e),n)return hi(e,t)}return null};function hi(e,t){return new li(e,t)}function pi(e,t){return hi(e,t)}xa.registerSaveRouter(ci),xa.registerLoadRouter(ci);class di{constructor(e){this.modelArtifacts=e}load(){return this.modelArtifacts}}class fi{constructor(e){this.saveHandler=e}save(e){return this.saveHandler(e)}}class mi{constructor(e){e.load&&(this.load=()=>Promise.resolve(e.load())),e.save&&(this.save=t=>Promise.resolve(e.save(t)))}}function gi(e,t,n,s){if(1===arguments.length){return null!=e.modelTopology||null!=e.weightSpecs?new di(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 di({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 di({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:s})}var yi=Object.freeze({__proto__:null,browserFiles:function(e){return new si(e)},browserHTTPRequest:pi,concatenateArrayBuffers:ha,decodeWeights:oa,encodeWeights:ia,fromMemory:function(e,t,n,s){const r=arguments;return new mi(gi(...r))},fromMemorySync:gi,getLoadHandlers:va,getModelArtifactsForJSON:ma,getModelArtifactsForJSONSync:fa,getModelArtifactsInfoForJSON:ga,getSaveHandlers:wa,getWeightSpecs:ya,http:hi,isHTTPScheme:ui,loadWeights:ii,registerLoadRouter:e=>xa.registerLoadRouter(e),registerSaveRouter:e=>xa.registerSaveRouter(e),weightsLoaderFactory:oi,withSaveHandler:function(e){return new fi(e)},withSaveHandlerSync:function(e){return new fi(e)},copyModel:async function(e,t){return ja(e,t,!1)},listModels:async function(){const e=Ga.getSchemes(),t={};for(const n of e){const e=await Ga.getManager(n).listModels();for(const s in e){t[n+Ua+s]=e[s]}}return t},moveModel:async function(e,t){return ja(e,t,!0)},removeModel:async function(e){const t=Ha(e);return Ga.getManager(t.scheme).removeModel(t.path)}});const bi=ta({matMul_:function(e,t,n=!1,s=!1){let r=Jr(e,"a","matMul"),a=Jr(t,"b","matMul");[r,a]=_r(r,a);const i={a:r,b:a},o={transposeA:n,transposeB:s};return Vr.runKernel(ye,i,o)}});const xi=ta({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:Jr(e,"indices","oneHot","int32")},i={dtype:r,depth:t,onValue:n,offValue:s};return Vr.runKernel(Zt,a,i)}});function wi(e){X().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}function vi(){return Vr}function ki(){return Vr.memory()}function Ni(e,t){return Vr.tidy(e,t)}function Ii(e){Or(e).forEach((e=>e.dispose()))}function Si(e){return Vr.keep(e)}function Ti(e){return Vr.setBackend(e)}function Ci(e,t,n=1){return Vr.registerBackend(e,t,n)}function $i(){return Vr.backend}wr=wi;const Ei=ta({imag_:function(e){const t={input:Jr(e,"input","imag")};return Vr.runKernel(mt,t)}});const Ai=ta({neg_:function(e){const t={x:Jr(e,"x","neg")};return Vr.runKernel(Ht,t)}});const Ri=ta({real_:function(e){const t={input:Jr(e,"input","real")};return Vr.runKernel(ln,t)}});const _i=ta({transpose_:function(e,t,n){const s=Jr(e,"x","transpose");if(null==t&&(t=s.shape.map(((e,t)=>t)).reverse()),u(s.rank===t.length,(()=>`Error in transpose: rank of input ${s.rank} must match length of perm ${t}.`)),t.forEach((e=>{u(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?Ni((()=>{let e=Ri(s),t=Ei(s);return e=Vr.runKernel(Jn,{x:e},a),t=Vr.runKernel(Jn,{x:t},a),n&&(t=Ai(t)),na(e,t)})):Vr.runKernel(Jn,r,a)}});const Fi=ta({confusionMatrix_:function(e,t,n){const s=Jr(e,"labels","confusionMatrix"),r=Jr(t,"predictions","confusionMatrix");u(null==n||n>0&&Number.isInteger(n),(()=>`If provided, numClasses must be a positive integer, but got ${n}`)),u(1===s.rank,(()=>`Expected the rank of labels to be 1, but got ${s.rank}`)),u(1===r.rank,(()=>`Expected the rank of predictions to be 1, but got ${r.rank}`)),u(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.`)),u(n>0&&Number.isInteger(n),(()=>`numClasses is required to be a positive integer, but got ${n}`));const a=xi(Ja(s,"int32"),n),i=xi(Ja(r,"int32"),n),o=_i(a),l=bi(o,i);return Ja(l,"int32")}});var Di=Object.freeze({__proto__:null,confusionMatrix:Fi});function Oi(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 Mi(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 Li(e,t){const n=[],s=Math.max(e.length,t.length);for(let r=0;r<s;r++){let s=e[e.length-r-1];null==s&&(s=1);let a=t[t.length-r-1];if(null==a&&(a=1),1===s)n.unshift(a);else if(1===a)n.unshift(s);else{if(s!==a){throw Error(`Operands could not be broadcast together with shapes ${e} and ${t}.`)}n.unshift(s)}}return n}var zi=Object.freeze({__proto__:null,getBroadcastDims:Oi,getReductionAxes:Mi,assertAndGetBroadcastShape:Li});function Pi(e,t,n){if(h(e),null!=t&&3!==t.length)throw new Error("tensor3d() requires shape to have three numbers");const s=Xr(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 sa(e,t,s,n)}let Bi;function Wi(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!=ps(rs,Vr.backendName)){const n={pixels:e},s={numChannels:t};return Vr.runKernel(rs,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==Bi)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.");Bi=new OffscreenCanvas(1,1).getContext("2d")}else Bi=document.createElement("canvas").getContext("2d",{willReadFrequently:!0});Bi.canvas.width=l,Bi.canvas.height=u,Bi.drawImage(e,0,0,l,u),c=Bi.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 Pi(h,[u,l,t],"int32")}function Vi(e){return"undefined"!=typeof window&&"undefined"!=typeof ImageBitmap&&window.hasOwnProperty("createImageBitmap")&&!(e instanceof ImageBitmap)&&function(e){return null!=e&&0!==e.width&&0!==e.height}(e)&&!function(e){return null!=e&&e.data instanceof Uint8Array}(e)}const Ui=ta({fromPixels_:Wi});var Gi=Object.freeze({__proto__:null,fromPixelsAsync:async function(e,t=3){let n=null;if(X().getBool("WRAP_TO_IMAGEBITMAP")&&Vi(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 Wi(n,t)},toPixels:async function(e,t){let n=Jr(e,"img","toPixels");if(!(e instanceof vr)){const e=n;n=Ja(e,"int32"),e.dispose()}if(2!==n.rank&&3!==n.rank)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${n.rank}.`);const[s,r]=n.shape.slice(0,2),a=2===n.rank?1:n.shape[2];if(a>4||2===a)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${a}`);if("float32"!==n.dtype&&"int32"!==n.dtype)throw new Error(`Unsupported type for toPixels: ${n.dtype}. Please use float32 or int32 tensors.`);const 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){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},fromPixels:Ui});function Hi(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 ji=Object.freeze({__proto__:null,prepareAndValidate:Hi});function qi(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 Ki(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}`)}qi(n,t,e)}function Xi(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 Yi=Object.freeze({__proto__:null,validateUpdateShape:qi,validateInput:Ki,calculateShapes:Xi});function Zi(e,t,n){const s=e.shape.length;u(s===t.length,(()=>`Error in slice${s}D: Length of begin ${t} must match the rank of the array (${s}).`)),u(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)u(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 Ji(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 Qi(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 eo(e,t,n){return n<=e?n:n-(t-1)}function to(e,t){const n=[];for(let s=0;s<e;s++)n.push(t+s);return n}function no(e,t,n,s,r){const a=[...r],i=to(n,t);for(let r=0;r<a.length;r++)if(i.indexOf(r)>-1)a[r]=0;else{const i=eo(t,n,r);let o=s[i];e&1<<i&&(o=0),a[r]=o}return a}function so(e,t,n,s,r){const i=[...r],o=to(n,t);for(let r=0;r<i.length;r++)if(o.indexOf(r)>-1)i[r]=Number.MAX_SAFE_INTEGER;else{const a=eo(t,n,r);let o=s[a];e&1<<a&&(o=Number.MAX_SAFE_INTEGER),i[r]=o}for(let e=0;e<i.length;e++){const t=r[e];i[e]<0&&(i[e]+=t),i[e]=a(0,i[e],r[e])}return i}function ro(e,t,n){let s=e[t];return(n&1<<t||null==s)&&(s=1),s}function ao(e,t,n,s,r,i){let o=t[r];const l=n[r]||1;(e&1<<r||i&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=a(0,o,u-1),o}function io(e,t,n,s,r,i){let o=t[r];const l=n[r]||1;(e&1<<r||i&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?a(0,o,u):a(-1,o,u-1),o}function oo(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 lo(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 uo(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=>{u(-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:(u(-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 co(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]=ho(p.begin[t],0,p.strides[t],s,r,a),p.end[t]=ho(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 ho(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 po=Object.freeze({__proto__:null,assertParamsValid:Zi,maskToAxes:function(e){const t=[];let n=0;for(;e>0;)1&e&&t.push(n),e/=2,n++;return t},computeOutShape:Ji,stridesWithElidedDims:Qi,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=no(i,l,u,s,e),h=so(o,l,u,r,e),p=Qi(a,l,u,e)}else for(let t=0;t<u;t++)c[t]=ao(i,s,a,e,t,l),h[t]=io(o,r,a,e,t,l),p[t]=ro(a,t,l);return{begin:c,end:h,strides:p}},startIndicesWithElidedDims:no,stopIndicesWithElidedDims:so,stridesForAxis:ro,startForAxis:ao,stopForAxis:io,isSliceContinous:oo,computeFlatOffset:lo,parseSliceParams:uo,sliceInfo:co});class fo{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}}class mo{constructor(){this.classNameMap={}}static getMap(){return null==mo.instance&&(mo.instance=new mo),mo.instance}static register(e){mo.getMap().classNameMap[e.className]=[e,e.fromConfig]}}function go(e){u(null!=e.className,(()=>"Class being registered does not have the static className property defined.")),u("string"==typeof e.className,(()=>"className is required to be a string, but got type "+typeof e.className)),u(e.className.length>0,(()=>"Class being registered has an empty-string as its className, which is disallowed.")),mo.register(e)}var yo=Object.freeze({__proto__:null,Serializable:fo,SerializationMap:mo,registerClass:go});function bo(){return 32===Vr.backend.floatPrecision()?.001:.1}function xo(e,t,n){let s=!0;if((C(e)||C(t))&&(s=!1),C(e)&&C(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=Xr(e),s=Xr(t);if(!f(n,s))throw new Error(`Arrays have different shapes. Actual: [${n}]. Expected: [${s}]`)}const r=C(e)?e:p(e),a=C(t)?t:p(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 wo(e,t,n){if(null==n&&(n=bo()),!vo(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`);"undefined"!=typeof expect&&expect().nothing()}function vo(e,t,n){return!isFinite(e)&&!isFinite(t)||!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}var ko=Object.freeze({__proto__:null,TEST_EPSILON_FLOAT16:.1,expectArraysClose:function(e,t,n){return null==n&&(n=bo()),xo(e,t,((e,t)=>vo(e,t,n)))},testEpsilon:bo,expectPromiseToFail:function(e,t){e().then((()=>t.fail()),(()=>t())),"undefined"!=typeof expect&&expect().nothing()},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])?xo(e,n,((e,t)=>e==t)):xo(e,t,((e,t)=>vo(e,t,0)))},expectNumbersClose:wo,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}`)},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`)},encodeStrings:function e(t){for(let n=0;n<t.length;n++){const s=t[n];Array.isArray(s)?e(s):t[n]=ir(s)}return t},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()}))},play:async function(e){await e.play(),"requestVideoFrameCallback"in e&&await new Promise((t=>{e.requestVideoFrameCallback(t)}))}});const No="4.1.0";const Io=ta({add_:function(e,t){let n=Jr(e,"a","add"),s=Jr(t,"b","add");[n,s]=_r(n,s);const r={a:n,b:s};return Vr.runKernel(ne,r)}});const So=ta({floorDiv_:function(e,t){let n=Jr(e,"a","floorDiv"),s=Jr(t,"b","floorDiv");[n,s]=_r(n,s);const r={a:n,b:s};return Vr.runKernel(ot,r)}});const To=ta({div_:function(e,t){let n=Jr(e,"a","div"),s=Jr(t,"b","div");if([n,s]=_r(n,s),"int32"===n.dtype&&"int32"===s.dtype)return So(n,s);const r={a:n,b:s};return Vr.runKernel(Ke,r,{})}});const Co=ta({mul_:function(e,t){let n=Jr(e,"a","mul"),s=Jr(t,"b","mul");[n,s]=_r(n,s);const r={a:n,b:s};return Vr.runKernel(Gt,r)}});const $o=ta({abs_:function(e){const t=Jr(e,"x","abs");if("complex64"===t.dtype){const e={x:t};return Vr.runKernel(Te,e)}{const e={x:t};return Vr.runKernel(Q,e)}}});const Eo=ta({acos_:function(e){const t={x:Jr(e,"x","acos")};return Vr.runKernel(ee,t)}});const Ao=ta({acosh_:function(e){const t={x:Jr(e,"x","acosh")};return Vr.runKernel(te,t)}});const Ro=ta({addN_:function(e){u(Array.isArray(e),(()=>"The argument passed to tf.addN() must be a list of tensors")),u(e.length>=1,(()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`));const t=e.map(((e,t)=>Jr(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(!f(e.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")}));const s=t;return Vr.runKernel(se,s)}});const _o=ta({all_:function(e,t=null,n=!1){const s={x:Jr(e,"x","all","bool")},r={axis:t,keepDims:n};return Vr.runKernel(re,s,r)}});const Fo=ta({any_:function(e,t=null,n=!1){const s={x:Jr(e,"x","any","bool")},r={axis:t,keepDims:n};return Vr.runKernel(ae,s,r)}});const Do=ta({argMax_:function(e,t=0){const n={x:Jr(e,"x","argMax")},s={axis:t};return Vr.runKernel(ie,n,s)}});const Oo=ta({argMin_:function(e,t=0){const n={x:Jr(e,"x","argMin")},s={axis:t};return Vr.runKernel(oe,n,s)}});const Mo=ta({asin_:function(e){const t={x:Jr(e,"x","asin")};return Vr.runKernel(le,t)}});const Lo=ta({asinh_:function(e){const t={x:Jr(e,"x","asinh")};return Vr.runKernel(ue,t)}});const zo=ta({atan_:function(e){const t={x:Jr(e,"x","atan")};return Vr.runKernel(ce,t)}});const Po=ta({atan2_:function(e,t){let n=Jr(e,"a","atan2"),s=Jr(t,"b","atan2");[n,s]=_r(n,s);const r={a:n,b:s};return Vr.runKernel(pe,r)}});const Bo=ta({atanh_:function(e){const t={x:Jr(e,"x","atanh")};return Vr.runKernel(he,t)}});function Wo(e,t,n,s,r="NHWC",a){return Go(e,[...t,e[3]],n,a,s,null,null,Qo(r))}function Vo(e,t,n,s,r,a,i="channelsLast"){const[o,l]=qo(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 Go(e,u,n,s,r,a,!1,i)}function Uo(e,t,n,s,r,a,i="NDHWC"){const[o,l,u]=Ko(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 Ho(e,c,n,s,r,!1,h,a)}function Go(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]=qo(n),[y,b]=qo(s),x=Xo(p,y),w=Xo(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=jo(e,t,n));const a=e[0],i=e[1],o=Yo((a-t+2*s)/n+1,r),l=Yo((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=Yo((t-a+p+d)/s+1,o),h=Yo((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 Ho(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]=Ko(n),[w,v,k]=Ko(s),N=Xo(d,w),I=Xo(f,v),S=Xo(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;if("number"==typeof e){h={top:e,bottom:e,left:e,right:e,front:e,back:e,type:0===e?"VALID":"NUMBER"};const a=function(e,t,n,s,r,a){null==r&&(r=jo(e,t,s));const i=e[0],o=e[1],l=e[2],u=Yo((i-t+2*r)/s+1,a),c=Yo((o-t+2*r)/s+1,a),h=Yo((l-t+2*r)/s+1,a);return[u,c,h,n]}([t,n,s,1],o,1,r,e,c);p=a[0],d=a[1],f=a[2]}else if("same"===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"}}else{if("valid"!==e)throw Error(`Unknown padding parameter: ${e}`);h={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},p=Math.ceil((t-o+1)/r),d=Math.ceil((n-l+1)/a),f=Math.ceil((s-u+1)/i)}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 jo(e,t,n,s=1){const r=Xo(t,s);return Math.floor((e[0]*(n-1)-n+r)/2)}function qo(e){return"number"==typeof e?[e,e,e]:2===e.length?[e[0],e[1],1]:e}function Ko(e){return"number"==typeof e?[e,e,e]:e}function Xo(e,t){return t<=1?e:e+(e-1)*(t-1)}function Yo(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 Zo(e){const[t,n,s]=qo(e);return 1===t&&1===n&&1===s}function Jo(e,t){return Zo(e)||Zo(t)}function Qo(e){if("NHWC"===e)return"channelsLast";if("NCHW"===e)return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function el(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)u(m(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=>{u(m(t),(()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`))}))}))}}}const tl=ta({reshape_:function(e,t){const n={x:Jr(e,"x","reshape","string_or_numeric")},s={shape:t};return Vr.runKernel(hn,n,s)}});const nl=ta({avgPool_:function(e,t,n,s,r){const a=Jr(e,"x","avgPool","float32");u(Jo(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=tl(a,[1,a.shape[0],a.shape[1],a.shape[2]])),u(4===i.rank,(()=>`Error in avgPool: x must be rank 4 but got rank ${i.rank}.`)),el("avgPool",s,r);const l={x:i},c={filterSize:t,strides:n,pad:s,dimRoundingMode:r};let h=Vr.runKernel(de,l,c);return h=Ja(h,a.dtype),o?tl(h,[h.shape[1],h.shape[2],h.shape[3]]):h}});const sl=ta({avgPool3d_:function(e,t,n,s,r,a="NDHWC"){const i=Jr(e,"x","avgPool3d","float32");let o=i,l=!1;4===i.rank&&(l=!0,o=tl(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),u(5===o.rank,(()=>`Error in avgPool3d: x must be rank 5 but got rank ${o.rank}.`)),u("NDHWC"===a,(()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`)),el("avgPool3d",s,r);const c={x:o},h={filterSize:t,strides:n,pad:s,dimRoundingMode:r,dataFormat:a};let p=Vr.runKernel(me,c,h);return p=Ja(p,o.dtype),l?tl(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}});const rl=ta({concat_:function(e,t=0){u(e.length>=1,(()=>"Pass at least one tensor to concat"));const n=Qr(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 Qa(n[0]);const s=n,r={axis:t};return Vr.runKernel(Ce,s,r)}});const al=ta({sigmoid_:function(e){const t={x:Jr(e,"x","sigmoid","float32")};return Vr.runKernel($n,t)}});const il=ta({slice_:function(e,t,n){const s=Jr(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 Vr.runKernel(In,r,a)}});const ol=ta({tanh_:function(e){const t={x:Jr(e,"x","tanh","float32")};return Vr.runKernel(Kn,t)}});const ll=ta({basicLSTMCell_:function(e,t,n,s,r,a){const i=Jr(e,"forgetBias","basicLSTMCell"),o=Jr(t,"lstmKernel","basicLSTMCell"),l=Jr(n,"lstmBias","basicLSTMCell"),u=Jr(s,"data","basicLSTMCell"),c=Jr(r,"c","basicLSTMCell"),h=Jr(a,"h","basicLSTMCell"),p=rl([u,h],1),d=bi(p,o),f=Io(d,l),m=f.shape[0],g=f.shape[1]/4,y=[m,g],b=il(f,[0,0],y),x=il(f,[0,g],y),w=il(f,[0,2*g],y),v=il(f,[0,3*g],y),k=Io(Co(al(b),ol(x)),Co(c,al(Io(i,w))));return[k,Co(ol(k),al(v))]}});const ul=ta({batchToSpaceND_:function(e,t,n){const s=Jr(e,"x","batchToSpaceND"),r=t.reduce(((e,t)=>e*t));u(s.rank>=1+t.length,(()=>`input rank is ${s.rank} but should be > than blockShape.length ${t.length}`)),u(n.length===t.length,(()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`)),u(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 Vr.runKernel(be,a,i)}});const cl=ta({batchNorm_:function(e,t,n,s,r,a){null==a&&(a=.001);const i=Jr(e,"x","batchNorm"),o=Jr(t,"mean","batchNorm"),l=Jr(n,"variance","batchNorm");let c,h;null!=r&&(c=Jr(r,"scale","batchNorm")),null!=s&&(h=Jr(s,"offset","batchNorm")),u(o.rank===l.rank,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),u(null==h||o.rank===h.rank,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),u(null==c||o.rank===c.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?tl(e,[1,1,1,e.size]):2===e.rank?tl(e,[1,1,e.shape[0],e.shape[1]]):3===e.rank?tl(e,[1,e.shape[0],e.shape[1],e.shape[2]]):e,t}(i),d={x:p,scale:c,offset:h,mean:o,variance:l},f={varianceEpsilon:a},m=Vr.runKernel(lt,d,f);return tl(m,i.shape)}});const hl=ta({batchNorm2d_:function(e,t,n,s,r,a){const i=Jr(e,"x","batchNorm"),o=Jr(t,"mean","batchNorm"),l=Jr(n,"variance","batchNorm");let c,h;return null!=r&&(c=Jr(r,"scale","batchNorm")),null!=s&&(h=Jr(s,"offset","batchNorm")),u(2===i.rank,(()=>`Error in batchNorm2D: x must be rank 2 but got rank ${i.rank}.`)),u(2===o.rank||1===o.rank,(()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${o.rank}.`)),u(2===l.rank||1===l.rank,(()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`)),null!=c&&u(2===c.rank||1===c.rank,(()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${c.rank}.`)),null!=h&&u(2===h.rank||1===h.rank,(()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${h.rank}.`)),cl(i,o,l,h,c,a)}});const pl=ta({batchNorm3d_:function(e,t,n,s,r,a){const i=Jr(e,"x","batchNorm"),o=Jr(t,"mean","batchNorm"),l=Jr(n,"variance","batchNorm");let c,h;return null!=r&&(c=Jr(r,"scale","batchNorm")),null!=s&&(h=Jr(s,"offset","batchNorm")),u(3===i.rank,(()=>`Error in batchNorm3D: x must be rank 3 but got rank ${i.rank}.`)),u(3===o.rank||1===o.rank,(()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${o.rank}.`)),u(3===l.rank||1===l.rank,(()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`)),null!=c&&u(3===c.rank||1===c.rank,(()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${c.rank}.`)),null!=h&&u(3===h.rank||1===h.rank,(()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${h.rank}.`)),cl(i,o,l,h,c,a)}});const dl=ta({batchNorm4d_:function(e,t,n,s,r,a){const i=Jr(e,"x","batchNorm"),o=Jr(t,"mean","batchNorm"),l=Jr(n,"variance","batchNorm");let c,h;return null!=r&&(c=Jr(r,"scale","batchNorm")),null!=s&&(h=Jr(s,"offset","batchNorm")),u(4===i.rank,(()=>`Error in batchNorm4D: x must be rank 4 but got rank ${i.rank}.`)),u(4===o.rank||1===o.rank,(()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${o.rank}.`)),u(4===l.rank||1===l.rank,(()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`)),null!=c&&u(4===c.rank||1===c.rank,(()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${c.rank}.`)),null!=h&&u(4===h.rank||1===h.rank,(()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${h.rank}.`)),cl(i,o,l,h,c,a)}});const fl=ta({bincount_:function(e,t,n){const s=Jr(e,"x","bincount"),r=Jr(t,"weights","bincount");u("int32"===s.dtype,(()=>`Error in bincount: input dtype must be int32, but got ${s.dtype}`)),u(n>=0,(()=>`size must be non-negative, but got ${n}.`)),u(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 Vr.runKernel(xe,a,i)}});const ml=ta({broadcastArgs_:function(e,t){const n=Jr(e,"s0","broadcastArgs","int32"),s=Jr(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 Vr.runKernel(ve,r)}});const gl=ta({broadcastTo_:function(e,t){let n=Jr(e,"broadcastTo","x");const s=n.shape;if(V(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=tl(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 Qa(n);const i={x:n},o={reps:a};return Vr.runKernel(Xn,i,o)}});const yl=ta({ceil_:function(e){const t={x:Jr(e,"x","ceil","float32")};return Vr.runKernel(Ne,t)}});function bl(e,t,n){V(e);const s={shape:e,value:t,dtype:n};return Vr.runKernel(rt,{},s)}const xl=ta({clipByValue_:function(e,t,n){const s=Jr(e,"x","clipByValue");if(u(t<=n,(()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`)),t===n)return bl(s.shape,t,s.dtype);const r={x:s},a={clipValueMin:t,clipValueMax:n};return Vr.runKernel(Ie,r,a)}});const wl=ta({concat1d_:function(e){return rl(e,0)}});const vl=ta({concat2d_:function(e,t){return rl(e,t)}});const kl=ta({concat3d_:function(e,t){return rl(e,t)}});const Nl=ta({concat4d_:function(e,t){return rl(e,t)}});const Il=ta({conv2d_:function(e,t,n,s,r="NHWC",a=[1,1],i){const o=Jr(e,"x","conv2d","float32"),l=Jr(t,"filter","conv2d","float32");let c=o,h=!1;3===o.rank&&(h=!0,c=tl(o,[1,o.shape[0],o.shape[1],o.shape[2]])),u(4===c.rank,(()=>`Error in conv2d: input must be rank 4, but got rank ${c.rank}.`)),u(4===l.rank,(()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`)),el("conv2d",s,i);const p="NHWC"===r?c.shape[3]:c.shape[1];u(p===l.shape[2],(()=>`Error in conv2d: depth of input (${p}) must match input depth for filter ${l.shape[2]}.`)),u(Jo(n,a),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`));const d={x:c,filter:l},f={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:i},m=Vr.runKernel($e,d,f);return h?tl(m,[m.shape[1],m.shape[2],m.shape[3]]):m}});const Sl=ta({conv1d_:function(e,t,n,s,r="NWC",a=1,i){const o=Jr(e,"x","conv1d"),l=Jr(t,"filter","conv1d");let c=o,h=!1;2===o.rank&&(h=!0,c=tl(o,[1,o.shape[0],o.shape[1]])),u(3===c.rank,(()=>`Error in conv1d: input must be rank 3, but got rank ${c.rank}.`)),u(3===l.rank,(()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`)),el("conv1d",s,i),u(c.shape[2]===l.shape[1],(()=>`Error in conv1d: depth of input (${c.shape[2]}) must match input depth for filter ${l.shape[1]}.`)),u(Jo(n,a),(()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${a}'`)),u("NWC"===r,(()=>`Error in conv1d: got dataFormat of ${r} but only NWC is currently supported.`));const p=tl(l,[1,l.shape[0],l.shape[1],l.shape[2]]),d=tl(c,[c.shape[0],1,c.shape[1],c.shape[2]]),f=Il(d,p,[1,n],s,"NHWC",[1,a],i);return tl(f,h?[f.shape[2],f.shape[3]]:[f.shape[0],f.shape[2],f.shape[3]])}});const Tl=ta({conv2DBackpropInput_:function(e,t,n,s,r,a="NHWC",i){u(e.length===t.rank,(()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`));let o=e,l=t,c=!1;3===t.rank&&(c=!0,l=tl(t,[1,t.shape[0],t.shape[1],t.shape[2]]),o=[1,e[0],e[1],e[2]]),u(4===o.length,(()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${o.length}.`)),u(4===l.rank,(()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`)),u(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];u(h===n.shape[2],(()=>`Error in conv2dDerInput: depth of input (${h}) must match input depth for filter ${n.shape[2]}.`)),u(p===n.shape[3],(()=>`Error in conv2dDerInput: depth of output (${p}) must match output depth for filter ${n.shape[3]}.`)),el("conv2dDerInput",r,i);const d={dy:l,filter:n},f={strides:s,pad:r,dataFormat:a,dimRoundingMode:i,inputShape:o},m=Vr.runKernel(Ae,d,f);return c?tl(m,[m.shape[1],m.shape[2],m.shape[3]]):m}});const Cl=ta({conv2dTranspose_:function(e,t,n,s,r,a){const i=Jr(e,"x","conv2dTranspose"),o=Jr(t,"filter","conv2dTranspose");return Tl(n,i,o,s,r,"NHWC",a)}});const $l=ta({conv3d_:function(e,t,n,s,r="NDHWC",a=[1,1,1]){const i=Jr(e,"x","conv3d"),o=Jr(t,"filter","conv3d");let l=i,c=!1;4===i.rank&&(c=!0,l=tl(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),u(5===l.rank,(()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`)),u(5===o.rank,(()=>`Error in conv3d: filter must be rank 5, but got rank ${o.rank}.`)),u(l.shape[4]===o.shape[3],(()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${o.shape[3]}.`)),u(Jo(n,a),(()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`)),u("NDHWC"===r,(()=>`Error in conv3d: got dataFormat of ${r} but only NDHWC is currently supported.`));const h={x:l,filter:o},p={strides:n,pad:s,dataFormat:r,dilations:a},d=Vr.runKernel(Re,h,p);return c?tl(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}});const El=ta({conv3DBackpropInput_:function(e,t,n,s,r){u(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=tl(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],c=i.shape[4];u(5===a.length,(()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${a.length}.`)),u(5===i.rank,(()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${i.rank}`)),u(5===n.rank,(()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`)),u(l===n.shape[3],(()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[3]}.`)),u(c===n.shape[4],(()=>`Error in conv3dDerInput: depth of output (${c}) must match output depth for filter ${n.shape[4]}.`));const h={dy:i,filter:n},p={pad:r,strides:s,inputShape:a},d=Vr.runKernel(Fe,h,p);return o?tl(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}});const Al=ta({conv3dTranspose_:function(e,t,n,s,r){const a=Jr(e,"x","conv3dTranspose"),i=Jr(t,"filter","conv3dTranspose");return El(n,a,i,s,r)}});const Rl=ta({cos_:function(e){const t={x:Jr(e,"x","cos","float32")};return Vr.runKernel(De,t)}});const _l=ta({cosh_:function(e){const t={x:Jr(e,"x","cosh","float32")};return Vr.runKernel(Oe,t)}});const Fl=ta({cumprod_:function(e,t=0,n=!1,s=!1){const r={x:Jr(e,"x","cumprod")},a={axis:t,exclusive:n,reverse:s};return Vr.runKernel(Me,r,a)}});const Dl=ta({cumsum_:function(e,t=0,n=!1,s=!1){const r={x:Jr(e,"x","cumsum")},a={axis:t,exclusive:n,reverse:s};return Vr.runKernel(Le,r,a)}});const Ol=ta({denseBincount_:function(e,t,n,s=!1){const r=Jr(e,"x","denseBincount"),a=Jr(t,"weights","denseBincount");u("int32"===r.dtype,(()=>`Error in denseBincount: input dtype must be int32, but got ${r.dtype}`)),u(r.rank<=2,(()=>`Error in denseBincount: input must be at most rank 2, but got rank ${r.rank}.`)),u(n>=0,(()=>`size must be non-negative, but got ${n}.`)),u(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 Vr.runKernel(Pe,i,o)}});const Ml=ta({depthToSpace_:function(e,t,n="NHWC"){const s=Jr(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];u(t>1,(()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`)),u(r*t>=0,(()=>`Negative dimension size caused by overflow when multiplying\n ${r} and ${t} for depthToSpace with input shape\n ${s.shape}`)),u(a*t>=0,(()=>`Negative dimension size caused by overflow when multiplying\n ${a} and ${t} for depthToSpace with input shape\n ${s.shape}`)),u(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 Vr.runKernel(Be,o,l)}});const Ll=ta({depthwiseConv2d_:function(e,t,n,s,r="NHWC",a=[1,1],i){const o=Jr(e,"x","depthwiseConv2d","float32"),l=Jr(t,"filter","depthwiseConv2d","float32");let c=o,h=!1;3===o.rank&&(h=!0,c=tl(o,[1,o.shape[0],o.shape[1],o.shape[2]])),u(4===c.rank,(()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${c.rank}.`)),u(4===l.rank,(()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`));const p="NHWC"===r?c.shape[3]:c.shape[1];u(p===l.shape[2],(()=>`Error in depthwiseConv2d: number of input channels (${p}) must match the inChannels dimension in filter ${l.shape[2]}.`)),el("depthwiseConv2d",s,i);const d={x:c,filter:l},f={strides:n,pad:s,dataFormat:r,dilations:a,dimRoundingMode:i},m=Vr.runKernel(We,d,f);return h?tl(m,[m.shape[1],m.shape[2],m.shape[3]]):m}});const zl=ta({diag_:function(e){const t={x:Jr(e,"x","diag")};return Vr.runKernel(Ge,t)}});const Pl=ta({dilation2d_:function(e,t,n,s,r=[1,1],a="NHWC"){const i=Jr(e,"x","dilation2d"),o=Jr(t,"filter","dilation2d");u(3===i.rank||4===i.rank,(()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${i.rank}.`)),u(3===o.rank,(()=>`Error in dilation2d: filter must be rank 3, but got rank ${o.rank}.`)),u("NHWC"===a,(()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${a}`));let l=i,c=!1;3===i.rank&&(l=tl(i,[1,i.shape[0],i.shape[1],i.shape[2]]),c=!0);const h={x:l,filter:o},p={strides:n,pad:s,dilations:r},d=Vr.runKernel(He,h,p);return c?tl(d,[d.shape[1],d.shape[2],d.shape[3]]):d}});const Bl=ta({equal_:function(e,t){let n=Jr(e,"a","equal","string_or_numeric"),s=Jr(t,"b","equal","string_or_numeric");[n,s]=_r(n,s),Li(n.shape,s.shape);const r={a:n,b:s};return Vr.runKernel(Qe,r)}});const Wl=ta({where_:function(e,t,n){const s=Jr(t,"a","where"),r=Jr(n,"b","where"),a=Jr(e,"condition","where","bool"),i=Li(Li(a.shape,s.shape),r.shape),o={condition:gl(a,i),t:gl(s,i),e:gl(r,i)};return Vr.runKernel(kn,o)}});const Vl=ta({zerosLike_:function(e){const t={x:Jr(e,"x","zerosLike")};return Vr.runKernel(ns,t)}});const Ul=ta({divNoNan_:function(e,t){let n=Jr(e,"a","div"),s=Jr(t,"b","div");[n,s]=_r(n,s);const r=To(n,s),a=Vl(r),i=Bl(s,a);return Wl(i,a,r)}});const Gl=ta({dot_:function(e,t){const n=Jr(e,"t1","dot"),s=Jr(t,"t2","dot");u(!(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(u(r===a,(()=>`Error in dot: inner dimensions of inputs must match, but got ${r} and ${a}.`)),1===n.rank&&1===s.rank){const e=tl(n,[1,-1]),t=tl(s,[-1,1]),r=bi(e,t);return tl(r,[])}if(1===n.rank&&2===s.rank){const e=tl(n,[1,-1]),t=tl(s,[s.shape[0],s.shape[1]]),r=bi(e,t);return tl(r,[r.size])}if(2===n.rank&&1===s.rank){const e=tl(s,[-1,1]),t=bi(n,e);return tl(t,[t.size])}{const e=tl(s,[s.shape[0],s.shape[1]]);return bi(n,e)}}});const Hl=ta({einsum_:function(e,...t){const n=t.map(((e,t)=>Jr(e,`tensors${t}`,"einsum"))),s={equation:e};return Vr.runKernel(Xe,n,s)}});const jl=ta({elu_:function(e){const t={x:Jr(e,"x","elu","float32")};return Vr.runKernel(Ye,t)}});const ql=ta({erf_:function(e){let t=Jr(e,"x","erf");u("int32"===t.dtype||"float32"===t.dtype,(()=>"Input dtype must be `int32` or `float32`.")),"int32"===t.dtype&&(t=Ja(t,"float32"));const n={x:t};return Vr.runKernel(Je,n)}});function Kl(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function Xl(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 Yl(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 Zl(e,t){return Xl(e,t.map((e=>1)),t)}function Jl(e,t,n){u(Kl(t,n),(()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`))}function Ql(e,t){if(Kl(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 eu(e){return e.map(((e,t)=>[t,e])).sort(((e,t)=>e[1]-t[1])).map((e=>e[0]))}function tu(e,t){const n=[];for(let s=t-e;s<t;++s)n.push(s);return n}const nu=ta({max_:function(e,t=null,n=!1){const s={x:Jr(e,"x","max")},r={reductionIndices:t,keepDims:n};return Vr.runKernel(Rt,s,r)}});const su=ta({min_:function(e,t=null,n=!1){const s={x:Jr(e,"x","min")},r={axis:t,keepDims:n};return Vr.runKernel(Pt,s,r)}});const ru=ta({pow_:function(e,t){let n=Jr(e,"base","pow"),s=Jr(t,"exp","pow");[n,s]=_r(n,s);const r={a:n,b:s};return Vr.runKernel(en,r)}});function au(e,t){if((C(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&&C(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return sa(e,[],[],t)}const iu=ta({sqrt_:function(e){const t={x:Jr(e,"x","sqrt","float32")};return Vr.runKernel(An,t)}});const ou=ta({square_:function(e){const t=Jr(e,"x","square");return Vr.runKernel("Square",{x:t},{})}});const lu=ta({sum_:function(e,t=null,n=!1){let s=Jr(e,"x","sum");"bool"===s.dtype&&(s=Ja(s,"int32"));const r={x:s},a={axis:t,keepDims:n};return Vr.runKernel(Rn,r,a)}});function uu(e,t,n=null){if(0===e.rank)return $o(e);if(1!==e.rank&&null===n)return uu(tl(e,[-1]),t,n);if(1===e.rank||"number"==typeof n||Array.isArray(n)&&1===n.length){if(1===t)return lu($o(e),n);if(t===1/0)return nu($o(e),n);if(t===-1/0)return su($o(e),n);if("euclidean"===t||2===t)return iu(lu(ru($o(e),au(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&2===n.length){if(1===t)return nu(lu($o(e),n[0]),n[1]-1);if(t===1/0)return nu(lu($o(e),n[1]),n[0]);if(t===-1/0)return su(lu($o(e),n[1]),n[0]);if("fro"===t||"euclidean"===t)return iu(lu(ou(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}const cu=ta({norm_:function(e,t="euclidean",n=null,s=!1){const r=uu(e=Jr(e,"x","norm"),t,n);let a=r.shape;if(s){const t=w(n,e.shape);a=Zl(r.shape,t)}return tl(r,a)}});const hu=ta({euclideanNorm_:function(e,t=null,n=!1){return cu(e,"euclidean",t,n)}});const pu=ta({exp_:function(e){const t={x:Jr(e,"x","exp")};return Vr.runKernel(et,t)}});const du=ta({expandDims_:function(e,t=0){const n=Jr(e,"x","expandDims","string_or_numeric");u(t<=n.rank,(()=>"Axis must be <= rank of the tensor"));const s={input:n},r={dim:t};return Vr.runKernel(tt,s,r)}});const fu=ta({expm1_:function(e){const t={x:Jr(e,"x","expm1")};return Vr.runKernel(nt,t)}});const mu=ta({tile_:function(e,t){const n=Jr(e,"x","tile","string_or_numeric");u(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 Vr.runKernel(Xn,s,r)}});const gu=ta({eye_:function(e,t,n,s="float32"){null==t&&(t=e);const r=Za([e,t],s),a=e<=t?e:t;for(let e=0;e<a;++e)r.set(1,e,e);const i=tl(r.toTensor(),[e,t]);if(null==n)return i;if(1===n.length)return mu(du(i,0),[n[0],1,1]);if(2===n.length)return mu(du(du(i,0),0),[n[0],n[1],1,1]);if(3===n.length)return mu(du(du(du(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 yu=ta({floor_:function(e){const t={x:Jr(e,"x","floor","float32")};return Vr.runKernel(it,t)}});const bu=ta({gather_:function(e,t,n=0,s=0){const r={x:Jr(e,"x","gather"),indices:Jr(t,"indices","gather","int32")},a={axis:n,batchDims:s};return Vr.runKernel(ut,r,a)}});const xu=ta({greater_:function(e,t){let n=Jr(e,"a","greater","string_or_numeric"),s=Jr(t,"b","greater","string_or_numeric");[n,s]=_r(n,s),Li(n.shape,s.shape);const r={a:n,b:s};return Vr.runKernel(ht,r)}});const wu=ta({greaterEqual_:function(e,t){let n=Jr(e,"a","greaterEqual","string_or_numeric"),s=Jr(t,"b","greaterEqual","string_or_numeric");[n,s]=_r(n,s),Li(n.shape,s.shape);const r={a:n,b:s};return Vr.runKernel(pt,r)}});const vu=ta({isFinite_:function(e){const t={x:Jr(e,"x","isFinite")};return Vr.runKernel(gt,t)}});const ku=ta({isInf_:function(e){const t={x:Jr(e,"x","isInf")};return Vr.runKernel(yt,t)}});const Nu=ta({isNaN_:function(e){const t={x:Jr(e,"x","isNaN")};return Vr.runKernel(bt,t)}});const Iu=ta({leakyRelu_:function(e,t=.2){const n={x:Jr(e,"x","leakyRelu")},s={alpha:t};return Vr.runKernel(xt,n,s)}});const Su=ta({less_:function(e,t){let n=Jr(e,"a","less","string_or_numeric"),s=Jr(t,"b","less","string_or_numeric");[n,s]=_r(n,s),Li(n.shape,s.shape);const r={a:n,b:s};return Vr.runKernel(wt,r)}});const Tu=ta({lessEqual_:function(e,t){let n=Jr(e,"a","lessEqual","string_or_numeric"),s=Jr(t,"b","lessEqual","string_or_numeric");[n,s]=_r(n,s),Li(n.shape,s.shape);const r={a:n,b:s};return Vr.runKernel(vt,r)}});function Cu(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 Vr.runKernel(kt,{},s)}const $u=ta({localResponseNormalization_:function(e,t=5,n=1,s=1,r=.5){const a=Jr(e,"x","localResponseNormalization");u(4===a.rank||3===a.rank,(()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got\n rank ${a.rank}.`)),u(m(t),(()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`));let i=a,o=!1;3===a.rank&&(o=!0,i=tl(a,[1,a.shape[0],a.shape[1],a.shape[2]]));const l={x:i},c={depthRadius:t,bias:n,alpha:s,beta:r},h=Vr.runKernel(Et,l,c);return o?tl(h,[h.shape[1],h.shape[2],h.shape[3]]):h}});const Eu=ta({log_:function(e){const t={x:Jr(e,"x","log","float32")};return Vr.runKernel(Nt,t)}});const Au=ta({log1p_:function(e){const t={x:Jr(e,"x","log1p")};return Vr.runKernel(It,t)}});function Ru(e,t){u(D(e),(()=>"The f passed in variableGrads(f) must be a function")),u(null==t||Array.isArray(t)&&t.every((e=>e instanceof Nr)),(()=>"The varList passed in variableGrads(f, varList) must be an array of variables"));const n=null!=t;if(!n){t=[];for(const e in Vr.registeredVariables)t.push(Vr.registeredVariables[e])}const s=n?t.filter((e=>!e.trainable)):null,r=t.length;t=t.filter((e=>e.trainable)),u(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}=Vr.gradients(e,t,null,!0);u(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().")),u(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 _u(e){return Vr.customGrad(e)}function Fu(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 Du=ta({softplus_:function(e){const t={x:Jr(e,"x","softplus")};return Vr.runKernel(En,t)}});const Ou=ta({logSigmoid_:function(e){const t=Jr(e,"x","logSigmoid"),n=_u((e=>({value:Ai(Du(Ai(e))),gradFunc:t=>Co(t,al(Ai(e)))})));return n(t)}});const Mu=ta({sub_:function(e,t){let n=Jr(e,"a","sub"),s=Jr(t,"b","sub");[n,s]=_r(n,s);const r={a:n,b:s};return Vr.runKernel(jn,r)}});const Lu=ta({logSoftmax_:function(e,t=-1){const n=Jr(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=_u(((e,n)=>{const s=nu(e,t,!0),r=Mu(e,s),a=Mu(Ja(r,"float32"),Eu(lu(pu(r),t,!0)));n([a]);return{value:a,gradFunc:(e,n)=>{const[s]=n,r=pu(s);return Mu(e,Co(lu(e,t,!0),r))}}}));return s(n)}});const zu=ta({logSumExp_:function(e,t=null,n=!1){const s=Jr(e,"x","logSumExp"),r=w(t,s.shape),a=nu(s,r,!0),i=Mu(s,a),o=pu(i),l=lu(o,r),u=Eu(l),c=Io(tl(a,u.shape),u);if(n){const e=Zl(c.shape,r);return tl(c,e)}return c}});const Pu=ta({logicalAnd_:function(e,t){const n=Jr(e,"a","logicalAnd","bool"),s=Jr(t,"b","logicalAnd","bool");Li(n.shape,s.shape);const r={a:n,b:s};return Vr.runKernel(St,r)}});const Bu=ta({logicalNot_:function(e){const t={x:Jr(e,"x","logicalNot","bool")};return Vr.runKernel(Tt,t)}});const Wu=ta({logicalOr_:function(e,t){const n=Jr(e,"a","logicalOr","bool"),s=Jr(t,"b","logicalOr","bool");Li(n.shape,s.shape);const r={a:n,b:s};return Vr.runKernel(Ct,r)}});const Vu=ta({logicalXor_:function(e,t){const n=Jr(e,"a","logicalXor","bool"),s=Jr(t,"b","logicalXor","bool");return Li(n.shape,s.shape),Pu(Wu(e,t),Bu(Pu(e,t)))}}),Uu=2147483648;const Gu=ta({searchSorted_:function(e,t,n="left"){const s=Jr(e,"sortedSequence","searchSorted"),r=Jr(t,"values","searchSorted"),a=s.shape[s.shape.length-1],i=r.shape[r.shape.length-1],o=tl(s,[-1,a]),l=tl(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)>=Uu)throw new Error("values tensor size must less than 2147483648");if(o.shape[1]>=Uu)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 Vr.runKernel(vn,u,c)}});function Hu(e,t){return Gu(e,t,"left")}const ju=ta({maxPool_:function(e,t,n,s,r){const a=Jr(e,"x","maxPool");let i=a,o=!1;3===a.rank&&(o=!0,i=tl(a,[1,a.shape[0],a.shape[1],a.shape[2]])),u(4===i.rank,(()=>`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`)),u(Jo(n,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '1'`)),el("maxPool",s,r);const l={x:i},c={filterSize:t,strides:n,pad:s,dimRoundingMode:r},h=Vr.runKernel(Ft,l,c);return o?tl(h,[h.shape[1],h.shape[2],h.shape[3]]):h}});const qu=ta({maxPool3d_:function(e,t=[1,1,1],n,s,r,a="NDHWC"){const i=Jr(e,"x","maxPool3d");let o=i,l=!1;4===i.rank&&(l=!0,o=tl(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),u(5===o.rank,(()=>`Error in maxPool3d: x must be rank 5 but got rank ${o.rank}.`)),u("NDHWC"===a,(()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`)),el("maxPool3d",s,r);const c={x:o},h={filterSize:t,strides:n,pad:s,dimRoundingMode:r,dataFormat:a},p=Vr.runKernel(Ot,c,h);return l?tl(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}});const Ku=ta({maxPoolWithArgmax_:function(e,t,n,s,r=!1){const a={x:Jr(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:s,includeBatchInIndex:r},o=Vr.runKernel(Lt,a,i);return{result:o[0],indexes:o[1]}}});const Xu=ta({maximum_:function(e,t){let n=Jr(e,"a","maximum"),s=Jr(t,"b","maximum");[n,s]=_r(n,s),"bool"===n.dtype&&(n=Ja(n,"int32"),s=Ja(s,"int32")),Li(n.shape,s.shape);const r={a:n,b:s};return Vr.runKernel(_t,r)}});const Yu=ta({mean_:function(e,t=null,n=!1){const s={x:Jr(e,"x","mean")},r={axis:t,keepDims:n};return Vr.runKernel(zt,s,r)}});function Zu(e,t="float32"){if(V(e),"complex64"===t){const t=Zu(e,"float32"),n=Zu(e,"float32");return na(t,n)}const n=B(d(e),t);return Vr.makeTensor(n,e,t)}function Ju(e,t="float32"){if(V(e),"complex64"===t){const t=Ju(e,"float32"),n=Zu(e,"float32");return na(t,n)}const n=P(d(e),t);return Vr.makeTensor(n,e,t)}function Qu(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=Jr(e,"x","meshgrid",e instanceof vr?e.dtype:"float32");if(void 0===t)return[s];let r=Jr(t,"y","meshgrid",t instanceof vr?t.dtype:"float32");const a=d(s.shape),i=d(r.shape);return"xy"===n?(s=tl(s,[1,-1]),r=tl(r,[-1,1]),[bi(Ju([i,1],s.dtype),s),bi(r,Ju([1,a],r.dtype))]):(s=tl(s,[-1,1]),r=tl(r,[1,-1]),[bi(s,Ju([1,i],s.dtype)),bi(Ju([a,1],r.dtype),r)])}const ec=ta({minimum_:function(e,t){let n=Jr(e,"a","minimum"),s=Jr(t,"b","minimum");[n,s]=_r(n,s),"bool"===n.dtype&&(n=Ja(n,"int32"),s=Ja(s,"int32")),Li(n.shape,s.shape);const r={a:n,b:s};return Vr.runKernel(Bt,r)}});const tc=ta({mirrorPad_:function(e,t,n){u("reflect"===n||"symmetric"===n,(()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`));const s=Jr(e,"x","mirrorPad");if(0===s.rank)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");u(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++)u(2===t[e].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),u(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 Vr.runKernel(Wt,i,a)}});const nc=ta({mod_:function(e,t){let n=Jr(e,"a","mod"),s=Jr(t,"b","mod");[n,s]=_r(n,s);const r={a:n,b:s};return Vr.runKernel(Vt,r)}});const sc=ta({moments_:function(e,t=null,n=!1){const s=w(t,(e=Jr(e,"x","moments")).shape),r=Yu(e,s,n);let a=r.shape;n||(a=Zl(r.shape,s));const i=ou(Mu(Ja(e,"float32"),tl(r,a)));return{mean:r,variance:Yu(i,s,n)}}});const rc=ta({multiRNNCell_:function(e,t,n,s){const r=Jr(t,"data","multiRNNCell"),a=Qr(n,"c","multiRNNCell"),i=Qr(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 ac=ta({multinomial_:function(e,t,n,s=!1){const r=Jr(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?tl(r,[1,-1]):r},l={numSamples:t,seed:n,normalized:s},u=Vr.runKernel(Ut,o,l);return 1===i?tl(u,[u.size]):u}});const ic=ta({notEqual_:function(e,t){let n=Jr(e,"a","notEqual","string_or_numeric"),s=Jr(t,"b","notEqual","string_or_numeric");[n,s]=_r(n,s),Li(n.shape,s.shape);const r={a:n,b:s};return Vr.runKernel(jt,r)}});const oc=ta({onesLike_:function(e){const t={x:Jr(e,"x","onesLike")};return Vr.runKernel(Yt,t)}});const lc=ta({outerProduct_:function(e,t){const n=Jr(e,"v1","outerProduct"),s=Jr(t,"v2","outerProduct");u(1===n.rank&&1===s.rank,(()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${s.rank}.`));const r=tl(n,[-1,1]),a=tl(s,[1,-1]);return bi(r,a)}});const uc=ta({pad_:function(e,t,n=0){const s=Jr(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 Vr.runKernel(Qt,a,r)}});const cc=ta({pad1d_:function(e,t,n=0){return u(2===t.length,(()=>"Invalid number of paddings. Must be length of 2.")),uc(e,[t],n)}});const hc=ta({pad2d_:function(e,t,n=0){return u(2===t.length&&2===t[0].length&&2===t[1].length,(()=>"Invalid number of paddings. Must be length of 2 each.")),uc(e,t,n)}});const pc=ta({pad3d_:function(e,t,n=0){return u(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.")),uc(e,t,n)}});const dc=ta({pad4d_:function(e,t,n=0){return u(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.")),uc(e,t,n)}});const fc=ta({spaceToBatchND_:function(e,t,n){const s=Jr(e,"x","spaceToBatchND");u(s.rank>=1+t.length,(()=>`input rank ${s.rank} should be > than [blockShape] ${t.length}`)),u(n.length===t.length,(()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`)),u(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 Vr.runKernel(_n,r,a)}});const mc=ta({pool_:function(e,t,n,s,r,a,i){null==r&&(r=[1,1]),null==a&&(a=1),0===s&&(s="valid");const o=Jr(e,"x","maxPool");let l=o,c=!1;3===o.rank&&(c=!0,l=tl(o,[1,o.shape[0],o.shape[1],o.shape[2]])),u(Jo(a,r),(()=>`Error in pool: Either strides or dilations must be 1. Got strides ${a} and dilations '${r}'`));const h=Vo(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:fc(l,p,m),x=("avg"===n?()=>nl(b,t,a,y,i):()=>ju(b,t,a,y,i))(),w=f?x:ul(x,p,g);return c?tl(w,[w.shape[1],w.shape[2],w.shape[3]]):w}});const gc=ta({prelu_:function(e,t){const n={x:Jr(e,"x","prelu"),alpha:Jr(t,"alpha","prelu")};return Vr.runKernel(tn,n)}});const yc=ta({prod_:function(e,t=null,n=!1){let s=Jr(e,"x","prod");"bool"===s.dtype&&(s=Ja(s,"int32"));const r={x:s},a={axis:t,keepDims:n};return Vr.runKernel(nn,r,a)}});const bc=ta({raggedGather_:function(e,t,n,s){const r={paramsNestedSplits:e.map(((e,t)=>Jr(e,`tensors${t}`,"raggedGather","int32"))),paramsDenseValues:Jr(t,"paramsDenseValues","raggedGather"),indices:Jr(n,"indices","raggedGather","int32")},a={outputRaggedRank:s},i=Vr.runKernel(sn,r,a);return{outputNestedSplits:i.slice(0,i.length-1),outputDenseValues:i[i.length-1]}}});const xc=ta({raggedRange_:function(e,t,n){const s=Jr(e,"starts","raggedRange"),r={starts:s,limits:Jr(t,"limits","raggedRange",s.dtype),deltas:Jr(n,"deltas","raggedRange",s.dtype)},a=Vr.runKernel(rn,r);return{rtNestedSplits:a[0],rtDenseValues:a[1]}}});const wc=ta({raggedTensorToTensor_:function(e,t,n,s,r){const a=Jr(e,"shape","raggedTensorToTensor","int32"),i=Jr(t,"values","raggedTensorToTensor"),o={shape:a,values:i,defaultValue:Jr(n,"defaultValue","raggedTensorToTensor",i.dtype),rowPartitionTensors:s.map(((e,t)=>Jr(e,`tensors${t}`,"raggedTensorToTensor","int32")))},l={rowPartitionTypes:r};return Vr.runKernel(an,o,l)}});const vc=ta({rand_:function(e,t,n){V(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 Vr.makeTensor(r,e,n)}});var kc="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Nc(e,t){return e(t={exports:{}},t.exports),t.exports}var Ic=Nc((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)})),Sc=Nc((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)})),Tc=Nc((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)})),Cc=Nc((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)})),$c=Nc((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)})),Ec=Nc((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)})),Ac=Nc((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:kc,[],Math)}));Ac.alea=Ic,Ac.xor128=Sc,Ac.xorwow=Tc,Ac.xorshift7=Cc,Ac.xor4096=$c,Ac.tychei=Ec;var Rc=Ac.alea;class _c{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=Rc(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 Fc{constructor(e,t,n,s){this.alpha=e,this.beta=1/t,this.dtype=n;const r=s||Math.random();this.randu=Rc(r.toString()),this.randn=new _c(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 Dc{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=Rc(s)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}}const Oc=ta({randomGamma_:function(e,t,n=1,s="float32",r){if(V(e),null==n&&(n=1),null==s&&(s="float32"),"float32"!==s&&"int32"!==s)throw new Error(`Unsupported data type ${s}`);const a=new Fc(t,n,s,r),i=Za(e,s);for(let e=0;e<i.values.length;e++)i.values[e]=a.nextValue();return i.toTensor()}});const Mc=ta({randomNormal_:function(e,t=0,n=1,s,r){if(V(e),null!=s&&"bool"===s)throw new Error(`Unsupported data type ${s}`);const a=new _c(t,n,s,!1,r),i=Za(e,s);for(let e=0;e<i.values.length;e++)i.values[e]=a.nextValue();return i.toTensor()}});const Lc=ta({randomStandardNormal_:function(e,t,n){if(null!=t&&"bool"===t)throw new Error(`Unsupported data type ${t}`);return Mc(e,0,1,t,n)}});const zc=ta({randomUniform_:function(e,t=0,n=1,s="float32",r){V(e);const a=Za(e,s),i=new Dc(t,n,null,r);for(let e=0;e<a.values.length;e++)a.values[e]=i.nextValue();return a.toTensor()}});function Pc(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 Vr.runKernel(on,{},r)}const Bc=ta({reciprocal_:function(e){const t={x:Jr(e,"x","reciprocal")};return Vr.runKernel(un,t)}});const Wc=ta({relu_:function(e){const t={x:Jr(e,"x","relu")};return Vr.runKernel(cn,t)}});const Vc=ta({relu6_:function(e){const t={x:Jr(e,"x","relu6")};return Vr.runKernel(gn,t)}});const Uc=ta({reverse_:function(e,t){const n={x:Jr(e,"x","reverse")},s={dims:t};return Vr.runKernel(yn,n,s)}});const Gc=ta({reverse1d_:function(e){const t=Jr(e,"x","reverse");return u(1===t.rank,(()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`)),Uc(t,0)}});const Hc=ta({reverse2d_:function(e,t){const n=Jr(e,"x","reverse");return u(2===n.rank,(()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`)),Uc(n,t)}});const jc=ta({reverse3d_:function(e,t){const n=Jr(e,"x","reverse");return u(3===n.rank,(()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`)),Uc(n,t)}});const qc=ta({reverse4d_:function(e,t){const n=Jr(e,"x","reverse");return u(4===n.rank,(()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`)),Uc(n,t)}});const Kc=ta({round_:function(e){const t={x:Jr(e,"x","round")};return Vr.runKernel(bn,t)}});const Xc=ta({rsqrt_:function(e){const t={x:Jr(e,"x","rsqrt","float32")};return Vr.runKernel(xn,t)}});const Yc=ta({selu_:function(e){const t={x:Jr(e,"x","selu")};return Vr.runKernel(Nn,t)}});const Zc=ta({separableConv2d_:function(e,t,n,s,r,a=[1,1],i="NHWC"){const o=Jr(e,"x","separableConv2d"),l=Jr(t,"depthwiseFilter","separableConv2d"),c=Jr(n,"pointwiseFilter","separableConv2d");let h=o,p=!1;if(3===o.rank&&(p=!0,h=tl(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");u(4===h.rank,(()=>`Error in separableConv2d: input must be rank 4, but got rank ${h.rank}.`)),u(4===l.rank,(()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`)),u(4===c.rank,(()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`)),u(1===c.shape[0],(()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${c.shape[0]}.`)),u(1===c.shape[1],(()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${c.shape[1]}.`));const d=l.shape[2],f=l.shape[3];u(c.shape[2]===d*f,(()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${d*f}, but got ${c.shape[2]}.`));const m=Ll(h,l,s,r,i,a),g=Il(m,c,1,"valid",i);return p?tl(g,[g.shape[1],g.shape[2],g.shape[3]]):g}});const Jc=async function(e,t){const n=Jr(e,"x","setdiff1d"),s=Jr(t,"y","setdiff1d");u(n.dtype===s.dtype,(()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${s.dtype}).`)),u(1===n.rank,(()=>`x should be 1D tensor, but got x (${n.shape}).`)),u(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 yr([o],n.dtype),c=new yr([o],"int32");for(let e=0,t=0;e<r.length;e++)i.has(r[e])||(l.values[t]=r[e],c.values[t]=e,t++);return[l.toTensor(),c.toTensor()]};const Qc=ta({sign_:function(e){const t={x:Jr(e,"x","sign")};return Vr.runKernel(Cn,t)}});const eh=ta({sin_:function(e){const t={x:Jr(e,"x","sin","float32")};return Vr.runKernel(Sn,t)}});const th=ta({sinh_:function(e){const t={x:Jr(e,"x","sinh")};return Vr.runKernel(Tn,t)}});const nh=ta({slice1d_:function(e,t,n){const s=Jr(e,"x","slice1d");return u(1===s.rank,(()=>`slice1d expects a rank-1 tensor, but got a rank-${s.rank} tensor`)),il(s,[t],[n])}});const sh=ta({slice2d_:function(e,t,n){const s=Jr(e,"x","slice2d");return u(2===s.rank,(()=>`slice2d expects a rank-2 tensor, but got a rank-${s.rank} tensor`)),il(s,t,n)}});const rh=ta({slice3d_:function(e,t,n){const s=Jr(e,"x","slice3d");return u(3===s.rank,(()=>`slice3d expects a rank-3 tensor, but got a rank-${s.rank} tensor`)),il(s,t,n)}});const ah=ta({slice4d_:function(e,t,n){const s=Jr(e,"x","slice4d");return u(4===s.rank,(()=>`slice4d expects a rank-4 tensor, but got a rank-${s.rank} tensor`)),il(s,t,n)}});const ih=ta({softmax_:function(e,t=-1){const n=Jr(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 Vr.runKernel(Dn,s,r)}});const oh=ta({fft_:function(e){u("complex64"===e.dtype,(()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`));const t={input:e};return Vr.runKernel(st,t)}});const lh=ta({ifft_:function(e){u("complex64"===e.dtype,(()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`));const t={input:e};return Vr.runKernel(ft,t)}});const uh=ta({irfft_:function(e){const t=e.shape[e.shape.length-1],n=e.size/t;let s;if(t<=2){const r=tl(e,[n,t]);s=lh(r)}else{const r=[n,2*(t-1)],a=tl(Ri(e),[n,t]),i=tl(Ei(e),[n,t]),o=Uc(il(a,[0,1],[n,t-2]),1),l=Co(Uc(il(i,[0,1],[n,t-2]),1),au(-1)),u=rl([a,o],1),c=rl([i,l],1),h=tl(na(u,c),[r[0],r[1]]);s=lh(h)}if(s=Ri(s),3===e.rank&&0!==e.shape[0]){const t=s,n=e.shape[0];s=tl(s,[n,s.shape[0]/n,s.shape[1]]),t.dispose()}return s}});const ch=ta({split_:function(e,t,n=0){const s={x:Jr(e,"x","split")},r={numOrSizeSplits:t,axis:n};return Vr.runKernel(Fn,s,r)}});const hh=ta({rfft_:function(e,t){u("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=il(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=rl([e,Zu(s)],e.shape.length-1),n=t}else r=e;const a=Vl(r),i=tl(na(r,a),[s,n]),o=oh(i),l=Math.floor(n/2)+1,c=Ri(o),h=Ei(o),p=ch(c,[l,n-l],c.shape.length-1),d=ch(h,[l,n-l],h.shape.length-1),f=r.shape.slice();return f[r.shape.length-1]=l,tl(na(p[0],d[0]),f)}});const ph=ta({squaredDifference_:function(e,t){let n=Jr(e,"a","squaredDifference"),s=Jr(t,"b","squaredDifference");[n,s]=_r(n,s),Li(n.shape,s.shape);const r={a:n,b:s};return Vr.runKernel(Bn,r,{})}});const dh=ta({squeeze_:function(e,t){const n=Jr(e,"x","squeeze","string_or_numeric");return tl(n,v(n.shape,t).newShape)}});const fh=ta({stack_:function(e,t=0){const n=Qr(e,"tensors","stack","string_or_numeric");u(n.length>=1,(()=>"Pass at least one tensor to tf.stack")),n.length>0&&u(t<=n[0].rank,(()=>"Axis must be <= rank of the tensor"));const s=n,r={axis:t};return Vr.runKernel(Jt,s,r)}});const mh=ta({step_:function(e,t=0){const n={x:Jr(e,"x","step")},s={alpha:t};return Vr.runKernel(ss,n,s)}});const gh=ta({stridedSlice_:function(e,t,n,s,r=0,a=0,i=0,o=0,l=0){const u={x:Jr(e,"x","stridedSlice","string_or_numeric")},c={begin:t,end:n,strides:s,beginMask:r,endMask:a,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};return Vr.runKernel(Vn,u,c)}});const yh=ta({tan_:function(e){const t={x:Jr(e,"x","tan","float32")};return Vr.runKernel(qn,t)}});function bh(e,t){h(e);const n=Xr(e,t);if(1!==n.length)throw new Error("tensor1d() requires values to be a flat/TypedArray");return sa(e,null,n,t)}function xh(e,t,n){if(h(e),null!=t&&2!==t.length)throw new Error("tensor2d() requires shape to have two numbers");const s=Xr(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 sa(e,t,s,n)}function wh(e,t,n){if(h(e),null!=t&&4!==t.length)throw new Error("tensor4d() requires shape to have four numbers");const s=Xr(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 sa(e,t,s,n)}function vh(e,t,n){if(h(e),null!=t&&5!==t.length)throw new Error("tensor5d() requires shape to have five numbers");const s=Xr(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 sa(e,t,s,n)}function kh(e,t,n){if(h(e),null!=t&&6!==t.length)throw new Error("tensor6d() requires shape to have six numbers");const s=Xr(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 sa(e,t=t||s,s,n)}const Nh=ta({topk_:function(e,t=1,n=!0){const s=Jr(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]=Vr.runKernel(Yn,a,i);return{values:o,indices:l}}});const Ih=ta({truncatedNormal_:function(e,t=0,n=1,s,r){if(V(e),null!=s&&"bool"===s)throw new Error("Unsupported data type $ { dtype }");const a=new _c(t,n,s,!0,r),i=Za(e,s);for(let e=0;e<i.values.length;e++)i.values[e]=a.nextValue();return i.toTensor()}});const Sh=ta({unique_:function(e,t=0){const n=Jr(e,"x","unique","string_or_numeric");u(n.rank>0,(()=>"The input tensor must be at least 1D"));const s={x:n},r={axis:t},[a,i]=Vr.runKernel(Qn,s,r);return{values:a,indices:i}}});const Th=ta({unsortedSegmentSum_:function(e,t,n){const s=Jr(e,"x","unsortedSegmentSum"),r=Jr(t,"segmentIds","unsortedSegmentSum","int32");u(m(n),(()=>"numSegments must be of dtype int"));const a={x:s,segmentIds:r},i={numSegments:n};return Vr.runKernel(ts,a,i)}});const Ch=ta({unstack_:function(e,t=0){const n=Jr(e,"x","unstack","string_or_numeric");u(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 Vr.runKernel(es,s,r)}});function $h(e,t){return Gu(e,t,"right")}function Eh(e,t=!0,n,s){return Vr.makeVariable(e,t,n,s)}function Ah(e,t){const n=[];for(let e=0;e<t.length;e++)t[e]&&n.push(e);const s=Za(e,"int32"),r=Za([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 Rh=async function(e){const t=Jr(e,"condition","whereAsync","bool"),n=await t.data(),s=Ah(t.shape,n);return e!==t&&t.dispose(),s};const _h=async function(e,t,n){const s=Jr(e,"tensor","boolMask"),r=Jr(t,"mask","boolMask","bool"),a=null==n?0:n,i=r.rank,o=s.shape;u(i>0,(()=>"mask cannot be scalar")),c(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 h=o.slice(0,a).concat([l],o.slice(a+i)),p=tl(s,h),d=tl(r,[-1]),f=await Rh(d),m=dh(f,[1]),g=bu(p,m,a);return e!==s&&s.dispose(),t!==r&&r.dispose(),m.dispose(),p.dispose(),d.dispose(),f.dispose(),g};const Fh=ta({movingAverage_:function(e,t,n,s,r=!0){const a=Jr(e,"v","movingAverage"),i=Jr(t,"x","movingAverage"),o=Jr(n,"decay","movingAverage");Fr(a,i),u(f(a.shape,i.shape),(()=>"Shape mismatch in v and x"));const l=au(1),c=Mu(l,o);let h=Co(Mu(i,a),c);if(r){u(null!=s,(()=>"When using zeroDebias: true, step is required."));const e=Jr(s,"step","movingAverage");h=To(h,Mu(l,ru(o,e)))}return Io(a,h)}});const Dh=ta({scatterND_:function(e,t,n){V(n);const s=Jr(e,"indices","scatterND","int32"),r=Jr(t,"updates","scatterND");Ki(r,s,n);const a={indices:s,updates:r},i={shape:n};return Vr.runKernel(wn,a,i)}});const Oh=ta({sparseToDense_:function(e,t,n,s=0){V(n);const r=Jr(e,"sparseIndices","sparseToDense","int32"),a=Jr(t,"sparseValues","sparseToDense","string_or_numeric"),i=Jr(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 Vr.runKernel(Pn,o,l)}});const Mh=ta({gatherND_:function(e,t){const n=Jr(t,"indices","gatherND","int32"),s={params:Jr(e,"x","gatherND","string_or_numeric"),indices:n};return Vr.runKernel(ct,s)}});const Lh=ta({dropout_:function(e,t,n,s){const r=Jr(e,"x","dropout");if(u("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.`)),u(t>=0&&t<1,(()=>`rate must be a float in the range [0, 1), but got ${t}.`)),0===t)return e instanceof vr?r.clone():r;const a=function(e,t){if(null==t)return e.shape.slice();if(f(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=To(yu(Io(zc(a,0,1,"float32",s),i)),i);return Co(r,o)}});function zh(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function Ph(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 bh(r,"float32")}const Bh=async function(e,t,n=1){const s=Jr(e,"predictions","inTopK"),r=Jr(t,"targets","inTopK");u(s.rank>1,(()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${s.rank}`)),u(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}`)),c(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];u(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,h]=[i.length/a,a],p=k("bool",l);for(let e=0;e<l;e++){const t=e*h,s=i.subarray(t,t+h),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(),ra(p,r.shape,"bool")};const Wh=ta({conv2DBackpropFilter_:function(e,t,n,s,r,a="NHWC",i){let o=e;3===e.rank&&(o=tl(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;3===l.rank&&(l=tl(t,[1,t.shape[0],t.shape[1],t.shape[2]])),u(4===o.rank,(()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${o.shape}.`)),u(4===l.rank,(()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`)),u(4===n.length,(()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`));const c="NHWC"===a?o.shape[3]:o.shape[1],h="NHWC"===a?l.shape[3]:l.shape[1];u(c===n[2],(()=>`Error in conv2dDerFilter: depth of input ${c}) must match input depth in filter (${n[2]}.`)),u(h===n[3],(()=>`Error in conv2dDerFilter: depth of dy (${h}) must match output depth for filter (${n[3]}).`)),el("conv2dDerFilter",r,i);const p={x:o,dy:l},d={strides:s,pad:r,dataFormat:a,dimRoundingMode:i,filterShape:n};return Vr.runKernel(Ee,p,d)}});function Vh(e,t,n){if(null==n||"linear"===n)return e;if("relu"===n)return Co(e,mh(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function Uh(e,t){let n=t;const s=Mi(e.shape,t.shape);return s.length>0&&(n=lu(n,s)),tl(n,e.shape)}function Gh(e,t,n,s){if("linear"===t)return e;if("relu"===t)return Wc(e);if("elu"===t)return jl(e);if("relu6"===t)return Vc(e);if("prelu"===t)return gc(e,n);if("leakyrelu"===t)return Iu(e,s);if("sigmoid"===t)return al(e);throw new Error(`Unknown fused activation ${t}.`)}const Hh=(e,t)=>!(e>0)||"linear"===t;const jh=ta({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:c,leakyreluAlpha:h}){if(l=l||"linear",!1===Hh(Vr.state.gradientDepth,l)){u("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=Il(e,t,n,s,r,a,i);return null!=o&&(p=Io(p,o)),Gh(p,l,c,h)}const p=Jr(e,"x","conv2d","float32"),d=Jr(t,"filter","conv2d","float32");let f=p,m=!1;3===p.rank&&(m=!0,f=tl(p,[1,p.shape[0],p.shape[1],p.shape[2]])),u(4===f.rank,(()=>`Error in fused conv2d: input must be rank 4, but got rank ${f.rank}.`)),u(4===d.rank,(()=>`Error in fused conv2d: filter must be rank 4, but got rank ${d.rank}.`)),el("fused conv2d",s,i);const g="NHWC"===r?f.shape[3]:f.shape[1];u(d.shape[2]===g,(()=>`Error in conv2d: depth of input (${g}) must match input depth for filter ${d.shape[2]}.`)),u(Jo(n,a),(()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`));const y=Go(f.shape,d.shape,n,a,s,i);let b,x;if(null!=o&&(b=Jr(o,"bias","fused conv2d"),[b]=_r(b,p),"NHWC"===r?Li(y.outShape,b.shape):(u(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}.`)),u(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!=c){const e=c.shape;if(u(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)u(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{Li(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=Jr(c,"prelu weights","fused conv2d")}const w=(e,t)=>{u("NHWC"===r,(()=>`Error in gradient of fused conv2D: got dataFormat of ${r} but only NHWC is currently supported.`));const[i,o,c,h]=t,p=Vh(e,c,l);u(Zo(a),(()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`));const d=[Tl(o.shape,p,i,n,s),Wh(o,p,i.shape,n,s)];if(null!=h){const e=Uh(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=_u(((e,t,n)=>{let s=Vr.runKernel(os,v,k);return n([t,e,s]),m&&(s=tl(s,[s.shape[1],s.shape[2],s.shape[3]])),{value:s,gradFunc:w}}));return e(f,d)}{const e=_u(((e,t,n,s)=>{let r=Vr.runKernel(os,v,k);return s([t,e,r,n]),m&&(r=tl(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:w}}));return e(f,d,b)}}});const qh=ta({depthwiseConv2dNativeBackpropFilter_:function(e,t,n,s,r,a=[1,1],i){let o=e;3===e.rank&&(o=tl(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;3===l.rank&&(l=tl(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 Vr.runKernel(Ve,u,c)}});const Kh=ta({depthwiseConv2dNativeBackpropInput_:function(e,t,n,s,r,a=[1,1],i){let o=t,l=!1;3===t.rank&&(l=!0,o=tl(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=Vr.runKernel(Ue,u,c);return l?tl(h,[h.shape[1],h.shape[2],h.shape[3]]):h}});const Xh=ta({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:c,leakyreluAlpha:h}){if(!1===Hh(Vr.state.gradientDepth,l)){let u=Ll(e,t,n,s,r,a,i);return null!=o&&(u=Io(u,o)),Gh(u,l,c,h)}const p=Jr(e,"x","depthwiseConv2d","float32"),d=Jr(t,"filter","depthwiseConv2d","float32");let f=p,m=!1;3===p.rank&&(m=!0,f=tl(p,[1,p.shape[0],p.shape[1],p.shape[2]])),u(4===f.rank,(()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${f.rank}.`)),u(4===d.rank,(()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${d.rank}.`)),u(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]),u(Jo(n,a),(()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`)),el("fused depthwiseConv2d",s,i);const g=Go(f.shape,d.shape,n,a,s,i,!0);let y,b;null!=o&&(y=Jr(o,"bias","fused conv2d"),[y]=_r(y,p),Li(g.outShape,y.shape)),null!=c&&(b=Jr(c,"prelu weights","fused depthwiseConv2d"));const x=(e,t)=>{u(Zo(a),(()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`));const[r,o,c,h]=t,p=Vh(e,c,l),d=Kh(o.shape,p,r,n,s,a,i),f=qh(o,p,r.shape,n,s,a,i);if(null!=h){return[d,f,Uh(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=_u(((e,t,n)=>{let s=Vr.runKernel(ls,w,v);return n([t,e,s]),m&&(s=tl(s,[s.shape[1],s.shape[2],s.shape[3]])),{value:s,gradFunc:x}}));return e(f,d)}{const e=_u(((e,t,n,s)=>{let r=Vr.runKernel(ls,w,v);return s([t,e,r,n]),m&&(r=tl(r,[r.shape[1],r.shape[2],r.shape[3]])),{value:r,gradFunc:x}}));return e(f,d,y)}}});const Yh=ta({fusedMatMul_:function({a:e,b:t,transposeA:n=!1,transposeB:s=!1,bias:r,activation:a="linear",preluActivationWeights:i,leakyreluAlpha:o=.2}){if(!1===Hh(Vr.state.gradientDepth,a)){let l=bi(e,t,n,s);return null!=r&&(l=Io(l,r)),Gh(l,a,i,o)}let l=Jr(e,"a","fused matMul"),c=Jr(t,"b","fused matMul");[l,c]=_r(l,c);const h=n?l.shape[l.rank-2]:l.shape[l.rank-1],p=s?c.shape[c.rank-1]:c.shape[c.rank-2],f=n?l.shape[l.rank-1]:l.shape[l.rank-2],m=s?c.shape[c.rank-2]:c.shape[c.rank-1],g=l.shape.slice(0,-2),y=c.shape.slice(0,-2),b=d(g),x=d(y);u(h===p,(()=>`Error in fused matMul: inner shapes (${h}) and (${p}) of Tensors with shapes ${l.shape} and ${c.shape} and transposeA=${n} and transposeB=${s} must match.`));const w=Li(l.shape.slice(0,-2),c.shape.slice(0,-2)).concat([f,m]),v=tl(l,n?[b,h,f]:[b,f,h]),k=tl(c,s?[x,m,p]:[x,p,m]);let N,I;null!=r&&(N=Jr(r,"bias","fused matMul"),[N]=_r(N,l),Li(w,N.shape)),null!=i&&(I=Jr(i,"prelu weights","fused matMul"));const S=(e,t)=>{const[i,o,l,u]=t,c=Vh(tl(e,l.shape),l,a);let h,p;if(n||s?!n&&s?(h=bi(c,o,!1,!1),p=bi(c,i,!0,!1)):n&&!s?(h=bi(o,c,!1,!0),p=bi(i,c,!1,!1)):(h=bi(o,c,!0,!0),p=bi(c,i,!0,!0)):(h=bi(c,o,!1,!0),p=bi(i,c,!0,!1)),null!=r){return[h,p,Uh(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=_u(((e,t,n)=>{const s=Vr.runKernel(is,T,C);return n([e,t,s]),{value:tl(s,w),gradFunc:S}}));return e(v,k)}{const e=_u(((e,t,n,s)=>{const r=Vr.runKernel(is,T,C);return s([e,t,r,n]),{value:tl(r,w),gradFunc:S}}));return e(v,k,N)}}});var Zh=Object.freeze({__proto__:null,conv2d:jh,depthwiseConv2d:Xh,matMul:Yh});const Jh=ta({hammingWindow_:function(e){return Ph(e,.54,.46)}});const Qh=ta({hannWindow_:function(e){return Ph(e,.5,.5)}});const ep=ta({frame_:function(e,t,n,s=!1,r=0){let a=0;const i=[];for(;a+t<=e.size;)i.push(il(e,a,t)),a+=n;if(s)for(;a<e.size;){const s=a+t-e.size,o=rl([il(e,a,t-s),bl([s],r)]);i.push(o),a+=n}return 0===i.length?xh([],[0,t]):tl(rl(i),[i.length,t])}});const tp=ta({stft_:function(e,t,n,s,r=Qh){null==s&&(s=zh(t));const a=ep(e,t,n),i=Co(a,r(t));return hh(i,s)}});const np=ta({cropAndResize_:function(e,t,n,s,r="bilinear",a=0){const i=Jr(e,"image","cropAndResize"),o=Jr(t,"boxes","cropAndResize","float32"),l=Jr(n,"boxInd","cropAndResize","int32"),c=o.shape[0];u(4===i.rank,(()=>`Error in cropAndResize: image must be rank 4,but got rank ${i.rank}.`)),u(2===o.rank&&4===o.shape[1],(()=>`Error in cropAndResize: boxes must be have size [${c},4] but had shape ${o.shape}.`)),u(1===l.rank&&l.shape[0]===c,(()=>`Error in cropAndResize: boxInd must be have size [${c}] but had shape ${o.shape}.`)),u(2===s.length,(()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${s.length}.`)),u(s[0]>=1&&s[1]>=1,(()=>`cropSize must be atleast [1,1], but was ${s}`)),u("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 Vr.runKernel(ze,h,p)}});const sp=ta({flipLeftRight_:function(e){const t=Jr(e,"image","flipLeftRight","float32");u(4===t.rank,(()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`));const n={image:t};return Vr.runKernel(at,n,{})}});const rp=ta({grayscaleToRGB_:function(e){const t=Jr(e,"image","grayscaleToRGB"),n=t.rank-1,s=t.shape[n];u(t.rank>=2,(()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`)),u(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,mu(t,r)}});const ap=ta({rotateWithOffset_:function(e,t,n=0,s=.5){const r=Jr(e,"image","rotateWithOffset","float32");u(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 Vr.runKernel(as,a,i)}});function ip(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),u(0<=s&&s<=1,(()=>`iouThreshold must be in [0, 1], but was '${s}'`)),u(2===e.rank,(()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`)),u(4===e.shape[1],(()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`)),u(1===t.rank,(()=>"scores must be a 1D tensor")),u(t.shape[0]===i,(()=>`scores has incompatible shape with boxes. Expected ${i}, but was ${t.shape[0]}`)),u(0<=a&&a<=1,(()=>`softNmsSigma must be in [0, 1], but was '${a}'`)),{maxOutputSize:n,iouThreshold:s,scoreThreshold:r,softNmsSigma:a}}const op=ta({nonMaxSuppression_:function(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY){const a=Jr(e,"boxes","nonMaxSuppression","float32"),i=Jr(t,"scores","nonMaxSuppression","float32"),o=ip(a,i,n,s,r),l={maxOutputSize:n=o.maxOutputSize,iouThreshold:s=o.iouThreshold,scoreThreshold:r=o.scoreThreshold};return Vr.runKernel(qt,{boxes:a,scores:i},l)}});function lp(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||up)}(e,t,n),r=s<0?-(s+1):s;e.splice(r,0,t)}function up(e,t){return e>t?1:e<t?-1:0}function cp(e,t,n,s,r){return dp(e,t,n,s,r,0)}function hp(e,t,n,s,r,a){return dp(e,t,n,s,r,0,!1,a,!0)}function pp(e,t,n,s,r,a){return dp(e,t,n,s,r,a,!0)}function dp(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(gp);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=fp(e,a,h[n]);if(i>=s){o=!0;break}if(t.score=t.score*mp(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&&lp(u,t,gp))}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 fp(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 mp(e,t,n){const s=Math.exp(t*n*n);return n<=e?s:0}function gp(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}const yp=async function(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY){const a=Jr(e,"boxes","nonMaxSuppressionAsync"),i=Jr(t,"scores","nonMaxSuppressionAsync"),o=ip(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}=cp(u,c,n,s,r);return a!==e&&a.dispose(),i!==t&&i.dispose(),bh(h,"int32")};const bp=ta({nonMaxSuppressionWithScore_:function(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=0){const i=Jr(e,"boxes","nonMaxSuppression"),o=Jr(t,"scores","nonMaxSuppression"),l=ip(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=Vr.runKernel(Xt,u,c);return{selectedIndices:h[0],selectedScores:h[1]}}});const xp=async function(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=0){const i=Jr(e,"boxes","nonMaxSuppressionAsync"),o=Jr(t,"scores","nonMaxSuppressionAsync"),l=ip(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}=pp(c,h,n,s,r,a);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:bh(p,"int32"),selectedScores:bh(d)}};const wp=ta({nonMaxSuppressionPadded_:function(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=!1){const i=Jr(e,"boxes","nonMaxSuppression"),o=Jr(t,"scores","nonMaxSuppression"),l=ip(i,o,n,s,r,null),u={boxes:i,scores:o},c={maxOutputSize:l.maxOutputSize,iouThreshold:l.iouThreshold,scoreThreshold:l.scoreThreshold,padToMaxOutputSize:a},h=Vr.runKernel(Kt,u,c);return{selectedIndices:h[0],validOutputs:h[1]}}});const vp=async function(e,t,n,s=.5,r=Number.NEGATIVE_INFINITY,a=!1){const i=Jr(e,"boxes","nonMaxSuppressionAsync"),o=Jr(t,"scores","nonMaxSuppressionAsync"),l=ip(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}=hp(p,d,u,c,h,a);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:bh(f,"int32"),validOutputs:au(m,"int32")}};const kp=ta({resizeBilinear_:function(e,t,n=!1,s=!1){const r=Jr(e,"images","resizeBilinear");u(3===r.rank||4===r.rank,(()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${r.rank}.`)),u(2===t.length,(()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`)),u(!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=tl(r,[1,r.shape[0],r.shape[1],r.shape[2]]));const[]=t,o={images:a},l={alignCorners:n,halfPixelCenters:s,size:t},c=Vr.runKernel(fn,o,l);return i?tl(c,[c.shape[1],c.shape[2],c.shape[3]]):c}});const Np=ta({resizeNearestNeighbor_:function(e,t,n=!1,s=!1){const r=Jr(e,"images","resizeNearestNeighbor");u(3===r.rank||4===r.rank,(()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${r.rank}.`)),u(2===t.length,(()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`)),u("float32"===r.dtype||"int32"===r.dtype,(()=>"`images` must have `int32` or `float32` as dtype")),u(!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=tl(r,[1,r.shape[0],r.shape[1],r.shape[2]]));const[]=t,o={images:a},l={alignCorners:n,halfPixelCenters:s,size:t},c=Vr.runKernel(pn,o,l);return i?tl(c,[c.shape[1],c.shape[2],c.shape[3]]):c}});const Ip=ta({threshold_:function(e,t="binary",n=!1,s=.5){const r=Jr(e,"image","threshold"),a=r.shape[0]*r.shape[1];let i,o,l,c,h=Co(bh([s]),255);if(u(3===r.rank,(()=>`Error in threshold: image must be rank 3,but got rank ${r.rank}.`)),u(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]}.`)),u("int32"===r.dtype||"float32"===r.dtype,(()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${r.dtype}.`)),u("otsu"===t||"binary"===t,(()=>`Method must be binary or otsu, but was ${t}`)),3===r.shape[2]){[i,o,l]=ch(r,[1,1,1],-1);const e=Co(i,.2989),t=Co(o,.587),n=Co(l,.114);c=Io(Io(e,t),n)}else c=e;if("otsu"===t){h=function(e,t){let n,s,r,a,i,o,l=bh([-1]),u=bh([0]),c=bh([0]);for(let h=0;h<e.size-1;h++){n=il(e,0,h+1),s=il(e,h+1),i=To(lu(n),t),o=To(lu(s),t);const p=lu(Co(n,Pc(0,n.size)));r=To(p,lu(n));const d=bl(s.shape,n.size),f=Io(Pc(0,s.size),d),m=Co(s,f);a=To(lu(m),lu(s));const g=Mu(r,a),y=Mu(r,a),b=Co(i,o);c=Co(Co(b,g),y);const x=xu(c,u);u=Wl(x,c,u),l=Wl(x,bh([h]),l)}return l}(fl(Ja(Kc(c),"int32"),ra([]),256),a)}const p=n?Tu(c,h):xu(c,h);return Ja(Co(p,255),"int32")}});const Sp=ta({transform_:function(e,t,n="nearest",s="constant",r=0,a){const i=Jr(e,"image","transform","float32"),o=Jr(t,"transforms","transform","float32");u(4===i.rank,(()=>`Error in transform: image must be rank 4,but got rank ${i.rank}.`)),u(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")),u(null==a||2===a.length,(()=>`Error in transform: outputShape must be [height, width] or null, but got ${a}.`));const l={image:i,transforms:o},c={interpolation:n,fillMode:s,fillValue:r,outputShape:a};return Vr.runKernel(Zn,l,c)}});const Tp=ta({bandPart_:function(e,t,n){u(t%1==0,(()=>`bandPart(): numLower must be an integer, got ${t}.`)),u(n%1==0,(()=>`bandPart(): numUpper must be an integer, got ${n}.`));const s=Jr(e,"a","bandPart");u(s.rank>=2,(()=>`bandPart(): Rank must be at least 2, got ${s.rank}.`));const r=s.shape,[a,i]=s.shape.slice(-2);if(!(t<=a))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${a}).`);if(!(n<=i))throw new Error(`bandPart(): numUpper (${n}) must not be greater than the number of columns (${i}).`);t<0&&(t=a),n<0&&(n=i);const o=tl(Pc(0,a,1,"int32"),[-1,1]),l=Pc(0,i,1,"int32"),c=Mu(o,l),h=Pu(Tu(c,au(+t,"int32")),wu(c,au(-n,"int32"))),p=Zu([a,i],s.dtype);return tl(fh(Ch(tl(s,[-1,a,i])).map((e=>Wl(h,e,p)))),r)}});const Cp=ta({gramSchmidt_:function(e){let t;if(Array.isArray(e)){t=!1,u(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)u(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=ch(e,e.shape[0],0).map((e=>dh(e,[0])));u(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(Vr.tidy((()=>{let e=s[t];if(t>0)for(let s=0;s<t;++s){const t=Co(lu(Co(n[s],e)),n[s]);e=Mu(e,t)}return To(e,cu(e,"euclidean"))})));return t?fh(n,0):n}});function $p(e,t=!1){return Vr.tidy((()=>{u(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=gu(n),a=Qa(e);const i=xh([[1]],[1,1]);let o=Qa(i);const l=n>=s?s:n;for(let e=0;e<l;++e){const t=a,l=o,u=r;[o,a,r]=Vr.tidy((()=>{const t=il(a,[e,e],[n-e,1]),l=cu(t),u=il(a,[e,e],[1,1]),c=Wl(xu(u,0),xh([[-1]]),xh([[1]])),h=Mu(u,Co(c,l)),p=To(t,h);o=1===p.shape[0]?Qa(i):rl([i,il(p,[1,0],[p.shape[0]-1,p.shape[1]])],0);const d=Ai(To(bi(c,h),l)),f=il(a,[e,0],[n-e,s]),m=Co(d,o),g=_i(o);if(0===e)a=Mu(f,bi(m,bi(g,f)));else{const t=Mu(f,bi(m,bi(g,f)));a=rl([il(a,[0,0],[e,s]),t],0)}const y=_i(m),b=il(r,[0,e],[n,r.shape[1]-e]);if(0===e)r=Mu(b,bi(bi(b,o),y));else{const t=Mu(b,bi(bi(b,o),y));r=rl([il(r,[0,0],[n,e]),t],1)}return[o,a,r]})),Ii([t,l,u])}return!t&&n>s&&(r=il(r,[0,0],[n,s]),a=il(a,[0,0],[s,s])),[r,a]}))}const Ep=ta({qr_:function(e,t=!1){if(u(e.rank>=2,(()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`)),2===e.rank)return $p(e,t);{const n=e.shape.slice(0,e.shape.length-2).reduce(((e,t)=>e*t)),s=Ch(tl(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),r=[],a=[];s.forEach((e=>{const[n,s]=$p(e,t);r.push(n),a.push(s)}));return[tl(fh(r,0),e.shape),tl(fh(a,0),e.shape)]}}});var Ap;(Ap=e.Reduction||(e.Reduction={}))[Ap.NONE=0]="NONE",Ap[Ap.MEAN=1]="MEAN",Ap[Ap.SUM=2]="SUM",Ap[Ap.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS";const Rp=ta({computeWeightedLoss_:function(t,n,s=e.Reduction.SUM_BY_NONZERO_WEIGHTS){const r=Jr(t,"losses","computeWeightedLoss");let a=null;null!=n&&(a=Jr(n,"weights","computeWeightedLoss"));const i=null==a?r:Co(r,a);if(s===e.Reduction.NONE)return i;if(s===e.Reduction.SUM)return lu(i);if(s===e.Reduction.MEAN){if(null==a)return Yu(i);{const e=r.size/a.size,t=To(lu(i),lu(a));return e>1?To(t,au(e)):t}}if(s===e.Reduction.SUM_BY_NONZERO_WEIGHTS){if(null==a)return To(lu(i),au(r.size));{const e=Co(a,Ju(r.shape)),t=Ja(lu(ic(e,au(0))),"float32");return To(lu(i),t)}}throw Error(`Unknown reduction: ${s}`)}});const _p=ta({absoluteDifference_:function(t,n,s,r=e.Reduction.SUM_BY_NONZERO_WEIGHTS){const a=Jr(t,"labels","absoluteDifference"),i=Jr(n,"predictions","absoluteDifference");let o=null;null!=s&&(o=Jr(s,"weights","absoluteDifference")),c(a.shape,i.shape,"Error in absoluteDifference: ");const l=$o(Mu(a,i));return Rp(l,o,r)}});const Fp=ta({cosineDistance_:function(t,n,s,r,a=e.Reduction.SUM_BY_NONZERO_WEIGHTS){const i=Jr(t,"labels","cosineDistance"),o=Jr(n,"predictions","cosineDistance");let l=null;null!=r&&(l=Jr(r,"weights","cosineDistance")),c(i.shape,o.shape,"Error in cosineDistance: ");const u=au(1),h=Mu(u,lu(Co(i,o),s,!0));return Rp(h,l,a)}});const Dp=ta({hingeLoss_:function(t,n,s,r=e.Reduction.SUM_BY_NONZERO_WEIGHTS){let a=Jr(t,"labels","hingeLoss");const i=Jr(n,"predictions","hingeLoss");let o=null;null!=s&&(o=Jr(s,"weights","hingeLoss")),c(a.shape,i.shape,"Error in hingeLoss: ");const l=au(1);a=Mu(Co(au(2),a),l);const u=Wc(Mu(l,Co(a,i)));return Rp(u,o,r)}});const Op=ta({huberLoss_:function(t,n,s,r=1,a=e.Reduction.SUM_BY_NONZERO_WEIGHTS){const i=Jr(t,"labels","huberLoss"),o=Jr(n,"predictions","huberLoss");let l=null;null!=s&&(l=Jr(s,"weights","huberLoss")),c(i.shape,o.shape,"Error in huberLoss: ");const u=au(r),h=$o(Mu(o,i)),p=ec(h,u),d=Mu(h,p),f=Io(Co(au(.5),ou(p)),Co(u,d));return Rp(f,l,a)}});const Mp=ta({logLoss_:function(t,n,s,r=1e-7,a=e.Reduction.SUM_BY_NONZERO_WEIGHTS){const i=Jr(t,"labels","logLoss"),o=Jr(n,"predictions","logLoss");let l=null;null!=s&&(l=Jr(s,"weights","logLoss")),c(i.shape,o.shape,"Error in logLoss: ");const u=au(1),h=au(r),p=Ai(Co(i,Eu(Io(o,h)))),d=Co(Mu(u,i),Eu(Io(Mu(u,o),h))),f=Mu(p,d);return Rp(f,l,a)}});const Lp=ta({meanSquaredError_:function(t,n,s,r=e.Reduction.SUM_BY_NONZERO_WEIGHTS){const a=Jr(t,"labels","meanSquaredError"),i=Jr(n,"predictions","meanSquaredError");let o=null;null!=s&&(o=Jr(s,"weights","meanSquaredError")),c(a.shape,i.shape,"Error in meanSquaredError: ");const l=ph(a,i);return Rp(l,o,r)}});const zp=ta({sigmoidCrossEntropy_:function(t,n,s,r=0,a=e.Reduction.SUM_BY_NONZERO_WEIGHTS){let i=Jr(t,"multiClassLabels","sigmoidCrossEntropy");const o=Jr(n,"logits","sigmoidCrossEntropy");let l=null;if(null!=s&&(l=Jr(s,"weights","sigmoidCrossEntropy")),c(i.shape,o.shape,"Error in sigmoidCrossEntropy: "),r>0){const e=au(r),t=au(1),n=au(.5);i=Io(Co(i,Mu(t,e)),Co(n,e))}const u=function(e,t){const n=Jr(e,"labels","sigmoidCrossEntropyWithLogits"),s=Jr(t,"logits","sigmoidCrossEntropyWithLogits");c(n.shape,s.shape,"Error in sigmoidCrossEntropyWithLogits: ");const r=Wc(s),a=Co(s,n),i=Au(pu(Ai($o(s))));return Io(Mu(r,a),i)}(i,o);return Rp(u,l,a)}});const Pp=ta({softmaxCrossEntropy_:function(t,n,s,r=0,a=e.Reduction.SUM_BY_NONZERO_WEIGHTS){let i=Jr(t,"onehotLabels","softmaxCrossEntropy");const o=Jr(n,"logits","softmaxCrossEntropy");let l=null;if(null!=s&&(l=Jr(s,"weights","softmaxCrossEntropy")),c(i.shape,o.shape,"Error in softmaxCrossEntropy: "),r>0){const e=au(r),t=au(1),n=au(i.shape[1]);i=Io(Co(i,Mu(t,e)),To(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=_u(((e,t,s)=>{const r=zu(t,[n],!0),a=Mu(Ja(t,"float32"),r);s([e,a]);const i=Ai(Co(a,e));return{value:lu(i,[n]),gradFunc:(e,t)=>{const[s,r]=t,a=Zl(e.shape,[n]);return[Co(tl(e,a),Mu(Ja(s,"float32"),pu(r))),Co(tl(e,a),Mu(pu(r),Ja(s,"float32")))]}}}));return s(e,t)}(i,o);return Rp(u,l,a)}});const Bp=ta({sparseFillEmptyRows_:function(e,t,n,s){const r=Jr(e,"indices","sparseFillEmptyRows","int32"),a=Jr(t,"values","sparseFillEmptyRows"),i=Jr(n,"denseShape","sparseFillEmptyRows","int32"),o=Jr(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=Vr.runKernel(On,l);return{outputIndices:u[0],outputValues:u[1],emptyRowIndicator:u[2],reverseIndexMap:u[3]}}});const Wp=ta({sparseReshape_:function(e,t,n){const s=Jr(e,"inputIndices","sparseReshape","int32"),r=Jr(t,"inputShape","sparseReshape","int32"),a=Jr(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=Vr.runKernel(Mn,i);return{outputIndices:o[0],outputShape:o[1]}}});const Vp=ta({sparseSegmentMean_:function(e,t,n){const s=Jr(e,"data","sparseSegmentMean"),r=Jr(t,"indices","sparseSegmentMean","int32"),a=Jr(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 Vr.runKernel(Ln,i)}});const Up=ta({sparseSegmentSum_:function(e,t,n){const s=Jr(e,"data","sparseSegmentSum"),r=Jr(t,"indices","sparseSegmentSum","int32"),a=Jr(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 Vr.runKernel(zn,i)}});const Gp=ta({stringNGrams_:function(e,t,n,s,r,a,i,o){const l=Jr(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=Jr(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=Vr.runKernel(Un,h,c);return{nGrams:p[0],nGramsSplits:p[1]}}});const Hp=ta({stringSplit_:function(e,t,n=!0){const s=Jr(e,"input","stringSplit","string"),r=Jr(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=Vr.runKernel(Gn,i,a);return{indices:o[0],values:o[1],shape:o[2]}}});const jp=ta({stringToHashBucketFast_:function(e,t){const n=Jr(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 Vr.runKernel(Hn,r,s)}}),qp={fft:oh,ifft:lh,rfft:hh,irfft:uh},Kp={hammingWindow:Jh,hannWindow:Qh,frame:ep,stft:tp},Xp={flipLeftRight:sp,grayscaleToRGB:rp,resizeNearestNeighbor:Np,resizeBilinear:kp,rotateWithOffset:ap,cropAndResize:np,nonMaxSuppression:op,nonMaxSuppressionAsync:yp,nonMaxSuppressionWithScore:bp,nonMaxSuppressionWithScoreAsync:xp,nonMaxSuppressionPadded:wp,nonMaxSuppressionPaddedAsync:vp,threshold:Ip,transform:Sp},Yp={bandPart:Tp,gramSchmidt:Cp,qr:Ep},Zp={absoluteDifference:_p,computeWeightedLoss:Rp,cosineDistance:Fp,hingeLoss:Dp,huberLoss:Op,logLoss:Mp,meanSquaredError:Lp,sigmoidCrossEntropy:zp,softmaxCrossEntropy:Pp},Jp={sparseFillEmptyRows:Bp,sparseReshape:Wp,sparseSegmentMean:Vp,sparseSegmentSum:Up},Qp={stringNGrams:Gp,stringSplit:Hp,stringToHashBucketFast:jp};class ed extends fo{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 Ii(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 Ru(e,t)}dispose(){null!=this.iterations_&&Ii(this.iterations_)}async saveIterations(){return null==this.iterations_&&(this.iterations_=0),{name:"iter",tensor:au(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(ed,Symbol.hasInstance,{value:e=>null!=e.minimize&&null!=e.computeGradients&&null!=e.applyGradients});class td extends ed{constructor(e,t,n=null){super(),this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],null==n&&(this.epsilon=Vr.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const s=Vr.registeredVariables[t];null==this.accumulatedGrads[n]&&(this.accumulatedGrads[n]={originalName:`${t}/accum_grad`,variable:Ni((()=>Vl(s).variable(false)))}),null==this.accumulatedUpdates[n]&&(this.accumulatedUpdates[n]={originalName:`${t}/accum_var`,variable:Ni((()=>Vl(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;Ni((()=>{const e=Io(Co(a,this.rho),Co(ou(r),1-this.rho)),t=Co(To(iu(Io(i,this.epsilon)),iu(Io(a,this.epsilon))),r),n=Io(Co(i,this.rho),Co(ou(t),1-this.rho));a.assign(e),i.assign(n);const o=Io(Co(t,-this.learningRate),s);s.assign(o)}))})),this.incrementIterations()}dispose(){null!=this.accumulatedUpdates&&(Ii(this.accumulatedGrads.map((e=>e.variable))),Ii(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)}}td.className="Adadelta",go(td);class nd extends ed{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=Vr.registeredVariables[t];if(null==this.accumulatedGrads[n]){const e=!1;this.accumulatedGrads[n]={originalName:`${t}/accumulator`,variable:Ni((()=>bl(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;Ni((()=>{const e=Io(a,ou(r));a.assign(e);const t=Io(Co(To(r,iu(Io(e,Vr.backend.epsilon()))),-this.learningRate),s);s.assign(t)}))})),this.incrementIterations()}dispose(){null!=this.accumulatedGrads&&Ii(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)}}nd.className="Adagrad",go(nd);class sd extends ed{constructor(e,t,n,s=null){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=s,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],Ni((()=>{this.accBeta1=au(t).variable(),this.accBeta2=au(n).variable()})),null==s&&(this.epsilon=Vr.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);Ni((()=>{const n=Mu(1,this.accBeta1),s=Mu(1,this.accBeta2);t.forEach(((t,r)=>{const a=Vr.registeredVariables[t];null==this.accumulatedFirstMoment[r]&&(this.accumulatedFirstMoment[r]={originalName:`${t}/m`,variable:Ni((()=>Vl(a).variable(false)))}),null==this.accumulatedSecondMoment[r]&&(this.accumulatedSecondMoment[r]={originalName:`${t}/v`,variable:Ni((()=>Vl(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=Io(Co(o,this.beta1),Co(i,1-this.beta1)),c=Io(Co(l,this.beta2),Co(ou(i),1-this.beta2)),h=To(u,n),p=To(c,s);o.assign(u),l.assign(c);const d=Io(Co(To(h,Io(iu(p),this.epsilon)),-this.learningRate),a);a.assign(d)})),this.accBeta1.assign(Co(this.accBeta1,this.beta1)),this.accBeta2.assign(Co(this.accBeta2,this.beta2))})),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),null!=this.accumulatedFirstMoment&&Ii(this.accumulatedFirstMoment.map((e=>e.variable))),null!=this.accumulatedSecondMoment&&Ii(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),Ni((()=>{this.accBeta1.assign(ru(this.beta1,this.iterations_+1)),this.accBeta2.assign(ru(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)}}sd.className="Adam",go(sd);class rd extends ed{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=[],Ni((()=>{this.iteration=au(0).variable(),this.accBeta1=au(t).variable()})),null==s&&(this.epsilon=Vr.backend.epsilon())}applyGradients(e){const t=Array.isArray(e)?e.map((e=>e.name)):Object.keys(e);Ni((()=>{const n=Mu(1,this.accBeta1),s=To(-this.learningRate,Io(Co(this.iteration,this.decay),1));t.forEach(((t,r)=>{const a=Vr.registeredVariables[t];null==this.accumulatedFirstMoment[r]&&(this.accumulatedFirstMoment[r]={originalName:`${t}/m`,variable:Vl(a).variable(false)}),null==this.accumulatedWeightedInfNorm[r]&&(this.accumulatedWeightedInfNorm[r]={originalName:`${t}/v`,variable:Vl(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=Io(Co(o,this.beta1),Co(i,1-this.beta1)),c=Co(l,this.beta2),h=$o(i),p=Xu(c,h);o.assign(u),l.assign(p);const d=Io(Co(To(s,n),To(u,Io(p,this.epsilon))),a);a.assign(d)})),this.iteration.assign(Io(this.iteration,1)),this.accBeta1.assign(Co(this.accBeta1,this.beta1))})),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),null!=this.accumulatedFirstMoment&&Ii(this.accumulatedFirstMoment.map((e=>e.variable))),null!=this.accumulatedWeightedInfNorm&&Ii(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)}}rd.className="Adamax",go(rd);class ad extends ed{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=Vr.registeredVariables[t];Ni((()=>{const e=Io(Co(this.c,s),r);r.assign(e)}))})),this.incrementIterations()}setLearningRate(e){this.learningRate=e,null!=this.c&&this.c.dispose(),this.c=Si(au(-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)}}ad.className="SGD",go(ad);class id extends ad{constructor(e,t,n=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=au(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map((e=>e.name)):Object.keys(e)).forEach(((t,n)=>{const s=Vr.registeredVariables[t];if(null==this.accumulations[n]){const e=!1;this.accumulations[n]={originalName:`${t}/momentum`,variable:Ni((()=>Vl(s).variable(e)))}}const r=this.accumulations[n].variable,a=Array.isArray(e)?e[n].tensor:e[t];null!=a&&Ni((()=>{let e;const t=Io(Co(this.m,r),a);e=this.useNesterov?Io(Co(this.c,Io(a,Co(t,this.m))),s):Io(Co(this.c,t),s),r.assign(t),s.assign(e)}))})),this.incrementIterations()}dispose(){this.m.dispose(),null!=this.accumulations&&Ii(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)}}id.className="Momentum",go(id);class od extends ed{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=Vr.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=Vr.registeredVariables[t],r=!1;null==this.accumulatedMeanSquares[n]&&(this.accumulatedMeanSquares[n]={originalName:`${t}/rms`,variable:Ni((()=>Vl(s).variable(r)))}),null==this.accumulatedMoments[n]&&(this.accumulatedMoments[n]={originalName:`${t}/momentum`,variable:Ni((()=>Vl(s).variable(r)))}),null==this.accumulatedMeanGrads[n]&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${t}/mg`,variable:Ni((()=>Vl(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;Ni((()=>{const e=Io(Co(i,this.decay),Co(ou(a),1-this.decay));if(this.centered){const t=this.accumulatedMeanGrads[n].variable,r=Io(Co(t,this.decay),Co(a,1-this.decay)),l=To(Co(a,this.learningRate),iu(Mu(e,Io(ou(r),this.epsilon)))),u=Io(Co(o,this.momentum),l);i.assign(e),t.assign(r),o.assign(u);const c=Mu(s,u);s.assign(c)}else{const e=Io(Co(i,this.decay),Co(ou(a),1-this.decay)),t=Io(Co(o,this.momentum),To(Co(a,this.learningRate),iu(Io(e,this.epsilon))));i.assign(e),o.assign(t);const n=Mu(s,t);s.assign(n)}}))})),this.incrementIterations()}dispose(){null!=this.accumulatedMeanSquares&&Ii(this.accumulatedMeanSquares.map((e=>e.variable))),null!=this.accumulatedMeanGrads&&this.centered&&Ii(this.accumulatedMeanGrads.map((e=>e.variable))),null!=this.accumulatedMoments&&Ii(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)}}od.className="RMSProp",go(od);class ld{static sgd(e){return new ad(e)}static momentum(e,t,n=!1){return new id(e,t,n)}static rmsprop(e,t=.9,n=0,s=null,r=!1){return new od(e,t,n,s,r)}static adam(e=.001,t=.9,n=.999,s=null){return new sd(e,t,n,s)}static adadelta(e=.001,t=.95,n=null){return new td(e,t,n)}static adamax(e=.002,t=.9,n=.999,s=null,r=0){return new rd(e,t,n,s,r)}static adagrad(e,t=.1){return new nd(e,t)}}const ud={sgd:ld.sgd,momentum:ld.momentum,adadelta:ld.adadelta,adagrad:ld.adagrad,rmsprop:ld.rmsprop,adamax:ld.adamax,adam:ld.adam},cd="undefined"!=typeof requestAnimationFrame?requestAnimationFrame:"undefined"!=typeof setImmediate?setImmediate:e=>e();function hd(){return new Promise((e=>cd((()=>e()))))}function pd(e,t){const n=e[0].length;e.forEach(((e,t)=>{u(e.length===n,(()=>`Error in concat${n}D: rank of tensors[${t}] must be the same as the rank of the rest (${n})`))})),u(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++)u(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 dd(e,t){const n=e[0].slice();for(let s=1;s<e.length;s++)n[t]+=e[s][t];return n}var fd;function md(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 gd(e){const t={FIRST_DIM_SIZE:fd.FIRST_DIM_SIZE,VALUE_ROWIDS:fd.VALUE_ROWIDS,ROW_LENGTHS:fd.ROW_LENGTHS,ROW_SPLITS:fd.ROW_SPLITS,ROW_LIMITS:fd.ROW_LIMITS,ROW_STARTS:fd.ROW_STARTS},n=[];for(const s of e){if(!(s in t))break;n.push(t[s])}return n}function yd(e){return 0===e.length?0:e[0]===fd.FIRST_DIM_SIZE?e.length-1:e.length}function bd(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"}(fd||(fd={}));function xd(e){return e<=30?e:O(e,Math.floor(Math.sqrt(e)))}function wd(e,t,n){return[n*("number"==typeof e?e:e[0]),t*("number"==typeof e?e:e[1])]}function vd(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 kd(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 Nd(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 Id(e,t){const n=[0];for(let s=0;s<t;++s)n.push(e[s][0]);return n}function Sd(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 Td=1.7580993408473768,Cd=1.0507009873554805,$d=.3275911,Ed=.254829592,Ad=-.284496736,Rd=1.421413741,_d=-1.453152027,Fd=1.061405429;function Dd(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 Od(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 Md(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 Ld(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 zd(e,t){return{real:e[2*t],imag:e[2*t+1]}}function Pd(e,t,n,s){e[2*s]=t,e[2*s+1]=n}function Bd(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 Wd(e,t,n){const s=(n?2:-2)*Math.PI*(e/t);return{real:Math.cos(s),imag:Math.sin(s)}}const Vd="->",Ud=/->/g;function Gd(e,t){const n=((e=e.replace(/\s/g,"")).length-e.replace(Ud,"").length)/Vd.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(Vd);u(-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 c=o.length,h=[];for(let e=r.length;e<c;++e)h.push(e);return{allDims:o,summedDims:h,idDims:l}}function Hd(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 jd(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]:u(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 qd(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=Xd(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 Kd(e){return e.every(((e,t)=>e===t))}function Xd(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 Yd(e,t,n=0){let s=[];if("number"==typeof t)u(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);u(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}u(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 Zd(e){return`Received SparseTensor with denseShape[0] = 0 but\n indices.shape[0] = ${e}`}function Jd(e,t){return`indices(${e}, 0) is invalid: ${t} < 0`}function Qd(e,t,n){return`indices(${e}, 0) is invalid: ${t} >= ${n}`}function ef(e,t){return`only one output dimension may be -1, not both ${e} and ${t}`}function tf(e,t){return`size ${e} must be non-negative, not ${t}`}function nf(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function sf(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 rf(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 af(){return"segment ids must be >= 0"}function of(){return"segment ids are not increasing"}function lf(e,t){return`Segment id ${e} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function uf(e,t,n){return`Bad: indices[${e}] == ${t} out of range [0, ${n})`}function cf(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 hf(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 pf(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 df=Object.freeze({__proto__:null,segOpComputeOptimalWindowSize:cf,computeOutShape:hf,collectGatherOpShapeInfo:pf});function ff(e){try{return e.map((e=>or(e)))}catch(e){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${e}`)}}function mf(e){return e.map((e=>ir(e)))}var gf=Object.freeze({__proto__:null,slice_util:po,segment_util:df,fromUint8ToStringArray:ff,fromStringArrayToUint8:mf,upcastType:Ar,axesAreInnerMostDims:Kl,combineLocations:Xl,computeOutAndReduceShapes:Yl,expandShapeToKeepDim:Zl,assertAxesAreInnerMostDims:Jl,getAxesPermutation:Ql,getUndoAxesPermutation:eu,getInnerMostAxes:tu,getBroadcastDims:Oi,getReductionAxes:Mi,assertAndGetBroadcastShape:Li,assertParamsConsistent:pd,computeOutShape:dd,computeDilation2DInfo:Wo,computePool2DInfo:Vo,computePool3DInfo:Uo,computeConv2DInfo:Go,computeConv3DInfo:Ho,computeDefaultPad:jo,tupleValuesAreOne:Zo,eitherStridesOrDilationsAreOne:Jo,convertConv2DDataFormat:Qo,checkPadOnDimRoundingMode:el,getFusedDyActivation:Vh,getFusedBiasGradient:Uh,applyActivation:Gh,shouldFuse:Hh,get RowPartitionType(){return fd},combineRaggedTensorToTensorShapes:md,getRowPartitionTypesHelper:gd,getRaggedRank:yd,validateDefaultValueShape:bd,PARALLELIZE_THRESHOLD:30,computeOptimalWindowSize:xd,getImageCenter:wd,getReshaped:vd,getPermuted:kd,getReshapedPermuted:Nd,getSliceBeginCoords:Id,getSliceSize:Sd,prepareAndValidate:Hi,validateUpdateShape:qi,validateInput:Ki,calculateShapes:Xi,SELU_SCALEALPHA:Td,SELU_SCALE:Cd,ERF_P:$d,ERF_A1:Ed,ERF_A2:Ad,ERF_A3:Rd,ERF_A4:_d,ERF_A5:Fd,warn:us,log:function(...e){X().getBool("IS_TEST")||X().getBool("PROD")||console.log(...e)},mergeRealAndImagArrays:Dd,splitRealAndImagArrays:Od,complexWithEvenIndex:Md,complexWithOddIndex:Ld,getComplexWithIndex:zd,assignToTypedArray:Pd,exponents:Bd,exponent:Wd,decodeEinsumEquation:Gd,getEinsumPermutation:Hd,checkEinsumDimSizes:jd,getEinsumComputePath:qd,isIdentityPermutation:Kd,prepareSplitSize:Yd,getSparseFillEmptyRowsIndicesDenseShapeMismatch:Zd,getSparseFillEmptyRowsNegativeIndexErrorMessage:Jd,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:Qd,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:ef,getSparseReshapeNegativeOutputDimErrorMessage:tf,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:nf,getSparseReshapeInputOutputMultipleErrorMessage:sf,getSparseReshapeInputOutputMismatchErrorMessage:rf,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:af,getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:of,getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:lf,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:uf}),yf=Object.freeze({__proto__:null,nonMaxSuppressionV3Impl:cp,nonMaxSuppressionV4Impl:hp,nonMaxSuppressionV5Impl:pp,whereImpl:Ah});const bf={kernelName:Q,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Co(e,mh(Ja(n,"float32"),-1))}}},xf={kernelName:ee,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=ou(Ja(n,"float32")),s=iu(Mu(au(1),t));return Ai(To(e,s))}}}},wf={kernelName:te,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=iu(Mu(ou(Ja(n,"float32")),1));return To(e,t)}}}},vf={kernelName:ne,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=Li(n.shape,s.shape);return{a:()=>{let t=e;const s=Mi(n.shape,r);return s.length>0&&(t=lu(t,s)),tl(t,n.shape)},b:()=>{let t=e;const n=Mi(s.shape,r);return n.length>0&&(t=lu(t,n)),tl(t,s.shape)}}}},kf={kernelName:se,saveAllInputs:!0,gradFunc:(e,t)=>{const n={};return t.forEach(((t,s)=>{n[s]=()=>e.clone()})),n}},Nf={kernelName:ie,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Vl(n)}}},If={kernelName:oe,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Vl(n)}}},Sf={kernelName:le,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>To(e,iu(Mu(au(1),ou(Ja(n,"float32")))))}}},Tf={kernelName:ue,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=iu(Io(au(1),ou(Ja(n,"float32"))));return To(e,t)}}}},Cf={kernelName:pe,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=Li(n.shape,s.shape);return{a:()=>{const t=Io(ou(n),ou(s));let a=Co(e,To(s,t));const i=Mi(n.shape,r);return i.length>0&&(a=lu(a,i)),tl(a,n.shape)},b:()=>{const t=Io(ou(n),ou(s));let a=Ai(Co(e,To(n,t)));const i=Mi(s.shape,r);return i.length>0&&(a=lu(a,i)),tl(a,s.shape)}}}},$f={kernelName:ce,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>To(e,Io(ou(Ja(n,"float32")),1))}}},Ef={kernelName:he,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>To(e,Mu(au(1),ou(Ja(n,"float32"))))}}};const Af=ta({avgPool3dGrad_:function(e,t,n,s,r,a){const i=Jr(e,"dy","avgPool3dGrad"),o=Jr(t,"input","avgPool3dGrad");let l=i,c=o,h=!1;4===o.rank&&(h=!0,l=tl(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),c=tl(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),u(5===l.rank,(()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`)),u(5===c.rank,(()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${c.rank}.`)),el("avgPool3dGrad",r,a);const p={dy:l,input:c},d={filterSize:n,strides:s,pad:r,dimRoundingMode:a},f=Vr.runKernel(ge,p,d);return h?tl(f,[f.shape[1],f.shape[2],f.shape[3],f.shape[4]]):f}}),Rf={kernelName:me,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{filterSize:r,strides:a,pad:i,dimRoundingMode:o}=n;return{x:()=>Af(e,s,r,a,i,o)}}};const _f=ta({avgPoolGrad_:function(e,t,n,s,r){const a=Jr(e,"dy","avgPoolGrad"),i=Jr(t,"input","avgPoolGrad");u(i.rank===a.rank,(()=>`Rank of input (${i.rank}) does not match rank of dy (${a.rank})`));let o=i,l=a,c=!1;3===i.rank&&(c=!0,o=tl(i,[1,i.shape[0],i.shape[1],i.shape[2]]),l=tl(a,[1,a.shape[0],a.shape[1],a.shape[2]])),u(4===l.rank,(()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`)),u(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=Vr.runKernel(fe,h,p);return c?tl(d,[d.shape[1],d.shape[2],d.shape[3]]):d}}),Ff={kernelName:de,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{filterSize:r,strides:a,pad:i}=n;return{x:()=>_f(e,s,r,a,i)}}},Df={kernelName:ye,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{const[s,r]=t,{transposeA:a,transposeB:i}=n;return a||i?!a&&i?{a:()=>bi(e,r,!1,!1),b:()=>bi(e,s,!0,!1)}:a&&!i?{a:()=>bi(r,e,!1,!0),b:()=>bi(s,e,!1,!1)}:{a:()=>bi(r,e,!0,!0),b:()=>bi(e,s,!0,!0)}:{a:()=>bi(e,r,!1,!0),b:()=>bi(s,e,!0,!1)}}},Of={kernelName:be,gradFunc:(e,t,n)=>{const{blockShape:s,crops:r}=n;return{x:()=>fc(e,s,r)}}},Mf={kernelName:we,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:()=>lu(e,o,!0)}}},Lf={kernelName:ke,gradFunc:e=>({x:()=>e.clone()})},zf={kernelName:Ne,gradFunc:e=>({x:()=>Vl(e)})},Pf={kernelName:Ie,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{clipValueMin:r,clipValueMax:a}=n;return{x:()=>Wl(Pu(wu(s,r),Tu(s,a)),e,Vl(e))}}},Bf={kernelName:Te,inputsToSave:["x"],gradFunc:bf.gradFunc},Wf={kernelName:Ce,saveAllInputs:!0,gradFunc:(e,t,n)=>{const s=t.map((e=>e.shape)),{axis:r}=n,a=w(r,t[0].shape)[0],i=s.map((e=>e[a]));return ch(e,i,a).map((e=>()=>e))}},Vf={kernelName:$e,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const[s,r]=t,{dilations:a,strides:i,pad:o,dataFormat:l}=n;return u(Zo(a),(()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`)),{x:()=>Tl(s.shape,e,r,i,o,l),filter:()=>Wh(s,e,r.shape,i,o,l)}}},Uf={kernelName:Ae,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{const[s,r]=t,{strides:a,pad:i,dataFormat:o,dimRoundingMode:l}=n;return{dy:()=>Il(e,r,a,i,o,1,l),filter:()=>Wh(e,s,r.shape,a,i,o,l)}}};const Gf=ta({conv3DBackpropFilter_:function(e,t,n,s,r){let a=e;4===e.rank&&(a=tl(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let i=t;4===i.rank&&(i=tl(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),u(5===a.rank,(()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${a.shape}.`)),u(5===i.rank,(()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${i.shape}.`)),u(5===n.length,(()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`)),u(a.shape[4]===n[3],(()=>`Error in conv3dDerFilter: depth of input ${a.shape[4]}) must match input depth in filter (${n[3]}.`)),u(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 Vr.runKernel(_e,o,l)}}),Hf={kernelName:Re,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:s,strides:r,pad:a}=n;u(Zo(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:()=>El(i.shape,e,o,r,a),filter:()=>Gf(i,e,o.shape,r,a)}}},jf={kernelName:De,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Co(Ai(eh(Ja(n,"float32"))),e)}}},qf={kernelName:Oe,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Co(th(Ja(n,"float32")),e)}}},Kf={kernelName:Le,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{axis:r,exclusive:a,reverse:i}=n;return{x:()=>{const t=Ql([r],s.rank);let n=Dl(e,r,a,!i);return null!=t&&(n=_i(n,t)),n}}}},Xf={kernelName:We,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{const{dilations:s,strides:r,pad:a,dimRoundingMode:i}=n,o=null==s?[1,1]:s;u(Zo(o),(()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`));const[l,c]=t;return u(4===l.rank,(()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`)),u(4===c.rank,(()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${c.rank}.`)),u(l.shape[3]===c.shape[2],(()=>`Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${c.shape[2]}.`)),u(Jo(r,o),(()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${r} and dilations '${o}'.`)),el("depthwiseConv2d",a,i),{x:()=>Kh(l.shape,e,c,r,a,o,i),filter:()=>qh(l,e,c.shape,r,a,o,i)}}},Yf={kernelName:He,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:()=>Vr.runKernel(je,a,n),filter:()=>Vr.runKernel(qe,i,n)}}},Zf={kernelName:Ye,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t,s={dy:e,y:n};return{x:()=>Vr.runKernel(Ze,s)}}},Jf={kernelName:Je,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,s=Co(pu(Ai(ou(n))),2/Math.sqrt(Math.PI));return{x:()=>Co(e,s)}}},Qf={kernelName:et,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Co(e,n)}}},em={kernelName:tt,inputsToSave:["input"],gradFunc:(e,t)=>{const[n]=t;return{input:()=>tl(e,n.shape)}}},tm={kernelName:nt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Co(e,pu(n))}}},nm={kernelName:it,gradFunc:e=>({x:()=>Vl(e)})},sm={kernelName:ot,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=Li(n.shape,s.shape);return{a:()=>{const t=To(e,Ja(s,"float32")),a=Mi(n.shape,r);return a.length>0?tl(lu(t,a),n.shape):t},b:()=>{let t=Co(e,Ja(n,"float32"));const a=Mi(s.shape,r);a.length>0&&(t=tl(lu(t,a),s.shape));const i=ou(s);return Ai(To(t,Ja(i,"float32")))}}}},rm={kernelName:lt,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{const{varianceEpsilon:s}=n,[r,a,i,o]=t,l=null==o?au(1):o,u=Mi(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=Mu(r,a),p=Co(e,l),d=Xc(Io(i,au(s))),f=Co(Co(Co(d,d),d),au(-.5));return{x:()=>1===a.rank?tl(Co(Co(e,mu(tl(d,[1,1,1,a.shape[0]]),c)),l),r.shape):tl(Co(Co(e,d),l),r.shape),mean:()=>{let e=Co(Co(d,au(-1)),p);return 1===a.rank&&(e=lu(e,u)),tl(e,a.shape)},variance:()=>{let e=Co(Co(f,h),p);return 1===a.rank&&(e=lu(e,u)),tl(e,a.shape)},scale:()=>{const t=Co(h,d);let n=Co(e,t);return 1===a.rank&&(n=lu(n,u)),tl(n,a.shape)},offset:()=>{let t=e;return 1===a.rank&&(t=lu(t,u)),tl(t,a.shape)}}}},am={kernelName:ut,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{const[s,r]=t,{axis:a}=n,i=w(a,s.shape)[0];return{x:()=>{const t=s.shape,n=r.size,o=t.slice(0,i),l=o.length,u=t.slice(a,t.length).slice(1),c=u.length,h=im(0,l),p=im(l+1,l+1+c),d=om([o,[n],u]),f=tl(e,d),m=tl(r,[n]),g=om([[l],h,p]),y=_i(f,g);let b=Th(y,m,s.shape[i]);const x=eu(g);return b=_i(b,x),b},indices:()=>r}}};function im(e,t){const n=[];for(let s=e;s<t;++s)n.push(s);return n}function om(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 lm={kernelName:pt,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t;return{a:()=>Vl(n),b:()=>Vl(s)}}},um={kernelName:dt,gradFunc:e=>({x:()=>Ja(e,"float32")})},cm={kernelName:gt,gradFunc:e=>({x:()=>Vl(e)})},hm={kernelName:yt,gradFunc:e=>({x:()=>Vl(e)})},pm={kernelName:bt,gradFunc:e=>({x:()=>Vl(e)})},dm={kernelName:xt,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{alpha:r}=n,a=xu(s,0);return{x:()=>Wl(a,e,Co(e,r))}}},fm={kernelName:It,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>To(e,Io(n,1))}}},mm={kernelName:Nt,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>To(e,Ja(n,"float32"))}}},gm={kernelName:$t,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s]=t,{axis:r}=n;return{logits:()=>{const t=pu(s);return Mu(e,Co(lu(e,r,!0),t))}}}};const ym=ta({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 Vr.runKernel(At,o,l)}}),bm={kernelName:Et,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s,r]=t,{depthRadius:a,bias:i,alpha:o,beta:l}=n;return{x:()=>ym(s,r,e,a,i,o,l)}}};function xm(e,t,n,s){return t.rank<n.rank&&(t=tl(t,Zl(t.shape,s))),e.rank<n.rank&&(e=tl(e,Zl(e.shape,s))),{x:()=>Co(e,Ja(Bl(n,t),e.dtype))}}const wm={kernelName:Rt,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const s=n,{reductionIndices:r}=s,a=t[0],i=xm(e,t[1],a,w(r,a.shape));return{x:()=>i.x()}}},vm={kernelName:_t,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t;return{a:()=>Co(e,Ja(wu(n,s),"float32")),b:()=>Co(e,Ja(Su(n,s),"float32"))}}};const km=ta({maxPool3dGrad_:function(e,t,n,s,r,a,i){const o=Jr(e,"dy","maxPool3dGrad"),l=Jr(t,"input","maxPool3dGrad"),c=Jr(n,"output","maxPool3dGrad");let h=o,p=l,d=c,f=!1;4===l.rank&&(f=!0,h=tl(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),p=tl(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),d=tl(c,[1,c.shape[0],c.shape[1],c.shape[2],c.shape[3]])),u(5===h.rank,(()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${h.rank}.`)),u(5===p.rank,(()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${p.rank}.`)),u(5===d.rank,(()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${d.rank}.`)),el("maxPool3dGrad",a,i);const m={dy:h,input:p,output:d},g={filterSize:s,strides:r,pad:a,dimRoundingMode:i},y=Vr.runKernel(Mt,m,g);return f?tl(y,[y.shape[1],y.shape[2],y.shape[3],y.shape[4]]):y}}),Nm={kernelName:Ot,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s,r]=t,{filterSize:a,strides:i,pad:o,dimRoundingMode:l}=n;return{x:()=>km(e,s,r,a,i,o,l)}}};const Im=ta({maxPoolGrad_:function(e,t,n,s,r,a,i){const o=Jr(e,"dy","maxPoolGrad"),l=Jr(t,"input","maxPoolGrad"),c=Jr(n,"output","maxPoolGrad");u(l.rank===o.rank,(()=>`Rank of input (${l.rank}) does not match rank of dy (${o.rank})`)),u(4===o.rank,(()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${o.rank}.`)),u(4===l.rank,(()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`)),el("maxPoolGrad",a,i);const h={dy:o,input:l,output:c},p={filterSize:s,strides:r,pad:a,dimRoundingMode:i};return Vr.runKernel(Dt,h,p)}}),Sm={kernelName:Ft,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s,r]=t,{filterSize:a,strides:i,pad:o}=n;return{x:()=>Im(e,s,r,a,i,o)}}},Tm={kernelName:Wt,inputsToSave:["x"],gradFunc:(e,t,n)=>{const s=t[0],{paddings:r}=n,a=r.map((e=>e[0]));return{x:()=>il(e,a,s.shape)}}},Cm={kernelName:Qt,inputsToSave:["x"],gradFunc:(e,t,n)=>{const s=t[0],{paddings:r}=n,a=r.map((e=>e[0]));return{x:()=>il(e,a,s.shape)}}},$m={kernelName:en,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{const[n,s,r]=t,a=n,i=s,o=Li(a.shape,i.shape);return{a:()=>{const t=Ja(i,"float32");let n=Co(e,Co(t,ru(a,Mu(t,au(1)))));const s=Mi(a.shape,o);return s.length>0&&(n=lu(n,s)),tl(n,a.shape)},b:()=>{const t=xu(a,0),n=Wl(t,Eu(a),Vl(a));let s=Co(e,Co(r,n));const l=Mi(i.shape,o);return l.length>0&&(s=lu(s,l)),tl(s,i.shape)}}}};function Em(e,t,n){const s=e.shape.length,r=s-n.length,a=Ql(n,s);let i=e;null!=a&&(i=_i(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=tl(t,s),a=Fl(e,n,!0,!1),i=Fl(e,n,!0,!0),o=Co(a,i);return Co(r,o)}(i.reshape(o),t,r);if(u=u.reshape(i.shape),null!=a){const e=eu(a);u=_i(u,e)}return u}const Am={kernelName:Nn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>{const t=xu(n,au(0)),s=au(Td),r=au(Cd),a=Co(e,r),i=Co(Co(e,s),pu(Ja(n,"float32")));return Wl(t,a,i)}}}},Rm={kernelName:_n,gradFunc:(e,t,n)=>{const{blockShape:s,paddings:r}=n;return{x:()=>ul(e,s,r)}}},_m={kernelName:Fn,gradFunc:(e,t,n)=>{const{axis:s}=n;return{x:()=>rl(e,s)}}};const Fm=[bf,xf,wf,vf,kf,Nf,If,Sf,Tf,Cf,$f,Ef,Rf,Ff,Df,Of,Mf,Lf,zf,Pf,Bf,Wf,Uf,Vf,Hf,jf,qf,Kf,Xf,Yf,{kernelName:Ke,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=Li(n.shape,s.shape);return{a:()=>{const t=To(e,Ja(s,"float32")),a=Mi(n.shape,r);return a.length>0?tl(lu(t,a),n.shape):t},b:()=>{let t=Co(e,Ja(n,"float32"));const a=Mi(s.shape,r);a.length>0&&(t=tl(lu(t,a),s.shape));const i=ou(s);return Ai(To(t,Ja(i,"float32")))}}}},Zf,Jf,Qf,em,tm,sm,nm,rm,am,lm,um,cm,hm,pm,dm,fm,mm,gm,bm,wm,wm,vm,Nm,Sm,{kernelName:zt,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{axis:r}=n,a=w(r,s.shape),i=d(Yl(s.shape,a)[1]);return{x:()=>{const t=s.shape.slice();a.forEach((e=>{t[e]=1}));const n=tl(e,t);return To(Co(n,Ju(s.shape,"float32")),i)}}}},{kernelName:Pt,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{const s=n,{axis:r}=s,[a,i]=t,o=xm(e,i,a,w(r,a.shape));return{x:()=>o.x()}}},{kernelName:Bt,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t;return{a:()=>Co(e,Ja(Tu(n,s),"float32")),b:()=>Co(e,Ja(xu(n,s),"float32"))}}},Tm,{kernelName:Vt,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=Li(n.shape,s.shape);return{a:()=>{const t=Mi(n.shape,r);return t.length>0?tl(lu(e,t),n.shape):e},b:()=>{const t=Co(e,Ai(yu(To(n,s)))),a=Mi(s.shape,r);return a.length>0?tl(lu(t,a),s.shape):t}}}},{kernelName:Gt,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=Li(n.shape,s.shape);return{a:()=>{const t=Co(e,Ja(s,"float32")),a=Mi(n.shape,r);return a.length>0?tl(lu(t,a),n.shape):t},b:()=>{const t=Co(e,Ja(n,"float32")),a=Mi(s.shape,r);return a.length>0?tl(lu(t,a),s.shape):t}}}},{kernelName:Ht,gradFunc:e=>({x:()=>Ai(e)})},{kernelName:Zt,inputsToSave:["indices"],gradFunc:(e,t)=>{const n=t[0];return{indices:()=>Zu(n.shape,"float32")}}},{kernelName:Yt,gradFunc:e=>({x:()=>Vl(e)})},{kernelName:Jt,saveAllInputs:!0,gradFunc:(e,t,n)=>{const{axis:s}=n;return Ch(e,s).map((e=>()=>e))}},Cm,Cm,$m,{kernelName:tn,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{const[n,s]=t,r=xu(n,0);return{x:()=>Wl(r,e,Co(e,s)),alpha:()=>{let t=Wl(r,Vl(e),Co(e,n));const a=Mi(s.shape,e.shape);return a.length>0&&(t=lu(t,a)),tl(t,s.shape)}}}},{kernelName:nn,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:()=>Em(s,e,a)}}},{kernelName:un,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>To(e,Ai(ou(n)))}}},{kernelName:gn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t,s=Co(Tu(n,6),mh(n));return{x:()=>Co(e,Ja(s,"float32"))}}},{kernelName:cn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Co(e,Ja(mh(n),"float32"))}}},{kernelName:hn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>tl(e,n.shape)}}},{kernelName:fn,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[s]=t,r={dy:e,images:s};return{images:()=>Vr.runKernel(mn,r,n)}}},{kernelName:pn,inputsToSave:["images"],gradFunc:(e,t,n)=>{const[s]=t,r={dy:e,images:s};return{images:()=>Vr.runKernel(dn,r,n)}}},{kernelName:yn,gradFunc:(e,t,n)=>{const{dims:s}=n,r=w(s,e.shape);return{x:()=>Uc(e,r)}}},{kernelName:bn,gradFunc:e=>({x:()=>Vl(e)})},{kernelName:xn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Ai(To(e,Co(ru(n,1.5),2)))}}},{kernelName:kn,inputsToSave:["condition"],gradFunc:(e,t)=>{const[n]=t;return{condition:()=>Ja(Vl(n),"float32"),t:()=>Co(e,Ja(n,e.dtype)),e:()=>Co(e,Ja(Bu(n),e.dtype))}}},Am,{kernelName:$n,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Co(e,Co(n,Mu(au(1),n)))}}},{kernelName:Cn,gradFunc:e=>({x:()=>Vl(e)})},{kernelName:Sn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Co(Rl(Ja(n,"float32")),e)}}},{kernelName:Tn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Co(_l(Ja(n,"float32")),e)}}},{kernelName:In,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{begin:r,size:a}=n,i=s.shape,[o,l]=uo(s,r,a),u=[];for(let t=0;t<e.rank;t++)u.push([o[t],i[t]-o[t]-l[t]]);return{x:()=>uc(e,u)}}},{kernelName:Dn,outputsToSave:[!0],gradFunc:(e,t,n)=>{const[s]=t,{dim:r}=n,a=Co(e,s);return{logits:()=>Mu(a,Co(lu(a,[r],true),s))}}},{kernelName:En,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Co(e,al(n))}}},Rm,Rm,_m,_m,{kernelName:An,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>To(e,Co(iu(Ja(n,"float32")),2))}}},{kernelName:Bn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=au(2);return{a:()=>Co(e,Co(r,Mu(n,s))),b:()=>Co(e,Co(r,Mu(s,n)))}}},{kernelName:Wn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Co(e,Co(Ja(n,"float32"),2))}}},{kernelName:ss,gradFunc:e=>({x:()=>Vl(e)})},{kernelName:jn,inputsToSave:["a","b"],gradFunc:(e,t)=>{const[n,s]=t,r=Li(n.shape,s.shape);return{a:()=>{let t=e;const s=Mi(n.shape,r);return s.length>0&&(t=lu(t,s)),tl(t,n.shape)},b:()=>{let t=e;const n=Mi(s.shape,r);return n.length>0&&(t=lu(t,n)),tl(Ai(t),s.shape)}}}},{kernelName:Rn,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,r=s.shape.slice(),{axis:a}=n;w(a,s.shape).forEach((e=>{r[e]=1}));const i=tl(e,r),o=Co(i,Ju(s.shape,"float32"));return{x:()=>o}}},{kernelName:qn,inputsToSave:["x"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>To(e,ou(Rl(n)))}}},{kernelName:Kn,outputsToSave:[!0],gradFunc:(e,t)=>{const[n]=t;return{x:()=>Co(Mu(au(1),ou(n)),e)}}},{kernelName:Xn,inputsToSave:["x"],gradFunc:(e,t,n)=>{const[s]=t,{reps:r}=n;return{x:()=>{let t=Vl(s);if(1===s.rank)for(let n=0;n<r[0];++n)t=Io(t,il(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=Io(t,il(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=Io(t,il(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=Io(t,il(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:Jn,gradFunc:(e,t,n)=>{const s=n,{perm:r}=s,a=eu(r);return{x:()=>_i(e,a)}}},{kernelName:es,gradFunc:(e,t,n)=>{const s=n,{axis:r}=s;return{value:()=>fh(e,r)}}},{kernelName:ts,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{const[n]=t;return{x:()=>function(e,t){const n=Xu(t,Vl(t)),s=bu(e,n);let r=wu(t,au(0,"int32"));const a=s.rank-r.rank;for(let e=0;e<a;++e)r=du(r,e+1);r=Pu(r,Ju(s.shape,"bool"));const i=Vl(s);return Wl(r,s,i)}(e,n)}}},{kernelName:ns,gradFunc:e=>({x:()=>Vl(e)})}];for(const e of Fm)gs(e);kr().prototype.abs=function(){return this.throwIfDisposed(),$o(this)},kr().prototype.acos=function(){return this.throwIfDisposed(),Eo(this)},kr().prototype.acosh=function(){return this.throwIfDisposed(),Ao(this)},kr().prototype.add=function(e){return this.throwIfDisposed(),Io(this,e)},kr().prototype.all=function(e,t){return this.throwIfDisposed(),_o(this,e,t)},kr().prototype.any=function(e,t){return this.throwIfDisposed(),Fo(this,e,t)},kr().prototype.argMax=function(e){return this.throwIfDisposed(),Do(this,e)},kr().prototype.argMin=function(e){return this.throwIfDisposed(),Oo(this,e)},kr().prototype.asScalar=function(){return this.throwIfDisposed(),u(1===this.size,(()=>"The array must have only 1 element.")),tl(this,[])},kr().prototype.asType=function(e){return this.throwIfDisposed(),Ja(this,e)},kr().prototype.as1D=function(){return this.throwIfDisposed(),tl(this,[this.size])},kr().prototype.as2D=function(e,t){return this.throwIfDisposed(),tl(this,[e,t])},kr().prototype.as3D=function(e,t,n){return this.throwIfDisposed(),tl(this,[e,t,n])},kr().prototype.as4D=function(e,t,n,s){return this.throwIfDisposed(),tl(this,[e,t,n,s])},kr().prototype.as5D=function(e,t,n,s,r){return this.throwIfDisposed(),tl(this,[e,t,n,s,r])},kr().prototype.asin=function(){return this.throwIfDisposed(),Mo(this)},kr().prototype.asinh=function(){return this.throwIfDisposed(),Lo(this)},kr().prototype.atan=function(){return this.throwIfDisposed(),zo(this)},kr().prototype.atan2=function(e){return this.throwIfDisposed(),Po(this,e)},kr().prototype.atanh=function(){return this.throwIfDisposed(),Bo(this)},kr().prototype.avgPool=function(e,t,n,s){return this.throwIfDisposed(),nl(this,e,t,n,s)},kr().prototype.batchToSpaceND=function(e,t){return this.throwIfDisposed(),ul(this,e,t)},kr().prototype.batchNorm=function(e,t,n,s,r){return this.throwIfDisposed(),cl(this,e,t,n,s,r)},kr().prototype.broadcastTo=function(e){return this.throwIfDisposed(),gl(this,e)},kr().prototype.cast=function(e){return this.throwIfDisposed(),Ja(this,e)},kr().prototype.ceil=function(){return this.throwIfDisposed(),yl(this)},kr().prototype.clipByValue=function(e,t){return this.throwIfDisposed(),xl(this,e,t)},kr().prototype.concat=function(e,t){return this.throwIfDisposed(),e instanceof vr&&(e=[e]),rl([this,...e],t)},kr().prototype.conv1d=function(e,t,n,s,r,a){return this.throwIfDisposed(),Sl(this,e,t,n,s,r,a)},kr().prototype.conv2dTranspose=function(e,t,n,s,r){return this.throwIfDisposed(),Cl(this,e,t,n,s,r)},kr().prototype.conv2d=function(e,t,n,s,r,a){return this.throwIfDisposed(),Il(this,e,t,n,s,r,a)},kr().prototype.cos=function(){return this.throwIfDisposed(),Rl(this)},kr().prototype.cosh=function(){return this.throwIfDisposed(),_l(this)},kr().prototype.cumprod=function(e,t,n){return this.throwIfDisposed(),Fl(this,e,t,n)},kr().prototype.cumsum=function(e,t,n){return this.throwIfDisposed(),Dl(this,e,t,n)},kr().prototype.depthToSpace=function(e,t){return this.throwIfDisposed(),Ml(this,e,t)},kr().prototype.depthwiseConv2d=function(e,t,n,s,r,a){return this.throwIfDisposed(),Ll(this,e,t,n,s,r,a)},kr().prototype.dilation2d=function(e,t,n,s,r){return this.throwIfDisposed(),Pl(this,e,t,n,s,r)},kr().prototype.divNoNan=function(e){return this.throwIfDisposed(),Ul(this,e)},kr().prototype.div=function(e){return this.throwIfDisposed(),To(this,e)},kr().prototype.dot=function(e){return this.throwIfDisposed(),Gl(this,e)},kr().prototype.elu=function(){return this.throwIfDisposed(),jl(this)},kr().prototype.equal=function(e){return this.throwIfDisposed(),Bl(this,e)},kr().prototype.erf=function(){return this.throwIfDisposed(),ql(this)},kr().prototype.euclideanNorm=function(e,t){return this.throwIfDisposed(),hu(this,e,t)},kr().prototype.exp=function(){return this.throwIfDisposed(),pu(this)},kr().prototype.expandDims=function(e){return this.throwIfDisposed(),du(this,e)},kr().prototype.expm1=function(){return this.throwIfDisposed(),fu(this)},kr().prototype.fft=function(){return this.throwIfDisposed(),oh(this)},kr().prototype.flatten=function(){return this.throwIfDisposed(),tl(this,[this.size])},kr().prototype.floor=function(){return this.throwIfDisposed(),yu(this)},kr().prototype.floorDiv=function(e){return this.throwIfDisposed(),So(this,e)},kr().prototype.gather=function(e,t){return this.throwIfDisposed(),bu(this,e,t)},kr().prototype.greaterEqual=function(e){return this.throwIfDisposed(),wu(this,e)},kr().prototype.greater=function(e){return this.throwIfDisposed(),xu(this,e)},kr().prototype.ifft=function(){return this.throwIfDisposed(),lh(this)},kr().prototype.irfft=function(){return this.throwIfDisposed(),uh(this)},kr().prototype.isFinite=function(){return this.throwIfDisposed(),vu(this)},kr().prototype.isInf=function(){return this.throwIfDisposed(),ku(this)},kr().prototype.isNaN=function(){return this.throwIfDisposed(),Nu(this)},kr().prototype.leakyRelu=function(e){return this.throwIfDisposed(),Iu(this,e)},kr().prototype.lessEqual=function(e){return this.throwIfDisposed(),Tu(this,e)},kr().prototype.less=function(e){return this.throwIfDisposed(),Su(this,e)},kr().prototype.localResponseNormalization=function(e,t,n,s){return this.throwIfDisposed(),$u(this,e,t,n,s)},kr().prototype.logSigmoid=function(){return this.throwIfDisposed(),Ou(this)},kr().prototype.logSoftmax=function(e){return this.throwIfDisposed(),Lu(this,e)},kr().prototype.logSumExp=function(e,t){return this.throwIfDisposed(),zu(this,e,t)},kr().prototype.log=function(){return this.throwIfDisposed(),Eu(this)},kr().prototype.log1p=function(){return this.throwIfDisposed(),Au(this)},kr().prototype.logicalAnd=function(e){return this.throwIfDisposed(),Pu(this,e)},kr().prototype.logicalNot=function(){return this.throwIfDisposed(),Bu(this)},kr().prototype.logicalOr=function(e){return this.throwIfDisposed(),Wu(this,e)},kr().prototype.logicalXor=function(e){return this.throwIfDisposed(),Vu(this,e)},kr().prototype.matMul=function(e,t,n){return this.throwIfDisposed(),bi(this,e,t,n)},kr().prototype.maxPool=function(e,t,n,s){return this.throwIfDisposed(),ju(this,e,t,n,s)},kr().prototype.max=function(e,t){return this.throwIfDisposed(),nu(this,e,t)},kr().prototype.maximum=function(e){return this.throwIfDisposed(),Xu(this,e)},kr().prototype.mean=function(e,t){return this.throwIfDisposed(),Yu(this,e,t)},kr().prototype.min=function(e,t){return this.throwIfDisposed(),su(this,e,t)},kr().prototype.minimum=function(e){return this.throwIfDisposed(),ec(this,e)},kr().prototype.mirrorPad=function(e,t){return this.throwIfDisposed(),tc(this,e,t)},kr().prototype.mod=function(e){return this.throwIfDisposed(),nc(this,e)},kr().prototype.mul=function(e){return this.throwIfDisposed(),Co(this,e)},kr().prototype.neg=function(){return this.throwIfDisposed(),Ai(this)},kr().prototype.norm=function(e,t,n){return this.throwIfDisposed(),cu(this,e,t,n)},kr().prototype.notEqual=function(e){return this.throwIfDisposed(),ic(this,e)},kr().prototype.oneHot=function(e,t=1,n=0){return this.throwIfDisposed(),xi(this,e,t,n)},kr().prototype.onesLike=function(){return this.throwIfDisposed(),oc(this)},kr().prototype.pad=function(e,t){return this.throwIfDisposed(),uc(this,e,t)},kr().prototype.pool=function(e,t,n,s,r,a){return this.throwIfDisposed(),mc(this,e,t,n,s,r,a)},kr().prototype.pow=function(e){return this.throwIfDisposed(),ru(this,e)},kr().prototype.prelu=function(e){return this.throwIfDisposed(),gc(this,e)},kr().prototype.prod=function(e,t){return this.throwIfDisposed(),yc(this,e,t)},kr().prototype.reciprocal=function(){return this.throwIfDisposed(),Bc(this)},kr().prototype.relu=function(){return this.throwIfDisposed(),Wc(this)},kr().prototype.relu6=function(){return this.throwIfDisposed(),Vc(this)},kr().prototype.reshapeAs=function(e){return this.throwIfDisposed(),tl(this,e.shape)},kr().prototype.reshape=function(e){return this.throwIfDisposed(),tl(this,e)},kr().prototype.resizeBilinear=function(e,t,n){return this.throwIfDisposed(),kp(this,e,t,n)},kr().prototype.resizeNearestNeighbor=function(e,t,n){return this.throwIfDisposed(),Np(this,e,t,n)},kr().prototype.reverse=function(e){return this.throwIfDisposed(),Uc(this,e)},kr().prototype.rfft=function(){return this.throwIfDisposed(),hh(this)},kr().prototype.round=function(){return this.throwIfDisposed(),Kc(this)},kr().prototype.rsqrt=function(){return this.throwIfDisposed(),Xc(this)},kr().prototype.selu=function(){return this.throwIfDisposed(),Yc(this)},kr().prototype.separableConv2d=function(e,t,n,s,r,a){return this.throwIfDisposed(),Zc(this,e,t,n,s,r,a)},kr().prototype.sigmoid=function(){return this.throwIfDisposed(),al(this)},kr().prototype.sign=function(){return this.throwIfDisposed(),Qc(this)},kr().prototype.sin=function(){return this.throwIfDisposed(),eh(this)},kr().prototype.sinh=function(){return this.throwIfDisposed(),th(this)},kr().prototype.slice=function(e,t){return this.throwIfDisposed(),il(this,e,t)},kr().prototype.softmax=function(e){return this.throwIfDisposed(),ih(this,e)},kr().prototype.softplus=function(){return this.throwIfDisposed(),Du(this)},kr().prototype.spaceToBatchND=function(e,t){return this.throwIfDisposed(),fc(this,e,t)},kr().prototype.split=function(e,t){return this.throwIfDisposed(),ch(this,e,t)},kr().prototype.sqrt=function(){return this.throwIfDisposed(),iu(this)},kr().prototype.square=function(){return this.throwIfDisposed(),ou(this)},kr().prototype.squaredDifference=function(e){return this.throwIfDisposed(),ph(this,e)},kr().prototype.squeeze=function(e){return this.throwIfDisposed(),dh(this,e)},kr().prototype.stack=function(e,t){this.throwIfDisposed();const n=e instanceof vr?[this,e]:[this,...e];return fh(n,t)},kr().prototype.step=function(e){return this.throwIfDisposed(),mh(this,e)},kr().prototype.stridedSlice=function(e,t,n,s,r,a,i,o){return this.throwIfDisposed(),gh(this,e,t,n,s,r,a,i,o)},kr().prototype.sub=function(e){return this.throwIfDisposed(),Mu(this,e)},kr().prototype.sum=function(e,t){return this.throwIfDisposed(),lu(this,e,t)},kr().prototype.tan=function(){return this.throwIfDisposed(),yh(this)},kr().prototype.tanh=function(){return this.throwIfDisposed(),ol(this)},kr().prototype.tile=function(e){return this.throwIfDisposed(),mu(this,e)},kr().prototype.toBool=function(){return this.throwIfDisposed(),Ja(this,"bool")},kr().prototype.toFloat=function(){return this.throwIfDisposed(),Ja(this,"float32")},kr().prototype.toInt=function(){return this.throwIfDisposed(),Ja(this,"int32")},kr().prototype.topk=function(e,t){return this.throwIfDisposed(),Nh(this,e,t)},kr().prototype.transpose=function(e){return this.throwIfDisposed(),_i(this,e)},kr().prototype.unique=function(e){return this.throwIfDisposed(),Sh(this,e)},kr().prototype.unsortedSegmentSum=function(e,t){return this.throwIfDisposed(),Th(this,e,t)},kr().prototype.unstack=function(e){return this.throwIfDisposed(),Ch(this,e)},kr().prototype.where=function(e,t){return this.throwIfDisposed(),Wl(e,this,t)},kr().prototype.zerosLike=function(){return this.throwIfDisposed(),Vl(this)};class Dm extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Dm.prototype)}}class Om extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Om.prototype)}}class Mm extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Mm.prototype)}}class Lm extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Lm.prototype)}}class zm extends Error{constructor(e){super(e),Object.setPrototypeOf(this,zm.prototype)}}Error;class Pm{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 Bm(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 Wm(e,t){if(!e)throw new zm(t)}function Vm(e,t){let n=0;for(const s of e)s===t&&n++;return n}function Um(e){return 1===e.length?e[0]:e}function Gm(e){return Array.isArray(e)?e:[e]}function Hm(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 jm(e){return e.length<=1||-1===e.indexOf("_")?e:e.replace(/[_]+(\w|$)/g,((e,t)=>t.toUpperCase()))}let qm={};function Km(e){if(null==e)return null;const t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function Xm(e){if(null!=e&&"object"==typeof e)if(Array.isArray(e))e.forEach((e=>Xm(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?Xm(t):e[n]=t.value)}}}function Ym(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 qm)a=qm[r];else if(a=t[r],null==a)throw new Mm(`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 Mm(`${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 qm?[o,l]=qm.className:i in t&&([o,l]=t[i]),null==o)throw new Mm(`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(qm))e[t]=qm[t];for(const t of Object.keys(n))e[t]=n[t];a.config.customObjects=e;const t=Object.assign({},qm);for(const e of Object.keys(n))qm[e]=n[e];Xm(a.config);const s=l(o,a.config,n,r);return qm=Object.assign({},t),s}{const e=Object.assign({},qm);for(const e of Object.keys(n))qm[e]=n[e];const t=new o(a.config);return qm=Object.assign({},e),t}}}function Zm(e,t){return-1*function(e,t){return e<t?-1:e>t?1:0}(e,t)}function Jm(e){if(null==e)return e;const t=[];for(const n of e)-1===t.indexOf(n)&&t.push(n);return t}function Qm(e){if(null==e)throw new Mm(`Invalid value in obj: ${JSON.stringify(e)}`);for(const t in e)if(e.hasOwnProperty(t))return!1;return!0}function eg(e,t,n){if(null!=n&&e.indexOf(n)<0)throw new Mm(`${n} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function tg(e,t,n=0,s=1/0){return Wm(n>=0),Wm(s>=n),Array.isArray(e)&&e.length>=n&&e.length<=s&&e.every((e=>typeof e===t))}function ng(e,t){Array.isArray(e)?(u(e.length>0,(()=>`${t} is unexpectedly an empty array.`)),e.forEach(((e,n)=>ng(e,`element ${n+1} of ${t}`)))):u(Number.isInteger(e)&&e>0,(()=>`Expected ${t} to be a positive integer, but got ${sg(e)}.`))}function sg(e){return null===e?"null":Array.isArray(e)?"["+e.map((e=>sg(e))).join(",")+"]":"string"==typeof e?`"${e}"`:`${e}`}function rg(e){return"relu"===e?"relu":"linear"===e?"linear":"elu"===e?"elu":null}let ag=0;function ig(){return ag++}const og={};function lg(e=""){return e in og||(og[e]=0),og[e]+=1,e+og[e].toString()}const ug=["channelsFirst","channelsLast"],cg=["nearest","bilinear"],hg=["valid","same","causal"],pg=["max","avg"],dg=["sum","mul","concat","ave"],fg=new Map;function mg(e){eg(ug,"DataFormat",e)}function gg(e){eg(hg,"PaddingMode",e)}function yg(e){eg(pg,"PoolMode",e)}const bg=[];function xg(e,t){bg.push(e);try{const e=t();return bg.pop(),e}catch(e){throw bg.pop(),e}}function wg(e){if(!Ng(e))throw new Error("Not a valid tensor name: '"+e+"'");return(0===bg.length?"":bg.join("/")+"/")+e}function vg(e){if(!Ng(e))throw new Error("Not a valid tensor name: '"+e+"'");fg.has(e)||fg.set(e,0);const t=fg.get(e);if(fg.set(e,fg.get(e)+1),t>0){const n=`${e}_${t}`;return fg.set(n,1),n}return e}const kg=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function Ng(e){return!!e.match(kg)}function Ig(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 Sg(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 Tg(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 Cg(e,t){if(t<e)throw new Mm(`end (${t}) < begin (${e}) is forbidden.`);const n=[];for(let s=e;s<t;++s)n.push(s);return n}let $g;function Eg(){return null==$g&&($g=$i().epsilon()),$g}function Ag(e,t){return Ja(e,t)}function Rg(e,t=-1){const n=e.shape.slice();return t<0&&(t=n.length+t+1),n.splice(t,0,1),tl(e,n)}function _g(e,t,n){return Ni((()=>{switch(e.rank){case 1:return nh(e,t,n);case 2:return sh(e,[t,0],[n,e.shape[1]]);case 3:return rh(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return ah(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return il(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return il(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 Mm(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Fg(e,t,n){return Ni((()=>{switch(e.rank){case 1:return nh(e,t,n);case 2:return sh(e,[0,t],[e.shape[0],n]);case 3:return rh(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return ah(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new Mm(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Dg(e,t,n,s){return Ni((()=>{switch(e.rank){case 1:return nh(e,t,n);case 2:switch(s){case 1:return _g(e,t,n);case 2:return Fg(e,t,n);default:throw new Mm(`The axis is not within the rank of the tensor ${s}`)}case 3:switch(s){case 1:return _g(e,t,n);case 2:return rh(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return Fg(e,t,n);default:throw new Mm(`The axis is not within the rank of the tensor ${s}`)}case 4:switch(s){case 1:return _g(e,t,n);case 2:return ah(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return ah(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return Fg(e,t,n);default:throw new Mm(`The axis is not within the rank of the tensor ${s}`)}default:throw new Mm(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}}))}function Og(e,t=-1){let n;return t<0&&(n=e[0].rank,t=0!==n?n:0),t===e[0].rank&&(t=-1),rl(e,t)}function Mg(e,t){switch(e.rank){case 1:return wl([e,t]);case 2:return vl([e,t],0);case 3:return kl([e,t],0);case 4:return Nl([e,t],0);default:throw new Mm(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function Lg(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new Mm(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return mu(e,t)}function zg(e,t=0,n=1,s,r){return Mc(e,t,n,s,r)}function Pg(e,t,n,s){if(e.rank<2||t.rank<2)throw new Lm(`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 Lm(`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 Yh({a:e,b:t,transposeA:!1,transposeB:!1,bias:s?Vg(e.rank,s,"channelsLast"):null,activation:n})}{const r=e.shape.slice(),a=r.pop();e=tl(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=tl(_i(t,c),[l,-1]);const h=[...r,...u];return tl(Yh({a:e,b:t,transposeA:!1,transposeB:!1,bias:s?Vg(e.rank,s,"channelsLast"):null,activation:n}),h)}}function Bg(e,t,n){return Ni((()=>(t=Array.isArray(t)?bh(t,"int32"):Ja(t,"int32"),bu(e,t,n))))}function Wg(e){return Co(e,e)}function Vg(e,t,n){const s=t.shape;if(1!==t.rank&&t.rank!==e)throw new Mm(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(5===e){if("channelsFirst"===n)return 1===s.length?tl(t,[1,s[0],1,1,1]):tl(t,[1,s[3],s[0],s[1],s[2]]);if("channelsLast"===n)return 1===s.length?tl(t,[1,1,1,1,s[0]]):tl(t,[1].concat(s))}else if(4===e){if("channelsFirst"===n)return 1===s.length?tl(t,[1,s[0],1,1]):tl(t,[1,s[2],s[0],s[1]]);if("channelsLast"===n)return 1===s.length?tl(t,[1,1,1,s[0]]):tl(t,[1].concat(s))}else if(3===e){if("channelsFirst"===n)return 1===s.length?tl(t,[1,s[0],1]):tl(t,[1,s[1],s[0]]);if("channelsLast"===n)return 1===s.length?tl(t,[1,1,s[0]]):tl(t,[1].concat(s))}else if(e<3)return t;throw new Mm(`Unsupported input rank by biasAdd: ${t.rank}`)}function Ug(e,t,n){return Ni((()=>(null==n&&(n="channelsLast"),mg(n),Io(e,Vg(e.rank,t,n)))))}function Gg(e,t,n,s){return Ni((()=>Lh(e,t,n,s)))}function Hg(e,t,n=!1){return n?e():t()}const jg=["fanIn","fanOut","fanAvg"],qg=["normal","uniform","truncatedNormal"];class Kg extends fo{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}}class Xg extends Kg{apply(e,t){return Zu(e,t)}}Xg.className="Zeros",go(Xg);class Yg extends Kg{apply(e,t){return Ju(e,t)}}Yg.className="Ones",go(Yg);class Zg extends Kg{constructor(e){if(super(),"object"!=typeof e)throw new Mm(`Expected argument of type ConstantConfig but got ${e}`);if(void 0===e.value)throw new Mm(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return Ni((()=>Co(au(this.value),Ju(e,t))))}getConfig(){return{value:this.value}}}Zg.className="Constant",go(Zg);class Jg extends Kg{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 zc(e,this.minval,this.maxval,t)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}}Jg.className="RandomUniform",go(Jg);class Qg extends Kg{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 Lm(`randomNormal does not support dType ${t}.`);return zg(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}Qg.className="RandomNormal",go(Qg);class ey extends Kg{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 Lm(`truncatedNormal does not support dType ${t}.`);return Ih(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}}ey.className="TruncatedNormal",go(ey);class ty extends Kg{constructor(e){super(),this.gain=null!=e.gain?e.gain:1}apply(e,t){return Ni((()=>{if(2!==e.length||e[0]!==e[1])throw new Mm("Identity matrix initializer can only be used for 2D square matrices.");return Co(this.gain,gu(e[0]))}))}getConfig(){return{gain:this.gain}}}ty.className="Identity",go(ty);class ny extends Kg{constructor(e){if(super(),e.scale<0)throw new Mm(`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,eg(jg,"FanMode",t),this.distribution=null==e.distribution?"normal":e.distribution,function(e){eg(qg,"Distribution",e)}(this.distribution),this.seed=e.seed}apply(e,t){const n=function(e,t="channelsLast"){let n,s;if(mg(t),2===e.length)n=e[0],s=e[1];else if(-1!==[3,4,5].indexOf(e.length)){if("channelsFirst"===t){const t=Ig(e,2);n=e[1]*t,s=e[0]*t}else if("channelsLast"===t){const t=Ig(e,0,e.length-2);n=e[e.length-2]*t,s=e[e.length-1]*t}}else{const t=Ig(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 Lm(`${this.getClassName()} does not support dType ${t}.`);return Ih(e,0,n,t,this.seed)}{const n=Math.sqrt(3*a);return zc(e,-n,n,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}}ny.className="VarianceScaling",go(ny);class sy extends ny{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return ny.className}}sy.className="GlorotUniform",go(sy);class ry extends ny{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return ny.className}}ry.className="GlorotNormal",go(ry);class ay extends ny{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return ny.className}}ay.className="HeNormal",go(ay);class iy extends ny{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return ny.className}}iy.className="HeUniform",go(iy);class oy extends ny{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:null==e?null:e.seed})}getClassName(){return ny.className}}oy.className="LeCunNormal",go(oy);class ly extends ny{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:null==e?null:e.seed})}getClassName(){return ny.className}}ly.className="LeCunNormal",go(ly);class uy extends Kg{constructor(e){if(super(),this.DEFAULT_GAIN=1,this.gain=null==e.gain?this.DEFAULT_GAIN:e.gain,this.seed=e.seed,null!=this.seed)throw new Lm("Random seed is not implemented for Orthogonal Initializer yet.")}apply(e,t){return Ni((()=>{if(e.length<2)throw new Lm("Shape must be at least 2D.");e[0]*e[1]>2e3&&console.warn(`Orthogonal initializer is being called on a matrix with more than 2000 (${e[0]*e[1]}) elements: Slowness may result.`);const t=zg(e[0]>e[1]?[e[1],e[0]]:e,0,1,"float32");let n=Yp.gramSchmidt(t);return e[0]>e[1]&&(n=_i(n)),Co(this.gain,n)}))}getConfig(){return{gain:this.gain,seed:this.seed}}}uy.className="Orthogonal",go(uy);const cy={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 hy(e,t={}){return Ym(e,mo.getMap().classNameMap,t,"initializer")}function py(e){return Km(e)}function dy(e){if("string"==typeof e){const t=e in cy?cy[e]:e;if("GlorotNormal"===t)return new ry;if("GlorotUniform"===t)return new sy;if("HeNormal"===t)return new ay;if("HeUniform"===t)return new iy;if("LeCunNormal"===t)return new oy;if("LeCunUniform"===t)return new ly;{const e={};return e.className=t,e.config={},hy(e)}}return e instanceof Kg?e:hy(e)}function fy(e){return Array.isArray(e)&&Array.isArray(e[0])}function my(e){return 0===e.length?[]:Array.isArray(e[0])?e:[e]}function gy(e){let t;if(Array.isArray(e)){if(1!==e.length)throw new Mm(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function yy(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(1===e.length)return e[0];throw new Mm(`Expected exactly 1 Shape; got ${e.length}`)}return e}function by(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 xy="Variable";class wy{constructor(e,t="float32",n="Variable",s=!0,r=null){this.dtype=null==t?"float32":t,this.shape=e.shape,this.id=ig(),n=null==n?xy:n,this.originalName=wg(n),this.name=vg(this.originalName),this.trainable_=s,this.constraint=r,this.val=Eh(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 vy(e){return e.map((e=>e.read()))}function ky(e){e.forEach((e=>{e[0].write(e[1])}))}class Ny{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 Iy{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=ig(),null!=a&&(this.originalName=wg(a),this.name=vg(this.originalName)),this.rank=t.length}}let Sy=0;class Ty{constructor(e,t){this.callArgs=t,this.id=Sy++,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 Cy=0;class $y extends fo{constructor(e={}){super(),this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=Cy++,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=Hm(e)+"_"+lg(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 Om(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new Mm(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return Um(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return Um(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new Dm(`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 Dm(`Layer ${this.name} is not connected, no input to return.`);return Um(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(0===this.inboundNodes.length)throw new Dm(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new Dm(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return Um(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){if(e=Gm(e),null==this.inputSpec||0===this.inputSpec.length)return;const t=Gm(this.inputSpec);if(e.length!==t.length)throw new Mm(`Layer ${this.name} expects ${t.length} inputs, but it received ${e.length} input tensors. Input received: ${e}`);for(let n=0;n<e.length;n++){const s=e[n],r=t[n];if(null==r)continue;const a=s.rank;if(null!=r.ndim&&a!==r.ndim)throw new Mm(`Input ${n} is incompatible with layer ${this.name}: expected ndim=${r.ndim}, found ndim=${a}`);if(null!=r.maxNDim&&a>r.maxNDim)throw new Mm(`Input ${n} is incompatible with layer ${this.name}: expected max_ndim=${r.maxNDim}, found ndim=${a}`);if(null!=r.minNDim&&a<r.minNDim)throw new Mm(`Input ${n} is incompatible with layer ${this.name}: expected min_ndim=${r.minNDim}, found ndim=${a}.`);if(null!=r.dtype&&s.dtype!==r.dtype)throw new Mm(`Input ${n} is incompatible with layer ${this.name} : expected dtype=${r.dtype}, found dtype=${s.dtype}.`);if(r.axes){const e=s.shape;for(const t in r.axes){const s=Number(t),a=r.axes[t],i=s>=0?e[s]:e[e.length+s];if(null!=a&&-1===[a,null].indexOf(i))throw new Mm(`Input ${n} is incompatible with layer ${this.name}: expected axis ${s} of input shape to have value ${a} but got shape ${e}.`)}}if(null!=r.shape)for(let e=0;e<r.shape.length;++e){const t=r.shape[e],a=s.shape[e];if(null!=t&&null!=a&&t!==a)throw new Mm(`Input ${n} 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=Gm(e);let s=!0;for(const e of n)if(!(e instanceof Iy)){s=!1;break}let r=!0;for(const e of n)if(e instanceof Iy){r=!1;break}if(s===r)throw new Mm("Arguments to apply() must be all SymbolicTensors or all Tensors");return xg(this.name,(()=>{if(!this.built){this.assertInputCompatibility(e);const t=[];for(const n of Gm(e))t.push(n.shape);this.build(Um(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);const r=Gm(s),a=[];for(let e of r)-1!==n.indexOf(e)&&(e=e.clone()),a.push(e);if(s=Um(a),null!=this.activityRegularizer)throw new Lm("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return s}{const n=function(e){e=Gm(e);const t=[];for(const n of e)t.push(n.shape);return Um(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 Iy(a,n,this,Gm(e),t,this.name,s))):new Iy(a,s,this,Gm(e),t,this.name),this.addInboundNode(e,r,null,null,n,s,t),this._refCount++,null!=this.activityRegularizer)throw new Lm("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 Dm(`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 Dm(`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 Om(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return by(this.weights)}build(e){this.built=!0}getWeights(e=!1){return vy(e?this.trainableWeights:this.weights)}setWeights(e){Ni((()=>{const t=this.weights;if(t.length!==e.length)throw new Mm(`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=vy(t);for(let r=0;r<s.length;++r){const a=s[r],i=t[r],o=e[r];if(!f(a.shape,o.shape))throw new Mm(`Layer weight shape ${a.shape} not compatible with provided weight shape ${o.shape}`);n.push([i,o])}ky(n)}))}addWeight(e,t,n,s,r,a,i,o){if(-1!==this._addedWeightNames.indexOf(e))throw new Mm(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),null==n&&(n="float32"),this.fastWeightInitDuringBuild&&(s=null!=o?o():dy("zeros"));const l=s.apply(t,n),u=new wy(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=Gm(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}addInboundNode(e,t,n,s,r,a,i=null){const o=Gm(e);t=Gm(t),n=Gm(n),s=Gm(s),r=my(r),a=my(a);const l=[],u=[],c=[];for(const e of o)l.push(e.sourceLayer),u.push(e.nodeIndex),c.push(e.tensorIndex);new Ty({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 Ey(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=Ey(e.inputTensors[n],e.inboundLayers[n],e.nodeIndices[n]);for(const e of s)-1===t.indexOf(e)&&t.push(e)}return t}}}class Ay extends $y{constructor(e){if(super({dtype:e.dtype,name:null!=e.name?e.name:lg("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 Mm("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 Mm("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(null!=e.batchSize)throw new Mm("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 Iy(this.dtype,this.batchInputShape,this,[],{},this.name);s.nodeIndex=0,s.tensorIndex=0,new Ty({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[s],outputTensors:[s],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new Mm(`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 Ry(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 Mm("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 Ay({batchInputShape:t,name:e.name,dtype:n,sparse:e.sparse}).inboundNodes[0].outputTensors[0]}Ay.className="InputLayer",go(Ay);class _y{constructor(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof _y)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 Mm(`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 Ja(t,e.dtype)}catch(n){throw new Mm(`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 Iy){if(null==this.id2Value[e.id])throw new Mm(`Nonexistent key: ${e.name}`);return this.id2Value[e.id]}{const t=this.name2Id[e];if(null==t)throw new Mm(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Value[t]}}getMask(e){if(e instanceof Iy){if(null==this.id2Value[e.id])throw new Mm(`Nonexistent key: ${e.name}`);return this.id2Mask[e.id]}{const t=this.name2Id[e];if(null==t)throw new Mm(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Mask[t]}}disposeMasks(){null!=this.id2Mask&&Ii(this.id2Mask)}}const Fy=new Pm,Dy=new Pm;function Oy(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=[],c=t.names();for(const e of o)-1!==c.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=Fy.get(h);if(null==d){const e=function(e,t){u(null!=e&&e.length>0,(()=>"Expected at least one fetch, got none"));let n=[],s={};if(1===e.length){const r=Ly(e[0],t);n=r.sorted,s=r.recipientMap}else{const r=new Set;for(const a of e){const{sorted:e,recipientMap:i}=Ly(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:My(s)}}(i,t);d=e.sorted,p=e.recipientCounts,Fy.put(h,d),Dy.put(h,p)}p={},r||Object.assign(p,Dy.get(h));const f=new _y(t);for(let e=0;e<d.length;++e){if(null!=s){const e=ki().numTensors;e>s.maxNumTensors&&(s.maxNumTensors=e),e<s.minNumTensors&&(s.minNumTensors=e)}const a=d[e],i=a.sourceLayer;if(i instanceof Ay)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=Gm(i.apply(u,n));let y=null;i.supportsMasking&&(y=i.computeMask(u,c));const b=zy(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||Ii(h)}return f.disposeMasks(),a?l:l[0]}function My(e){const t={};for(const n in e)t[n]=e[n].size;return t}function Ly(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 zy(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 Py(e,t){return Ni((()=>iu(lu(Co(e,e),t,!0))))}X().registerFlag("TOPOLOGICAL_SORT_CACHE_MAX_ENTRIES",(()=>100),(function(e){null!=Fy&&Fy.setMaxEntries(e),null!=Dy&&Dy.setMaxEntries(e)}));class By extends fo{getConfig(){return{}}}class Wy extends By{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 Ni((()=>{const t=Py(e,this.axis),n=xl(t,0,this.maxValue);return Co(e,To(n,Io(Eg(),t)))}))}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}}Wy.className="MaxNorm",go(Wy);class Vy extends By{constructor(e){super(),this.defaultAxis=0,this.axis=null!=e.axis?e.axis:this.defaultAxis}apply(e){return Ni((()=>To(e,Io(Eg(),Py(e,this.axis)))))}getConfig(){return{axis:this.axis}}}Vy.className="UnitNorm",go(Vy);class Uy extends By{apply(e){return Wc(e)}}Uy.className="NonNeg",go(Uy);class Gy extends By{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 Ni((()=>{const t=Py(e,this.axis),n=Io(Co(this.rate,xl(t,this.minValue,this.maxValue)),Co(1-this.rate,t));return Co(e,To(n,Io(Eg(),t)))}))}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}}Gy.className="MinMaxNorm",go(Gy);const Hy={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function jy(e){return Km(e)}function qy(e,t={}){return Ym(e,mo.getMap().classNameMap,t,"constraint")}function Ky(e){if(null==e)return null;if("string"==typeof e){return qy({className:e in Hy?Hy[e]:e,config:{}})}return e instanceof By?e:qy(e)}var Xy=Object.freeze({__proto__:null,maxNorm:function(e){return new Wy(e)},unitNorm:function(e){return new Vy(e)},nonNeg:function(){return new Uy},minMaxNorm:function(e){return new Gy(e)}});var Yy,Zy=Object.freeze({__proto__:null,zeros:function(){return new Xg},ones:function(){return new Yg},constant:function(e){return new Zg(e)},randomUniform:function(e){return new Jg(e)},randomNormal:function(e){return new Qg(e)},truncatedNormal:function(e){return new ey(e)},identity:function(e){return new ty(e)},varianceScaling:function(e){return new ny(e)},glorotUniform:function(e){return new sy(e)},glorotNormal:function(e){return new ry(e)},heNormal:function(e){return new ay(e)},heUniform:function(e){return new iy(e)},leCunNormal:function(e){return new oy(e)},leCunUniform:function(e){return new ly(e)},orthogonal:function(e){return new uy(e)}});async function Jy(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];Ii(s)}}function Qy(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"}(Yy||(Yy={}));class eb{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 tb{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 nb extends eb{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=Ni((()=>Io(this.totals[e],Co(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:Ni((()=>{const n=Co(To(1,this.seen),this.totals[e]);t[e]=n,this.totals[e].dispose(),Si(t[e])})))}}class sb extends eb{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 rb extends eb{constructor(e,t){if(super(),this.currentEpoch=0,this.nowFunc=e.nowFunc,this.nextFrameFunc=e.nextFrameFunc||hd,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():rr();return(...a)=>{const i=null!=n?n():rr();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 Jy(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 Jy(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){const n=[];null!=this.epochEnd&&(await Jy(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 Jy(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){const n=[];null!=this.batchEnd&&(await Jy(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 Jy(e),await this.trainBegin(e))}async onTrainEnd(e){null!=this.trainEnd&&(await Jy(e),await this.trainEnd(e))}}function ab(e,t){if(null==e&&(e={}),e instanceof eb)return[e];if(Array.isArray(e)&&e[0]instanceof eb)return e;return Gm(e).map((e=>new rb(e,t)))}class ib{constructor(){}static registerCallbackConstructor(e,t){u(e>=0&&Number.isInteger(e),(()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`)),ib.checkForDuplicate(t),null==ib.constructors[e]&&(ib.constructors[e]=[]),ib.constructors[e].push(t)}static checkForDuplicate(e){for(const t in ib.constructors){ib.constructors[+t].forEach((t=>{if(t===e)throw new Mm("Duplicate callback constructor.")}))}}static clear(){ib.constructors={}}static createCallbacks(e){const t=[];for(const n in ib.constructors){const s=+n;e>=s&&t.push(...ib.constructors[s])}return t.map((e=>new e))}}function ob(e,t,n,s,r,a,i,o,l){const u=new sb,c=[new nb,...ib.createCallbacks(t)];null!=e&&c.push(...e),c.push(u);const h=new tb(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 lb(e,t={},n=!1){return Ym(e,mo.getMap().classNameMap,t,"layer",n)}function ub(e,t){return Ni((()=>{"float32"!==e.dtype&&(e=Ja(e,"float32"));const n=lu(Wg(e),t,!0),s=bl(n.shape,Eg()),r=iu(Xu(n,s));return To(e,r)}))}function cb(e,t){return Ni((()=>Yu(Wg(Mu(t,e)),-1)))}function hb(e,t){return Ni((()=>Yu($o(Mu(t,e)),-1)))}function pb(e,t){return Ni((()=>{const n=Mu(e,t),s=xl($o(e),Eg(),Number.MAX_VALUE),r=$o(To(n,s));return Co(100,Yu(r,-1))}))}function db(e,t){return Ni((()=>{const n=xl(t,Eg(),Number.MAX_VALUE),s=Eu(Io(1,n)),r=xl(e,Eg(),Number.MAX_VALUE),a=Eu(Io(1,r));return Yu(Wg(Mu(s,a)),-1)}))}function fb(e,t,n=!1){return Ni((()=>{if(n)t=ih(t);else{const e=lu(t,t.shape.length-1,!0);t=To(t,e)}return t=xl(t,Eg(),1-Eg()),Ai(lu(Co(Ja(e,"float32"),Eu(t)),t.shape.length-1))}))}function mb(e,t,n=!1){return Ni((()=>{const s=Ja(yu(function(e){const t=[Ig(e.shape)];return tl(e,t)}(e)),"int32"),r=(t=xl(t,Eg(),1-Eg())).shape;return fb(tl(xi(s,r[r.length-1]),r),t,n)}))}function gb(e,t){return Ni((()=>{let n;return n=xl(t,Eg(),1-Eg()),n=Eu(To(n,Mu(1,n))),Yu(function(e,t){if(!f(e.shape,t.shape))throw new Mm(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return Ni((()=>{const n=Wc(t),s=Ai($o(t));return Io(Mu(n,Co(t,e)),Au(pu(s)))}))}(e,n),-1)}))}function yb(e,t){return Ni((()=>{const n=xl(e,Eg(),1),s=xl(t,Eg(),1);return lu(Co(e,Eu(To(n,s))),-1)}))}function bb(e,t){return Ni((()=>{const n=ub(e,-1),s=ub(t,-1),r=Co(n,s);return Ai(lu(r,-1))}))}ib.constructors={};const xb={meanSquaredError:cb,meanAbsoluteError:hb,meanAbsolutePercentageError:pb,meanSquaredLogarithmicError:db,squaredHinge:function(e,t){return Ni((()=>{const n=Xu(0,Mu(1,Co(e,t)));return Yu(Wg(n),-1)}))},hinge:function(e,t){return Ni((()=>{const n=Xu(0,Mu(1,Co(e,t)));return Yu(n,-1)}))},categoricalHinge:function(e,t){return Ni((()=>{const n=lu(Co(e,t),-1),s=nu(Co(Mu(1,e),t),-1);return Xu(0,Io(1,Mu(s,n)))}))},logcosh:function(e,t){return Ni((()=>{const n=Math.log(2),s=Mu(t,e),r=Mu(Io(s,Du(Co(-2,s))),n);return Yu(r,-1)}))},categoricalCrossentropy:fb,sparseCategoricalCrossentropy:mb,binaryCrossentropy:gb,kullbackLeiblerDivergence:yb,poisson:function(e,t){return Ni((()=>{const n=Eu(Io(Eg(),t));return Yu(Mu(t,Co(e,n)),-1)}))},cosineProximity:bb};function wb(e){if("string"==typeof e){if(e in xb)return xb[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 Mm(t)}return e}function vb(e,t){return Ni((()=>{const n=Co(.5,oc(t)),s=Ag(xu(t,n),e.dtype);return Yu(Bl(e,s),-1)}))}function kb(e,t){return Ni((()=>Ag(Bl(Do(e,-1),Do(t,-1)),"float32")))}function Nb(e,t){return Ni((()=>Ja(lu(Pu(Bl(e,1),Bl(t,1))),"float32")))}function Ib(e,t){return Ni((()=>{const n=Nb(e,t),s=function(e,t){return Ni((()=>Ja(lu(Pu(Bl(e,0),Bl(t,1))),"float32")))}(e,t),r=Io(n,s);return Ja(Wl(xu(r,0),To(n,r),0),"float32")}))}function Sb(e,t){return Ni((()=>{const n=Nb(e,t),s=function(e,t){return Ni((()=>Ja(lu(Pu(Bl(e,1),Bl(t,0))),"float32")))}(e,t),r=Io(n,s);return Ja(Wl(xu(r,0),To(n,r),0),"float32")}))}function Tb(e,t){return gb(e,t)}function Cb(e,t){return e.rank===t.rank&&(e=dh(e,[e.rank-1])),(t=Do(t,-1)).dtype!==e.dtype&&(t=Ja(t,e.dtype)),Ja(Bl(e,t),"float32")}const $b=fb,Eb=mb,Ab={binaryAccuracy:vb,categoricalAccuracy:kb,precision:Ib,categoricalCrossentropy:$b,sparseCategoricalCrossentropy:Eb,mse:cb,MSE:cb,mae:hb,MAE:hb,mape:pb,MAPE:pb,cosine:bb};function Rb(e){if("string"==typeof e&&e in Ab)return Ab[e];if("string"!=typeof e&&null!=e)return e;throw new Mm(`Unknown metric ${e}`)}function _b(e){if(Wm(null!==e,`Unknown LossOrMetricFn ${e}`),"string"==typeof e)return e;{let t;for(const n of Object.keys(xb))if(xb[n]===e){t=n;break}if(void 0!==t)return t;for(const n of Object.keys(Ab))if(Ab[n]===e){t=n;break}return void 0!==t?t:e.name}}const Fb=1048576;function Db(e,t,n=!1){if(null==e||"object"!=typeof e||Object.getPrototypeOf(e)!==Object.prototype||!Ob(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>Fb&&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 Ob(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(!Ob(e[n]))return!1}return!0}if(Array.isArray(e)){for(const t of e)if(!Ob(t))return!1;return!0}return!1}{const t=typeof e;return"string"===t||"number"===t||"boolean"===t}}function Mb(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)),Lb(a,n,s),s("=".repeat(t));const o=e.layers;for(let e=0;e<o.length;++e)r?zb(o[e],n,s):Pb(o[e],n,i,s),s((e===o.length-1?"=":"_").repeat(t));e.checkTrainableWeightsConsistency();const l=function(e){let t;t=null!=e.collectedTrainableWeights?by(e.collectedTrainableWeights):by(e.trainableWeights);return t}(e),u=by(e.nonTrainableWeights);s(`Total params: ${l+u}`),s(`Trainable params: ${l}`),s(`Non-trainable params: ${u}`),s("_".repeat(t))}function Lb(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 zb(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"}Lb([`${e.name} (${e.getClassName()})`,r,s,e.countParams().toString()],t,n)}function Pb(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];Lb([`${o} (${l})`,a,r,e.countParams().toString(),u],t,s);for(let e=1;e<i.length;++e)Lb(["","","","",i[e]],t,s)}function Bb(e,t,n){return("inboundNodes"===e||"outputLayers"===e||"inputLayers"===e)&&0===t&&"string"==typeof n}function Wb(e,t){if(null===e)return null;if("string"==typeof e)return jm(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];Bb(t,r,s)?n.push(s):n.push(Wb(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=jm(n);t[e]=Wb(s,e)}}return t}}function Vb(e,t){if(null==e)return null;if("string"==typeof e)return Hm(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];Bb(t,r,s)?n.push(s):n.push(Vb(s,t))}return n}{const t={};for(const n of Object.keys(e)){const s=e[n],r=Hm(n);t[r]="name"!==n&&"className"!==n||"string"!=typeof s?Vb(s,n):s}return t}}const Ub="4.1.0";class Gb extends $y{constructor(e){if(super({}),this.containerNodes=new Set,this.name=e.name,null==this.name){const e=this.getClassName().toLowerCase();this.name=lg(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],Jm(this.inputs).length!==this.inputs.length)throw new Mm(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map((e=>e.name))}`);Jm(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;Wm(0===n,"input layer has >1 nodes"),Wm(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 Ay))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 Om(`The tensor ${e.name} at layer "${s.name}" is part of a cycle.`);if(-1!==t.indexOf(u))return;this.containerNodes.add(Gb.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(Zm);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 Gb&&this.internalContainerRefs.push(e),this.layers.push(e)}this.layersByDepth=p,d=Object.keys(h).map((e=>parseInt(e,10))).sort(Zm);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 Om(`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 Om(`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 Ty({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 Mm("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;for(const e of this.layers)for(const t of e.weights){if(null!=n[t.originalName])throw new Mm(`Duplicate weight name: ${t.originalName}`);n[t.originalName]=t,s++}const r=[];for(const s in e){let a=s;if(null==n[s]){const e=s.split("/");a=e.slice(0,-2).concat([e[e.length-1]]).join("/")}if(null!=n[a])r.push([n[a],e[s]]);else if(t)throw new Mm(`Provided weight data has no target variable: ${s}`);delete n[a]}if(t){const e=[];for(const t in n)e.push(t);if(e.length>0)throw new Mm(`${e.length} of ${s} weights are not set: ${e}`)}ky(r)}updatedConfig(){const e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion="tfjs-layers 4.1.0",t.backend="TensorFlow.js",t}toJSON(e,t=!0){const n=Vb(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return Ni((()=>{e=Gm(e);const n=new _y;for(let t=0;t<this.inputs.length;++t)n.add(this.inputs[t],e[t]);return Oy(this.outputs,n,t)}))}computeMask(e,t){return Ni((()=>{let n;return e=Gm(e),n=null==t?Bm(null,e.length):Gm(t),this.runInternalGraph(e,n)[1]}))}computeOutputShape(e){const t=my(e);if(t.length!==this.inputLayers.length)throw new Mm(`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(Zm);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=my(t.computeOutputShape(Um(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];Wm(t in n),r.push(n[t])}return Um(r)}runInternalGraph(e,t){null==t&&(t=Bm(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(Zm);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=Gm(t.call(e,u)),l=Gm(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=Gm(t.call(s,u)),l=Gm(t.computeMask(s,i));if(t.activityRegularizer)throw new Lm("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){Wm(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 Gb?1:0;for(let s=0;s<e.inboundNodes.length;s++){const r=Gb.nodeKey(e,s);this.containerNodes.has(r)&&(t[r]=n,n+=1)}}return t}getLayer(e,t){if(null!=t){if(this.layers.length<=t)throw new Mm(`Was asked to retrieve layer at index ${t}, but model only has ${this.layers.length} layer(s).`);return this.layers[t]}if(null==e)throw new Mm("Provide either a layer name or layer index");for(const t of this.layers)if(t.name===e)return t;throw new Mm(`No such layer: ${e}`)}calculateLosses(){return Ni((()=>{const e=[];for(const t of this.layers)for(let n=0;n<t.inboundNodes.length;++n){const s=Gb.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=Gb.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[Gb.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=Gb.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=Gb.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(Um(n),s)}function l(e){const n=e.name,a=lb(e,null!=t.customObjects?t.customObjects:{});a.setFastWeightInitDuringBuild(s),r[n]=a;e.inboundNodes.forEach((e=>{if(!(e instanceof Array))throw new Mm(`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(;!Qm(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];Wm(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];Wm(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 Mm("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(){Ni((()=>{this.layers.forEach((e=>{e.stateful&&e.resetStates()}))}))}}function Hb(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 jb(e,t){return Hb(e,t,"classWeight")}async function qb(e,t,n,s){if(null!=t||null!=s)throw new Error("Support sampleWeight is not implemented yet");if(null!=n){const t=Ni((()=>{if(1===e.shape.length)return Qa(e);if(2===e.shape.length){if(e.shape[1]>1){return Do(e,1)}if(1===e.shape[1])return tl(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());Ii(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])})),bh(r,"float32")}return null}function Kb(e,t){return Co(e,t)}function Xb(e,t){let n,s;const r=t;n=r.xs,s=r.ys,u(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=Yb("input",e.inputNames,n),i=Yb("output",e.outputNames,s),o=a[0].shape[0];u(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)})`)),u(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++)u(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++)u(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 Yb(e,t,n){if(n instanceof vr)return[n];if(Array.isArray(n))return u(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 Mm(`The feature data generated by the dataset lacks the required ${e} key '${r}'.`);s.push(n[r])}return s}}async function Zb(e,t,n){const s=null!=n.batchesPerEpoch;if(u(null!=e.optimizer,(()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig).")),u(null!=n,(()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call.")),u(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}`)),u(!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}`)),u(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(Jb(n.validationData))u(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 Lm("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 c;c=r?l.slice().concat(l.map((e=>"val_"+e))):l.slice();const h=ab(n.callbacks,n.yieldEvery),p=null==n.verbose?1:n.verbose,{callbackList:d,history:f}=ob(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,c);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}=Xb(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=jb(n.classWeight,e.outputNames);for(let e=0;e<t.length;++e)i.push(await qb(r[e],null,t[e]))}const u=s.concat(r).concat(i),p=o(u);Ii(u);for(let e=0;e<l.length;++e){const t=l[e],n=p[e];a[t]=n,Si(n)}await d.onBatchEnd(h,a),Qy(a),h++,c++}if(s?c>=n.batchesPerEpoch:t.done){if(r){let t;t=Jb(n.validationData)?Gm(await e.evaluateDataset(n.validationData,{batches:n.validationBatches})):Gm(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 Jb(e){return"function"==typeof e.iterator}function Qb(e){u(e>0&&Number.isInteger(e),(()=>`batchSize is required to be a positive integer, but got ${e}`))}function ex(e,t,n){return null==e?[null]:Array.isArray(e)?e.map((e=>_g(e,t,n-t))):_g(e,t,n-t)}function tx(e,t){return Ni((()=>null==e?null:Array.isArray(e)?e.map((e=>tx(e,t))):Bg(e,"int32"===t.dtype?t:Ja(t,"int32"))))}function nx(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 sx(e){const t=[];e instanceof vr&&(e=[e]);for(let n=0;n<e.length;++n){const s=e[n];if(1===s.rank)t.push(Rg(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 rx(e,t){if(null==e)return;const n=[];if(t instanceof vr)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 vr)-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 ax(e){return Array.isArray(e)}function ix(e){return!function(e){return e instanceof vr}(e)&&!ax(e)}function ox(e,t,n,s=!0,r=""){if(null==t||0===t.length){if(null!=e){let t=!1;if(ax(e)&&e.length>0)t=!0;else if(ix(e)){for(const n in e)if(e.hasOwnProperty(n)){t=!0;break}}else t=!0;if(t)throw new Mm(`Error when checking model ${r} expected no data, but got ${e}`)}return[]}if(null==e)return t.map((e=>null));let a;if(ix(e)){a=[];for(const n of t){if(null==e[n])throw new Mm(`No data provided for "${n}". Need data for each key in: ${t}`);a.push(e[n])}}else if(ax(e)){if(e.length!==t.length)throw new Mm(`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 Mm(`The model ${r} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);a=[e]}if(a=sx(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 Mm(`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 Mm(`${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 lx(e,t,n,s=!0,r=""){let a;if(Array.isArray(e)){if(e.length!==t.length)throw new Mm(`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 Mm(`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 Mm(`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 Mm(`Error when checking ${r}: expected ${t[e]} to have shape ${JSON.stringify(n[e])} but got array with shape ${JSON.stringify(i.shape)}.`)}}}class ux extends Gb{constructor(e){super(e),this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new Mm("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).");Mb(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:()=>ud.adagrad(.01),Adadelta:()=>ud.adadelta(1,.95,Eg()),Adam:()=>ud.adam(.001,.9,.999,Eg()),Adamax:()=>ud.adamax(.002,.9,.999,Eg(),0),RMSProp:()=>ud.rmsprop(.001,.9,0,Eg()),SGD:()=>ud.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 Mm(`Unknown Optimizer ${e}`)}(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof ed))throw new Mm("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 Mm(`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=>wb(e)))}else{const n=wb(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 Mm(`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(wb(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=[],xg("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])};xg("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]===gb?-1!==["accuracy","acc"].indexOf(i)?s=vb:-1!==["crossentropy","ce"].indexOf(i)&&(s=Tb):this.lossFunctions[e]===mb?-1!==["accuracy","acc"].indexOf(i)?s=Cb:-1!==["crossentropy","ce"].indexOf(i)&&(s=Eb):-1!==["accuracy","acc"].indexOf(i)?s=kb:-1!==["crossentropy","ce"].indexOf(i)&&(s=$b),-1!==["accuracy","acc"].indexOf(i)?r="acc":-1!==["crossentropy","ce"].indexOf(i)&&(r="ce"),a=s,n=""+r}else{const e=Rb(i);a=e,n=""+_b(i)}let t;xg(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;Qb(s);const r=this.standardizeUserDataXY(e,t,!0,s);try{const a=r[0].concat(r[1]);this.makeTestFunction();const i=this.testFunction;return Um(this.testLoop(i,a,s,n.verbose,n.steps))}finally{rx(r[0],e),rx(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 Lm("Verbose mode is not implemented yet.");u(!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=Ni((()=>{if(t.value){const{xs:n,ys:s}=Xb(e,t.value),i=n.concat(s),u=Ni((()=>r(i)));if(Ii(i),0===l)for(let e=0;e<u.length;++e)a.push(au(0));const c=i[0].shape[0];for(let e=0;e<u.length;++e){const t=u[e],n=a[e];a[e]=Ni((()=>Io(a[e],Co(c,t)))),l>0&&Ii(n)}Ii(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]=To(a[e],o),Ii(t)}return Um(a)}(this,e,t)}checkNumSamples(e,t,n,s="steps"){let r;if(null!=n){if(r=null,null!=t)throw new Mm(`If ${s} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else{if(null==e)throw new Mm(`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 Mm("`outputs` is an empty Array, which is not allowed.");const n=Array.isArray(t),s=n?t:[t],r=this.retrieveSymbolicTensors(s),a=new _y;if(e instanceof vr&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new Mm(`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 Mm(`No value is provided for the model's input ${t.name}`);a.add(t,n)}const i=Oy(r,a);return n?i:i[0]}retrieveSymbolicTensors(e){const t=Bm(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 Mm(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(n)}`)}return t}predictLoop(e,t=32,n=!1){return Ni((()=>{const s=this.checkNumSamples(e);if(n)throw new Lm("Verbose predictLoop() is not implemented yet.");const r=nx(s,t),a=this.outputs.map((e=>[]));for(let t=0;t<r.length;++t){Ni((()=>{const n=r[t][0],s=r[t][1],a=ex(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 _y(i);return Oy(this.outputs,o)})).forEach(((e,t)=>a[t].push(e)))}return Um(a.map((e=>rl(e,0))))}))}predict(e,t={}){const n=sx(e);lx(n,this.inputNames,this.feedInputShapes,!1);try{const s=null==t.batchSize?32:t.batchSize;return Qb(s),this.predictLoop(n,s)}finally{rx(n,e)}}predictOnBatch(e){lx(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 Om("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]===mb?r.push(t.slice(0,t.length-1).concat([1])):r.push(t)}if(function(e,t,n){const s=Jm(e.map((e=>e.shape[0])));s.sort();const r=Jm(t.map((e=>e.shape[0])));if(r.sort(),s.length>1)throw new Mm(`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 Mm(`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&&!f(s,r))throw new Mm(`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=ox(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=ox(t,this.feedOutputNames,r,!1,"target")),function(e,t,n){const s=[cb,gb,fb];for(let r=0;r<e.length;++r){const a=e[r],i=t[r],o=n[r];if(null!=i){if(i===fb&&1===a.shape[a.shape.length-1])throw new Mm(`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 Mm(`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 Mm(`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=jb(s,this.outputNames);l=[];for(let t=0;t<e.length;++t)l.push(await qb(o[t],null,e[t]))}return[i,o,l]}testLoop(e,t,n,s=0,r){return Ni((()=>{const a=this.checkNumSamples(t,n,r,"steps"),i=[];if(s>0)throw new Lm("Verbose mode is not implemented yet.");if(null!=r)throw new Lm("steps mode in testLoop() is not implemented yet");{const s=nx(a,n),r=bh(Cg(0,a));for(let n=0;n<s.length;++n){const a=s[n][0],o=s[n][1],l=_g(r,a,o-a),u=tx(t,l),c=e(u);if(0===n)for(let e=0;e<c.length;++e)i.push(au(0));for(let e=0;e<c.length;++e){const t=c[e];i[e]=Io(i[e],Co(o-a,t))}}for(let e=0;e<i.length;++e)i[e]=To(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(Vm(e,s)>1){r+=`_${Vm(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 _y(e),o=Oy(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=Kb(n,r[e]));const a=Yu(n);t.push(a),l=0===e?n:Io(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=Yu(t(s[r],o[r]))}Si(n),a.push(n)}return l=Yu(l),this.calculateLosses().forEach((e=>{l=Io(l,e)})),l}),!0,i)].concat(a)}}makeTestFunction(){this.testFunction=e=>Ni((()=>{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 _y(a),o=Oy(this.outputs,i);for(let e=0;e<this.lossFunctions.length;++e){const s=this.lossFunctions[e],a=Yu(s(r[e],o[e]));n=0===e?a:Io(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=Yu(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;Qb(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 Lm("validationData including sample weights is not supported yet."):new Mm(`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=ex(s,e,t),a=s,s=ex(s,0,e),c=ex(r,e,t),i=r,r=ex(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=ab(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,rx(s,e),rx(r,t),rx(a,e),rx(i,t),rx(u,o),rx(c,l),null!=h&&Ii(h)}}async fitLoop(e,t,n,s,a,i,o,l,u,c,h,p,d,f){null==s&&(s=32),null==a&&(a=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 Mm("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=Cg(0,g)),null==i&&(i=1);const{callbackList:b,history:x}=ob(o,i,a,p,g,d,s,m,h);b.setModel(this),this.history=x,await b.onTrainBegin(),this.stopTraining_=!1;for(let i=p;i<a;++i){await b.onEpochBegin(i);const a={};if(null!=d)throw new Lm("stepsPerEpoch mode is not implemented yet.");{if("batch"===c)throw new Lm("batch shuffling is not implemneted yet");c&&r(y);const i=bh(y),o=nx(g,s);for(let r=0;r<o.length;++r){const c={};if(await b.onBatchBegin(r,c),Ni((()=>{const h=o[r][0],p=o[r][1],d=_g(i,h,p-h);c.batch=r,c.size=p-h;const f=tx(t,d),g=e(f);for(let e=0;e<n.length;++e){const t=n[e],s=g[e];c[t]=s,Si(s)}if(r===o.length-1&&m){const e=this.testLoop(l,u,s);for(let t=0;t<n.length;++t){const s=n[t],r=e[t];Si(r),a["val_"+s]=r}}})),await b.onBatchEnd(r,c),Qy(c),this.stopTraining_)break}i.dispose()}if(await b.onEpochEnd(i,a),this.stopTraining_)break}return await b.onTrainEnd(),await this.history.syncData(),this.history}async fitDataset(e,t){return Zb(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 Ii(a),rx(n[0],e),rx(n[1],t),Um(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=ki().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-ki().numTensors}return e}getLossIdentifiers(){let e;if("string"==typeof this.loss)e=Hm(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=>Hm(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]=Hm(n[s])}}return e}getMetricIdentifiers(){if("string"==typeof this.metrics||"function"==typeof this.metrics)return[Hm(_b(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map((e=>Hm(_b(e))));{const e={};for(const t in this.metrics)e[t]=Hm(_b(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=lb(Wb(e.optimizer_config));let n,s;if("string"==typeof e.loss)n=jm(e.loss);else if(Array.isArray(e.loss))n=e.loss.map((e=>jm(e)));else if(null!=e.loss){n={};for(const t in e.loss)n[t]=jm(e.loss[t])}if(Array.isArray(e.metrics))s=e.metrics.map((e=>jm(e)));else if(null!=e.metrics){s={};for(const t in e.metrics)s[t]=jm(e.metrics[t])}this.compile({loss:n,metrics:s,optimizer:t})}async save(e,t){if("string"==typeof e){const t=wa(e);if(0===t.length)throw new Mm(`Cannot find any save handlers for URL '${e}'`);if(t.length>1)throw new Mm(`Found more than one (${t.length}) save handlers for URL '${e}'`);e=t[0]}if(null==e.save)throw new Mm("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");const n=await ia(this.getNamedWeights(t)),s={modelTopology:this.toJSON(null,!1),format:"layers-model",generatedBy:"TensorFlow.js tfjs-layers v4.1.0",convertedBy:null};if(null!=t&&t.includeOptimizer&&null!=this.optimizer){s.trainingConfig=this.getTrainingConfig();const e="optimizer",{data:t,specs:r}=await ia(await this.optimizer.getWeights(),e);n.specs.push(...r),n.data=ha([n.data,t])}if(null!=this.userDefinedMetadata){const e=!0;Db(this.userDefinedMetadata,this.name,e),s.userDefinedMetadata=this.userDefinedMetadata}return s.weightData=n.data,s.weightSpecs=n.specs,e.save(s)}setUserDefinedMetadata(e){Db(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}}ux.className="Model",go(ux);class cx extends ux{}cx.className="Functional",go(cx);class hx extends ux{constructor(e){if(super({inputs:[],outputs:[]}),e=e||{},this.trainable=!0,this.built=!1,this.name=null!=e.name?e.name:lg("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 Mm(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){const t=e instanceof hx||e instanceof ux;let n;if(t){if(n=e,1!==n.outputs.length)throw new Mm("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 Mm("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 Mm("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");const t=Ry({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 Mm(`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 Mm("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=Ey(this.outputs[0])}this.inboundNodes=[],new Ty({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:Bm(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(yy(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 ux({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 Om("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 Om("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 Om("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 Om("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 Mm("Legacy serialization format not supported yet.");r=t}else u(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 hx))throw new Lm(`Sequential.fromConfig called on non-Sequential input: ${i}`);for(const e of r){const t=lb(e,void 0,s);s&&t.setFastWeightInitDuringBuild(!0),i.add(t)}return i}set stopTraining(e){if(null==this.model)throw new Mm("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 Mm("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 px(e){return Ry(e)}hx.className="Sequential",go(hx);class dx extends fo{getConfig(){return{}}}class fx extends dx{apply(e,t=1){return function(e,t=1){if(1!==t)throw new Lm(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return jl(e)}(e,t)}}fx.className="elu",go(fx);class mx extends dx{apply(e){return Yc(e)}}mx.className="selu",go(mx);class gx extends dx{apply(e){return Wc(e)}}gx.className="relu",go(gx);class yx extends dx{apply(e){return Ni((()=>ec(6,Wc(e))))}}yx.className="relu6",go(yx);class bx extends dx{apply(e){return e}}bx.className="linear",go(bx);class xx extends dx{apply(e){return al(e)}}xx.className="sigmoid",go(xx);class wx extends dx{apply(e){return function(e){return Ni((()=>{const t=Io(.5,Co(.2,e));return xl(t,0,1)}))}(e)}}wx.className="hardSigmoid",go(wx);class vx extends dx{apply(e){return Du(e)}}vx.className="softplus",go(vx);class kx extends dx{apply(e){return function(e){return Ni((()=>To(e,Io($o(e),1))))}(e)}}kx.className="softsign",go(kx);class Nx extends dx{apply(e){return ol(e)}}Nx.className="tanh",go(Nx);class Ix extends dx{apply(e,t=-1){return ih(e,t)}}Ix.className="softmax",go(Ix);class Sx extends dx{apply(e,t=-1){return Lu(e,t)}}Sx.className="logSoftmax",go(Sx);class Tx extends dx{apply(e,t=1){return Ni((()=>Co(al(Co(e,t)),e)))}}Tx.className="swish",go(Tx);class Cx extends dx{apply(e){return Ni((()=>Co(e,ol(Du(e)))))}}function $x(e){return e.getClassName()}function Ex(e,t={}){return Ym(e,mo.getMap().classNameMap,t,"activation")}function Ax(e){if(null==e){const e={className:"linear",config:{}};return Ex(e)}if("string"==typeof e){const t={};return t.className=e,t.config={},Ex(t)}return e instanceof dx?e:Ex(e)}function Rx(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}`)}Cx.className="mish",go(Cx);class _x extends fo{}class Fx extends _x{constructor(e){super(),Rx(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 Ni((()=>{let t=Zu([1]);return this.hasL1&&(t=Io(t,lu(Co(this.l1,$o(e))))),this.hasL2&&(t=Io(t,lu(Co(this.l2,Wg(e))))),tl(t,[])}))}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}}Fx.className="L1L2",go(Fx);const Dx={l1l2:"L1L2"};function Ox(e){return Km(e)}function Mx(e,t={}){return Ym(e,mo.getMap().classNameMap,t,"regularizer")}function Lx(e){if(null==e)return null;if("string"==typeof e){return Mx({className:e in Dx?Dx[e]:e,config:{}})}return e instanceof _x?e:Mx(e)}class zx extends $y{constructor(e){super(null==e?{}:e),this.supportsMasking=!0,null!=e&&(this.maxValue=e.maxValue)}call(e,t){e=gy(e);let n=Wc(e);return null!=this.maxValue&&(n=xl(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){const e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}}zx.className="ReLU",go(zx);class Px extends $y{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=gy(e);return Iu(n,this.alpha)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}Px.className="LeakyReLU",go(Px);class Bx extends $y{constructor(e){if(super(null==e?{}:e),this.DEFAULT_ALPHA_INITIALIZER="zeros",null==e&&(e={}),this.supportsMasking=!0,this.alphaInitializer=dy(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=Lx(e.alphaRegularizer),this.alphaConstraint=Ky(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 Mm(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`);this.sharedAxes=[e.sharedAxes]}}build(e){const t=(e=yy(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 Ny({ndim:e.length,axes:n})],this.built=!0}call(e,t){return e=gy(e),gc(e,this.alpha.read())}getConfig(){const e={alphaInitializer:py(this.alphaInitializer),alphaRegularizer:Ox(this.alphaRegularizer),alphaConstraint:jy(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}}Bx.className="PReLU",go(Bx);class Wx extends $y{constructor(e){if(super(null==e?{}:e),this.DEFAULT_ALPHA=1,null==e&&(e={}),null!=e.alpha&&e.alpha!==this.DEFAULT_ALPHA)throw new Lm(`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=gy(e);return jl(n)}computeOutputShape(e){return e}getConfig(){const e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}}Wx.className="ELU",go(Wx);class Vx extends $y{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=gy(e);return Co(n,Ja(xu(n,this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){const e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}}Vx.className="ThresholdedReLU",go(Vx);class Ux extends $y{constructor(e){super(null==e?{}:e),this.DEFAULT_AXIS=1,null==e&&(e={}),this.softmax=(new Ix).apply,this.axis=null==e.axis?this.DEFAULT_AXIS:e.axis}call(e,t){const n=gy(e);return 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 Gx(e,t,n){if("number"==typeof e)return Bm(e,t);if(e.length!==t)throw new Mm(`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 Mm(`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 Hx(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 jx(e,t,n,s){if(null==e)return null;if("valid"===s)e=e*t+Tg([n-t,0]);else{if("same"!==s)throw new Mm(`Unsupport padding mode: ${s}.`);e*=t}return e}function qx(e,t){return Ni((()=>(mg(t),"channelsFirst"===t?_i(e,[0,2,3,1]):e)))}function Kx(e,t){return Ni((()=>(mg(t),"channelsFirst"===t?_i(e,[0,2,3,4,1]):e)))}function Xx(e,t,n,s=1,r="valid",a,i=1){return Ni((()=>{if(null==a&&(a="channelsLast"),mg(a),3!==e.shape.length)throw new Mm(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(3!==t.shape.length)throw new Mm(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(null!=n&&1!==n.shape.length)throw new Mm(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if("channelsFirst"===a&&(e=_i(e,[0,2,1])),"causal"===r)throw new Lm("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let o=Sl(e,t,s,"same"===r?"same":"valid","NWC",i);return null!=n&&(o=Ug(o,n)),o}))}function Yx(e,t,n,s=[1,1],r="valid",a,i,o=null){return Ni((()=>{if(null==a&&(a="channelsLast"),mg(a),3!==e.rank&&4!==e.rank)throw new Mm(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(3!==t.rank&&4!==t.rank)throw new Mm(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=qx(e,a);if("causal"===r)throw new Lm("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=jh({x:l,filter:t,strides:s,pad:"same"===r?"same":"valid",dilations:i,dataFormat:"NHWC",bias:n,activation:o}),"channelsFirst"===a&&(l=_i(l,[0,3,1,2])),l}))}function Zx(e,t,n,s=[1,1,1],r="valid",a,i){return Ni((()=>{if(null==a&&(a="channelsLast"),mg(a),4!==e.rank&&5!==e.rank)throw new Mm(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(4!==t.rank&&5!==t.rank)throw new Mm(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let o=Kx(e,a);if("causal"===r)throw new Lm("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return o=$l(o,t,s,"same"===r?"same":"valid","NDHWC",i),null!=n&&(o=Ug(o,n)),"channelsFirst"===a&&(o=_i(o,[0,4,1,2,3])),o}))}Ux.className="Softmax",go(Ux);class Jx extends $y{constructor(e,t){if(super(t),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",Jx.verifyArgs(t),this.rank=e,ng(this.rank,"rank"),1!==this.rank&&2!==this.rank&&3!==this.rank)throw new Lm(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=Gx(t.kernelSize,e,"kernelSize"),this.strides=Gx(null==t.strides?1:t.strides,e,"strides"),this.padding=null==t.padding?"valid":t.padding,gg(this.padding),this.dataFormat=null==t.dataFormat?"channelsLast":t.dataFormat,mg(this.dataFormat),this.activation=Ax(t.activation),this.useBias=null==t.useBias||t.useBias,this.biasInitializer=dy(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=Ky(t.biasConstraint),this.biasRegularizer=Lx(t.biasRegularizer),this.activityRegularizer=Lx(t.activityRegularizer),this.dilationRate=Gx(null==t.dilationRate?1:t.dilationRate,e,"dilationRate"),1===this.rank&&Array.isArray(this.dilationRate)&&1!==this.dilationRate.length)throw new Mm(`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 Mm(`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 Mm(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}static verifyArgs(e){if(Wm("kernelSize"in e,"required key 'kernelSize' not in config"),"number"!=typeof e.kernelSize&&!tg(e.kernelSize,"number",1,3))throw new Mm(`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:$x(this.activation),useBias:this.useBias,biasInitializer:py(this.biasInitializer),biasRegularizer:Ox(this.biasRegularizer),activityRegularizer:Ox(this.activityRegularizer),biasConstraint:jy(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}class Qx extends Jx{constructor(e,t){super(e,t),this.kernel=null,Qx.verifyArgs(t),this.filters=t.filters,ng(this.filters,"filters"),this.kernelInitializer=dy(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=Ky(t.kernelConstraint),this.kernelRegularizer=Lx(t.kernelRegularizer)}build(e){e=yy(e);const t="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[t])throw new Mm(`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 Ni((()=>{let t;e=gy(e);const n=null==this.bias?null:this.bias.read(),s=rg(this.activation.getClassName());if(null!=s&&2===this.rank)t=Yx(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate,s);else{if(1===this.rank)t=Xx(e,this.kernel.read(),n,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(2===this.rank)t=Yx(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate);else{if(3!==this.rank)throw new Lm("convolutions greater than 3D are not implemented yet.");t=Zx(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=yy(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=Hx(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:py(this.kernelInitializer),kernelRegularizer:Ox(this.kernelRegularizer),kernelConstraint:jy(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 Mm(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}}class ew extends Qx{constructor(e){super(2,e),ew.verifyArgs(e)}getConfig(){const e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if("number"!=typeof e.kernelSize&&!tg(e.kernelSize,"number",1,2))throw new Mm(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}}ew.className="Conv2D",go(ew);class tw extends Qx{constructor(e){super(3,e),tw.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 Mm(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}}tw.className="Conv3D",go(tw);class nw extends ew{constructor(e){if(super(e),this.inputSpec=[new Ny({ndim:4})],"same"!==this.padding&&"valid"!==this.padding)throw new Mm(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(4!==(e=yy(e)).length)throw new Mm("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 Mm("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 Ny({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return Ni((()=>{let t=gy(e);if(4!==t.shape.length)throw new Mm(`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,jx(i,c,l,this.padding),jx(o,h,u,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(t=_i(t,[0,2,3,1]));let d=Cl(t,this.kernel.read(),p,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(d=_i(d,[0,3,1,2])),null!=this.bias&&(d=Ug(d,this.bias.read(),this.dataFormat)),null!=this.activation&&(d=this.activation.apply(d)),d}))}computeOutputShape(e){const t=(e=yy(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]=jx(t[s],o,a,this.padding),t[r]=jx(t[r],l,i,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}nw.className="Conv2DTranspose",go(nw);class sw extends tw{constructor(e){if(super(e),this.inputSpec=[new Ny({ndim:5})],"same"!==this.padding&&"valid"!==this.padding)throw new Mm(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(5!==(e=yy(e)).length)throw new Mm("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 Mm("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 Ny({ndim:5,axes:{[t]:n}})],this.built=!0}call(e,t){return Ni((()=>{let t=gy(e);if(5!==t.shape.length)throw new Mm(`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,jx(o,d,c,this.padding),jx(l,f,h,this.padding),jx(u,m,p,this.padding),this.filters];"channelsLast"!==this.dataFormat&&(t=_i(t,[0,2,3,4,1]));let y=Al(t,this.kernel.read(),g,this.strides,this.padding);return"channelsLast"!==this.dataFormat&&(y=_i(y,[0,4,1,2,3])),null!==this.bias&&(y=Ug(y,this.bias.read(),this.dataFormat)),null!==this.activation&&(y=this.activation.apply(y)),y}))}computeOutputShape(e){const t=(e=yy(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]=jx(t[s],u,i,this.padding),t[r]=jx(t[r],c,o,this.padding),t[a]=jx(t[a],h,l,this.padding),t}getConfig(){const e=super.getConfig();return delete e.dilationRate,e}}sw.className="Conv3DTranspose",go(sw);class rw extends Qx{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 Mm("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(null!=t.kernelInitializer||null!=t.kernelRegularizer||null!=t.kernelConstraint)throw new Mm("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 Mm(`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=dy(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=Lx(t.depthwiseRegularizer),this.depthwiseConstraint=Ky(t.depthwiseConstraint),this.pointwiseInitializer=dy(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=Lx(t.pointwiseRegularizer),this.pointwiseConstraint=Ky(t.pointwiseConstraint)}build(e){if((e=yy(e)).length<this.rank+2)throw new Mm(`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 Mm(`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 Ny({ndim:this.rank+2,axes:{[t]:n}})],this.built=!0}call(e,t){return Ni((()=>{let t;if(e=gy(e),1===this.rank)throw new Lm("1D separable convolution is not implemented yet.");return 2===this.rank&&("channelsFirst"===this.dataFormat&&(e=_i(e,[0,2,3,1])),t=Zc(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(t=Ug(t,this.bias.read(),this.dataFormat)),null!=this.activation&&(t=this.activation.apply(t)),"channelsFirst"===this.dataFormat&&(t=_i(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=py(this.depthwiseInitializer),e.pointwiseInitializer=py(this.pointwiseInitializer),e.depthwiseRegularizer=Ox(this.depthwiseRegularizer),e.pointwiseRegularizer=Ox(this.pointwiseRegularizer),e.depthwiseConstraint=jy(this.depthwiseConstraint),e.pointwiseConstraint=jy(this.pointwiseConstraint),e}}rw.className="SeparableConv";class aw extends rw{constructor(e){super(2,e)}}aw.className="SeparableConv2D",go(aw);class iw extends Qx{constructor(e){super(1,e),iw.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&&!tg(e.kernelSize,"number",1,1))throw new Mm(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}}iw.className="Conv1D",go(iw);class ow extends $y{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 Ni((()=>{if(e=gy(e),"channelsLast"===this.dataFormat){const t=Dg(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Dg(t,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}{const t=Dg(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Dg(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}}ow.className="Cropping2D",go(ow);class lw extends $y{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,mg(this.dataFormat),this.interpolation=null==e.interpolation?"nearest":e.interpolation,t=this.interpolation,eg(cg,"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 Ni((()=>{let t=gy(e);const n=t.shape;if("channelsFirst"===this.dataFormat){t=_i(t,[0,2,3,1]);const e=this.size[0]*n[2],s=this.size[1]*n[3],r="nearest"===this.interpolation?Xp.resizeNearestNeighbor(t,[e,s]):Xp.resizeBilinear(t,[e,s]);return _i(r,[0,3,1,2])}{const e=this.size[0]*n[1],s=this.size[1]*n[2];return"nearest"===this.interpolation?Xp.resizeNearestNeighbor(t,[e,s]):Xp.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}}lw.className="UpSampling2D",go(lw);class uw extends Jx{constructor(e){super(2,e),this.depthwiseKernel=null,this.depthMultiplier=null==e.depthMultiplier?1:e.depthMultiplier,this.depthwiseInitializer=dy(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=Ky(e.depthwiseConstraint),this.depthwiseRegularizer=Lx(e.depthwiseRegularizer)}build(e){if((e=yy(e)).length<4)throw new Mm(`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 Mm(`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 Ni((()=>{let t=function(e,t,n=[1,1],s="valid",r,a){return Ni((()=>{null==r&&(r="channelsLast"),mg(r);let i=qx(e,r);if(4!==e.rank)throw new Mm(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(4!==t.rank)throw new Mm(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return i=Ll(i,t,n,"same"===s?"same":"valid","NHWC",a),"channelsFirst"===r&&(i=_i(i,[0,3,1,2])),i}))}(e=gy(e),this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(t=Ug(t,this.bias.read(),this.dataFormat)),null!=this.activation&&(t=this.activation.apply(t)),t}))}computeOutputShape(e){e=yy(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=Hx(t,this.kernelSize[0],this.padding,this.strides[0]),a=Hx(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=py(this.depthwiseInitializer),e.depthwiseRegularizer=Ox(this.depthwiseRegularizer),e.depthwiseConstraint=jy(this.depthwiseRegularizer),e}}function cw(e,t,n,s){if(Array.isArray(e)){if(null!=t||null!=n)throw new Mm("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 hw(e,t,n,s=!1,r,a,i=!1,o=!1){return Ni((()=>{const l=t.shape.length;if(l<3)throw new Mm(`Input should be at least 3D, but is ${l}D.`);const u=[1,0].concat(Cg(2,l));if(t=_i(t,u),null!=a)throw new Lm("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=Ja(Ja(r,"bool"),"float32")).rank===l-1&&(r=du(r,-1)),r=_i(r,u)),s&&(t=Uc(t,0),null!=r&&(r=Uc(r,0)));const c=[];let h,p=n;const d=t.shape[0],f=Ch(t);let m,g;null!=r&&(m=Ch(r));for(let t=0;t<d;++t){const n=f[t],s=Ni((()=>e(n,p)));if(null==r)h=s[0],p=s[1];else{const e=Ni((()=>{const e=m[t],n=Mu(oc(e),e);return{output:Io(Co(s[0],e),Co(p[0],n)),newStates:p.map(((t,r)=>Io(Co(s[1][r],e),Co(t,n))))}}));h=e.output,p=e.newStates}o&&c.push(h)}if(o){g=fh(c,1)}return[h,g,p]}))}uw.className="DepthwiseConv2D",go(uw);class pw extends $y{constructor(e){let t;if(super(e),null==e.cell)throw new Mm("cell property is missing for the constructor of RNN.");if(t=Array.isArray(e.cell)?new ww({cells:e.cell}):e.cell,null==t.stateSize)throw new Mm("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 Ny({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(null==this.states_){return Cg(0,Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1).map((e=>null))}return this.states_}setStates(e){this.states_=e}computeOutputShape(e){fy(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 Ni((()=>{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 Lm("Constants support is not implemented in RNN yet.");fy(e)&&(e=e[0]);const t=this.stateful?e[0]:null,n=e.slice(2);this.inputSpec[0]=new Ny({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(!f(this.stateSpec.map((e=>e.shape[e.shape.length-1])),r))throw new Mm(`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 Ny({shape:[null,e]})));this.stateful&&this.resetStates()}resetStates(e,t=!1){Ni((()=>{if(!this.stateful)throw new Dm("Cannot call resetStates() on an RNN Layer that is not stateful.");const n=this.inputSpec[0].shape[0];if(null==n)throw new Mm("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=>Zu([n,e]))):this.states_=[Zu([n,this.cell.stateSize])];else if(null==e)Ii(this.states_),null!=this.keptStates&&(Ii(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((e=>Zu([n,e]))):this.states_[0]=Zu([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new Mm(`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()):Ii(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(!f(s.shape,a))throw new Mm(`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=>Si(e.clone())))}))}apply(e,t){let n=null==t?null:t.initialState,s=null==t?null:t.constants;null==t&&(t={});const r=cw(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 Ny({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 Iy){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 Ni((()=>{const n=null==t?null:t.mask,s=null==t?null:t.training;let r=null==t?null:t.initialState;e=gy(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 Mm(`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=hw(((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 Ni((()=>{let t=Zu(e.shape);return t=lu(t,[1,2]),t=Rg(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map((e=>e>1?Lg(t,[1,e]):t)):this.cell.stateSize>1?[Lg(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()===pw.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=lb(t.cell,n);return new e(Object.assign(t,{cell:s}))}}pw.className="RNN",go(pw);class dw extends $y{}class fw extends dw{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,ng(this.units,"units"),this.activation=Ax(null==e.activation?this.DEFAULT_ACTIVATION:e.activation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=dy(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=dy(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=dy(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Lx(e.kernelRegularizer),this.recurrentRegularizer=Lx(e.recurrentRegularizer),this.biasRegularizer=Lx(e.biasRegularizer),this.kernelConstraint=Ky(e.kernelConstraint),this.recurrentConstraint=Ky(e.recurrentConstraint),this.biasConstraint=Ky(e.biasConstraint),this.dropout=Sg([1,Tg([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=Sg([1,Tg([0,null==e.recurrentDropout?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=yy(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 Ni((()=>{if(2!==e.length)throw new Mm(`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=vw({ones:()=>oc(e),rate:this.dropout,training:s,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=vw({ones:()=>oc(n),rate:this.recurrentDropout,training:s,dropoutFunc:this.dropoutFunc}));const a=this.dropoutMask,i=this.recurrentDropoutMask;r=Pg(null!=a?Co(e,a):e,this.kernel.read()),null!=this.bias&&(r=Ug(r,this.bias.read())),null!=i&&(n=Co(n,i));let o=Io(r,Pg(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:$x(this.activation),useBias:this.useBias,kernelInitializer:py(this.kernelInitializer),recurrentInitializer:py(this.recurrentInitializer),biasInitializer:py(this.biasInitializer),kernelRegularizer:Ox(this.kernelRegularizer),recurrentRegularizer:Ox(this.recurrentRegularizer),biasRegularizer:Ox(this.biasRegularizer),activityRegularizer:Ox(this.activityRegularizer),kernelConstraint:jy(this.kernelConstraint),recurrentConstraint:jy(this.recurrentConstraint),biasConstraint:jy(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return Object.assign(Object.assign({},e),t)}}fw.className="SimpleRNNCell",go(fw);class mw extends pw{constructor(e){e.cell=new fw(e),super(e)}call(e,t){return Ni((()=>{null!=this.cell.dropoutMask&&(Ii(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(Ii(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)}}mw.className="SimpleRNN",go(mw);class gw extends dw{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 Mm("GRUCell does not support reset_after parameter set to true.");this.units=e.units,ng(this.units,"units"),this.activation=Ax(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Ax(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=dy(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=dy(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=dy(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Lx(e.kernelRegularizer),this.recurrentRegularizer=Lx(e.recurrentRegularizer),this.biasRegularizer=Lx(e.biasRegularizer),this.kernelConstraint=Ky(e.kernelConstraint),this.recurrentConstraint=Ky(e.recurrentConstraint),this.biasConstraint=Ky(e.biasConstraint),this.dropout=Sg([1,Tg([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=Sg([1,Tg([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=yy(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 Ni((()=>{if(2!==e.length)throw new Mm(`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=vw({ones:()=>oc(e),rate:this.dropout,training:n,count:3,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=vw({ones:()=>oc(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=Co(e,r[0]));let u=Pg(e,this.kernel.read());this.useBias&&(u=Ug(u,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(s=Co(s,a[0]));const c=this.recurrentKernel.read(),[h,p]=ch(c,[2*this.units,this.units],c.rank-1),d=Pg(s,h),[f,m,g]=ch(u,3,u.rank-1),[y,b]=ch(d,2,d.rank-1);i=this.recurrentActivation.apply(Io(f,y)),o=this.recurrentActivation.apply(Io(m,b));const x=Pg(Co(o,s),p);l=this.activation.apply(Io(g,x));const w=Io(Co(i,s),Co(Io(1,Ai(i)),l));return[w,w]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:$x(this.activation),recurrentActivation:$x(this.recurrentActivation),useBias:this.useBias,kernelInitializer:py(this.kernelInitializer),recurrentInitializer:py(this.recurrentInitializer),biasInitializer:py(this.biasInitializer),kernelRegularizer:Ox(this.kernelRegularizer),recurrentRegularizer:Ox(this.recurrentRegularizer),biasRegularizer:Ox(this.biasRegularizer),activityRegularizer:Ox(this.activityRegularizer),kernelConstraint:jy(this.kernelConstraint),recurrentConstraint:jy(this.recurrentConstraint),biasConstraint:jy(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return Object.assign(Object.assign({},e),t)}}gw.className="GRUCell",go(gw);class yw extends pw{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 gw(e),super(e)}call(e,t){return Ni((()=>{null!=this.cell.dropoutMask&&(Ii(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(Ii(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)}}yw.className="GRU",go(yw);class bw extends dw{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,ng(this.units,"units"),this.activation=Ax(void 0===e.activation?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Ax(void 0===e.recurrentActivation?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=null==e.useBias||e.useBias,this.kernelInitializer=dy(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=dy(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=dy(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=Lx(e.kernelRegularizer),this.recurrentRegularizer=Lx(e.recurrentRegularizer),this.biasRegularizer=Lx(e.biasRegularizer),this.kernelConstraint=Ky(e.kernelConstraint),this.recurrentConstraint=Ky(e.recurrentConstraint),this.biasConstraint=Ky(e.biasConstraint),this.dropout=Sg([1,Tg([0,null==e.dropout?0:e.dropout])]),this.recurrentDropout=Sg([1,Tg([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=yy(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 Kg{apply(t,s){const r=e.apply([n]),a=(new Yg).apply([n]),i=e.apply([2*n]);return Mg(Mg(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 Ni((()=>{const n=null!=t.training&&t.training;if(3!==e.length)throw new Mm(`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=vw({ones:()=>oc(e),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&null==this.recurrentDropoutMask&&(this.recurrentDropoutMask=vw({ones:()=>oc(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=Co(e,a[0]));let h=Pg(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(s=Co(s,i[0])),h=Io(h,Pg(s,this.recurrentKernel.read())),this.useBias&&(h=Ug(h,this.bias.read()));const[p,d,f,m]=ch(h,4,h.rank-1);o=this.recurrentActivation.apply(p),l=this.recurrentActivation.apply(d),u=Io(Co(l,r),Co(o,this.activation.apply(f))),c=this.recurrentActivation.apply(m);const g=Co(c,this.activation.apply(u));return[g,g,u]}))}getConfig(){const e=super.getConfig(),t={units:this.units,activation:$x(this.activation),recurrentActivation:$x(this.recurrentActivation),useBias:this.useBias,kernelInitializer:py(this.kernelInitializer),recurrentInitializer:py(this.recurrentInitializer),biasInitializer:py(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:Ox(this.kernelRegularizer),recurrentRegularizer:Ox(this.recurrentRegularizer),biasRegularizer:Ox(this.biasRegularizer),activityRegularizer:Ox(this.activityRegularizer),kernelConstraint:jy(this.kernelConstraint),recurrentConstraint:jy(this.recurrentConstraint),biasConstraint:jy(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return Object.assign(Object.assign({},e),t)}}bw.className="LSTMCell",go(bw);class xw extends pw{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 bw(e),super(e)}call(e,t){return Ni((()=>{null!=this.cell.dropoutMask&&(Ii(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(Ii(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)}}xw.className="LSTM",go(xw);class ww extends dw{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 Ni((()=>{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;fy(e)&&(e=e[0]),this.cells.forEach(((n,s)=>{xg(`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(lb(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 vy(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]])}ky(t)}}function vw(e){const{ones:t,rate:n,training:s=!1,count:r=1,dropoutFunc:a}=e,i=()=>null!=a?a(t(),n):Gg(t(),n),o=()=>Hg(i,t,s);if(!r||r<=1)return Si(o().clone());return Array(r).fill(void 0).map(o).map((e=>Si(e.clone())))}ww.className="StackedRNNCells",go(ww);var kw=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 Nw extends pw{constructor(e){if(e.unroll)throw new Lm("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new Lm("It is not possible at the moment to stack convolutional cells.");super(e),this.inputSpec=[new Ny({ndim:5})]}call(e,t){return Ni((()=>{if(null!=this.cell.dropoutMask&&(Ii(this.cell.dropoutMask),this.cell.dropoutMask=null),null!=this.cell.recurrentDropoutMask&&(Ii(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new Mm("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 Ni((()=>{const{stateSize:t}=this.cell,n=e.shape,s=this.computeSingleOutputShape(n),r=Zu([s[0],...s.slice(2)]);return Array.isArray(t)?Array(t.length).fill(r):[r]}))}resetStates(e,t=!1){Ni((()=>{if(!this.stateful)throw new Dm("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 Mm("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((()=>Zu(r))):this.states_=[Zu(r)];else if(null==e)Ii(this.states_),null!=this.keptStates&&(Ii(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map((()=>Zu(r))):this.states_[0]=Zu(r);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new Mm(`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()):Ii(this.states_);for(let t=0;t<this.states_.length;++t){const n=e[t],s=r;if(!f(n.shape,s))throw new Mm(`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=>Si(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=Hx(l,s[0],r,a[0],i[0]),h=Hx(u,s[1],r,a[1],i[1]);return[...e.slice(0,2),...o?[n,c,h]:[c,h,n]]}}Nw.className="ConvRNN2D";class Iw extends bw{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,ng(this.filters,"filters"),this.kernelSize=Gx(n,2,"kernelSize"),this.kernelSize.forEach((e=>ng(e,"kernelSize"))),this.strides=Gx(s||1,2,"strides"),this.strides.forEach((e=>ng(e,"strides"))),this.padding=r||"valid",gg(this.padding),this.dataFormat=a||"channelsLast",mg(this.dataFormat),this.dilationRate=Gx(i||1,2,"dilationRate"),this.dilationRate.forEach((e=>ng(e,"dilationRate")))}build(e){var t;e=yy(e);const n="channelsFirst"===this.dataFormat?1:e.length-1;if(null==e[n])throw new Mm(`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 Kg{apply(e,t){return Og([n.apply([s]),Ju([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 Ni((()=>{if(3!==e.length)throw new Mm(`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=vw({ones:()=>oc(s),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));const i=this.dropoutMask,o=(e,t,n)=>t&&t[n]?Co(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=vw({ones:()=>oc(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]=ch(this.kernel.read(),4,3),[v,k,N,I]=this.useBias?ch(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,$]=ch(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(Io(l,d)),A=this.recurrentActivation.apply(Io(u,f)),R=Io(Co(A,a),Co(E,this.activation.apply(Io(c,m)))),_=Co(this.recurrentActivation.apply(Io(h,g)),this.activation.apply(R));return[_,_,R]}))}getConfig(){const e=super.getConfig(),{units:t}=e,n=kw(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=Il(e,t,this.strides,s||"valid","channelsFirst"===this.dataFormat?"NCHW":"NHWC",this.dilationRate);return n?Ug(r,n,this.dataFormat):r}recurrentConv(e,t){return Il(e,t,1,"same","channelsFirst"===this.dataFormat?"NCHW":"NHWC")}}Iw.className="ConvLSTM2DCell",go(Iw);class Sw extends Nw{constructor(e){const t=new Iw(e);super(Object.assign(Object.assign({},e),{cell:t}))}static fromConfig(e,t){return new e(t)}}Sw.className="ConvLSTM2D",go(Sw);class Tw extends $y{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 Ni((()=>{this.invokeCallHook(e,t);const n=gy(e);if(0<this.rate&&this.rate<1){const e=null!=t.training&&t.training,s=this.getNoiseShape(n);return Hg((()=>Gg(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()}}Tw.className="Dropout",go(Tw);class Cw extends Tw{constructor(e){super(e),this.inputSpec=[{ndim:3}]}getNoiseShape(e){const t=e.shape;return[t[0],1,t[2]]}}Cw.className="SpatialDropout1D",go(Cw);class $w extends $y{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,ng(this.units,"units"),this.activation=Ax(e.activation),null!=e.useBias&&(this.useBias=e.useBias),this.kernelInitializer=dy(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=dy(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=Ky(e.kernelConstraint),this.biasConstraint=Ky(e.biasConstraint),this.kernelRegularizer=Lx(e.kernelRegularizer),this.biasRegularizer=Lx(e.biasRegularizer),this.activityRegularizer=Lx(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){const t=(e=yy(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=yy(e)).slice();return t[t.length-1]=this.units,t}call(e,t){return Ni((()=>{this.invokeCallHook(e,t);const n=gy(e),s=rg(this.activation.getClassName());let r;return null!=s?r=Pg(n,this.kernel.read(),s,this.bias?this.bias.read():null):(r=Pg(n,this.kernel.read()),null!=this.bias&&(r=Ug(r,this.bias.read())),null!=this.activation&&(r=this.activation.apply(r))),r}))}getConfig(){const e={units:this.units,activation:$x(this.activation),useBias:this.useBias,kernelInitializer:py(this.kernelInitializer),biasInitializer:py(this.biasInitializer),kernelRegularizer:Ox(this.kernelRegularizer),biasRegularizer:Ox(this.biasRegularizer),activityRegularizer:Ox(this.activityRegularizer),kernelConstraint:jy(this.kernelConstraint),biasConstraint:jy(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}}$w.className="Dense",go($w);class Ew extends $y{constructor(e){super(e=e||{}),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=yy(e);for(const t of e.slice(1))if(null==t)throw new Mm(`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],Ig(e,1)]}call(e,t){return Ni((()=>{this.invokeCallHook(e,t);let n=gy(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=_i(n,e)}return function(e){if(e.rank<=1)throw new Mm(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);const t=[e.shape[0],Ig(e.shape,1)];return tl(e,t)}(n)}))}getConfig(){const e={};null!=this.dataFormat&&(e.dataFormat=this.dataFormat);const t=super.getConfig();return Object.assign(e,t),e}}Ew.className="Flatten",go(Ew);class Aw extends $y{constructor(e){super(e),this.supportsMasking=!0,this.activation=Ax(e.activation)}call(e,t){return Ni((()=>{this.invokeCallHook(e,t);const n=gy(e);return this.activation.apply(n)}))}getConfig(){const e={activation:$x(this.activation)},t=super.getConfig();return Object.assign(e,t),e}}Aw.className="Activation",go(Aw);class Rw extends $y{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 Ni((()=>{return e=gy(e),t=e,n=this.n,Ni((()=>{if(2!==t.shape.length)throw new Mm(`repeat() expects a rank-2 tensor, but received a rank-${t.shape.length} tensor.`);return Lg(Rg(t,1),[1,n,1])}));var t,n}))}getConfig(){const e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}}Rw.className="RepeatVector",go(Rw);class _w extends $y{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 Mm("Can only specifiy one unknown dimension.");a=e}else r*=t}const i=Ig(e);if(null!==a){if(0===r||i%r!=0)throw new Mm(n);s[a]=i/r}else if(i!==r)throw new Mm(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 Ni((()=>{this.invokeCallHook(e,t);const n=gy(e),s=n.shape,r=s.slice(0,1).concat(this.fixUnknownDimension(s.slice(1),this.targetShape));return tl(n,r)}))}getConfig(){const e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}}_w.className="Reshape",go(_w);class Fw extends $y{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=Cg(1,e.dims.length+1);if(!f(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 Ny({ndim:this.dims.length+1})]}computeOutputShape(e){const t=(e=yy(e)).slice();return this.dims.forEach(((n,s)=>{t[s+1]=e[n]})),t}call(e,t){return _i(gy(e),this.dimsIncludingBatch)}getConfig(){const e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}}Fw.className="Permute",go(Fw);class Dw extends $y{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=gy(e);return Fo(ic(n,this.maskValue),-1)}call(e,t){return Ni((()=>{this.invokeCallHook(e,t);const n=gy(e),s=Fo(ic(n,this.maskValue),-1,!0);return Co(n,Ja(s,n.dtype))}))}}Dw.className="Masking",go(Dw);class Ow extends $y{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(Gm(e.inputLength))}this.inputDim=e.inputDim,ng(this.inputDim,"inputDim"),this.outputDim=e.outputDim,ng(this.outputDim,"outputDim"),this.embeddingsInitializer=dy(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=Lx(e.embeddingsRegularizer),this.activityRegularizer=Lx(e.activityRegularizer),this.embeddingsConstraint=Ky(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 Ni((()=>this.maskZero?(e=gy(e),ic(e,Vl(e))):null))}computeOutputShape(e){if(e=yy(e),null==this.inputLength)return[...e,this.outputDim];const t=Gm(this.inputLength);if(t.length!==e.length-1)throw new Mm(`"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 Mm(`"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 Ni((()=>{this.invokeCallHook(e,t);let n=gy(e);"int32"!==n.dtype&&(n=Ag(n,"int32"));const s=Bg(this.embeddings.read(),tl(n,[n.size]));return tl(s,yy(this.computeOutputShape(n.shape)))}))}getConfig(){const e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:py(this.embeddingsInitializer),embeddingsRegularizer:Ox(this.embeddingsRegularizer),activityRegularizer:Ox(this.activityRegularizer),embeddingsConstraint:jy(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}}Ow.className="Embedding",go(Ow);class Mw extends $y{constructor(e){super(e||{}),this.supportsMasking=!0}mergeFunction(e){throw new Lm}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 Mm("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=[yy(e)]),e.length<2)throw new Mm(`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=Jm(t),t.length>1)throw new Mm(`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===Jm(s).length?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return Ni((()=>{if(this.reshapeRequired){const t=[],n=e.map((e=>e.rank));if(-1===n.indexOf(null)){const s=Tg(n);for(let n of e){const e=n.rank;for(let t=0;t<s-e;++t)n=Rg(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=tl(s,[r].concat(Ig(e.slice(1))));i=_i(i,[1,0]),i=tl(i,a),t.push(i),n=!0}else if(e>1){const r=Cg(1,e).concat([0]);t.push(_i(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=tl(_i(tl(s,[-1,t]),[1,0]),n)}else if(r>1){const e=[r-1].concat(Cg(0,r-1));s=_i(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=Jm(n),t=1===n.length?n.concat(t):[null].concat(t),t}computeMask(e,t){return Ni((()=>{if(null==t)return null;if(!Array.isArray(t))throw new Mm("`mask` should be an Array");if(!Array.isArray(e))throw new Mm("`inputs` should be an Array");if(t.length!==e.length)throw new Mm(`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:du(e,0))))[0];for(let e=1;e<t.length-1;++e)n=Pu(n,t[e]);return n}))}}class Lw extends Mw{constructor(e){super(e)}mergeFunction(e){return Ni((()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=Io(t,e[n]);return t}))}}Lw.className="Add",go(Lw);class zw extends Mw{constructor(e){super(e)}mergeFunction(e){return Ni((()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=Co(t,e[n]);return t}))}}zw.className="Multiply",go(zw);class Pw extends Mw{constructor(e){super(e)}mergeFunction(e){return Ni((()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=Io(t,e[n]);return Co(1/e.length,t)}))}}Pw.className="Average",go(Pw);class Bw extends Mw{constructor(e){super(e)}mergeFunction(e){return Ni((()=>{let t=e[0];for(let n=1;n<e.length;++n)t=Xu(t,e[n]);return t}))}}Bw.className="Maximum",go(Bw);class Ww extends Mw{constructor(e){super(e)}mergeFunction(e){return Ni((()=>{let t=e[0];for(let n=1;n<e.length;++n)t=ec(t,e[n]);return t}))}}Ww.className="Minimum",go(Ww);class Vw extends Mw{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 Mm("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(f(e,s)){r=!0;break}r||n.push(s)}if(n.length>1)throw new Mm("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return Ni((()=>Og(e,this.axis)))}computeOutputShape(e){if(!Array.isArray(e)||!Array.isArray(e[0]))throw new Mm("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 Mm("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new Mm("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new Mm(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return Ni((()=>{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(Ja(oc(e[n]),"bool")):t[n].rank<e[n].rank?s.push(du(t[n],-1)):s.push(t[n]);const r=rl(s,this.axis);return _o(r,-1,!1)}))}getConfig(){const e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}}function Uw(e,t){for(;e<0;)e+=t;return e}Vw.className="Concatenate",go(Vw);class Gw extends Mw{constructor(e){super(e),this.axes=e.axes,this.normalize=null!=e.normalize&&e.normalize,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){u(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 Lm("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 Mm(`Dimension incompatibility: ${t[s[0]]} !== ${n[s[1]]}`)}mergeFunction(e){if(2!==e.length)throw new Mm(`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)=>Uw(t,e[n].shape.length))):[Uw(this.axes,n.shape.length),Uw(this.axes,s.shape.length)],this.normalize&&(n=ub(n,t[0]),s=ub(s,t[1])),function(e,t,n){if(e.shape.length>3||t.shape.length>3)throw new Lm("batchDot is not implemented for tensors of 4D or higher rank yet");if(u(e.shape.length>=2,(()=>`batchDot requires the rank of x to be >= 2, but got ${e.shape.length}`)),u(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 Lm("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 Ni((()=>{let n,i;if(s>r){n=s-r;const e=[];for(let t=0;t<n;++t)e.push(1);t=tl(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=tl(e,e.shape.concat(t))}else n=0;if(2===e.shape.length&&2===t.shape.length)i=a[0]===a[1]?lu(Co(e,t),a[0]):lu(Co(_i(e,[1,0]),t),a[1]);else{const n=a[0]!==e.shape.length-1,s=a[1]===t.shape.length-1;i=bi(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=dh(i,t)}return 1===i.shape.length&&(i=du(i,1)),i}))}(n,s,t)}interpretAxes(e,t){let n;return n=Array.isArray(this.axes)?this.axes:[Uw(this.axes,e.length),Uw(this.axes,t.length)],n}computeOutputShape(e){u(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 Lm("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}}Gw.className="Dot",go(Gw);class Hw extends $y{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 Ni((()=>{this.invokeCallHook(e,t);const n=gy(e);return Hg((()=>Io(zg(n.shape,0,this.stddev),n)),(()=>n),t.training||!1)}))}}Hw.className="GaussianNoise",go(Hw);class jw extends $y{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 Ni((()=>{this.invokeCallHook(e,t);const n=gy(e);if(this.rate>0&&this.rate<1){return Hg((()=>{const e=Math.sqrt(this.rate/(1-this.rate));return Co(n,zg(n.shape,1,e))}),(()=>n),t.training||!1)}return n}))}}jw.className="GaussianDropout",go(jw);class qw extends $y{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||gy(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 Ni((()=>{if(this.rate<1&&this.rate>0){const n=this._getNoiseShape(e),s=()=>{const t=gy(e),s=-1.7580993408473766;let r=wu(zc(n),this.rate);r=Ag(r,"float32");const a=((1-this.rate)*(1+this.rate*s**2))**-.5,i=-a*s*this.rate,o=Io(Co(t,r),Co(Io(r,-1),s));return Io(Co(o,a),i)};return Hg(s,(()=>gy(e)),t.training||!1)}return e}))}}function Kw(e,t,n,s,r,a=.001){let i;if(2===e.rank)i=hl(e,t,n,s,r,a);else if(3===e.rank)i=pl(e,t,n,s,r,a);else{if(4!==e.rank)throw new Lm(`batchNormalization is not implemented for array of rank ${e.rank} yet`);i=dl(e,t,n,s,r,a)}return i}function Xw(e,t,n,s,r=.001){return f(s.slice().sort(),Cg(0,e.rank-1))?function(e,t,n,s,r=.001){return Ni((()=>{const a=sc(e,s),i=a.mean,o=a.variance;return[Kw(e,i,o,n,t,r),i,o]}))}(e,t,n,s,r):function(e,t,n,s,r=.001){return Ni((()=>{const a=sc(e,s),i=a.mean,o=a.variance,l=[];for(const t of Cg(0,e.rank))-1!==s.indexOf(t)?l.push(1):l.push(e.shape[t]);const u=tl(i,l),c=tl(o,l),h=null==t?null:tl(t,l),p=null==n?null:tl(n,l);return[Kw(e,u,c,p,h,r),i,o]}))}(e,t,n,s,r)}qw.className="AlphaDropout",go(qw);class Yw extends $y{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=dy(e.betaInitializer||"zeros"),this.gammaInitializer=dy(e.gammaInitializer||"ones"),this.movingMeanInitializer=dy(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=dy(e.movingVarianceInitializer||"ones"),this.betaConstraint=Ky(e.betaConstraint),this.gammaConstraint=Ky(e.gammaConstraint),this.betaRegularizer=Lx(e.betaRegularizer),this.gammaRegularizer=Lx(e.gammaRegularizer)}build(e){e=yy(e);const t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(null==n)throw new Mm(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new Ny({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 Ni((()=>{const n=null!=t.training&&t.training,s=gy(e),r=s.shape,a=r.length,i=Cg(0,a),o=this.axis>=0?this.axis:this.axis+a;i.splice(o,1);const l=Bm(1,a);l[o]=r[o];const u=i.slice();u.sort();const c=!f(u,Cg(0,a).slice(0,a-1));if(!n)return(()=>{if(c){const e=tl(this.movingMean.read(),l),t=tl(this.movingVariance.read(),l),n=this.center?tl(this.beta.read(),l):null,r=this.scale?tl(this.gamma.read(),l):null;return Kw(s,e,t,n,r,this.epsilon)}return Kw(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]=Xw(s,this.gamma.read(),this.beta.read(),i,this.epsilon),m=(e,t,n)=>{Ni((()=>{const s=1-n,r=e.read(),a=Co(Mu(r,t),s);e.write(Mu(r,a))}))};return(()=>{m(this.movingMean,p,this.momentum),m(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:py(this.betaInitializer),gammaInitializer:py(this.gammaInitializer),movingMeanInitializer:py(this.movingMeanInitializer),movingVarianceInitializer:py(this.movingVarianceInitializer),betaRegularizer:Ox(this.betaRegularizer),gammaRegularizer:Ox(this.gammaRegularizer),betaConstraint:jy(this.betaConstraint),gammaConstraint:jy(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}}Yw.className="BatchNormalization",go(Yw);class Zw extends $y{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=dy(e.betaInitializer||"zeros"),this.gammaInitializer=dy(e.gammaInitializer||"ones"),this.betaRegularizer=Lx(e.betaRegularizer),this.gammaRegularizer=Lx(e.gammaRegularizer),this.supportsMasking=!0}build(e){const t=(e=yy(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!==Jm(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=gy(e),s=n.shape,r=s.length;return Ni((()=>{let{mean:e,variance:t}=sc(n,this.axis,!0);const a=Bm(1,r);for(const e of this.axis)a[e]=s[e];const i=e=>null!=e&&e.shape.length!==r?tl(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=mu(e,u),t=mu(t,u),null!=o&&(o=mu(o,c)),null!=l&&(l=mu(l,c)),Kw(n,e,t,l,o,this.epsilon)}))}getConfig(){const e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:py(this.betaInitializer),gammaInitializer:py(this.gammaInitializer),betaRegularizer:Ox(this.betaRegularizer),gammaRegularizer:Ox(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}}Zw.className="LayerNormalization",go(Zw);class Jw extends $y{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 Mm(`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 Mm(`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 Mm(`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 Ny({ndim:4})]}computeOutputShape(e){let t,n;return e=yy(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 Ni((()=>{return t=gy(e),n=this.padding,s=this.dataFormat,Ni((()=>{if(4!==t.rank)throw new Mm(`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 Mm("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 Mm(`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]],uc(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 Qw(e,t,n,s,r,a){return Ni((()=>{let i;mg(r),yg(a),gg(s),null==n&&(n=[1,1]),null==s&&(s="valid"),null==r&&(r="channelsLast"),null==a&&(a="max"),e=qx(e,r);const o="same"===s?"same":"valid";return i="max"===a?ju(e,t,n,o):nl(e,t,n,o),"channelsFirst"===r&&(i=_i(i,[0,3,1,2])),i}))}function ev(e,t,n,s,r,a){return Ni((()=>{let i;mg(r),yg(a),gg(s),null==n&&(n=[1,1,1]),null==s&&(s="valid"),null==r&&(r="channelsLast"),null==a&&(a="max"),e=Kx(e,r);const o="same"===s?"same":"valid";return i="max"===a?qu(e,t,n,o):sl(e,t,n,o),"channelsFirst"===r&&(i=_i(i,[0,4,1,2,3])),i}))}Jw.className="ZeroPadding2D",go(Jw);class tv extends $y{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 Mm(`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(ng(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 Mm(`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}ng(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,gg(this.padding),this.inputSpec=[new Ny({ndim:3})]}computeOutputShape(e){const t=Hx((e=yy(e))[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return Ni((()=>{this.invokeCallHook(e,t),e=Rg(gy(e),2);const n=this.poolingFunction(gy(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return dh(n,[2])}))}getConfig(){const e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}}class nv extends tv{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return mg(r),gg(s),Qw(e,t,n,s,r,"max")}}nv.className="MaxPooling1D",go(nv);class sv extends tv{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return mg(r),gg(s),Qw(e,t,n,s,r,"avg")}}sv.className="AveragePooling1D",go(sv);class rv extends $y{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 Mm(`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];ng(this.poolSize,"poolSize"),ng(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,mg(this.dataFormat),gg(this.padding),this.inputSpec=[new Ny({ndim:4})]}computeOutputShape(e){e=yy(e);let t="channelsFirst"===this.dataFormat?e[2]:e[1],n="channelsFirst"===this.dataFormat?e[3]:e[2];return t=Hx(t,this.poolSize[0],this.padding,this.strides[0]),n=Hx(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 Ni((()=>(this.invokeCallHook(e,t),this.poolingFunction(gy(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 av extends rv{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return mg(r),gg(s),Qw(e,t,n,s,r,"max")}}av.className="MaxPooling2D",go(av);class iv extends rv{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return mg(r),gg(s),Qw(e,t,n,s,r,"avg")}}iv.className="AveragePooling2D",go(iv);class ov extends $y{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 Mm(`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];ng(this.poolSize,"poolSize"),ng(this.strides,"strides"),this.padding=null==e.padding?"valid":e.padding,this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,mg(this.dataFormat),gg(this.padding),this.inputSpec=[new Ny({ndim:5})]}computeOutputShape(e){e=yy(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=Hx(t,this.poolSize[0],this.padding,this.strides[0]),n=Hx(n,this.poolSize[1],this.padding,this.strides[1]),s=Hx(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 Ni((()=>(this.invokeCallHook(e,t),this.poolingFunction(gy(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 lv extends ov{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return mg(r),gg(s),ev(e,t,n,s,r,"max")}}lv.className="MaxPooling3D",go(lv);class uv extends ov{constructor(e){super(e)}poolingFunction(e,t,n,s,r){return mg(r),gg(s),ev(e,t,n,s,r,"avg")}}uv.className="AveragePooling3D",go(uv);class cv extends $y{constructor(e){super(e),this.inputSpec=[new Ny({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Lm}}class hv extends cv{constructor(e){super(e||{})}call(e,t){return Ni((()=>{const t=gy(e);return Yu(t,1)}))}}hv.className="GlobalAveragePooling1D",go(hv);class pv extends cv{constructor(e){super(e||{})}call(e,t){return Ni((()=>{const t=gy(e);return nu(t,1)}))}}pv.className="GlobalMaxPooling1D",go(pv);class dv extends $y{constructor(e){super(e),this.dataFormat=null==e.dataFormat?"channelsLast":e.dataFormat,mg(this.dataFormat),this.inputSpec=[new Ny({ndim:4})]}computeOutputShape(e){return"channelsLast"===this.dataFormat?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new Lm}getConfig(){const e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}}class fv extends dv{call(e,t){return Ni((()=>{const t=gy(e);return"channelsLast"===this.dataFormat?Yu(t,[1,2]):Yu(t,[2,3])}))}}fv.className="GlobalAveragePooling2D",go(fv);class mv extends dv{call(e,t){return Ni((()=>{const t=gy(e);return"channelsLast"===this.dataFormat?nu(t,[1,2]):nu(t,[2,3])}))}}mv.className="GlobalMaxPooling2D",go(mv);class gv extends $y{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=lb(t.layer,n);delete t.layer;const r={layer:s};return Object.assign(r,t),new e(r)}}class yv extends gv{constructor(e){super(e),this.supportsMasking=!0}build(e){if((e=yy(e)).length<3)throw new Mm(`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=yy(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 Ni((()=>hw(((e,n)=>[gy(this.layer.call(e,t)),[]]),e=gy(e),[],!1,null,null,!1,!0)[1]))}}yv.className="TimeDistributed",go(yv);class bv extends gv{constructor(e){super(e);const t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=lb(n),t.goBackwards=!0!==t.goBackwards;const s={};var r;if(s.className=e.layer.getClassName(),s.config=t,this.backwardLayer=lb(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,eg(dg,"BidirectionalMergeMode",r),e.weights)throw new Lm("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()):Um(n)}apply(e,t){let n=null==t?null:t.initialState,s=null==t?null:t.constants;null==t&&(t={});const r=cw(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 Mm("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 Ny({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 Lm("Support for constants in Bidirectional layers is not implemented yet.");const o=a[0]instanceof Iy;for(const e of a)if(e instanceof Iy!==o)throw new Mm("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 Ni((()=>{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=Uc(r,1)),"concat"===this.mergeMode?i=Og([s,r]):"sum"===this.mergeMode?i=Io(s,r):"ave"===this.mergeMode?i=Co(.5,Io(s,r)):"mul"===this.mergeMode?i=Co(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){xg(this.forwardLayer.name,(()=>{this.forwardLayer.build(e)})),xg(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=lb(t.layer);if(delete t.layer,null!=t.numConstants)throw new Lm("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");const s=t;return s.layer=n,new e(s)}}bv.className="Bidirectional",go(bv);class xv extends $y{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 Ni((()=>("float32"!==(e=gy(e)).dtype&&(e=Ag(e,"float32")),Io(Co(e,this.scale),this.offset))))}}xv.className="Rescaling",go(xv);const{resizeBilinear:wv,cropAndResize:vv}=Xp;class kv extends $y{constructor(e){super(e),this.height=e.height,this.width=e.width}centerCrop(e,t,n,s,r,a,i,o){return Ni((()=>{let l,u=!1;const c=[t/a,n/i,(s+t)/a,(r+n)/i],h=[];3===e.rank?(u=!0,l=fh([e])):l=e;for(let e=0;e<l.shape[0];e++)h.push(c);const p=ra(h,[h.length,4]),d=Pc(0,h.length,1,"int32"),f=vv(l,p,d,[s,r],"nearest");return Ag(u?gy(Ch(f)):f,o)}))}upsize(e,t,n,s){return Ni((()=>Ag(wv(e,[t,n]),s)))}call(e,t){return Ni((()=>{const t=gy(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=yy(e)).length-3,n=e.length-2;return e[t]=this.height,e[n]=this.width,e}}kv.className="CenterCrop",go(kv);class Nv extends $y{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=yy(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 Ni((()=>{let n;if("int32"!==(e=gy(e)).dtype&&(e=Ag(e,"int32")),void 0!==t.countWeights){if("count"!==this.outputMode)throw new Mm(`countWeights is not used when outputMode !== count.\n Received countWeights=${t.countWeights}`);n=gy(t.countWeights)}const s=nu(e),r=su(e),a=xu(this.numTokens,s).bufferSync().get(0),i=wu(r,0).bufferSync().get(0);if(!a||!i)throw new Mm(`Input values must be between 0 < values <= numTokens with numTokens=${this.numTokens}`);return function(e,t,n,s){let r=gy(e);if("int32"!==r.dtype&&(r=Ag(r,"int32")),"int"===t)return r;const a=r.shape;if(0===r.rank&&(r=du(r,-1)),"oneHot"===t&&1!==r.shape[r.shape.length-1]&&(r=du(r,-1)),r.rank>2)throw new Mm(`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=Ol(r,void 0!==s&&"count"===t?s:[],n,i),"tfIdf"!==t)return o;if(s)return Co(o,s);throw new Mm("When outputMode is 'tfIdf', weights must be provided.")}(e,this.outputMode,this.numTokens,n)}))}}Nv.className="CategoryEncoding",go(Nv);const Iv=new Set(["bilinear","nearest"]);class Sv extends $y{constructor(e){if(super(e),this.height=e.height,this.width=e.width,e.interpolation){if(!Iv.has(e.interpolation))throw new Mm(`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=yy(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 Ni((()=>{const t=[this.height,this.width];if("bilinear"===this.interpolation)return Xp.resizeBilinear(e,t,!this.cropToAspectRatio);if("nearest"===this.interpolation)return Xp.resizeNearestNeighbor(e,t,!this.cropToAspectRatio);throw new Error(`Interpolation is ${this.interpolation} but only ${[...Iv]} are supported`)}))}}function Tv(e){return new sv(e)}function Cv(e){return new iv(e)}function $v(e){return new uv(e)}function Ev(e){return new pv(e)}function Av(e){return new mv(e)}function Rv(e){return new nv(e)}function _v(e){return new av(e)}Sv.className="Resizing",go(Sv);const Fv=Ev,Dv=Av,Ov=Rv,Mv=_v;var Lv=Object.freeze({__proto__:null,inputLayer:function(e){return new Ay(e)},elu:function(e){return new Wx(e)},reLU:function(e){return new zx(e)},leakyReLU:function(e){return new Px(e)},prelu:function(e){return new Bx(e)},softmax:function(e){return new Ux(e)},thresholdedReLU:function(e){return new Vx(e)},conv1d:function(e){return new iw(e)},conv2d:function(e){return new ew(e)},conv2dTranspose:function(e){return new nw(e)},conv3d:function(e){return new tw(e)},conv3dTranspose:function(e){return new sw(e)},separableConv2d:function(e){return new aw(e)},cropping2D:function(e){return new ow(e)},upSampling2d:function(e){return new lw(e)},depthwiseConv2d:function(e){return new uw(e)},activation:function(e){return new Aw(e)},dense:function(e){return new $w(e)},dropout:function(e){return new Tw(e)},spatialDropout1d:function(e){return new Cw(e)},flatten:function(e){return new Ew(e)},repeatVector:function(e){return new Rw(e)},reshape:function(e){return new _w(e)},permute:function(e){return new Fw(e)},embedding:function(e){return new Ow(e)},add:function(e){return new Lw(e)},average:function(e){return new Pw(e)},concatenate:function(e){return new Vw(e)},maximum:function(e){return new Bw(e)},minimum:function(e){return new Ww(e)},multiply:function(e){return new zw(e)},dot:function(e){return new Gw(e)},batchNormalization:function(e){return new Yw(e)},layerNormalization:function(e){return new Zw(e)},zeroPadding2d:function(e){return new Jw(e)},averagePooling1d:Tv,avgPool1d:function(e){return Tv(e)},avgPooling1d:function(e){return Tv(e)},averagePooling2d:Cv,avgPool2d:function(e){return Cv(e)},avgPooling2d:function(e){return Cv(e)},averagePooling3d:$v,avgPool3d:function(e){return $v(e)},avgPooling3d:function(e){return $v(e)},globalAveragePooling1d:function(e){return new hv(e)},globalAveragePooling2d:function(e){return new fv(e)},globalMaxPooling1d:Ev,globalMaxPooling2d:Av,maxPooling1d:Rv,maxPooling2d:_v,maxPooling3d:function(e){return new lv(e)},gru:function(e){return new yw(e)},gruCell:function(e){return new gw(e)},lstm:function(e){return new xw(e)},lstmCell:function(e){return new bw(e)},simpleRNN:function(e){return new mw(e)},simpleRNNCell:function(e){return new fw(e)},convLstm2d:function(e){return new Sw(e)},convLstm2dCell:function(e){return new Iw(e)},rnn:function(e){return new pw(e)},stackedRNNCells:function(e){return new ww(e)},bidirectional:function(e){return new bv(e)},timeDistributed:function(e){return new yv(e)},globalMaxPool1d:Fv,globalMaxPool2d:Dv,maxPool1d:Ov,maxPool2d:Mv,Layer:$y,RNN:pw,RNNCell:dw,input:px,gaussianNoise:function(e){return new Hw(e)},gaussianDropout:function(e){return new jw(e)},alphaDropout:function(e){return new qw(e)},masking:function(e){return new Dw(e)},rescaling:function(e){return new xv(e)},centerCrop:function(e){return new kv(e)},resizing:function(e){return new Sv(e)},categoryEncoding:function(e){return new Nv(e)}});var zv=Object.freeze({__proto__:null,binaryAccuracy:function(e,t){return vb(e,t)},binaryCrossentropy:function(e,t){return Tb(e,t)},sparseCategoricalAccuracy:function(e,t){return Cb(e,t)},categoricalAccuracy:function(e,t){return kb(e,t)},categoricalCrossentropy:function(e,t){return $b(e,t)},precision:function(e,t){return Ib(e,t)},recall:function(e,t){return Sb(e,t)},cosineProximity:function(e,t){return bb(e,t)},meanAbsoluteError:function(e,t){return hb(e,t)},meanAbsolutePercentageError:function(e,t){return pb(e,t)},MAPE:function(e,t){return pb(e,t)},mape:function(e,t){return pb(e,t)},meanSquaredError:function(e,t){return cb(e,t)},MSE:function(e,t){return cb(e,t)},mse:function(e,t){return cb(e,t)}}),Pv=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=lb(Wb(n),t);if(null!=e.weightsManifest){const t=await ii(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),Ii(t)}return s}});var Bv=Object.freeze({__proto__:null,l1l2:function(e){return new Fx(e)},l1:function(e){return Rx(t=e),new Fx({l1:null!=t?t.l1:null,l2:0});var t},l2:function(e){return Rx(t=e),new Fx({l2:null!=t?t.l2:null,l1:0});var t}});class Wv extends eb{constructor(){super(...arguments),this.model=null}setModel(e){if(!(e instanceof ux))throw new Error("model must be a LayersModel, not some other Container");this.model=e}}function Vv(e,t){return e<t}function Uv(e,t){return e>t}class Gv extends Wv{constructor(e){if(super(),null==e&&(e={}),e.restoreBestWeights)throw new Lm("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=Vv:"max"===this.mode||-1!==this.monitor.indexOf("acc")?this.monitorFunc=Uv:this.monitorFunc=Vv,this.monitorFunc===Vv&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,null!=this.baseline?this.best=this.baseline:this.best=this.monitorFunc===Vv?1/0:-1/0}async onEpochEnd(e,t){await Jy(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 Hv={earlyStopping:function(e){return new Gv(e)}};var jv,qv;X().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"}(jv||(jv={})),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={}))}(qv||(qv={}));const Kv={};function Xv(e){return Kv[e]}function Yv(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;if("tensor"===a.type)return Zv(t.inputNames[a.inputIndexStart],n,s,r);if("tensors"===a.type){return t.inputNames.slice(e,i).map((e=>Zv(e,n,s,r)))}const o=Zv(t.inputNames.slice(e)[0],n,s,r),l=o.dataSync();return"number"===a.type?l[0]:z(o.shape,l)}const i=t.attrParams[e];return i&&i.value}function Zv(e,t,n,s){const[r,a]=ek(e);if(null!=s){const e=s.getHashTableHandleByName(r);if(null!=e)return e}const i=n.currentContextIds.find((e=>!!t[Qv(r,e)]));return void 0!==i?t[Qv(r,i)][a]:void 0}function Jv(e,t){const[n,s,r]=ek(e);return[Qv(n,t&&t.currentContextId),s,r]}function Qv(e,t){return t?`${e}-${t}`:e}function ek(e){const t=e.split(":");if(1===t.length)return[e,0,void 0];const n=t[0],s=3===t.length?t[1]:void 0;return[n,Number(t[t.length-1]),s]}function tk(e,t,n){let s=Yv("pad",e,t,n);if("explicit"===s){s=Yv("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 nk(e){return e.kept?e:Qa(e)}var sk=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 rk=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:"Prod",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axes",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LeakyRelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"alpha",name:"alpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsNan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}]});var ak=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 ik=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 ok=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:"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 lk=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 uk=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 ck=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 hk=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 pk=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 dk=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}]}]});var fk=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"}]}]});var mk=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"}]},{tfOpName:"SparseToDense",category:"normalization",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!0,notSupported:!0}]}]});var gk=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"}]},{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 yk=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}]}]});var bk=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 xk=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 wk=Object.freeze({__proto__:null,json:[{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 vk=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:"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 kk{constructor(){const e=[].concat(...[sk,rk,ak,ik,ok,lk,uk,ck,hk,pk,dk,fk,mk,gk,yk,bk,xk,wk,vk].map((e=>e.json)));this.opMappers=e.reduce(((e,t)=>(e[t.tfOpName]=t,e)),{})}static get Instance(){return this._instance||(this._instance=new this)}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]=Jv(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]=Jv(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]=Jv(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=Xv(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=Ik(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=Ik(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"string[]":r=Dk(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=Dk(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number":r=Tk(e.attr,n.tfName,n.defaultValue||0),void 0===r&&n.tfDeprecatedName&&(r=Tk(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number[]":r=Fk(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=Fk(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool":r=Sk(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=Sk(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool[]":r=Mk(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=Mk(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape":r=_k(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=_k(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape[]":r=Ok(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=Ok(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype":r=Ek(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=Ek(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype[]":r=Ak(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=Ak(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"func":r=$k(e.attr,n.tfName,n.defaultValue),void 0===r&&n.tfDeprecatedName&&(r=$k(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]=Jv(e.name),n={name:t,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:Ck(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]=Jv(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]=Jv(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 Nk(e,t){const n=Array.isArray(e)?String.fromCharCode.apply(null,e):function(e){const t=X().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 Ik(e,t,n,s=!1){const r=e[t];return null!=r?Nk(r.s,s):n}function Sk(e,t,n){const s=e[t];return s?s.b:n}function Tk(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 Ck(e){switch("string"==typeof e&&(e=jv[e]),e){case jv.DT_FLOAT:case jv.DT_HALF:return"float32";case jv.DT_INT32:case jv.DT_INT64:case jv.DT_INT8:case jv.DT_UINT8:return"int32";case jv.DT_BOOL:return"bool";case jv.DT_DOUBLE:return"float32";case jv.DT_STRING:return"string";default:return null}}function $k(e,t,n){const s=e[t];return s&&s.func?s.func.name:n}function Ek(e,t,n){const s=e[t];return s&&s.type?Ck(s.type):n}function Ak(e,t,n){const s=e[t];return s&&s.list&&s.list.type?s.list.type.map((e=>Ck(e))):n}function Rk(e){if(!e.unknownRank)return null!=e.dim?e.dim.map((e=>"number"==typeof e.size?e.size:parseInt(e.size,10))):[]}function _k(e,t,n){const s=e[t];return s&&s.shape?Rk(s.shape):n}function Fk(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 Dk(e,t,n,s=!1){const r=e[t];return r&&r.list&&r.list.s?r.list.s.map((e=>Nk(e,s))):n}function Ok(e,t,n){const s=e[t];return s&&s.list&&s.list.shape?s.list.shape.map((e=>Rk(e))):n}function Mk(e,t,n){const s=e[t];return s&&s.list&&s.list.b?s.list.b:n}class Lk{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 Zv(e,this.tensorMap,this.context)}getAttr(e,t){const n=this.node.rawAttrs[e];if(null!=n.tensor)return Zv(e,this.tensorMap,this.context);if(null!=n.i||null!=n.f)return Tk(this.node.rawAttrs,e,t);if(null!=n.s)return Ik(this.node.rawAttrs,e,t);if(null!=n.b)return Sk(this.node.rawAttrs,e,t);if(null!=n.shape)return _k(this.node.rawAttrs,e,t);if(null!=n.type)return Ek(this.node.rawAttrs,e,t);if(null!=n.list){if(null!=n.list.i||null!=n.list.f)return Fk(this.node.rawAttrs,e,t);if(null!=n.list.s)return Dk(this.node.rawAttrs,e,t);if(null!=n.list.shape)return Ok(this.node.rawAttrs,e,t);if(null!=n.list.b)return Mk(this.node.rawAttrs,e,t);if(null!=n.list.type)return Ak(this.node.rawAttrs,e,t)}return t}}var zk=Object.freeze({__proto__:null,abs:$o,acos:Eo,acosh:Ao,add:Io,addN:Ro,all:_o,any:Fo,argMax:Do,argMin:Oo,asin:Mo,asinh:Lo,atan:zo,atan2:Po,atanh:Bo,avgPool:nl,avgPool3d:sl,basicLSTMCell:ll,batchToSpaceND:ul,batchNorm:cl,batchNorm2d:hl,batchNorm3d:pl,batchNorm4d:dl,bincount:fl,broadcastArgs:ml,broadcastTo:gl,buffer:Za,cast:Ja,ceil:yl,clipByValue:xl,clone:Qa,complex:na,concat:rl,concat1d:wl,concat2d:vl,concat3d:kl,concat4d:Nl,conv1d:Sl,conv2d:Il,conv2dTranspose:Cl,conv3d:$l,conv3dTranspose:Al,cos:Rl,cosh:_l,cumprod:Fl,cumsum:Dl,denseBincount:Ol,depthToSpace:Ml,depthwiseConv2d:Ll,diag:zl,dilation2d:Pl,div:To,divNoNan:Ul,dot:Gl,einsum:Hl,elu:jl,equal:Bl,erf:ql,euclideanNorm:hu,exp:pu,expandDims:du,expm1:fu,eye:gu,fill:bl,floor:yu,floorDiv:So,gather:bu,greater:xu,greaterEqual:wu,imag:Ei,isFinite:vu,isInf:ku,isNaN:Nu,leakyRelu:Iu,less:Su,lessEqual:Tu,linspace:Cu,localResponseNormalization:$u,log:Eu,log1p:Au,logSigmoid:Ou,logSoftmax:Lu,logSumExp:zu,logicalAnd:Pu,logicalNot:Bu,logicalOr:Wu,logicalXor:Vu,lowerBound:Hu,matMul:bi,max:nu,maxPool:ju,maxPool3d:qu,maxPoolWithArgmax:Ku,maximum:Xu,mean:Yu,meshgrid:Qu,min:su,minimum:ec,mirrorPad:tc,mod:nc,moments:sc,mul:Co,multiRNNCell:rc,multinomial:ac,neg:Ai,notEqual:ic,oneHot:xi,ones:Ju,onesLike:oc,outerProduct:lc,pad:uc,pad1d:cc,pad2d:hc,pad3d:pc,pad4d:dc,pool:mc,pow:ru,prelu:gc,print:ei,prod:yc,raggedGather:bc,raggedRange:xc,raggedTensorToTensor:wc,rand:vc,randomGamma:Oc,randomNormal:Mc,randomStandardNormal:Lc,randomUniform:zc,range:Pc,real:Ri,reciprocal:Bc,relu:Wc,relu6:Vc,reshape:tl,reverse:Uc,reverse1d:Gc,reverse2d:Hc,reverse3d:jc,reverse4d:qc,round:Kc,rsqrt:Xc,scalar:au,selu:Yc,separableConv2d:Zc,setdiff1dAsync:Jc,sigmoid:al,sign:Qc,sin:eh,sinh:th,slice:il,slice1d:nh,slice2d:sh,slice3d:rh,slice4d:ah,softmax:ih,softplus:Du,spaceToBatchND:fc,fft:oh,ifft:lh,irfft:uh,rfft:hh,split:ch,sqrt:iu,square:ou,squaredDifference:ph,squeeze:dh,stack:fh,step:mh,stridedSlice:gh,sub:Mu,sum:lu,tan:yh,tanh:ol,tensor:ra,tensor1d:bh,tensor2d:xh,tensor3d:Pi,tensor4d:wh,tensor5d:vh,tensor6d:kh,tile:mu,topk:Nh,truncatedNormal:Ih,unique:Sh,unsortedSegmentSum:Th,unstack:Ch,upperBound:$h,variable:Eh,where:Wl,whereAsync:Rh,zeros:Zu,zerosLike:Vl,op:ta,OP_SCOPE_SUFFIX:ea,booleanMaskAsync:_h,transpose:_i,norm:cu,movingAverage:Fh,scatterND:Dh,searchSorted:Gu,sparseToDense:Oh,gatherND:Mh,dropout:Lh,enclosingPowerOfTwo:zh,cosineWindow:Ph,inTopKAsync:Bh,image:Xp,linalg:Yp,losses:Zp,spectral:qp,fused:Zh,signal:Kp,sparse:Jp,string:Qp});function Pk(e,t,n=""){if("number"!=typeof e&&"number"!=typeof t){u(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];u(r<0||a<0||r===a,(()=>n+` Shapes ${e} and ${t} must match`))}}}function Bk(e){return"number"!=typeof e&&!e.some((e=>e<0))}function Wk(e,t,n){let s=Vk(e,n);const r=!Bk(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=Vk(e.shape,s)})),!Bk(s))throw new Error(`Non-fully-defined elementShape: ${s}`);return s}function Vk(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 Uk{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=au(0),Si(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),Pk(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,Si(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 ra([],[0].concat(this.elementShape));const n=this.readMany(e);return Pk(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),fh(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 ra([],[0].concat(this.elementShape));const t=[];for(let e=0;e<this.size();e++)t.push(e);const n=this.readMany(t);return Pk(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),rl(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,Ch(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=[];Ni((()=>{t=tl(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]=tl(il(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 Gk{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}`);Pk(t,e.shape,"TensorList shape mismatch: "),Si(e)})),this.idTensor=au(0),this.maxNumElements=s,Si(this.idTensor)}get id(){return this.idTensor.id}copy(){return new Gk([...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.`);Pk(e,this.elementShape,"TensorList shape mismatch: ");const s=Wk(this.elementShape,this.tensors,e);return Ni((()=>{const e=this.tensors.map((e=>tl(e,s)));return fh(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=Wk(this.elementShape,this.tensors,e),s=this.tensors.pop();return s.kept=!1,Pk(s.shape,e,"TensorList shape mismatch: "),tl(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(Pk(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Si(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 Gk([],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.`);Pk(this.tensors[e].shape,t,"TensorList shape mismatch: ");const s=Wk(this.elementShape,this.tensors,t);return tl(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.`);Pk(this.elementShape,t.shape,"TensorList shape mismatch: "),Si(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}`);Pk(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());const s=Wk(this.elementShape,this.tensors,n);return 0===e.length?ra([],[0].concat(s)):Ni((()=>{const t=e.map((e=>tl(this.tensors[e],s)));return fh(t,0)}))}concat(e,t){if(e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);Pk(this.elementShape,t,"TensorList shape mismatch: ");const n=Wk(this.elementShape,this.tensors,t);return 0===this.size()?ra([],[0].concat(n)):Ni((()=>{const e=this.tensors.map((e=>tl(e,n)));return rl(e,0)}))}}const Hk=async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{const s=Yv("thenBranch",e,t,n),r=Yv("elseBranch",e,t,n),a=Yv("cond",e,t,n),i=Yv("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=Yv("body",e,t,n),r=Yv("cond",e,t,n),a=Yv("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[nk(Yv("pred",e,t,n))];case"Switch":{const s=Yv("pred",e,t,n);let r=Yv("data",e,t,n);return r.kept||(r=nk(r)),(await s.data())[0]?[void 0,r]:[r,void 0]}case"Merge":{const s=e.inputNames.find((e=>void 0!==Zv(e,t,n)));if(s){return[nk(Zv(s,t,n))]}return}case"Enter":{const s=Yv("frameName",e,t,n),r=Yv("tensor",e,t,n);return n.enterFrame(s),[nk(r)]}case"Exit":{const s=Yv("tensor",e,t,n);return n.exitFrame(),[nk(s)]}case"NextIteration":{const s=Yv("tensor",e,t,n);return n.nextIteration(),[nk(s)]}case"TensorArrayV3":{const s=Yv("size",e,t,n),r=Yv("dtype",e,t,n),a=Yv("elementShape",e,t,n),i=Yv("dynamicSize",e,t,n),o=Yv("clearAfterRead",e,t,n),l=Yv("identicalElementShapes",e,t,n),u=Yv("name",e,t,n),c=new Uk(u,r,s,a,l,i,o);return n.addTensorArray(c),[c.idTensor,au(1)]}case"TensorArrayWriteV3":{const s=Yv("tensorArrayId",e,t,n),r=Yv("index",e,t,n),a=Yv("tensor",e,t,n),i=n.getTensorArray(s.id);return i.write(r,a),[i.idTensor]}case"TensorArrayReadV3":{const s=Yv("tensorArrayId",e,t,n),r=Yv("index",e,t,n);return[n.getTensorArray(s.id).read(r)]}case"TensorArrayGatherV3":{const s=Yv("tensorArrayId",e,t,n),r=Yv("indices",e,t,n),a=Yv("dtype",e,t,n);return[n.getTensorArray(s.id).gather(r,a)]}case"TensorArrayScatterV3":{const s=Yv("tensorArrayId",e,t,n),r=Yv("indices",e,t,n),a=Yv("tensor",e,t,n),i=n.getTensorArray(s.id);return i.scatter(r,a),[i.idTensor]}case"TensorArrayConcatV3":{const s=Yv("tensorArrayId",e,t,n),r=n.getTensorArray(s.id),a=Yv("dtype",e,t,n);return[r.concat(a)]}case"TensorArraySplitV3":{const s=Yv("tensorArrayId",e,t,n),r=Yv("tensor",e,t,n),a=Yv("lengths",e,t,n),i=n.getTensorArray(s.id);return i.split(a,r),[i.idTensor]}case"TensorArraySizeV3":{const s=Yv("tensorArrayId",e,t,n);return[au(n.getTensorArray(s.id).size(),"int32")]}case"TensorArrayCloseV3":{const s=Yv("tensorArrayId",e,t,n),r=n.getTensorArray(s.id);return r.clearAndClose(),[r.idTensor]}case"TensorListSetItem":{const s=Yv("tensorListId",e,t,n),r=Yv("index",e,t,n),a=Yv("tensor",e,t,n),i=n.getTensorList(s.id);return i.setItem(r,a),[i.idTensor]}case"TensorListGetItem":{const s=Yv("tensorListId",e,t,n),r=Yv("index",e,t,n),a=Yv("elementShape",e,t,n),i=Yv("elementDType",e,t,n);return[n.getTensorList(s.id).getItem(r,a,i)]}case"TensorListScatterV2":case"TensorListScatter":{const s=Yv("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 Gk([],n,e.dtype,s),i=Ch(e,0);return t.forEach(((e,t)=>{a.setItem(e,i[t])})),a}(Yv("tensor",e,t,n),s,Yv("elementShape",e,t,n),Yv("numElements",e,t,n));return n.addTensorList(r),[r.idTensor]}case"TensorListReserve":case"EmptyTensorList":{const s=Yv("elementShape",e,t,n),r=Yv("elementDType",e,t,n);let a;a="TensorListReserve"===e.op?"numElements":"maxNumElements";const i=Yv(a,e,t,n),o=function(e,t,n,s){return new Gk([],e,t,s)}(s,r,0,"TensorListReserve"===e.op?-1:i);return n.addTensorList(o),[o.idTensor]}case"TensorListGather":{const s=Yv("tensorListId",e,t,n),r=Yv("indices",e,t,n),a=Yv("elementShape",e,t,n),i=Yv("elementDType",e,t,n);return[n.getTensorList(s.id).gather(r,i,a)]}case"TensorListStack":{const s=Yv("tensorListId",e,t,n),r=Yv("elementShape",e,t,n),a=Yv("elementDType",e,t,n),i=Yv("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}`);Pk(e.shape.slice(1),t,"TensorList shape mismatch: ");const r=Ch(e);return new Gk(r,t,s)}(Yv("tensor",e,t,n),Yv("elementShape",e,t,n),Yv("elementDType",e,t,n));return n.addTensorList(s),[s.idTensor]}case"TensorListConcat":case"TensorListConcatV2":{const s=Yv("tensorListId",e,t,n),r=n.getTensorList(s.id),a=Yv("dtype",e,t,n),i=Yv("elementShape",e,t,n);return[r.concat(a,i)]}case"TensorListPushBack":{const s=Yv("tensorListId",e,t,n),r=Yv("tensor",e,t,n),a=n.getTensorList(s.id);return a.pushBack(r),[a.idTensor]}case"TensorListPopBack":{const s=Yv("tensorListId",e,t,n),r=Yv("elementShape",e,t,n),a=Yv("elementDType",e,t,n);return[n.getTensorList(s.id).popBack(r,a)]}case"TensorListSplit":{const s=Yv("tensor",e,t,n),r=Yv("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=Vk(e.shape.slice(1),n),i=0===s?0:e.size/s,o=Ni((()=>{const n=[];e=tl(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]=tl(il(e,o,l),a)}return e.dispose(),n})),l=new Gk([],n,e.dtype,t.length);for(let e=0;e<o.length;e++)l.setItem(e,o[e]);return l}(s,Yv("lengths",e,t,n),r);return n.addTensorList(a),[a.idTensor]}case"TensorListLength":{const s=Yv("tensorListId",e,t,n);return[au(n.getTensorList(s.id).size(),"int32")]}case"TensorListResize":{const s=Yv("tensorListId",e,t,n),r=Yv("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 jk(e,t,n){const[s,r]=Yv("fusedOps",e,t,n),a="biasadd"===s,i=!a,o="prelu"===r,l="fusedbatchnorm"===s,u=Yv("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=Yv("strides",e,t,n),h=tk(e,t,n),p=Yv("dataFormat",e,t,n).toUpperCase(),d=Yv("dilations",e,t,n);let[f,m]=Yv("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:Yv("leakyreluAlpha",e,t,n)}}function qk(e,t,n){return{boxes:Yv("boxes",e,t,n),scores:Yv("scores",e,t,n),maxOutputSize:Yv("maxOutputSize",e,t,n),iouThreshold:Yv("iouThreshold",e,t,n),scoreThreshold:Yv("scoreThreshold",e,t,n),softNmsSigma:Yv("softNmsSigma",e,t,n)}}class Kk{constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=au(0),this.tensorMap=new Map,Si(this.handle)}get id(){return this.handle.id}clearAndClose(){this.tensorMap.forEach((e=>e.dispose())),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return au(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(),Ni((()=>{const e=Ch(t),s=n.length,r=e.length;u(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];Si(r),this.tensorMap.set(s,r)}return this.handle}))}async find(e,t){this.checkKeyAndValueTensor(e,t);const n=await e.data();return Ni((()=>{const e=[];for(let s=0;s<n.length;s++){const r=n[s],a=this.findWithDefault(r,t);e.push(a)}return fh(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 Xk(e,t,n,s,r=Ni){const a=((e,t,n)=>{switch(e.category){case"arithmetic":return r((()=>((e,t,n,s=zk)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[s.add(Yv("a",e,t,n),Yv("b",e,t,n))];case"AddN":return[s.addN(Yv("tensors",e,t,n))];case"FloorMod":case"Mod":return[s.mod(Yv("a",e,t,n),Yv("b",e,t,n))];case"Mul":return[s.mul(Yv("a",e,t,n),Yv("b",e,t,n))];case"RealDiv":case"Div":return[s.div(Yv("a",e,t,n),Yv("b",e,t,n))];case"DivNoNan":return[s.divNoNan(Yv("a",e,t,n),Yv("b",e,t,n))];case"FloorDiv":return[s.floorDiv(Yv("a",e,t,n),Yv("b",e,t,n))];case"Sub":return[s.sub(Yv("a",e,t,n),Yv("b",e,t,n))];case"Minimum":return[s.minimum(Yv("a",e,t,n),Yv("b",e,t,n))];case"Maximum":return[s.maximum(Yv("a",e,t,n),Yv("b",e,t,n))];case"Pow":return[s.pow(Yv("a",e,t,n),Yv("b",e,t,n))];case"SquaredDifference":return[s.squaredDifference(Yv("a",e,t,n),Yv("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=zk)=>{switch(e.op){case"Abs":case"ComplexAbs":return[s.abs(Yv("x",e,t,n))];case"Acos":return[s.acos(Yv("x",e,t,n))];case"Acosh":return[s.acosh(Yv("x",e,t,n))];case"Asin":return[s.asin(Yv("x",e,t,n))];case"Asinh":return[s.asinh(Yv("x",e,t,n))];case"Atan":return[s.atan(Yv("x",e,t,n))];case"Atan2":return[s.atan2(Yv("x",e,t,n),Yv("y",e,t,n))];case"Atanh":return[s.atanh(Yv("x",e,t,n))];case"Ceil":return[s.ceil(Yv("x",e,t,n))];case"Complex":return[s.complex(Yv("real",e,t,n),Yv("imag",e,t,n))];case"Cos":return[s.cos(Yv("x",e,t,n))];case"Cosh":return[s.cosh(Yv("x",e,t,n))];case"Elu":return[s.elu(Yv("x",e,t,n))];case"Erf":return[s.erf(Yv("x",e,t,n))];case"Exp":return[s.exp(Yv("x",e,t,n))];case"Expm1":return[s.expm1(Yv("x",e,t,n))];case"Floor":return[s.floor(Yv("x",e,t,n))];case"Log":return[s.log(Yv("x",e,t,n))];case"Log1p":return[s.log1p(Yv("x",e,t,n))];case"Imag":return[s.imag(Yv("x",e,t,n))];case"Neg":return[s.neg(Yv("x",e,t,n))];case"Reciprocal":return[s.reciprocal(Yv("x",e,t,n))];case"Real":return[s.real(Yv("x",e,t,n))];case"Relu":return[s.relu(Yv("x",e,t,n))];case"Round":return[s.round(Yv("x",e,t,n))];case"Selu":return[s.selu(Yv("x",e,t,n))];case"Sigmoid":return[s.sigmoid(Yv("x",e,t,n))];case"Sin":return[s.sin(Yv("x",e,t,n))];case"Sign":return[s.sign(Yv("x",e,t,n))];case"Sinh":return[s.sinh(Yv("x",e,t,n))];case"Softplus":return[s.softplus(Yv("x",e,t,n))];case"Sqrt":return[s.sqrt(Yv("x",e,t,n))];case"Square":return[s.square(Yv("x",e,t,n))];case"Tanh":return[s.tanh(Yv("x",e,t,n))];case"Tan":return[s.tan(Yv("x",e,t,n))];case"ClipByValue":return[s.clipByValue(Yv("x",e,t,n),Yv("clipValueMin",e,t,n),Yv("clipValueMax",e,t,n))];case"Relu6":return[s.relu6(Yv("x",e,t,n))];case"Rsqrt":return[s.rsqrt(Zv(e.inputNames[0],t,n))];case"Prod":return[s.prod(Yv("x",e,t,n),Yv("axes",e,t,n))];case"LeakyRelu":return[s.leakyRelu(Yv("x",e,t,n),Yv("alpha",e,t,n))];case"Prelu":return[s.prelu(Yv("x",e,t,n),Yv("alpha",e,t,n))];case"IsNan":return[s.isNaN(Zv(e.inputNames[0],t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"control":return Hk(e,t,n);case"convolution":return r((()=>((e,t,n,s=zk)=>{switch(e.op){case"Conv1D":{const r=Yv("stride",e,t,n),a=Yv("pad",e,t,n),i=Yv("dataFormat",e,t,n).toUpperCase(),o=Yv("dilation",e,t,n);return[s.conv1d(Yv("x",e,t,n),Yv("filter",e,t,n),r,a,i,o)]}case"Conv2D":{const r=Yv("strides",e,t,n),a=tk(e,t,n),i=Yv("dataFormat",e,t,n).toUpperCase(),o=Yv("dilations",e,t,n);return[s.conv2d(Yv("x",e,t,n),Yv("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}=jk(e,t,n);return[s.fused.conv2d({x:Yv("x",e,t,n),filter:Yv("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}=jk(e,t,n);return[s.fused.depthwiseConv2d({x:Yv("x",e,t,n),filter:Yv("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=Yv("outputShape",e,t,n),a=Yv("strides",e,t,n),i=tk(e,t,n);return[s.conv2dTranspose(Yv("x",e,t,n),Yv("filter",e,t,n),r,[a[1],a[2]],i)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{const r=Yv("strides",e,t,n),a=tk(e,t,n),i=Yv("dilations",e,t,n),o=Yv("dataFormat",e,t,n).toUpperCase();return[s.depthwiseConv2d(Yv("input",e,t,n),Yv("filter",e,t,n),[r[1],r[2]],a,o,[i[1],i[2]])]}case"Conv3D":{const r=Yv("strides",e,t,n),a=Yv("pad",e,t,n),i=Yv("dataFormat",e,t,n).toUpperCase(),o=Yv("dilations",e,t,n);return[s.conv3d(Yv("x",e,t,n),Yv("filter",e,t,n),[r[1],r[2],r[3]],a,i,[o[1],o[2],o[3]])]}case"AvgPool":{const r=Yv("strides",e,t,n),a=Yv("pad",e,t,n),i=Yv("kernelSize",e,t,n);return[s.avgPool(Yv("x",e,t,n),[i[1],i[2]],[r[1],r[2]],a)]}case"MaxPool":{const r=Yv("strides",e,t,n),a=Yv("pad",e,t,n),i=Yv("kernelSize",e,t,n);return[s.maxPool(Yv("x",e,t,n),[i[1],i[2]],[r[1],r[2]],a)]}case"MaxPoolWithArgmax":{const r=Yv("strides",e,t,n),a=Yv("pad",e,t,n),i=Yv("kernelSize",e,t,n),o=Yv("includeBatchInIndex",e,t,n),{result:l,indexes:u}=s.maxPoolWithArgmax(Yv("x",e,t,n),[i[1],i[2]],[r[1],r[2]],a,o);return[l,u]}case"AvgPool3D":{const r=Yv("strides",e,t,n),a=Yv("pad",e,t,n),i=Yv("kernelSize",e,t,n);return[s.avgPool3d(Yv("x",e,t,n),[i[1],i[2],i[3]],[r[1],r[2],r[3]],a)]}case"MaxPool3D":{const r=Yv("strides",e,t,n),a=Yv("pad",e,t,n),i=Yv("kernelSize",e,t,n);return[s.maxPool3d(Yv("x",e,t,n),[i[1],i[2],i[3]],[r[1],r[2],r[3]],a)]}case"Dilation2D":{const r=Yv("strides",e,t,n),a=Yv("pad",e,t,n),i=Yv("dilations",e,t,n),o=r[1],l=r[2],u=i[1],c=i[2];return[s.dilation2d(Yv("x",e,t,n),Yv("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=zk)=>{switch(e.op){case"Fill":{const r=Yv("shape",e,t,n),a=Yv("dtype",e,t,n),i=Yv("value",e,t,n);return[s.fill(r,i,a)]}case"LinSpace":{const r=Yv("start",e,t,n),a=Yv("stop",e,t,n),i=Yv("num",e,t,n);return[s.linspace(r,a,i)]}case"Multinomial":{const r=Yv("logits",e,t,n),a=Yv("numSamples",e,t,n),i=Yv("seed",e,t,n);return[s.multinomial(r,a,i)]}case"OneHot":{const r=Yv("indices",e,t,n),a=Yv("depth",e,t,n),i=Yv("onValue",e,t,n),o=Yv("offValue",e,t,n),l=Yv("dtype",e,t,n);return[s.oneHot(r,a,i,o,l)]}case"Ones":return[s.ones(Yv("shape",e,t,n),Yv("dtype",e,t,n))];case"OnesLike":return[s.onesLike(Yv("x",e,t,n))];case"RandomStandardNormal":return[s.randomStandardNormal(Yv("shape",e,t,n),Yv("dtype",e,t,n),Yv("seed",e,t,n))];case"RandomUniform":return[s.randomUniform(Yv("shape",e,t,n),Yv("minval",e,t,n),Yv("maxval",e,t,n),Yv("dtype",e,t,n))];case"Range":{const r=Yv("start",e,t,n),a=Yv("stop",e,t,n),i=Yv("step",e,t,n);return[s.range(r,a,i,Yv("dtype",e,t,n))]}case"TruncatedNormal":{const r=Yv("shape",e,t,n),a=Yv("mean",e,t,n),i=Yv("stdDev",e,t,n),o=Yv("seed",e,t,n);return[s.truncatedNormal(r,a,i,Yv("dtype",e,t,n),o)]}case"Zeros":return[s.zeros(Yv("shape",e,t,n),Yv("dtype",e,t,n))];case"ZerosLike":return[s.zerosLike(Yv("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=zk)=>{switch(e.op){case"NonMaxSuppressionV5":{const{boxes:s,scores:a,maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:u}=qk(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}=qk(e,t,n),u=Yv("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}=qk(e,t,n);return[await r.image.nonMaxSuppressionAsync(s,a,i,o,l)]}case"Where":{const s=r.cast(Yv("condition",e,t,n),"bool"),a=[await r.whereAsync(s)];return s.dispose(),a}case"ListDiff":return r.setdiff1dAsync(Yv("x",e,t,n),Yv("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=zk)=>{switch(e.op){case"LowerBound":{const r=Yv("sortedSequence",e,t,n),a=Yv("values",e,t,n);return[s.lowerBound(r,a)]}case"TopKV2":{const r=Yv("x",e,t,n),a=Yv("k",e,t,n),i=Yv("sorted",e,t,n),o=s.topk(r,a,i);return[o.values,o.indices]}case"UpperBound":{const r=Yv("sortedSequence",e,t,n),a=Yv("values",e,t,n);return[s.upperBound(r,a)]}case"Unique":{const r=Yv("x",e,t,n),a=s.unique(r);return[a.values,a.indices]}case"UniqueV2":{const r=Yv("x",e,t,n),a=Yv("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=zk)=>{switch(e.op){case"ResizeBilinear":{const r=Yv("images",e,t,n),a=Yv("size",e,t,n),i=Yv("alignCorners",e,t,n),o=Yv("halfPixelCenters",e,t,n);return[s.image.resizeBilinear(r,[a[0],a[1]],i,o)]}case"ResizeNearestNeighbor":{const r=Yv("images",e,t,n),a=Yv("size",e,t,n),i=Yv("alignCorners",e,t,n),o=Yv("halfPixelCenters",e,t,n);return[s.image.resizeNearestNeighbor(r,[a[0],a[1]],i,o)]}case"CropAndResize":{const r=Yv("image",e,t,n),a=Yv("boxes",e,t,n),i=Yv("boxInd",e,t,n),o=Yv("cropSize",e,t,n),l=Yv("method",e,t,n),u=Yv("extrapolationValue",e,t,n);return[s.image.cropAndResize(r,a,i,o,l,u)]}case"ImageProjectiveTransformV3":{const r=Yv("images",e,t,n),a=Yv("transforms",e,t,n),i=Yv("outputShape",e,t,n),o=Yv("fillValue",e,t,n),l=Yv("interpolation",e,t,n),u=Yv("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=zk)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":const r=Yv("default",e,t,n);return[Zv(e.name,t,n)||r];case"Placeholder":return[Zv(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":case"Snapshot":return[nk(Yv("x",e,t,n))];case"IdentityN":return Yv("x",e,t,n).map((e=>nk(e)));case"Shape":return[s.tensor1d(Yv("x",e,t,n).shape,"int32")];case"ShapeN":return Yv("x",e,t,n).map((e=>s.tensor1d(e.shape)));case"Size":return[s.scalar(Yv("x",e,t,n).size,"int32")];case"Rank":return[s.scalar(Yv("x",e,t,n).rank,"int32")];case"NoOp":return[s.scalar(1)];case"Print":const a=Yv("x",e,t,n),i=Yv("data",e,t,n),o=Yv("message",e,t,n),l=Yv("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=zk)=>{switch(e.op){case"Equal":return[s.equal(Yv("a",e,t,n),Yv("b",e,t,n))];case"NotEqual":return[s.notEqual(Yv("a",e,t,n),Yv("b",e,t,n))];case"Greater":return[s.greater(Yv("a",e,t,n),Yv("b",e,t,n))];case"GreaterEqual":return[s.greaterEqual(Yv("a",e,t,n),Yv("b",e,t,n))];case"Less":return[s.less(Yv("a",e,t,n),Yv("b",e,t,n))];case"LessEqual":return[s.lessEqual(Yv("a",e,t,n),Yv("b",e,t,n))];case"LogicalAnd":return[s.logicalAnd(Yv("a",e,t,n),Yv("b",e,t,n))];case"LogicalNot":return[s.logicalNot(Yv("a",e,t,n))];case"LogicalOr":return[s.logicalOr(Yv("a",e,t,n),Yv("b",e,t,n))];case"Select":case"SelectV2":return[s.where(Yv("condition",e,t,n),Yv("a",e,t,n),Yv("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=zk)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[s.matMul(Yv("a",e,t,n),Yv("b",e,t,n),Yv("transposeA",e,t,n),Yv("transposeB",e,t,n))];case"Einsum":return[s.einsum(Yv("equation",e,t,n),...Yv("tensors",e,t,n))];case"Transpose":return[s.transpose(Yv("x",e,t,n),Yv("perm",e,t,n))];case"_FusedMatMul":const[r,a]=Yv("fusedOps",e,t,n),i="biasadd"===r,o="prelu"===a,l=Yv("numArgs",e,t,n),u=Yv("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]=Yv("args",e,t,n);return[s.fused.matMul({a:Yv("a",e,t,n),b:Yv("b",e,t,n),transposeA:Yv("transposeA",e,t,n),transposeB:Yv("transposeB",e,t,n),bias:c,activation:a,preluActivationWeights:h,leakyreluAlpha:u})];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"normalization":return r((()=>((e,t,n,s=zk)=>{switch(e.op){case"EuclideanNorm":return[s.euclideanNorm(Yv("x",e,t,n),Yv("axis",e,t,n),Yv("keepDims",e,t,n))];case"FusedBatchNorm":case"FusedBatchNormV2":case"FusedBatchNormV3":return[s.batchNorm(Yv("x",e,t,n),Yv("mean",e,t,n),Yv("variance",e,t,n),Yv("offset",e,t,n),Yv("scale",e,t,n),Yv("epsilon",e,t,n))];case"LRN":return[s.localResponseNormalization(Yv("x",e,t,n),Yv("radius",e,t,n),Yv("bias",e,t,n),Yv("alpha",e,t,n),Yv("beta",e,t,n))];case"Softmax":return[s.softmax(Yv("x",e,t,n))];case"LogSoftmax":return[s.logSoftmax(Yv("x",e,t,n))];case"SparseToDense":return[s.sparseToDense(Yv("sparseIndices",e,t,n),Yv("outputShape",e,t,n),Yv("sparseValues",e,t,n),Yv("defaultValue",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"ragged":return r((()=>((e,t,n,s=zk)=>{switch(e.op){case"RaggedGather":{const{outputNestedSplits:r,outputDenseValues:a}=s.raggedGather(Yv("paramsNestedSplits",e,t,n),Yv("paramsDenseValues",e,t,n),Yv("indices",e,t,n),Yv("outputRaggedRank",e,t,n));return r.concat(a)}case"RaggedRange":{const{rtNestedSplits:r,rtDenseValues:a}=s.raggedRange(Yv("starts",e,t,n),Yv("limits",e,t,n),Yv("splits",e,t,n));return[r,a]}case"RaggedTensorToTensor":return[s.raggedTensorToTensor(Yv("shape",e,t,n),Yv("values",e,t,n),Yv("defaultValue",e,t,n),Yv("rowPartitionTensors",e,t,n),Yv("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=zk)=>{switch(e.op){case"Max":{const r=Yv("axis",e,t,n),a=Yv("keepDims",e,t,n);return[s.max(Yv("x",e,t,n),r,a)]}case"Mean":{const r=Yv("axis",e,t,n),a=Yv("keepDims",e,t,n);return[s.mean(Yv("x",e,t,n),r,a)]}case"Min":{const r=Yv("axis",e,t,n),a=Yv("keepDims",e,t,n);return[s.min(Yv("x",e,t,n),r,a)]}case"Sum":{const r=Yv("axis",e,t,n),a=Yv("keepDims",e,t,n);return[s.sum(Yv("x",e,t,n),r,a)]}case"All":{const r=Yv("axis",e,t,n),a=Yv("keepDims",e,t,n);return[s.all(Yv("x",e,t,n),r,a)]}case"Any":{const r=Yv("axis",e,t,n),a=Yv("keepDims",e,t,n);return[s.any(Yv("x",e,t,n),r,a)]}case"ArgMax":{const r=Yv("axis",e,t,n);return[s.argMax(Yv("x",e,t,n),r)]}case"ArgMin":{const r=Yv("axis",e,t,n);return[s.argMin(Yv("x",e,t,n),r)]}case"Prod":{const r=Yv("axis",e,t,n),a=Yv("keepDims",e,t,n);return[s.prod(Yv("x",e,t,n),r,a)]}case"Cumprod":{const r=Yv("axis",e,t,n),a=Yv("exclusive",e,t,n),i=Yv("reverse",e,t,n);return[s.cumprod(Yv("x",e,t,n),r,a,i)]}case"Cumsum":{const r=Yv("axis",e,t,n),a=Yv("exclusive",e,t,n),i=Yv("reverse",e,t,n);return[s.cumsum(Yv("x",e,t,n),r,a,i)]}case"Bincount":const r=Yv("x",e,t,n),a=Yv("weights",e,t,n),i=Yv("size",e,t,n);return[s.bincount(r,a,i)];case"DenseBincount":{const r=Yv("x",e,t,n),a=Yv("weights",e,t,n),i=Yv("size",e,t,n),o=Yv("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=zk)=>{switch(e.op){case"ConcatV2":case"Concat":{const r=Yv("n",e,t,n),a=Yv("axis",e,t,n);let i=Yv("tensors",e,t,n);return i=i.slice(0,r),[s.concat(i,a)]}case"Gather":{const r=Yv("x",e,t,n),a=Yv("indices",e,t,n);return[s.gather(r,s.cast(a,"int32"),0)]}case"GatherV2":{const r=Yv("axis",e,t,n),a=Yv("batchDims",e,t,n),i=Yv("x",e,t,n),o=Yv("indices",e,t,n);return[s.gather(i,s.cast(o,"int32"),r,a)]}case"Reverse":{const r=Yv("dims",e,t,n),a=[];for(let e=0;e<r.length;e++)r[e]&&a.push(e);const i=Yv("x",e,t,n);return[s.reverse(i,a)]}case"ReverseV2":{const r=Yv("axis",e,t,n),a=Yv("x",e,t,n);return[s.reverse(a,r)]}case"Slice":{const r=Yv("begin",e,t,n),a=Yv("size",e,t,n);return[s.slice(Yv("x",e,t,n),r,a)]}case"StridedSlice":{const r=Yv("begin",e,t,n),a=Yv("end",e,t,n),i=Yv("strides",e,t,n),o=Yv("beginMask",e,t,n),l=Yv("endMask",e,t,n),u=Yv("ellipsisMask",e,t,n),c=Yv("newAxisMask",e,t,n),h=Yv("shrinkAxisMask",e,t,n),p=Yv("x",e,t,n);return[s.stridedSlice(p,r,a,i,o,l,u,c,h)]}case"Pack":return Ni((()=>{const r=Yv("axis",e,t,n),a=Yv("tensors",e,t,n),i=a[0].shape,o=s.squeeze(a[0]).shape,l=a.map((e=>{const t=f(e.shape,i);if(!t&&!f(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=Yv("axis",e,t,n),a=Yv("tensor",e,t,n);return s.unstack(a,r)}case"Tile":{const r=Yv("reps",e,t,n);return[s.tile(Yv("x",e,t,n),r)]}case"Split":case"SplitV":{const r=Yv("axis",e,t,n),a=Yv("numOrSizeSplits",e,t,n),i=Yv("x",e,t,n);return s.split(i,a,r)}case"ScatterNd":{const r=Yv("indices",e,t,n),a=Yv("values",e,t,n),i=Yv("shape",e,t,n);return[s.scatterND(r,a,i)]}case"GatherNd":{const r=Yv("x",e,t,n),a=Yv("indices",e,t,n);return[s.gatherND(r,a)]}case"SparseToDense":{const r=Yv("sparseIndices",e,t,n),a=Yv("outputShape",e,t,n),i=Yv("sparseValues",e,t,n),o=Yv("defaultValue",e,t,n);return[s.sparseToDense(r,i,a,i.dtype===o.dtype?o:s.cast(o,i.dtype))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}})(e,t,n)));case"sparse":return r((()=>((e,t,n,s=zk)=>{switch(e.op){case"SparseFillEmptyRows":{const{outputIndices:r,outputValues:a,emptyRowIndicator:i,reverseIndexMap:o}=s.sparse.sparseFillEmptyRows(Yv("indices",e,t,n),Yv("values",e,t,n),Yv("denseShape",e,t,n),Yv("defaultValue",e,t,n));return[r,a,i,o]}case"SparseReshape":{const{outputIndices:r,outputShape:a}=s.sparse.sparseReshape(Yv("inputIndices",e,t,n),Yv("inputShape",e,t,n),Yv("newShape",e,t,n));return[r,a]}case"SparseSegmentMean":return[s.sparse.sparseSegmentMean(Yv("data",e,t,n),Yv("indices",e,t,n),Yv("segmentIds",e,t,n))];case"SparseSegmentSum":return[s.sparse.sparseSegmentSum(Yv("data",e,t,n),Yv("indices",e,t,n),Yv("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=zk)=>{switch(e.op){case"FFT":return[s.fft(Yv("x",e,t,n))];case"IFFT":return[s.ifft(Yv("x",e,t,n))];case"RFFT":return[s.rfft(Yv("x",e,t,n))];case"IRFFT":return[s.irfft(Yv("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=zk)=>{switch(e.op){case"StringNGrams":{const{nGrams:r,nGramsSplits:a}=s.string.stringNGrams(Yv("data",e,t,n),Yv("dataSplits",e,t,n),Yv("separator",e,t,n),Yv("nGramWidths",e,t,n),Yv("leftPad",e,t,n),Yv("rightPad",e,t,n),Yv("padWidth",e,t,n),Yv("preserveShortSequences",e,t,n));return[r,a]}case"StringSplit":{const{indices:r,values:a,shape:i}=s.string.stringSplit(Yv("input",e,t,n),Yv("delimiter",e,t,n),Yv("skipEmpty",e,t,n));return[r,a,i]}case"StringToHashBucketFast":return[s.string.stringToHashBucketFast(Yv("input",e,t,n),Yv("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=zk)=>{switch(e.op){case"Cast":return[s.cast(Yv("x",e,t,n),Yv("dtype",e,t,n))];case"ExpandDims":{const r=Yv("axis",e,t,n);return[s.expandDims(Yv("x",e,t,n),r)]}case"Squeeze":{const r=Yv("axis",e,t,n);return[s.squeeze(Yv("x",e,t,n),r)]}case"Reshape":return[s.reshape(Yv("x",e,t,n),Yv("shape",e,t,n))];case"MirrorPad":return[s.mirrorPad(Yv("x",e,t,n),Yv("padding",e,t,n),Yv("mode",e,t,n))];case"PadV2":case"Pad":return[s.pad(Yv("x",e,t,n),Yv("padding",e,t,n),Yv("constantValue",e,t,n))];case"SpaceToBatchND":{const r=Yv("blockShape",e,t,n),a=Yv("paddings",e,t,n);return[s.spaceToBatchND(Yv("x",e,t,n),r,a)]}case"BatchToSpaceND":{const r=Yv("blockShape",e,t,n),a=Yv("crops",e,t,n);return[s.batchToSpaceND(Yv("x",e,t,n),r,a)]}case"DepthToSpace":{const r=Yv("blockSize",e,t,n),a=Yv("dataFormat",e,t,n).toUpperCase();return[s.depthToSpace(Yv("x",e,t,n),r,a)]}case"BroadcastTo":return[s.broadcastTo(Yv("x",e,t,n),Yv("shape",e,t,n))];case"BroadcastArgs":return[s.broadcastArgs(Yv("s0",e,t,n),Yv("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=Yv("keyDType",e,t,n),a=Yv("valueDType",e,t,n),i=new Kk(r,a);return s.addHashTable(e.name,i),[i.handle]}}case"InitializeTable":case"InitializeTableV2":case"LookupTableImport":case"LookupTableImportV2":{const r=Yv("tableHandle",e,t,n,s),a=Yv("keys",e,t,n),i=Yv("values",e,t,n),o=s.getHashTableById(r.id);return[await o.import(a,i)]}case"LookupTableFind":case"LookupTableFindV2":{const r=Yv("tableHandle",e,t,n,s),a=Yv("keys",e,t,n),i=Yv("defaultValue",e,t,n),o=s.getHashTableById(r.id);return[await o.find(a,i)]}case"LookupTableSize":case"LookupTableSizeV2":{const r=Yv("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=Xv(e.op);if(a&&a.customExecutor)return a.customExecutor(new Lk(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 H(a)?a.then((e=>[].concat(e))):[].concat(a)}class Yk{constructor(e={},t={},n={},s={}){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=n,this.functionMap=s,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 Zk(e,t,n,s){const r=new Set,a=[];let i=null,o=null;const l=new Set,u=Object.keys(e).map((e=>ek(e)[0]));let c=[];null!=s&&(c=s.map((e=>ek(e.name)[0])));const h=[...t];for(;h.length>0;){const e=h.pop();(tN(e)||nN(e)||sN(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]&&(-1===u.indexOf(e.name)&&-1===c.indexOf(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}}const Jk=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],Qk=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"],eN=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"];function tN(e){return Jk.indexOf(e.op)>=0}function nN(e){return Qk.indexOf(e.op)>=0}function sN(e){return eN.indexOf(e.op)>=0}class rN{constructor(e,t){this.graph=e,this.parent=t,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",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 rN(e.functions[t],this)}))}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)),{})}getCompilationKey(e,t){const n=e.map((e=>e.name)).sort(),s=t.map((e=>e.name)).sort();return n.join(this.SEPERATOR)+"--"+s.join(this.SEPERATOR)}compile(e,t){const n=Zk(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}]`)}return function(e,t,n){const{usedNodes:s,inputs:r}=n,a=[],i=Object.keys(r).map((e=>ek(e)[0])).map((t=>e.nodes[t])),o=e.initNodes;i.forEach((e=>{s.has(e.name)&&a.push(e)})),e.weights.forEach((e=>{s.has(e.name)&&a.push(e)})),null!=o&&o.forEach((e=>{s.has(e.name)&&a.push(e)}));const l=new Set,u=[];for(;a.length>0;){const e=a.pop();l.add(e.name),t[e.name]||u.push(e),e.children.forEach((e=>{!l.has(e.name)&&s.has(e.name)&&e.inputs.every((e=>l.has(e.name)))&&a.push(e)}))}return u}(this.graph,this.weightMap,n)}cloneAndKeepTensor(e){if(null==e)return null;const t=e.clone();return Si(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[ek(e)[0]])),r=t.map((e=>ek(e)[0]));let a=r.map((e=>this.graph.nodes[e]));0===a.length&&(a=this._outputs);const i=this.getCompilationKey(s,a);let o=this.compiledMap.get(i);null==o&&(o=this.compile(e,a),this.compiledMap.set(i,o));try{this.keepIntermediateTensors=X().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(e){this.keepIntermediateTensors=!1,console.warn(e.message)}const l={},u={};return Ni((()=>{const n=new Yk(this.weightMap,l,u,this.functionExecutorMap),s=Object.assign({},this.weightMap);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap)),Object.keys(e).forEach((t=>{const[n,r]=ek(t),a=[];a[r]=e[t],s[n]=a,this.keepIntermediateTensors&&(this.clonedTensorsMap[n]=this.cloneTensorList(a))}));const a=this.getFrozenTensorIds(s),i={};for(let e=0;e<o.length;e++){const t=o[e];if(!s[t.name]){const e=Xk(t,s,n,this._resourceManager);if(H(e))throw new Error(`The execution of the op '${t.op}' returned a promise. Please use model.executeAsync() instead.`);s[t.name]=e,this.keepIntermediateTensors&&(this.clonedTensorsMap[t.name]=this.cloneTensorList(e)),this.checkTensorForDisposal(t.name,t,s,n,a,r,i)}}return null==this.parent&&n.dispose(a),t.map((e=>Zv(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){"control"!==t.category&&-1===a.indexOf(e)&&(n[e].forEach((e=>{null!=e&&(i[e.id]=(i[e.id]||0)+t.children.length)})),t.inputs.forEach((e=>{if("control"!==e.category){const t=function(e,t,n){return t[Qv(e,n.currentContextId)]}(e.name,n,s);null!=t&&t.forEach((e=>{if(e&&!e.kept&&!r.has(e.id)){const t=i[e.id];1===t?(e.dispose(),delete i[e.id]):null!=t&&i[e.id]--}}))}})))}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=X().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(e){this.keepIntermediateTensors=!1,console.warn(e.message)}const a=new Yk(this.weightMap,s,r,this.functionExecutorMap);this.keepIntermediateTensors&&(this.clonedTensorsMap=this.cloneTensorMap(this.weightMap));const i=await this.executeWithControlFlow(e,a,t,n),o=t.map((e=>Zv(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[ek(e)[0]])),i=n.map((e=>ek(e)[0]));let o=i.map((e=>this.graph.nodes[e]));0===o.length&&(o=this._outputs);const{usedNodes:l,missingInputs:u,dynamicNode:c,syncInputs:h}=Zk(e,o,this.weightMap,this._initNodes),p=[...a,...this.graph.weights,...this._initNodes||[]].map((e=>({node:e,contexts:t.currentContext}))),d=Object.assign({},this.weightMap);Object.keys(e).forEach((t=>{const[n,s]=ek(t),r=[];r[s]=e[t],d[n]=r}));const f={},m=this.getFrozenTensorIds(d),g={};for(;p.length>0;){const e=this.processStack(a,p,t,d,g,m,i,f,l);await Promise.all(e)}null!=c||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 y=o.filter((e=>!tN(e)&&!Zv(e.name,d,t))).map((e=>e.name));if(y.length>0){let e="";throw null!=c&&(e=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${h}]`),new Error(`Cannot compute the outputs [${y}] from the provided inputs [${r}]. Consider providing the following inputs: [${u}]. ${e}`)}return d}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&&Yv("isConstant",e.node,s,n)&&([c]=Jv(e.node.name,n)),null==s[e.node.name]){const h=Xk(e.node,s,n,this._resourceManager);c||([c]=Jv(e.node.name,n));const p=n.currentContext;H(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]=Jv(e.name,n);!r[i]&&a.has(e.name)&&("Merge"===e.op?e.inputNames.some((e=>!!Zv(e,s,n)))&&(r[i]=!0,t.push({contexts:n.currentContext,node:e})):e.inputNames.every((e=>!!Zv(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]=ek(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));u(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&&u(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]=ek(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]=ek(e);if(!this.graph.nodes[t])throw new Error(`The output '${e}' is not found in the graph`)}))}}class aN{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 iN{constructor(e,t={},n=yi){this.modelUrl=e,this.loadOptions=t,this.version="n/a",this.io=n,null==t&&(this.loadOptions={}),this.resourceManager=new aN}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}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 H(e)?e.then((e=>this.loadSync(e))):this.loadSync(e)}loadSync(e){this.artifacts=e;const t=this.artifacts.modelTopology;let n=this.artifacts.signature;if(null!=this.artifacts.userDefinedMetadata){const e=this.artifacts.userDefinedMetadata;null!=e.signature&&(n=e.signature),null!=e.structuredOutputKeys&&(this.structuredOutputKeys=e.structuredOutputKeys)}this.signature=n,this.version=`${t.versions.producer}.${t.versions.minConsumer}`;const s=this.io.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new rN(kk.Instance.transformGraph(t,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(s),this.executor.resourceManager=this.resourceManager,null!=e.modelInitializer&&null!=e.modelInitializer.node){const t=kk.Instance.transformGraph(e.modelInitializer);this.initializer=new rN(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 vr?[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 vr||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&&Ii(this.resourceIdToCapturedInput)),this.resourceManager.dispose()}}const oN="4.1.0";function lN(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(dN(e)){const r=Array.isArray(e)?[]:{};s.add(e);for(const a in e){const i=lN(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 uN(e,t=hN){return cN(e,t)}function cN(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(dN(s)){const r=Array.isArray(s)?[]:{};n.add(s);for(const a in s){const s=cN(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 hN(e){return null===e?null:dN(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}async function pN(e,t){const n=new Map;lN(e,t,n);for(const e of Array.from(n.keys())){const t=n.get(e);if(H(t)){const s=await t;n.set(e,s)}}return lN(e,t,n)}function dN(e){let t=!1;if(X().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 vr)&&!(e instanceof Promise)&&!t)}function fN(e){return function(e,t){return lN(e,t)}(e,mN)}function mN(e){return e instanceof vr?{value:e.clone(),recurse:!1}:dN(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}class gN{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 yN extends gN{constructor(){super(yN.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 bN(e){return new kN(e)}function xN(e){return new NN(e)}function wN(e,t){return new DN(e,t)}yN.INITIAL_CAPACITY=32;class vN{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 AN(this,e)}filter(e){return new $N(this,e)}map(e){return new EN(this,e)}mapAsync(e){return new RN(this,e)}serialMapAsync(e){return new RN(this,e).serial()}flatmap(e){return new FN(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 CN(this,e,t)}columnMajorBatch(e,t=!0,n=hN){return this.rowMajorBatch(e,t).map((e=>uN(e,n)))}concatenate(e,t){return new DN(bN([this,e]),t)}take(e){return e<0||null==e?this:new TN(this,e)}skip(e){return e<0||null==e?this:new SN(this,e)}prefetch(e){return new LN(this,e)}shuffle(e,t){return new zN(this,e,t)}serial(){return new IN(this)}}class kN extends vN{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:fN(e),done:!1}}}class NN extends vN{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 IN extends vN{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 SN extends vN{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;Ii(e.value)}return this.upstream.next()}}class TN extends vN{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 CN extends vN{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 $N extends vN{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;Ii(e.value)}}}class EN extends vN{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=Or(e.value),n=this.transform(e.value),s=Or(n);for(const e of t)Dr(e,s)||e.dispose();return{value:n,done:!1}}}class AN extends vN{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 RN extends vN{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=Or(e.value),n=await this.transform(e.value),s=Or(n);for(const e of t)Dr(e,s)||e.dispose();return{value:n,done:!1}}}class _N extends vN{constructor(){super(),this.outputQueue=new yN,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 FN extends _N{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=Or(e.value),n=this.transform(e.value),s=Or(n);this.outputQueue.pushAll(n);for(const e of t)Dr(e,s)||e.dispose();return!0}}class DN extends vN{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 ON;!function(e){e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST"}(ON||(ON={}));class MN extends vN{constructor(e,t=ON.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 pN(this.iterators,(function(e){if(e instanceof vN){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 ON.FAIL:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case ON.SHORTEST:return{value:null,done:!0};case ON.LONGEST:}return this.count++,{value:s,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}}class LN extends vN{constructor(e,t){super(),this.upstream=e,this.bufferSize=t,this.buffer=new gN(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 zN extends LN{constructor(e,t,n){super(e,t),this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=Rc(n||rr().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 PN{constructor(){this.size=null}batch(e,t=!0){const n=this;let s;return u(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),BN((async()=>(await n.iterator()).columnMajorBatch(e,t,WN)),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,BN((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,BN((async()=>(await t.iterator()).filter((t=>Ni((()=>e(t)))))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){const t=this;return BN((async()=>(await t.iterator()).map((t=>Ni((()=>e(t)))))),this.size)}mapAsync(e){const t=this;return BN((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 BN((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,BN((async()=>wN(xN((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,BN((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=Rc(t||rr().toString());return BN((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,BN((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 BN(e,t=null){return new class extends PN{constructor(){super(...arguments),this.size=t}async iterator(){return e()}}}function WN(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 vr||C(n)){return{value:function(e){if(0===e.length)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof vr?fh(e):ra(e)}(e),recurse:!1}}var n,s;return{value:null,recurse:!0}}PN.MAX_BUFFER_SIZE=1e4;class VN extends PN{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 UN='"',GN=Symbol("out"),HN=Symbol("field"),jN=Symbol("quote"),qN=Symbol("quoteafterquote"),KN=Symbol("quoteinquote");class XN extends PN{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 VN(e),t||(t={}),this.hasHeader=!1!==t.hasHeader,this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(u(null==t.delimiter,(()=>"Delimiter should not be provided when delimWhitespace is true.")),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=t.delimiter?t.delimiter:","}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&&u(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(u(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}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=GN;for(let t=0;t<r;t++)switch(a){case GN:switch(e.charAt(t)){case UN:s=t+1,a=jN;break;case this.delimiter:if(s=t+1," "===this.delimiter&&this.delimWhitespace)break;n.push(""),a=GN;break;default:a=HN,s=t}break;case HN:if(e.charAt(t)===this.delimiter)n.push(e.substring(s,t)),a=GN,s=t+1;break;case jN:if(e.charAt(t)===UN)a=qN;break;case qN:switch(e.charAt(t)){case this.delimiter:n.push(e.substring(s,t-1)),a=GN,s=t+1;break;case UN:a=jN;break;default:a=KN}break;case KN:if(e.charAt(t)===UN)a=jN}if(a===qN?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 YN extends vN{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(!X().get("IS_BROWSER"))throw new Error("microphone API is only supported in browser environment.");const t=new YN(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),ra(n,t)}}class ZN extends vN{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=bh([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=xh([s,n,a,r],[1,4])}else this.cropBox=xh([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(!X().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 ZN(e,t);return await n.start(),n}async start(){this.webcamConfig.facingMode&&u("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=Ui(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 Ni((()=>{const t=du(Ja(e,"float32"),0);let n;n=Xp.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");const s=n.shape;return tl(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 JN{}class QN extends vN{split(e){return new eI(this,e)}}class eI extends QN{constructor(e,t){super(),this.upstream=e,this.impl=new tI(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class tI extends _N{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 nI extends vN{decodeUTF8(){return new sI(this)}}class sI extends QN{constructor(e){super(),this.upstream=e,this.impl=new rI(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}}class rI extends _N{constructor(e){if(super(),this.upstream=e,X().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=X().get("IS_BROWSER")?this.decoder.decode(t,{stream:!0}):this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(n),!0)}}class aI extends nI{constructor(e,t={}){super(),this.file=e,this.options=t,u(e instanceof Uint8Array||!!X().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 iI=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 oI(e){return"string"==typeof e&&"file://"===e.slice(0,7)}class lI extends JN{constructor(e,t={}){super(),this.input=e,this.options=t}async iterator(){if(oI(this.input)&&X().get("IS_NODE")){const e=require("fs");this.input=e.readFileSync(this.input.slice(7))}return new aI(this.input,this.options)}}class uI extends JN{constructor(e,t={}){super(),this.url=e,this.fileOptions=t}async iterator(){return oI(this.url)?new lI(this.url,this.fileOptions).iterator():async function(e,t={},n){let s,r;"string"==typeof e?s=e:(s=e.url,r=iI(e));const a=await(n||ar)(s,r);if(a.ok){const e=new Uint8Array(await a.arrayBuffer());return new aI(e,t)}throw new Error(a.statusText)}(this.url,this.fileOptions)}}const cI="4.1.0";var hI=Object.freeze({__proto__:null,array:function(e){return BN((async()=>bN(e)),e.length)},Dataset:PN,zip:function(e){if(!dN(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 BN((async()=>function(e,t=ON.FAIL){return new MN(e,t)}(await pN(e,(e=>{if(e instanceof PN)return{value:e.iterator(),recurse:!1};if(dN(e))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")})),ON.SHORTEST)),t)},CSVDataset:XN,TextLineDataset:VN,csv:function(e,t={}){return new XN(new uI(e),t)},func:function(e){const t=xN(e);return BN((async()=>t))},generator:function(e){return BN((async()=>{const t=await e();return xN((()=>t.next()))}))},microphone:async function(e){return YN.create(e)},webcam:async function(e,t){return ZN.create(e,t)},FileDataSource:lI,URLDataSource:uI,version_data:cI});function pI(e,t){Array.isArray(e)||(e=[e]),e.forEach((e=>{null!=e&&u("complex64"!==e.dtype,(()=>`${t} does not support complex64 tensors in the CPU backend.`))}))}const dI=Ah;class fI extends n{constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new t(this,vi())}nextDataId(){return fI.nextDataId++}write(e,t,n){this.firstUse&&(this.firstUse=!1,X().get("IS_NODE")&&us("\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=>ir(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 Dd(this.readSync(n.real.dataId),this.readSync(n.imag.dataId))}return this.data.get(e).values}bufferSync(e){const t=this.readSync(e.dataId);if("string"===e.dtype)try{const n=t.map((e=>or(e)));return Za(e.shape,e.dtype,n)}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return Za(e.shape,e.dtype,t)}makeOutput(e,t,n){return vi().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=rr();e();return{kernelMs:rr()-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){pI([e],"where");const t=this.readSync(e.dataId);return dI(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}}function mI(e){const t=new Float32Array(e.length);for(let n=0;n<e.length;++n)t[n]=Math.abs(e[n]);return t}fI.nextDataId=0;const gI={kernelName:Q,backendName:"cpu",kernelFunc:e=>{const{x:t}=e.inputs,n=e.backend;pI(t,"abs");let s=new Float32Array(d(t.shape));return s=mI(n.data.get(t.dataId).values),n.makeOutput(s,t.shape,t.dtype)}};function yI(e){return(t,n,s,r,a)=>{const i=Li(t,n),o=i.length,l=M(i),u=k(a,d(i)),c=t.length,h=n.length,p=M(t),f=M(n),m=Oi(t,i),g=Oi(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=G(t,o,l),a=n.slice(-c);m.forEach((e=>a[e]=0));const i=U(a,c,p),d=n.slice(-h);g.forEach((e=>d[e]=0));const y=U(d,h,f);u[t]=e(s[i],r[y])}return[u,i]}}function bI(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 xI={kernelName:Se,backendName:"cpu",kernelFunc:bI};function wI(e,t,n="float32"){if("complex64"===n){return bI({inputs:{real:wI(e,t,"float32"),imag:wI(e,t,"float32")},backend:e})}const s=B(d(t),n);return e.makeTensorInfo(t,n,s)}function vI(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 kI={kernelName:dt,backendName:"cpu",kernelFunc:vI};function NI(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 II={kernelName:ln,backendName:"cpu",kernelFunc:NI};function SI(e,t,n,s){if("int32"===s){return[t,"int32",Int32Array.from(e)]}if("bool"===s){const s=sr([0],n),[r,a]=yI(((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 TI(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dtype:a}=s;if("complex64"===a){if("complex64"===r.dtype)return vI({inputs:{x:r},backend:n});const e=wI(n,r.shape,r.dtype),t=TI({inputs:{x:r},backend:n,attrs:{dtype:"float32"}}),s=bI({inputs:{real:t,imag:e},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),s}if("complex64"===r.dtype){const e=NI({inputs:{input:r},backend:n}),t=TI({inputs:{x:e},backend:n,attrs:{dtype:a}});return n.disposeIntermediateTensorInfo(e),t}if(!T(r.dtype,a)){const e=vI({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]=SI(i,r.shape,r.dtype,a);return n.makeTensorInfo(o,l,u)}const CI={kernelName:ke,backendName:"cpu",kernelFunc:TI};function $I(e,t,n,s){return null==n?({inputs:n,backend:r})=>{const{a:a,b:i}=n,o=r;pI([a,i],e);const l=o.data.get(a.dataId).values,u=o.data.get(i.dataId).values,c="string"===a.dtype?ff(l):l,h="string"===a.dtype?ff(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=TI({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=TI({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=bI({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 EI(e){return(t,n,s,r,a,i)=>{const o=Li(t,n),l=d(o),u=o.length,c=M(o),h=k("float32",l),p=k("float32",l),f=Oi(t,o),m=Oi(n,o),g=Dd(s,r),y=Dd(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=G(t,u,c),s=n.slice(-b);f.forEach((e=>s[e]=0));const r=U(s,b,x),a=n.slice(-w);m.forEach((e=>a[e]=0));const i=U(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 AI=yI(((e,t)=>e+t)),RI=EI(((e,t,n,s)=>({real:e+n,imag:t+s}))),_I=$I(ne,AI,RI),FI={kernelName:ne,backendName:"cpu",kernelFunc:_I};function DI(e,t,n,s,r){const a=d(s),i=B(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 OI(e,t,n,s=!1){const r=e.shape[0],a=e.shape[1],i=Za([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}function MI(e){return(t,n,s)=>{const r=k(n,t.length);for(let n=0;n<t.length;++n)r[n]=e(t[n],s);return r}}function LI(e,t,n){return({inputs:s,attrs:r,backend:a})=>{const{x:i}=s;if(pI(i,e),"string"===i.dtype||"string"===n)throw new Error("unaryKernelFunc does not support string input/output");const o=a,l=o.data.get(i.dataId).values,u=d(i.shape),c=n||i.dtype,h=N(c,u);for(let e=0;e<u;++e)h[e]=t(l[e],r);return o.makeTensorInfo(i.shape,c,h)}}function zI(e,t,n){return({inputs:s,attrs:r,backend:a})=>{const{x:i}=s;if(pI(i,e),"string"===i.dtype||"string"===n)throw new Error("unaryKernelFunc does not support string input/output");const o=a,l=o.data.get(i.dataId).values,u=n||i.dtype,c=t(l,u,r);return o.makeTensorInfo(i.shape,u,c)}}const PI=MI((e=>Math.ceil(e))),BI=zI(Ne,PI),WI={kernelName:Ne,backendName:"cpu",kernelFunc:BI};function VI(e,t,n,s){const r=N(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?ff(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 UI=yI(((e,t)=>e===t?1:0)),GI=$I(Qe,UI,null,"bool"),HI={kernelName:Qe,backendName:"cpu",kernelFunc:GI},jI=MI((e=>Math.exp(e))),qI=zI(et,jI,"float32"),KI={kernelName:et,backendName:"cpu",kernelFunc:qI},XI=MI((e=>Math.expm1(e))),YI=zI(nt,XI),ZI={kernelName:nt,backendName:"cpu",kernelFunc:YI},JI=MI((e=>Math.floor(e))),QI=zI(it,JI),eS={kernelName:it,backendName:"cpu",kernelFunc:QI};function tS(e,t,n,s,r,a,i,o,l){const u=Za([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 nS(e,t,n){const s=Za(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 sS=yI(((e,t)=>e>t?1:0)),rS=$I(ht,sS,null,"bool"),aS={kernelName:ht,backendName:"cpu",kernelFunc:rS},iS=yI(((e,t)=>e>=t?1:0)),oS=$I(pt,iS,null,"bool"),lS={kernelName:pt,backendName:"cpu",kernelFunc:oS},uS=yI(((e,t)=>e<t?1:0)),cS=$I(wt,uS,null,"bool"),hS={kernelName:wt,backendName:"cpu",kernelFunc:cS},pS=yI(((e,t)=>e<=t?1:0)),dS=$I(vt,pS,null,"bool"),fS={kernelName:vt,backendName:"cpu",kernelFunc:dS};function mS(e,t,n){const s=(t-e)/(n-1),r=B(n,"float32");r[0]=e;for(let e=1;e<r.length;e++)r[e]=r[e-1]+s;return r}const gS=MI((e=>Math.log(e))),yS=zI(Nt,gS),bS={kernelName:Nt,backendName:"cpu",kernelFunc:yS};function xS(e,t,n,s){const r=k(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 wS=yI(((e,t)=>Math.max(e,t))),vS=$I(_t,wS),kS={kernelName:_t,backendName:"cpu",kernelFunc:vS},NS=yI(((e,t)=>Math.min(e,t))),IS=$I(Bt,NS),SS={kernelName:Bt,backendName:"cpu",kernelFunc:IS},TS=yI(((e,t)=>e*t)),CS=EI(((e,t,n,s)=>({real:e*n-t*s,imag:e*s+t*n}))),$S=$I(Gt,TS,CS),ES={kernelName:Gt,backendName:"cpu",kernelFunc:$S};function AS(e,t,n){const s=nr(-1,n);return TS([],t,s,e,n)}const RS={kernelName:Ht,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:s}=t;pI(s,"neg");const r=n.data.get(s.dataId).values,[a,i]=AS(r,s.shape,s.dtype);return n.makeTensorInfo(i,s.dtype,a)}},_S=yI(((e,t)=>e!==t?1:0)),FS=$I(jt,_S,null,"bool"),DS={kernelName:jt,backendName:"cpu",kernelFunc:FS};function OS(e,t,n,s,r){const a=t.length,i=d(t),o=M(t),l=M(r),u=k(n,d(r));for(let t=0;t<i;++t){const n=G(t,a,o),r=new Array(n.length);for(let e=0;e<r.length;e++)r[e]=n[s[e]];u[U(r,a,l)]=e[t]}return u}function MS(e){const{inputs:t,attrs:n,backend:s}=e,{x:r}=t,{perm:a}=n;pI(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=OS(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 LS={kernelName:Jn,backendName:"cpu",kernelFunc:MS};function zS(e,t,n,s){const[r,a]=Yl(e,s),i=Ar(t,"int32"),o=B(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 PS={kernelName:nn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s;pI(r,"prod");const o=r.shape.length,l=w(a,r.shape),u=Ql(l,o);let c=l,h=r;const p=[];null!=u&&(h=MS({inputs:{x:r},backend:n,attrs:{perm:u}}),p.push(h),c=tu(c.length,o));const d=n.data.get(h.dataId).values,{outVals:f,outShape:m,outDtype:g}=zS(h.shape,h.dtype,d,c);let y=m;return i&&(y=Zl(m,l)),p.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(y,g,f)}};function BS(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 WS(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 VS(e,t,n,s,r){const a=t.slice();a[0]=r;const i=N(n,d(a)),o=e.length;return function(e,t,n,s,r,a){const i=WS(t,2)[1],o=WS(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 US(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=G(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}=BS(a,i,e,l),p=function(e){const t=[];for(let n=0;n<e.length;++n){const s=N("int32",e[n].length);t.push(s),e[n].forEach(((e,t)=>s[t]=e))}return t}(u),d=VS(n,s,r,c,h);return[p,d[0],d[1]]}const GS=2147483647;function HS(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=N("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>GS)throw new Error("Requires ((limit - start) / delta) <= 2147483647");p[t+1]=p[t]+c}const d=N(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 jS=fd;class qS{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=gd(u),this.raggedRank=yd(this.rowPartitionTypes)}getRowPartitionTypeByDimension(e){return this.rowPartitionTypes[0]===jS.FIRST_DIM_SIZE?this.rowPartitionTypes[e+1]:this.rowPartitionTypes[e]}getRowPartitionTensor(e){return this.rowPartitionTypes[0]===jS.FIRST_DIM_SIZE?this.rowPartitionValues[e+1]:this.rowPartitionValues[e]}getMaxWidth(e){const t=this.getRowPartitionTensor(e-1);switch(this.getRowPartitionTypeByDimension(e-1)){case jS.VALUE_ROWIDS:return qS.getMaxWidthValueRowID(t);case jS.ROW_SPLITS:return qS.getMaxWidthRowSplit(t);default:throw new Error(`Cannot handle partition type ${jS[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 XS(e,n)}calculateOutputSize(e){const t=this.valuesShape;bd(this.defaultValueShape,t);const n=this.tensorShapeFromTensor(this.shape,this.shapeShape),s=md(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 u(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 jS.VALUE_ROWIDS:return this.calculateOutputIndexValueRowID(r,t,n,s);case jS.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: ${jS[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 jS.FIRST_DIM_SIZE:return e[0];case jS.VALUE_ROWIDS:throw new Error("Cannot handle VALUE_ROWIDS in first dimension.");case jS.ROW_SPLITS:return this.rowPartitionValuesShapes[0][0]-1;default:throw new Error(`Cannot handle type ${jS[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=XS(t,!1),r=N(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;Ni((()=>{const t=tl(u,e),n=gl(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);KS(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;){KS(a.slice(p*o),u,o),++p}s<0?(c=e+1,h=p):(c=e,h=p,p=h+1)}else++p}}}function KS(e,t,n){for(let s=0;s<n;s++)e[s]=t[s]}function XS(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 YS(e,t,n,s,r,a,i,o,l,u){return new qS(e,t,n,s,r,a,i,o,l,u).compute()}function ZS(e,t,n,s){if(e===t||e<t&&n<0||t<e&&n>1)return B(0,s);const r=B(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 JS=MI((e=>1/Math.sqrt(e))),QS=zI(xn,JS),eT={kernelName:xn,backendName:"cpu",kernelFunc:QS};function tT(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 Za(n,t.dtype);const d=Za(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 nT=MI((e=>1/(1+Math.exp(-e)))),sT=LI($n,(e=>1/(1+Math.exp(-e)))),rT={kernelName:$n,backendName:"cpu",kernelFunc:sT};function aT(e,t,n,s,r){const a=oo(s,t,n),i=d(n),o=M(s);if(a){const n=lo(t,o);return"string"===r?e.slice(n,n+i):e.subarray(n,n+i)}const l=Za(s,r,"string"===r?ff(e):e),u=Za(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?mf(u.values):u.values}function iT(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,size:i}=s;pI(r,"slice");const[o,l]=uo(r,a,i);Zi(r,o,l);const u=aT(n.data.get(r.dataId).values,o,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,u)}const oT={kernelName:In,backendName:"cpu",kernelFunc:iT};function lT(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(Zd(o));return[N(n,0),[0,h],N(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(Jd(t,n));if(n>=l)throw new Error(Qd(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=N(n,t*h),p=N(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 uT(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(ef(c,e));c=e,l.push(1)}else{if(t<0)throw new Error(tf(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(sf(s,l));l[c]=e}if(d(l)!==a)throw new Error(rf(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=N(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 cT(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=N(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(lf(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(uf(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 hT=MI((e=>Math.sqrt(e))),pT=LI(An,(e=>Math.sqrt(e))),dT={kernelName:An,backendName:"cpu",kernelFunc:pT},fT=yI(((e,t)=>{const n=e-t;return n*n})),mT=$I(Bn,fT),gT={kernelName:Bn,backendName:"cpu",kernelFunc:mT};function yT(e,t,n,s){const r=Za(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 bT{constructor(e,t,n,s,r,a){this.separator=ir(e),this.nGramWidths=t,this.leftPad=ir(n),this.rightPad=ir(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=N("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 xT(e,t,n,s,r,a,i,o){return new bT(n,s,r,a,i,o).compute(e,t)}function wT(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 vT(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;wT(e[l],t,n,r);const u=r.length-s;o[l]=u,a+=u,i=Math.max(i,u)}const l=N("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 kT(e,t){const n=N("int32",e.length);for(let s=0;s<e.length;++s)n[s]=tr(e[s]).modulo(t).getLowBitsUnsigned();return n}const NT=yI(((e,t)=>e-t)),IT=EI(((e,t,n,s)=>({real:e-n,imag:t-s}))),ST=$I(jn,NT,IT),TT={kernelName:jn,backendName:"cpu",kernelFunc:ST};function CT(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=Za(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 $T=(e,t)=>{const n=t.value-e.value;return 0===n?e.index-t.index:n};function ET(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);ET(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(o(e,n,t),$T(e[s],r)>0&&o(e,n,s);a<i;){for(o(e,a,i),a++,i--;$T(e[a],r)<0;)a+=1;for(;$T(e[i],r)>0;)i-=1}0===$T(e[n],r)?o(e,n,i):(i+=1,o(e,i,s)),i<=t&&(n=i+1),t<=i&&(s=i-1)}}function AT(e,t,n,s,r){const a=t[t.length-1],[i,o]=[e.length/a,a],l=k(n,i*s),u=k("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&&(ET(i,s),i=i.slice(0,s)),r&&i.sort($T);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,[Za(c,n,l),Za(c,"int32",u)]}function RT(e,t,n,s){const r=w(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={},o=new Int32Array(n[r]),l=new yr(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(",")}if(void 0!==i[n])o[t]=i[n];else{const e=Object.keys(i).length;i[n]=e,o[t]=e,u.push(t)}}const h=a.slice();h[1]=Object.keys(i).length;const p=new yr(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 _T=Object.freeze({__proto__:null,simpleAbsImpl:mI,addImpl:AI,bincountImpl:DI,bincountReduceImpl:OI,castImpl:SI,ceilImpl:PI,concatImpl:VI,equalImpl:UI,expImpl:jI,expm1Impl:XI,floorImpl:JI,gatherNdImpl:tS,gatherV2Impl:nS,greaterImpl:sS,greaterEqualImpl:iS,lessImpl:uS,lessEqualImpl:pS,linSpaceImpl:mS,logImpl:gS,maxImpl:xS,maximumImpl:wS,minimumImpl:NS,multiplyImpl:TS,negImpl:AS,notEqualImpl:_S,prodImpl:zS,raggedGatherImpl:US,raggedRangeImpl:HS,raggedTensorToTensorImpl:YS,rangeImpl:ZS,rsqrtImpl:JS,scatterImpl:tT,sigmoidImpl:nT,sliceImpl:aT,sparseFillEmptyRowsImpl:lT,sparseReshapeImpl:uT,sparseSegmentReductionImpl:cT,sqrtImpl:hT,squaredDifferenceImpl:fT,stridedSliceImpl:yT,stringNGramsImpl:xT,stringSplitImpl:vT,stringToHashBucketFastImpl:kT,subImpl:NT,tileImpl:CT,topKImpl:AT,transposeImpl:OS,uniqueImpl:RT});Ci("cpu",(()=>new fI),1);const FT=LI(Ye,(e=>e>=0?e:Math.exp(e)-1)),DT={kernelName:Ye,backendName:"cpu",kernelFunc:FT};function OT(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{alpha:a}=s;pI([r],"leakyRelu");const i=d(r.shape),o=n.data.get(r.dataId).values,l=k("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 MT={kernelName:xt,backendName:"cpu",kernelFunc:OT},LT=yI(((e,t)=>e<0?t*e:e));function zT(e){const{inputs:t,backend:n}=e,{x:s,alpha:r}=t;pI([s,r],"prelu");const a=n.data.get(s.dataId).values,i=n.data.get(r.dataId).values,[o,l]=LT(s.shape,r.shape,a,i,"float32");return n.makeTensorInfo(l,"float32",o)}const PT={kernelName:tn,backendName:"cpu",kernelFunc:zT},BT=LI(cn,(e=>Math.max(0,e))),WT={kernelName:cn,backendName:"cpu",kernelFunc:BT},VT=LI(gn,(e=>Math.min(Math.max(0,e),6))),UT={kernelName:gn,backendName:"cpu",kernelFunc:VT};function GT(e,t,n,s,r){if("linear"===n)return vI({inputs:{x:t},backend:e});if("relu"===n)return BT({inputs:{x:t},backend:e});if("elu"===n)return FT({inputs:{x:t},backend:e});if("relu6"===n)return VT({inputs:{x:t},backend:e});if("prelu"===n)return zT({inputs:{x:t,alpha:s},backend:e});if("leakyrelu"===n)return OT({inputs:{x:t},backend:e,attrs:{alpha:r}});if("sigmoid"===n)return sT({inputs:{x:t},backend:e});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}function HT(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{shape:a}=s,i=d(r.shape),o=x(a,i),l=d(o);u(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 c=n.data.get(r.dataId);if(null!=c.complexTensorInfos){const e=c.complexTensorInfos.real,t=c.complexTensorInfos.imag;e.shape=o,t.shape=o}return{dataId:r.dataId,shape:o,dtype:r.dtype}}const jT={kernelName:hn,backendName:"cpu",kernelFunc:HT};function qT(e){const{inputs:t,backend:n,attrs:s}=e,{a:r,b:a}=t,{transposeA:i,transposeB:o}=s;pI([r,a],"matMul");const l=r.shape.length,c=a.shape.length,h=i?r.shape[l-2]:r.shape[l-1],p=o?a.shape[c-1]:a.shape[c-2],f=i?r.shape[l-1]:r.shape[l-2],m=o?a.shape[c-2]:a.shape[c-1],g=r.shape.slice(0,-2),y=a.shape.slice(0,-2),b=d(g),x=d(y),w=Li(r.shape.slice(0,-2),a.shape.slice(0,-2)).concat([f,m]);u(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=HT({inputs:{x:r},backend:n,attrs:{shape:i?[b,h,f]:[b,f,h]}}),N=HT({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=Za([C,S,T],k.dtype),W=B.values,V=n.blockSize;for(let e=0;e<C;e++)for(let t=0;t<S;t+=V)for(let n=0;n<T;n+=V)for(let s=0;s<I;s+=V){const r=Math.min(t+V,S),a=Math.min(n+V,T),i=Math.min(s+V,I);for(let o=t;o<r;o++)for(let t=n;t<a;t++){let n=0;for(let r=s;r<i;r++){const s=Math.min(e,b-1)*_,a=Math.min(e,x-1)*z;n+=$[s+o*F+r*D]*E[r*O+t*L+a]}W[e*P+(o*T+t)]+=n}}return n.disposeIntermediateTensorInfo(k),n.disposeIntermediateTensorInfo(N),n.makeTensorInfo(w,B.dtype,B.values)}const KT={kernelName:ye,backendName:"cpu",kernelFunc:qT};const XT={kernelName:is,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=qT({inputs:{a:r,b:a},attrs:{transposeA:l,transposeB:u},backend:n}),i&&(d=_I({inputs:{a:p,b:i},backend:n}),m.push(p),p=d),c&&(f=GT(n,p,c,o,h),m.push(p),p=f);for(const e of m)n.disposeIntermediateTensorInfo(e);return p}},YT=LI(ee,(e=>Math.acos(e))),ZT={kernelName:ee,backendName:"cpu",kernelFunc:YT},JT=LI(te,(e=>Math.acosh(e))),QT={kernelName:te,backendName:"cpu",kernelFunc:JT};const eC={kernelName:se,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,s=t;pI(t,"addN");const r=s.map((e=>n.data.get(e.dataId).values)),a=Za(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 tC={kernelName:re,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s;pI(r,"all");const o=w(a,r.shape);let l=o;const u=Ql(l,r.shape.length);let c=r;null!=u&&(c=MS({inputs:{x:r},backend:n,attrs:{perm:u}}),l=tu(l.length,r.shape.length)),Jl("all",l,c.shape.length);const[h,p]=Yl(c.shape,l),f=d(p),m=B(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=HT({inputs:{x:y},backend:n,attrs:{shape:Zl(h,o)}});return n.disposeIntermediateTensorInfo(y),e}return y}};const nC={kernelName:ae,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s;pI(r,"any");const o=w(a,r.shape);let l=o;const u=Ql(l,r.shape.length);let c=r;null!=u&&(c=MS({inputs:{x:r},backend:n,attrs:{perm:u}}),l=tu(l.length,r.shape.length)),Jl("any",l,c.shape.length);const[h,p]=Yl(c.shape,l),f=d(p),m=B(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=HT({inputs:{x:y},backend:n,attrs:{shape:Zl(h,o)}});return n.disposeIntermediateTensorInfo(y),e}return y}};const sC={kernelName:ie,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s;pI(r,"argMax");let i=w(a,r.shape);const o=Ql(i,r.shape.length);let l=r;const u=[];null!=o&&(l=MS({inputs:{x:r},backend:n,attrs:{perm:o}}),u.push(l),i=tu(i.length,l.shape.length)),i=[i[0]],Jl("argMax",i,l.shape.length);const[c,h]=Yl(l.shape,i),p=B(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 rC={kernelName:oe,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s;pI(r,"argMin");let i=w(a,r.shape);const o=Ql(i,r.shape.length);let l=r;const u=[];null!=o&&(l=MS({inputs:{x:r},backend:n,attrs:{perm:o}}),u.push(l),i=tu(i.length,l.shape.length)),i=[i[0]],Jl("argMin",i,l.shape.length);const[c,h]=Yl(l.shape,i),p=B(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)}},aC=LI(le,(e=>Math.asin(e))),iC={kernelName:le,backendName:"cpu",kernelFunc:aC},oC=LI(ue,(e=>Math.asinh(e))),lC={kernelName:ue,backendName:"cpu",kernelFunc:oC},uC=LI(ce,(e=>Math.atan(e))),cC={kernelName:ce,backendName:"cpu",kernelFunc:uC},hC=yI(((e,t)=>Math.atan2(e,t))),pC=$I(pe,hC),dC={kernelName:pe,backendName:"cpu",kernelFunc:pC},fC=LI(he,(e=>Math.atanh(e))),mC={kernelName:he,backendName:"cpu",kernelFunc:fC};function gC(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=Za(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 yC(e,t,n,s,r=!1,a=!1){const i=Za(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=Za(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 bC(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=Za(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/S:k}}}}return x}const xC={kernelName:de,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t;pI(r,"avgPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:l}=s;u(Jo(i,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const c=Vo(r.shape,a,i,1,o,l);let h;if(1===c.filterWidth&&1===c.filterHeight&&f(c.inShape,c.outShape))h=vI({inputs:{x:r},backend:n});else{const e=n.data.get(r.dataId).values,t=M(r.shape),s=gC(e,r.shape,r.dtype,t,c,"avg");h=n.makeTensorInfo(c.outShape,r.dtype,s.values)}return h}};const wC={kernelName:me,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;pI(r,"avgPool3d");const c=Uo(r.shape,a,i,1,o,l,u),h=bC(n.data.get(r.dataId).values,r.shape,r.dtype,M(r.shape),c,"avg");return n.makeTensorInfo(h.shape,"float32",h.values)}};const vC={kernelName:ge,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;pI([r,a],"avgPool3DGrad");const c=Uo(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=Za(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 kC={kernelName:fe,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,i=a;pI([r,a],"avgPoolGrad");const{filterSize:o,strides:l,pad:u}=s,c=Vo(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=Za(i.shape,"float32"),k=1/(d*f),N=n.data.get(r.dataId).values,I=Za(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 NC={kernelName:lt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,scale:a,offset:i,mean:o,variance:l}=t;u(o.shape.length===l.shape.length,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),u(null==i||o.shape.length===i.shape.length,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),u(null==a||o.shape.length===a.shape.length,(()=>"Batch normalization gradient requires mean and scale to have equal ranks.")),pI([r,o,l,a,i],"batchNorm");let{varianceEpsilon:c}=s;null==c&&(c=.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++]+c),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 IC={kernelName:be,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,crops:i}=s;pI([r],"batchToSpaceND");const o=a.reduce(((e,t)=>e*t)),l=vd(r.shape,a,o),u=kd(l.length,a.length),c=Nd(r.shape,a,o),h=Id(i,a.length),p=Sd(c,i,a.length),d=HT({inputs:{x:r},backend:n,attrs:{shape:l}}),f=MS({inputs:{x:d},backend:n,attrs:{perm:u}}),m=HT({inputs:{x:f},backend:n,attrs:{shape:c}}),g=iT({inputs:{x:m},backend:n,attrs:{begin:h,size:p}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}};const SC={kernelName:xe,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,weights:a}=t,{size:i}=s,o=DI(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 TC={kernelName:ve,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=Li(Array.from(a),Array.from(i));return n.makeTensorInfo([o.length],"int32",Int32Array.from(o))}},CC=LI(Ie,((e,t)=>{const n=t;return e>n.clipValueMax?n.clipValueMax:e<n.clipValueMin?n.clipValueMin:e})),$C={kernelName:Ie,backendName:"cpu",kernelFunc:CC},EC={kernelName:Te,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 AC(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 RC={kernelName:mt,backendName:"cpu",kernelFunc:AC};function _C(e){const{inputs:t,backend:n,attrs:s}=e,{axis:r}=s,a=w(r,t[0].shape)[0];pd(t.map((e=>e.shape)),a);let i=dd(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 vI({inputs:{x:o[0]},backend:n});if("complex64"===o[0].dtype){const e=o.map((e=>NI({inputs:{input:e},backend:n}))),t=o.map((e=>AC({inputs:{input:e},backend:n}))),s=_C({inputs:e,backend:n,attrs:{axis:a}}),r=_C({inputs:t,backend:n,attrs:{axis:a}}),i=bI({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 HT({inputs:{x:e},backend:n,attrs:{shape:[-1,t]}})})),u=l.map((e=>({vals:n.data.get(e.dataId).values,shape:e.shape})));i=dd(l.map((e=>e.shape)),1);const c=1===l[0].shape[0],h=VI(u,i,t[0].dtype,c),p=dd(o.map((e=>e.shape)),a),f=n.makeTensorInfo(p,t[0].dtype,h);return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),f}const FC={kernelName:Ce,backendName:"cpu",kernelFunc:_C};function DC(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;pI([r,a],"conv2d");const h=Qo(l),p=Go(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 yr(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 OC={kernelName:$e,backendName:"cpu",kernelFunc:DC};const MC={kernelName:Ee,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;pI([r,a],"conv2dBackpropFilter");const h=Qo(l),p=Go(r.shape,c,i,1,o,u,!1,h),{strideHeight:d,strideWidth:f,filterHeight:m,filterWidth:g}=p,y="channelsLast"===p.dataFormat,b=new yr(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 yr(r.shape,r.dtype,v),I=new yr(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 LC={kernelName:Ae,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;pI([r,a],"conv2dBackpropInput");const h=M(a.shape),p=M(r.shape);let d=Qo(u);const f=Go(i,a.shape,o,1,l,c,!1,d),m=new yr(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 zC={kernelName:Re,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;pI([r,a],"conv3d");const u=Ho(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 yr(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 PC={kernelName:_e,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;pI([r,a],"conv3dBackpropFilterV2");const u=M(r.shape),c=M(a.shape),h=Ho(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 yr(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 BC={kernelName:Fe,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;pI([r],"conv3dBackpropInputV2");const u=M(r.shape),c=M(a.shape),h=Ho(l,a.shape,o,1,i),p=new yr(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)}},WC=LI(De,(e=>Math.cos(e))),VC={kernelName:De,backendName:"cpu",kernelFunc:WC},UC=LI(Oe,(e=>Math.cosh(e))),GC={kernelName:Oe,backendName:"cpu",kernelFunc:UC};const HC={kernelName:ze,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=Za([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 jC={kernelName:Me,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,exclusive:i,reverse:o}=s;pI(r,"cumprod");const l=Ql([a],r.shape.length);let u=r;null!=l&&(u=MS({inputs:{x:r},backend:n,attrs:{perm:l}}));const c=tu(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=Ar(u.dtype,"int32"),p=P(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=MS({inputs:{x:y},backend:n,attrs:{perm:eu(l)}});return n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(u),e}return y}};const qC={kernelName:Le,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,exclusive:i,reverse:o}=s;pI(r,"cumsum");const l=Ql([a],r.shape.length);let u=r;null!=l&&(u=MS({inputs:{x:r},backend:n,attrs:{perm:l}}));const c=tu(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=Ar(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?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=MS({inputs:{x:y},backend:n,attrs:{perm:eu(l)}});return n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(u),e}return y}};const KC={kernelName:Pe,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=DI(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=OI(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 XC={kernelName:Be,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockSize:a,dataFormat:i}=s;u("NHWC"===i,(()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${i}`));const o=r.shape[0],l=r.shape[1],c=r.shape[2],h=r.shape[3],p=l*a,d=c*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+c*(n+l*e));g[y++]=m[s]}}}return n.makeTensorInfo([o,p,d,f],r.dtype,g)}};function YC(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,filter:a}=t,{strides:i,pad:o,dilations:l,dimRoundingMode:c}=s;pI([r,a],"depthwiseConv2DNative");const h=M(r.shape),p=M(a.shape);let d=l;null==d&&(d=[1,1]),u(Jo(i,d),(()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${d}'`));const f=Go(r.shape,a.shape,i,d,o,c,!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 yr(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 ZC={kernelName:We,backendName:"cpu",kernelFunc:YC};const JC={kernelName:Ve,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;pI([r,a],"depthwiseConv2dNativeBackpropFilter");const h=Go(r.shape,c,i,o,l,u,!0),{strideHeight:p,strideWidth:d,filterHeight:f,filterWidth:m}=h,g=new yr(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 yr(r.shape,r.dtype,w),k=n.data.get(a.dataId).values,N=new yr(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 QC={kernelName:Ue,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;pI([r,a],"depthwiseConv2DNativeBackpropInput");const h=M(r.shape),p=M(a.shape),d=Go(c,a.shape,i,o,l,u,!0),f=new yr(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 e$={kernelName:Ge,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=Za([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)}},t$={kernelName:He,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:I,filterWidth:S,dilationHeight:T,dilationWidth:C,outShape:$}=Wo(s.shape,r.shape,a,i,"NHWC",o),E=d($),A=$.length,R=N(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<I;++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=U([e,a,d,o],c,M(s.shape)),f=U([t,n,o],p,M(r.shape)),m=u[i]+h[f];m>l&&(l=m)}}}R[U([e,t,a,o],A,M($))]=l}}}return{dataId:l.write(sr(R,s.dtype),$,s.dtype),shape:$,dtype:s.dtype}}},n$={kernelName:qe,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s,filter:r,dy:a}=e,{strides:i,pad:o,dilations:l}=n,c=t,h=z(s.shape,c.data.get(s.dataId).values),p=z(r.shape,c.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}=Wo(s.shape,r.shape,i,o,"NHWC",l);u(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,c.data.get(a.dataId).values),$=W(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:c.write(sr($,s.dtype),r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},s$={kernelName:je,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s,filter:r,dy:a}=e,{strides:i,pad:o,dilations:l}=n,c=t,h=z(s.shape,c.data.get(s.dataId).values),p=z(r.shape,c.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}=Wo(s.shape,r.shape,i,o,"NHWC",l);u(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,c.data.get(a.dataId).values),$=W(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:c.write(sr($,s.dtype),s.shape,s.dtype),shape:s.shape,dtype:s.dtype}}};function r$(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s;let o;pI(r,"sum"),o="bool"===r.dtype?TI({inputs:{x:r},backend:n,attrs:{dtype:"int32"}}):vI({inputs:{x:r},backend:n});const l=o.shape.length,u=w(a,o.shape),c=Ql(u,l);let h=u,p=o;null!=c&&(p=MS({inputs:{x:o},backend:n,attrs:{perm:c}}),h=tu(h.length,l)),Jl("sum",h,p.shape.length);const[f,m]=Yl(p.shape,h);let g=wI(n,f,Ar(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=HT({inputs:{x:g},backend:n,attrs:{shape:Zl(g.shape,u)}}),n.disposeIntermediateTensorInfo(e)}return n.disposeIntermediateTensorInfo(o),null!=c&&n.disposeIntermediateTensorInfo(p),g}const a$={kernelName:Rn,backendName:"cpu",kernelFunc:r$};const i$={kernelName:Xe,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{equation:r}=s,a=t,{allDims:i,summedDims:o,idDims:l}=Gd(r,a.length);jd(i.length,l,a);const{path:u,steps:c}=qd(o,l),h=c.length;let p=null,d=i.length;const m=[];for(let e=0;e<h;++e){for(const t of c[e]){const{permutationIndices:e,expandDims:s}=Hd(d,l[t]);let r;Kd(e)?r=a[t]:(r=MS({inputs:{x:a[t]},backend:n,attrs:{perm:e}}),m.push(r));const i=r.shape.slice();for(let e=0;e<s.length;++e)i.splice(s[e],0,1);f(r.shape,i)||(r=HT({inputs:{x:r},backend:n,attrs:{shape:i}}),m.push(r)),null===p?p=r:(p=$S({inputs:{a:r,b:p},backend:n}),m.push(p))}e<h-1&&(u[e]>=0&&(p=r$({inputs:{x:p},backend:n,attrs:{axis:u[e]-(i.length-d),keepDims:!1}}),m.push(p)),d--)}for(const e of m)e!==p&&n.disposeIntermediateTensorInfo(e);return p}};const o$={kernelName:Ze,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{dy:s,y:r}=t;pI([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>=1?o[e]:o[e]*(t+1)}return n.makeTensorInfo(r.shape,"float32",a)}},l$=LI(Je,(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))})),u$={kernelName:Je,backendName:"cpu",kernelFunc:l$};function c$(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&&(u(-(i+1)<=a,(()=>`Axis must be in the interval [${-(i+1)}, ${i}]`)),l=i+a+1),o.splice(l,0,1),HT({inputs:{x:r},backend:n,attrs:{shape:o}})}const h$={kernelName:tt,backendName:"cpu",kernelFunc:c$},p$=yI(((e,t)=>e/t)),d$=$I(Ke,p$),f$={kernelName:Ke,backendName:"cpu",kernelFunc:d$};function m$(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=k("float32",c),p=k("float32",c);for(let e=0;e<r;e++){const s=iT({inputs:{x:o},backend:n,attrs:{begin:[e,0],size:[1,a]}}),r=iT({inputs:{x:l},backend:n,attrs:{begin:[e,0],size:[1,a]}}),i=bI({inputs:{real:s,imag:r},backend:n}),{real:u,imag:c}=g$(i,t,n),d=Dd(u,c);for(let t=0;t<a;t++){const n=zd(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=bI({inputs:{real:f,imag:m},backend:n});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}function g$(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=y$(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",nr(s,"float32")),i=vI({inputs:{x:a},backend:n}),l=f$.kernelFunc({inputs:{a:e,b:a},backend:n}),u=f$.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=Wd(r*s,t,n),l=zd(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),Pd(s,a,i,r)}return s}(Dd(a,i),s,t);return Od(e)}var o}function y$(e,t,n,s,r){if(1===n)return{real:e,imag:t};const a=Dd(e,t),i=n/2,o=Md(a),l=o.real,u=o.imag,c=[l.length],h=r.makeTensorInfo(c,"float32",l),p=r.makeTensorInfo(c,"float32",u),d=bI({inputs:{real:h,imag:p},backend:r}),f=Ld(a),m=f.real,g=f.imag,y=[m.length],b=r.makeTensorInfo(y,"float32",m),x=r.makeTensorInfo(y,"float32",g),w=bI({inputs:{real:b,imag:x},backend:r}),v=y$(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=bI({inputs:{real:S,imag:T},backend:r}),$=y$(m,g,i,s,r),E=$.real,A=$.imag,R=[E.length],_=r.makeTensorInfo(R,"float32",E),F=r.makeTensorInfo(R,"float32",A),D=bI({inputs:{real:_,imag:F},backend:r}),O=Bd(n,s),M=[O.real.length],L=r.makeTensorInfo(M,"float32",O.real),z=r.makeTensorInfo(M,"float32",O.imag),P=bI({inputs:{real:L,imag:z},backend:r}),B=$S({inputs:{a:P,b:D},backend:r}),W=_I({inputs:{a:C,b:B},backend:r}),V=ST({inputs:{a:C,b:B},backend:r}),U=NI({inputs:{input:W},backend:r}),G=NI({inputs:{input:V},backend:r}),H=AC({inputs:{input:W},backend:r}),j=AC({inputs:{input:V},backend:r}),q=_C({inputs:[U,G],backend:r,attrs:{axis:0}}),K=_C({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 b$={kernelName:st,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=HT({inputs:{x:s},backend:n,attrs:{shape:[r/a,a]}}),o=m$(i,!1,n),l=HT({inputs:{x:o},backend:n,attrs:{shape:s.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}};function x$(e){const{backend:t,attrs:n}=e,{shape:s,value:r,dtype:a}=n,i=a||F(r),o=N(i,d(s));return function(e,t,n){e.fill(t)}(o,r),t.makeTensorInfo(s,i,o)}const w$={kernelName:rt,backendName:"cpu",kernelFunc:x$};const v$={kernelName:at,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:s}=e,r=n,a=k(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}}},k$=yI(((e,t)=>Math.floor(e/t))),N$=$I(ot,k$,null,"int32"),I$={kernelName:ot,backendName:"cpu",kernelFunc:N$};const S$={kernelName:os,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=DC({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=HT({inputs:{x:i},backend:n,attrs:{shape:[i.shape[0],1,1]}});m=_I({inputs:{a:m,b:e},backend:n}),n.disposeIntermediateTensorInfo(e)}else m=_I({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=HT({inputs:{x:o},backend:n,attrs:{shape:[o.shape[0],1,1]}});m=GT(n,m,d,e,f),n.disposeIntermediateTensorInfo(e)}else m=GT(n,m,d,o,f);n.disposeIntermediateTensorInfo(e)}return m}};const T$={kernelName:ls,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=YC({inputs:{x:r,filter:a},backend:n,attrs:{strides:l,pad:u,dataFormat:c,dilations:h,dimRoundingMode:p}});if(i){const e=m;m=_I({inputs:{a:m,b:i},backend:n}),n.disposeIntermediateTensorInfo(e)}if(d){const e=m;m=GT(n,m,d,o,f),n.disposeIntermediateTensorInfo(e)}return m}};const C$={kernelName:ct,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]=Hi(s,r);if(0===u)return n.makeTensorInfo(l,s.dtype,[]);const p=tS(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 $$={kernelName:ut,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,indices:a}=t,{axis:i,batchDims:o}=s;pI([r,a],"gatherV2");const l=w(i,r.shape)[0],c=n.data.get(a.dataId).values,h=r.shape[l];for(let e=0;e<c.length;++e){const t=c[e];u(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=pf(r,a,l,p),g=HT({inputs:{x:r},backend:n,attrs:{shape:[m.batchSize,m.outerSize,m.dimSize,m.sliceSize]}}),y=HT({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),v=nS(n.bufferSync(g),x,b);return n.disposeIntermediateTensorInfo(g),n.disposeIntermediateTensorInfo(y),n.makeTensorInfo(m.outputShape,v.dtype,v.values)}};const E$={kernelName:ft,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=HT({inputs:{x:s},backend:n,attrs:{shape:[r/a,a]}}),o=m$(i,!0,n),l=HT({inputs:{x:o},backend:n,attrs:{shape:s.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}},A$=LI(gt,(e=>Number.isFinite(e)?1:0),"bool"),R$={kernelName:gt,backendName:"cpu",kernelFunc:A$},_$=LI(yt,(e=>Math.abs(e)===1/0?1:0),"bool"),F$={kernelName:yt,backendName:"cpu",kernelFunc:_$},D$=LI(bt,(e=>Number.isNaN(e)?1:0),"bool"),O$={kernelName:bt,backendName:"cpu",kernelFunc:D$};const M$={kernelName:kt,backendName:"cpu",kernelFunc:function(e){const{backend:t,attrs:n}=e,{start:s,stop:r,num:a}=n,i=mS(s,r,a);return t.makeTensorInfo([i.length],"float32",i)}},L$=LI(It,(e=>Math.log1p(e))),z$={kernelName:It,backendName:"cpu",kernelFunc:L$},P$=yI(((e,t)=>e&&t)),B$=$I(St,P$,null,"bool"),W$={kernelName:St,backendName:"cpu",kernelFunc:B$},V$=LI(Tt,(e=>e?0:1),"bool"),U$={kernelName:Tt,backendName:"cpu",kernelFunc:V$},G$=yI(((e,t)=>e||t)),H$=$I(Ct,G$,null,"bool"),j$={kernelName:Ct,backendName:"cpu",kernelFunc:H$};const q$={kernelName:Et,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;pI(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 K$={kernelName:At,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;pI(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 X$(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=w(a,l);let h=c;const p=Ql(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=OS(f,l,r.dtype,p,e),h=tu(h.length,u),l=e}pI(r,"max"),Jl("max",h,u);const[m,g]=Yl(l,h),y=xS(f,d(g),m,r.dtype),b=o.write(y,m,r.dtype);let x=m;if(i){x=Zl(m,c)}return{dataId:b,shape:x,dtype:r.dtype}}const Y$={kernelName:Rt,backendName:"cpu",kernelFunc:X$};const Z$={kernelName:Ft,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t;pI(r,"maxPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:l}=s;u(Jo(i,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const c=Vo(r.shape,a,i,1,o,l);let h;if(1===c.filterWidth&&1===c.filterHeight&&f(c.inShape,c.outShape))h=vI({inputs:{x:r},backend:n});else{const e=n.data.get(r.dataId).values,t=M(r.shape),s=gC(e,r.shape,r.dtype,t,c,"max");h=n.makeTensorInfo(c.outShape,r.dtype,s.values)}return h}};const J$={kernelName:Ot,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;pI(r,"maxPool3d");const c=Uo(r.shape,a,i,1,o,l,u),h=bC(n.data.get(r.dataId).values,r.shape,r.dtype,M(r.shape),c,"max");return n.makeTensorInfo(h.shape,"float32",h.values)}};const Q$={kernelName:Mt,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;pI([r,a],"maxPool3DGrad");const c=Uo(a.shape,i,o,1,l,u),h=function(e,t){const n=Za(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=Za(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 eE={kernelName:Dt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a,output:i}=t,o=a;pI([a,i],"maxPoolGrad");const{filterSize:l,strides:u,pad:c,dimRoundingMode:h}=s,p=Vo(o.shape,l,u,1,c,h),d=n.data.get(o.dataId).values,f=Za(p.outShape,o.dtype,yC(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=Za(o.shape,"float32"),I=n.data.get(r.dataId).values,S=Za(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 tE={kernelName:Lt,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{filterSize:r,strides:a,pad:i,includeBatchInIndex:o}=t,l=n;pI(s,"MaxPoolWithArgmax");const u=l.data.get(s.dataId).values,c=Vo(s.shape,r,a,[1,1],i),[h,p]=function(e,t,n,s,r){const a=gC(e,0,n,M(t),r,"max"),i=yC(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 nE={kernelName:zt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s,o=w(a,r.shape),l=d(Yl(r.shape,o)[1]),u=[],c=n.makeTensorInfo([],"float32",new Float32Array([l]));u.push(c);const h=TI({inputs:{x:r},backend:n,attrs:{dtype:"float32"}});u.push(h);const p=d$({inputs:{a:h,b:c},backend:n});u.push(p);const f=r$({inputs:{x:p},backend:n,attrs:{axis:a,keepDims:i}});return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),f}};const sE={kernelName:Pt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,keepDims:i}=s;pI(r,"min");const o=w(a,r.shape);let l=o;const u=Ql(l,r.shape.length);let c=r;null!=u&&(c=MS({inputs:{x:r},backend:n,attrs:{perm:u}}),l=tu(l.length,r.shape.length)),Jl("min",l,c.shape.length);const[h,p]=Yl(c.shape,l),f=d(p),m=B(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=HT({inputs:{x:y},backend:n,attrs:{shape:Zl(h,o)}});return n.disposeIntermediateTensorInfo(y),e}return y}};const rE={kernelName:Wt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{paddings:a,mode:i}=s;pI(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=k(r.dtype,m);for(let e=0;e<m;e++){let t=G(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=U(t,p,f);b[e]=h[n]}return{dataId:n.write(b,o,r.dtype),shape:o,dtype:r.dtype}}},aE=yI(((e,t)=>{const n=e%t;return e<0&&t<0||e>=0&&t>=0?n:(n+t)%t})),iE=$I(Vt,aE),oE={kernelName:Vt,backendName:"cpu",kernelFunc:iE};function lE(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=w([o],r.shape),u=X$({inputs:{x:r},backend:n,attrs:{reductionIndices:l,keepDims:!1}}),c=Zl(u.shape,l),h=HT({inputs:{x:u},backend:n,attrs:{shape:c}}),p=ST({inputs:{a:r,b:h},backend:n}),d=qI({inputs:{x:p},backend:n}),f=r$({inputs:{x:d},backend:n,attrs:{axis:l,keepDims:!1}}),m=HT({inputs:{x:f},backend:n,attrs:{shape:c}}),g=d$({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 uE={kernelName:Dn,backendName:"cpu",kernelFunc:lE};const cE={kernelName:Ut,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{numSamples:a,seed:i,normalized:o}=s;pI(r,"multinomial");const l=o?r:lE({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=B(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=Rc(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)}},hE=cp;const pE={kernelName:qt,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;pI(r,"NonMaxSuppression");const u=n.data.get(r.dataId).values,c=n.data.get(a.dataId).values,{selectedIndices:h}=hE(u,c,i,o,l);return n.makeTensorInfo([h.length],"int32",new Int32Array(h))}},dE=hp;const fE={kernelName:Kt,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;pI(r,"NonMaxSuppressionPadded");const c=n.data.get(r.dataId).values,h=n.data.get(a.dataId).values,{selectedIndices:p,validOutputs:d}=dE(c,h,i,o,l,u);return[n.makeTensorInfo([p.length],"int32",new Int32Array(p)),n.makeTensorInfo([],"int32",new Int32Array([d]))]}},mE=pp;const gE={kernelName:Xt,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;pI(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}=mE(c,h,p,d,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}};const yE={kernelName:Zt,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;pI(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 bE(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=NI({inputs:{input:s},backend:n}),t=bE({inputs:{x:e},backend:n}),r=AC({inputs:{input:s},backend:n}),a=bE({inputs:{x:r},backend:n}),i=bI({inputs:{real:t,imag:a},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(a),i}return x$({backend:n,attrs:{shape:s.shape,value:0,dtype:s.dtype}})}const xE={kernelName:ns,backendName:"cpu",kernelFunc:bE};const wE={kernelName:Yt,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=NI({inputs:{input:r},backend:s}),n=e({inputs:{x:t},backend:s}),a=AC({inputs:{input:r},backend:s}),i=bE({inputs:{x:a},backend:s}),o=bI({inputs:{real:n,imag:i},backend:s});return s.disposeIntermediateTensorInfo(t),s.disposeIntermediateTensorInfo(n),s.disposeIntermediateTensorInfo(a),s.disposeIntermediateTensorInfo(i),o}return x$({backend:s,attrs:{shape:r.shape,value:1,dtype:r.dtype}})}};function vE(e){const{inputs:t,backend:n,attrs:s}=e,{axis:r}=s;if(1===t.length)return c$({inputs:{input:t[0]},backend:n,attrs:{dim:r}});const a=t[0].shape,i=t[0].dtype;t.forEach((e=>{c(a,e.shape,"All tensors passed to stack must have matching shapes"),u(i===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const o=[],l=_C({inputs:t.map((e=>{const t=c$({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 kE={kernelName:Jt,backendName:"cpu",kernelFunc:vE};const NE={kernelName:Qt,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{paddings:a,constantValue:i}=s;pI(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=k(r.dtype,f);0!==i&&y.fill(i);for(let e=0;e<c;e++){y[U(G(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}}},IE=yI(((e,t)=>Math.pow(e,t))),SE=$I(en,IE),TE={kernelName:en,backendName:"cpu",kernelFunc:SE};const CE={kernelName:sn,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]=US(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 $E={kernelName:rn,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]=HS(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 EE={kernelName:an,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]=YS(u,r.shape,c,a.shape,a.dtype,h,i.shape,p,d,l);return n.makeTensorInfo(f,a.dtype,m)}};const AE={kernelName:on,backendName:"cpu",kernelFunc:function(e){const{backend:t,attrs:n}=e,{start:s,stop:r,dtype:a,step:i}=n,o=ZS(s,r,i,a);return t.makeTensorInfo([o.length],a,o)}},RE=LI(un,(e=>1/e)),_E={kernelName:un,backendName:"cpu",kernelFunc:RE};const FE={kernelName:fn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,halfPixelCenters:i,size:o}=s;pI(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 DE={kernelName:mn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{images:r,dy:a}=t,{alignCorners:i}=s;pI([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 OE={kernelName:pn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{images:r}=t,{alignCorners:a,halfPixelCenters:i,size:o}=s;pI(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 ME={kernelName:dn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{images:r,dy:a}=t,{alignCorners:i}=s;pI([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 LE={kernelName:yn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dims:a}=s;pI(r,"reverse");const i=r.shape.length,o=w(a,r.shape);if(0===i)return vI({inputs:{x:r},backend:n});const l=new yr(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)}},zE={kernelName:as,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:s}=e,{radians:r,fillValue:a,center:i}=t,o=n,l=k(s.dtype,d(s.shape)),[u,c,h,p]=s.shape,[f,m]=wd(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}}},PE=LI(bn,(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})),BE={kernelName:bn,backendName:"cpu",kernelFunc:PE};const WE={kernelName:wn,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}=Xi(0,r,i),p=tT(n.bufferSync(r),n.bufferSync(a),i,h,u,l,o,c,0,!0);return n.makeTensorInfo(i,p.dtype,p.values)}};function VE(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 UE(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 GE={kernelName:vn,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=N("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?VE(n,t[e+l]):UE(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 HE={kernelName:kn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n}=e,{condition:s,t:r,e:a}=t;pI([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=Ar(r.dtype,a.dtype),h=B(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)}},jE=LI(Nn,(e=>e>=0?1.0507009873554805*e:1.7580993408473768*(Math.exp(e)-1))),qE={kernelName:Nn,backendName:"cpu",kernelFunc:jE},KE=LI(Cn,(e=>e<0?-1:e>0?1:0)),XE={kernelName:Cn,backendName:"cpu",kernelFunc:KE},YE=LI(Sn,(e=>Math.sin(e))),ZE={kernelName:Sn,backendName:"cpu",kernelFunc:YE},JE=LI(Tn,(e=>Math.sinh(e))),QE={kernelName:Tn,backendName:"cpu",kernelFunc:JE},eA=Math.log(1.1920928955078125e-7)+2,tA=LI(En,(e=>{const t=e>-eA,n=e<eA,s=Math.exp(e);let r;return r=n?s:t?e:Math.log(1+s),r})),nA={kernelName:En,backendName:"cpu",kernelFunc:tA};const sA={kernelName:_n,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,paddings:i}=s;pI([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=NE.kernelFunc({inputs:{x:r},backend:n,attrs:{paddings:l,constantValue:0}}),c=vd(u.shape,a,o,!1),h=kd(c.length,a.length,!1),p=Nd(u.shape,a,o,!1),f=HT({inputs:{x:u},backend:n,attrs:{shape:c}}),m=MS({inputs:{x:f},backend:n,attrs:{perm:h}}),g=HT({inputs:{x:m},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}};const rA={kernelName:On,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]=lT(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 aA={kernelName:Mn,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]=uT(o,s.shape,s.dtype,i,l);return[n.makeTensorInfo(c,s.dtype,u),n.makeTensorInfo([h.length],a.dtype,new Int32Array(h))]}};const iA={kernelName:Ln,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]=cT(i,s.shape,s.dtype,o,l,!0);return n.makeTensorInfo(c,s.dtype,u)}};const oA={kernelName:zn,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]=cT(i,s.shape,s.dtype,o,l);return n.makeTensorInfo(c,s.dtype,u)}};const lA={kernelName:Pn,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}=Xi(0,r,o),d=!1,f=n.bufferSync(r);let m;switch(a.dtype){case"bool":m=tT(f,n.bufferSync(a),o,p,c,u,l,h,Boolean(n.data.get(i.dataId).values[0]),d);break;case"float32":m=tT(f,n.bufferSync(a),o,p,c,u,l,h,n.data.get(i.dataId).values[0],d);break;case"int32":m=tT(f,n.bufferSync(a),o,p,c,u,l,h,n.data.get(i.dataId).values[0],d);break;case"string":m=tT(f,n.bufferSync(a),o,p,c,u,l,h,or(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 uA={kernelName:Fn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{numOrSizeSplits:a,axis:i}=s,o=w(i,r.shape)[0],l=Yd(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=iT({inputs:{x:r},backend:n,attrs:{begin:u,size:t}});return u[o]+=e,s}))}},cA={kernelName:Wn,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{const{x:n}=e,s=t;pI(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}}},hA=LI(ss,((e,t)=>{const n=t;return isNaN(e)?NaN:e>0?1:n.alpha})),pA={kernelName:ss,backendName:"cpu",kernelFunc:hA};const dA={kernelName:Vn,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:c,ellipsisMask:h,newAxisMask:p,shrinkAxisMask:d}=s;pI(r,"stridedSlice");const{finalShapeSparse:f,finalShape:m,isIdentity:g,sliceDim0:y,isSimpleSlice:b,begin:x,end:w,strides:v}=co(r.shape,a,i,o,l,c,h,p,d);let k;if(g)k=HT({inputs:{x:r},backend:n,attrs:{shape:m}});else if(y||b){u(r.shape.length>=1,(()=>`Input must have rank at least 1, got: ${r.shape.length}`));const e=Ji(x,w,v),t=iT({inputs:{x:r},backend:n,attrs:{begin:x,size:e}});k=HT({inputs:{x:t},backend:n,attrs:{shape:m}}),n.disposeIntermediateTensorInfo(t)}else{const e=yT(f,n.bufferSync(r),v,x);k=n.makeTensorInfo(m,e.dtype,e.values)}return k}};const fA={kernelName:Un,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]=xT(p,d,r,a,i,o,l,u);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(h.shape,"int32",m)]}};const mA={kernelName:Gn,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]=vT(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 gA={kernelName:Hn,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=kT(n.data.get(a.dataId).values,r);return n.makeTensorInfo(a.shape,"int32",i)}},yA=LI(qn,(e=>Math.tan(e))),bA={kernelName:qn,backendName:"cpu",kernelFunc:yA},xA=LI(Kn,(e=>Math.tanh(e)));const wA={kernelName:Xn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{reps:a}=s;pI(r,"tile");const i=CT(n.bufferSync(r),a);return n.makeTensorInfo(i.shape,i.dtype,i.values)}};const vA={kernelName:Yn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{k:a,sorted:i}=s;pI(r,"topk");const o=n.data.get(r.dataId).values,[l,u]=AT(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 kA={kernelName:Zn,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],N=M(y),I=N[0],S=N[1],T=N[2],C=k(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=NA(c,p,o),m=NA(d,h,o);switch(i){case"nearest":a=SA($,h,p,x,w,v,e,m,f,r,l);break;case"bilinear":a=TA($,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 NA(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 a(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 a(0,n,t-1)}(e,t);case"nearest":return function(e,t){return a(0,e,t-1)}(e,t);default:return function(e,t){return e}(e)}}function IA(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 SA(e,t,n,s,r,a,i,o,l,u,c){return IA(e,t,n,s,r,a,i,Math.round(o),Math.round(l),u,c)}function TA(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)*IA(e,t,n,s,r,a,i,h,p,u,c)+(l-p)*IA(e,t,n,s,r,a,i,h,f,u,c))+(o-h)*((f-l)*IA(e,t,n,s,r,a,i,d,p,u,c)+(l-p)*IA(e,t,n,s,r,a,i,d,f,u,c))}const CA={kernelName:Qn,backendName:"cpu",kernelFunc:function(e){const{inputs:t,attrs:n,backend:s}=e,{axis:r}=n,{x:a}=t;pI(a,"unique");const i=s.data.get(a.dataId).values,{outputValues:o,outputShape:l,indices:u}=RT(i,r,a.shape,a.dtype);return[s.makeTensorInfo(l,a.dtype,o),s.makeTensorInfo([u.length],"int32",u)]}};const $A={kernelName:es,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=iT({inputs:{x:r},backend:n,attrs:{begin:c,size:h}});p[e]=HT({inputs:{x:t},backend:n,attrs:{shape:l}}),n.disposeIntermediateTensorInfo(t)}return p}};const EA={kernelName:ts,backendName:"cpu",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,segmentIds:a}=t,{numSegments:i}=s;pI(r,"unsortedSegmentSum");const o=[],l=[],u=r.shape.length-a.shape.length;let c=a;for(let e=0;e<u;++e){const t=c$({inputs:{input:c},backend:n,attrs:{dim:e+1}});c=t,l.push(t)}for(let e=0;e<i;++e){const t=nr(e,"int32"),s=n.makeTensorInfo([],"int32",t),a=GI({inputs:{a:s,b:c},backend:n}),i=TI({inputs:{x:a},backend:n,attrs:{dtype:"float32"}}),u=$S({inputs:{a:i,b:r},backend:n}),h=r$({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=vE({inputs:o,backend:n,attrs:{axis:0}});return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),h}},AA=[XT,gI,ZT,QT,FI,eC,tC,nC,sC,rC,iC,lC,cC,dC,mC,xC,wC,vC,kC,KT,NC,IC,SC,TC,CI,WI,$C,xI,EC,FC,OC,MC,LC,zC,PC,BC,VC,GC,HC,jC,qC,KC,XC,ZC,JC,QC,e$,t$,n$,s$,i$,DT,o$,HI,u$,KI,h$,ZI,b$,w$,v$,eS,I$,S$,T$,C$,$$,aS,lS,kI,E$,RC,R$,F$,O$,MT,hS,fS,M$,bS,z$,W$,U$,j$,q$,K$,Y$,kS,Z$,J$,Q$,eE,tE,nE,sE,SS,rE,oE,cE,ES,RS,pE,fE,gE,DS,yE,wE,kE,NE,TE,PT,PS,CE,$E,EE,AE,II,f$,_E,WT,UT,jT,FE,DE,OE,ME,LE,zE,BE,eT,WE,GE,HE,qE,rT,XE,ZE,QE,oT,uE,nA,sA,rA,aA,iA,oA,lA,uA,dT,cA,gT,pA,dA,fA,mA,gA,TT,a$,bA,{kernelName:Kn,backendName:"cpu",kernelFunc:xA},wA,vA,kA,LS,CA,$A,EA,xE];for(const e of AA)ms(e);const RA={},_A={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function FA(e,t){if(!(e in RA)||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("undefined"!=typeof OffscreenCanvas&&2===e)return new OffscreenCanvas(300,150);if("undefined"!=typeof document)return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}(e):t;n.addEventListener("webglcontextlost",(t=>{t.preventDefault(),delete RA[e]}),!1),X().getBool("SOFTWARE_WEBGL_ENABLED")&&(_A.failIfMajorPerformanceCaveat=!1);if(1===e)return n.getContext("webgl",_A)||n.getContext("experimental-webgl",_A);return n.getContext("webgl2",_A)}(e,t);if(null===n)return console.log("Could not get context for WebGL version",e),null;RA[e]=n}const n=RA[e];return null==n||n.isContextLost()?(delete RA[e],FA(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),RA[e])}var DA,OA,MA;function LA(e,t){return[t,e]}function zA(e){const t=d(e);return g(Math.ceil(t/4))}function PA(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function BA(e,t){const n=e;let s,r,a,i,o,l,u,c,h,p;return 2===X().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 WA(e,t){const n=t();return X().getBool("DEBUG")&&function(e){const t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+function(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}`}}(e,t))}(e),n}!function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"}(DA||(DA={})),function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"}(OA||(OA={})),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"}(MA||(MA={}));function VA(e){return!!(X().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||0===e||5.96e-8<Math.abs(e)&&Math.abs(e)<65504)}function UA(e,t){return JA(e,(()=>e.getExtension(t)),'Extension "'+t+'" not supported on this browser.')}const GA=/ERROR: [0-9]+:([0-9]+):/g;function HA(e,t){const n=GA.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)=>y((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 ${y(u[0],o)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(c.join("\n"))}function jA(e,t){if(WA(e,(()=>e.validateProgram(t))),!1===e.getProgramParameter(t,e.VALIDATE_STATUS))throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function qA(e,t,n,s,r,a,i){const o=e.getAttribLocation(t,n);return-1!==o&&(WA(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,s))),WA(e,(()=>e.vertexAttribPointer(o,r,e.FLOAT,!1,a,i))),WA(e,(()=>e.enableVertexAttribArray(o))),!0)}function KA(e,t,n,s){WA(e,(()=>function(e,t,n){QA(e,n),WA(e,(()=>e.activeTexture(e.TEXTURE0+n))),WA(e,(()=>e.bindTexture(e.TEXTURE_2D,t)))}(e,t,s))),WA(e,(()=>e.uniform1i(n,s)))}function XA(e,t,n){WA(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,n))),WA(e,(()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0)))}function YA(e,t){WA(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,t))),WA(e,(()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0)))}function ZA(e){const t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+function(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}`}}(e,t))}function JA(e,t,n){const s=WA(e,(()=>t()));if(null==s)throw new Error(n);return s}function QA(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 eR(e,t=2){return d(e.slice(0,e.length-t))}function tR(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 nR(e){let t=[1,1,1];return 0===e.length||1===e.length&&1===e[0]||(t=[eR(e),...tR(e)]),t}function sR(e){return e%2==0}function rR(e,t){if(f(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.slice(-1)[0],s=t.slice(-1)[0];if(n===s)return!0;if(sR(n)&&sR(s)&&(1===e[0]||1===t[0]))return!0}return e[1]===t[1]&&sR(e[0])&&sR(t[0])}let aR,iR;function oR(e,t){return null!=e.getExtension(t)}function lR(e){try{if(null!=FA(e))return!0}catch(e){return console.log("Error when getting WebGL context: ",e),!1}return!1}function uR(e){if(0===e)return!1;const t=FA(e);if(1!==e){if(oR(t,"EXT_color_buffer_float"))return cR(t);const e="EXT_color_buffer_half_float";if(oR(t,e)){const n=t.getExtension(e);return function(e,t){const n=BA(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(!oR(t,"OES_texture_float"))return!1;if(!oR(t,"WEBGL_color_buffer_float"))return!1;return cR(t)}function cR(e){const t=BA(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 hR(e,t){Array.isArray(e)||(e=[e]),e.forEach((e=>{null!=e&&u("complex64"!==e.dtype,(()=>`${t} does not support complex64 tensors in the WebGL backend.`))}))}const pR=X();function dR(){let e,t,n,s,r,a,i,o,l,u;return 2===X().getNumber("WEBGL_VERSION")?(e="#version 300 es",t="in",n="out",s="in",r="texture",a="outputColor",i="out vec4 outputColor;",o=X().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 fR(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 mR(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 gR(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 yR(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`}pR.registerFlag("HAS_WEBGL",(()=>pR.getNumber("WEBGL_VERSION")>0)),pR.registerFlag("WEBGL_VERSION",(()=>lR(2)?2:lR(1)?1:0)),pR.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",(()=>!1)),pR.registerFlag("WEBGL_BUFFER_SUPPORTED",(()=>2===pR.get("WEBGL_VERSION"))),pR.registerFlag("WEBGL_CPU_FORWARD",(()=>!0)),pR.registerFlag("WEBGL_FORCE_F16_TEXTURES",(()=>!1)),pR.registerFlag("WEBGL_PACK",(()=>pR.getBool("HAS_WEBGL"))),pR.registerFlag("WEBGL_PACK_NORMALIZATION",(()=>pR.getBool("WEBGL_PACK"))),pR.registerFlag("WEBGL_PACK_CLIP",(()=>pR.getBool("WEBGL_PACK"))),pR.registerFlag("WEBGL_PACK_DEPTHWISECONV",(()=>pR.getBool("WEBGL_PACK"))),pR.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",(()=>pR.getBool("WEBGL_PACK"))),pR.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",(()=>pR.getBool("WEBGL_PACK"))),pR.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",(()=>pR.getBool("WEBGL_PACK"))),pR.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",(()=>pR.getBool("WEBGL_PACK"))),pR.registerFlag("WEBGL_PACK_REDUCE",(()=>pR.getBool("WEBGL_PACK"))),pR.registerFlag("WEBGL_LAZILY_UNPACK",(()=>pR.getBool("WEBGL_PACK"))),pR.registerFlag("WEBGL_CONV_IM2COL",(()=>pR.getBool("WEBGL_PACK"))),pR.registerFlag("WEBGL_MAX_TEXTURE_SIZE",(()=>function(e){if(null==aR){const t=FA(e);aR=t.getParameter(t.MAX_TEXTURE_SIZE)}return aR}(pR.getNumber("WEBGL_VERSION")))),pR.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",(()=>function(e){if(null==iR){const t=FA(e);iR=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,iR)}(pR.getNumber("WEBGL_VERSION")))),pR.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",(()=>{const e=pR.getNumber("WEBGL_VERSION");return 0===e?0:function(e){if(0===e)return 0;let t;const n=FA(e);return t=oR(n,"EXT_disjoint_timer_query_webgl2")&&2===e?2:oR(n,"EXT_disjoint_timer_query")?1:0,t}(e)})),pR.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",(()=>pR.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!Hr())),pR.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",(()=>function(e){if(0===e)return!1;const t=FA(e);if(1===e){if(!oR(t,"OES_texture_float"))return!1}else if(!oR(t,"EXT_color_buffer_float"))return!1;return cR(t)}(pR.getNumber("WEBGL_VERSION")))),pR.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",(()=>!pR.getBool("WEBGL_FORCE_F16_TEXTURES")&&pR.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"))),pR.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",(()=>uR(pR.getNumber("WEBGL_VERSION")))),pR.registerFlag("WEBGL_FENCE_API_ENABLED",(()=>{return 2===(e=pR.getNumber("WEBGL_VERSION"))&&null!=FA(e).fenceSync;var e})),pR.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",(()=>pR.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0)),pR.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",(()=>-1),(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}.`)})),pR.registerFlag("WEBGL_FLUSH_THRESHOLD",(()=>Hr()?1:-1),(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}.`)})),pR.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",(()=>128)),pR.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",(()=>!1)),pR.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",(()=>1e5)),pR.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",(()=>128)),pR.registerFlag("WEBGL_EXP_CONV",(()=>!1)),pR.registerFlag("SOFTWARE_WEBGL_ENABLED",(()=>pR.getBool("IS_TEST"))),pR.registerFlag("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE",(()=>1/0)),pR.registerFlag("WEBGL_AUTO_SQUARIFY_NARROW_TEXTURE_SHAPE",(()=>!1)),pR.registerFlag("WEBGL2_ISNAN_CUSTOM",(()=>!1)),pR.registerFlag("ENGINE_COMPILE_ONLY",(()=>!1));const bR="\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:xR}=gf;function wR(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}=RR(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?kR(e,s):vR(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=xR(e.shapeInfo.logicalShape,t.logicalShape),l=AR(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&&f(i,a))return`\n float ${r}() {\n return sampleTexture(${n}, resultUV);\n }\n `;const u=AR(l),c=xR(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 m="";m=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}(${m});\n }\n `}(e,t));return r}(e,t,n.packedInputs,n.enableShapeUniforms))).join("\n"),i=t.texShape,o=dR(),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 ${NR}\n ${IR}\n ${SR}\n `}(o);t.isPacked?(u=function(e,t,n){switch(e.length){case 0:return CR();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(f(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 CR();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(f(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 ${mR(["r","c","d"],e)}\n return ivec3(r, c, d);\n }\n`}const s=fR(["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 ${mR(["r","c","d","d2"],e)}\n return ivec4(r, c, d, d2);\n }\n `}const s=fR(["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=fR(["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=fR(["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+=TR);return[h,l,c,r,u,a,n.userCode].join("\n")}function vR(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=$R(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 ${ER(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=$R(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&&f(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}=v(n),l=i;if(l.length<n.length){const n=["row","col"];return`\n ${vR(_R(e,l),t)}\n float ${r}(int row, int col) {\n return ${r}(${FR(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 ${ER(e)}\n }\n `;const u=a[0],c=a[1],h=$R(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}=v(n),u=o;if(u.length<n.length){const n=["row","col","depth"];return`\n ${vR(_R(e,u),t)}\n float ${r}(int row, int col, int depth) {\n return ${r}(${FR(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 ${ER(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=$R(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}=v(n);if(l.length<n.length){const n=["row","col","depth","depth2"];return`\n ${vR(_R(e,l),t)}\n float ${r}(int row, int col, int depth, int depth2) {\n return ${r}(${FR(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 ${ER(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=$R(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}=v(t);if(l.length<t.length){const t=["row","col","depth","depth2","depth3"];return`\n ${vR(_R(e,l))}\n float ${s}(int row, int col, int depth, int depth2, int depth3) {\n return ${s}(${FR(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 ${ER(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=$R(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}=v(t);if(r.length<t.length){const t=["row","col","depth","depth2","depth3","depth4"];return`\n ${vR(_R(e,r))}\n float ${s}(int row, int col, int depth,\n int depth2, int depth3, int depth4) {\n return ${s}(${FR(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 ${ER(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=$R(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 kR(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=dR();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=dR();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=dR();if(null!=a&&f(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 ${kR(_R(e,n.slice(1)),t)}\n vec4 ${r}(int b, int row, int col) {\n return ${r}(${FR(a,s)});\n }\n `}const o=dR();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=dR();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 NR="\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",IR="\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",SR="\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",TR="\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 CR(){return"\n int getOutputCoords() {\n return 0;\n }\n "}function $R(e){return`offset${e}`}function ER(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 AR(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 RR(e,t,n){const{newShape:s,keptDims:r}=v(t),a=t.length,i=e&&3===a&&1===t[0],o=i?t.slice(1):s,l=!e&&a>1&&!f(t,n)&&s.length<a||i;return{useSqueezeShape:l,uniformShape:l?o:t,keptDims:r}}function _R(e,t){const n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function FR(e,t){return t.map((t=>e[t])).join(", ")}function DR(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=wR(r,i,t),l=function(e,t){const n=JA(e,(()=>e.createShader(e.FRAGMENT_SHADER)),"Unable to create fragment WebGLShader.");if(WA(e,(()=>e.shaderSource(n,t))),WA(e,(()=>e.compileShader(n))),X().get("ENGINE_COMPILE_ONLY"))return n;if(!1===e.getShaderParameter(n,e.COMPILE_STATUS))throw HA(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}(e.gl,o),u=e.createProgram(l);return X().get("ENGINE_COMPILE_ONLY")?{program:t,fragmentShader:l,source:o,webGLProgram:u,inShapeInfos:a,outShapeInfo:i,uniformLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,inShapesLocations:null,inTexShapesLocations:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}:Object.assign({program:t,fragmentShader:l,source:o,webGLProgram:u,inShapeInfos:a,outShapeInfo:i},OR(e,t,u))}function OR(e,t,n){const s={},r={},a={},i=[];let o,l,u,c=null,h=null;h=e.getUniformLocation(n,"NAN",!1),1===X().getNumber("WEBGL_VERSION")&&(c=e.getUniformLocation(n,"INFINITY",!1));const p=!1;for(let i=0;i<t.variableNames.length;i++){const o=t.variableNames[i];s[o]=e.getUniformLocation(n,o,p),s[`offset${o}`]=e.getUniformLocation(n,`offset${o}`,p),t.enableShapeUniforms&&(r[`${o}Shape`]=e.getUniformLocation(n,`${o}Shape`,p),a[`${o}TexShape`]=e.getUniformLocation(n,`${o}TexShape`,p))}return t.enableShapeUniforms&&(o=e.getUniformLocation(n,"outShape",p),u=e.getUniformLocation(n,"outShapeStrides",p),l=e.getUniformLocation(n,"outTexShape",p)),t.customUniforms&&t.customUniforms.forEach(((t,s)=>{i[s]=e.getUniformLocation(n,t.name,p)})),{uniformLocations:s,customUniformLocations:i,infLoc:c,nanLoc:h,inShapesLocations:r,inTexShapesLocations:a,outShapeLocation:o,outShapeStridesLocation:u,outTexShapeLocation:l}}function MR(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(!f(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(!f(i,o))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${i} and ${o} must match`)}))}function LR(e){return X().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&e<=4}class zR{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=DA.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=dR();this.outputShape=e,this.enableShapeUniforms=LR(this.outputShape.length),this.userCode=`\n ivec3 outCoordsFromFlatIndex(int index) {\n ${this.enableShapeUniforms?mR(["r","c","d"],e):fR(["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 PR{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=DA.DENSE,this.customUniforms=[{name:"texShape",type:"ivec2"}];const t=dR();this.outputShape=e,this.enableShapeUniforms=LR(this.outputShape.length),this.userCode=`\n ivec3 outCoordsFromFlatIndex(int index) {\n ${this.enableShapeUniforms?mR(["r","c","d"],e):fR(["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 BR{constructor(e){this.variableNames=["A"],this.outTexUsage=OA.DOWNLOAD;const t=dR();this.outputShape=e,this.userCode=`\n ${bR}\n\n void main() {\n float x = getAAtOutCoords();\n ${t.output} = encode_float(x);\n }\n `}}class WR{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=OA.DOWNLOAD;const t=dR();this.outputShape=e,this.userCode=`\n ${bR}\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 VR={R:0,G:1,B:2,A:3};class UR{constructor(e,t=!1,n="RGBA"){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];const s=dR();this.outputShape=e,this.enableShapeUniforms=LR(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[${VR[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":yR(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 GR{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];const n=dR();this.outputShape=e,this.enableShapeUniforms=LR(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":yR(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 HR(e){const t=dR();return function(e,t){const n=JA(e,(()=>e.createShader(e.VERTEX_SHADER)),"Unable to create vertex WebGLShader.");if(WA(e,(()=>e.shaderSource(n,t))),WA(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}(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 jR(e){return function(e,t){const n=JA(e,(()=>e.createBuffer()),"Unable to create WebGLBuffer");return WA(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,n))),WA(e,(()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW))),n}(e,new Float32Array([-1,1,0,0,1,-1,-1,0,0,0,1,1,0,1,1,1,-1,0,1,0]))}function qR(e){return function(e,t){const n=JA(e,(()=>e.createBuffer()),"Unable to create WebGLBuffer");return WA(e,(()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n))),WA(e,(()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW))),n}(e,new Uint16Array([0,1,2,2,1,3]))}function KR(e,t,n,s,r,a){!function(e,t){const n=X().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}].`)}(t,n);const i=function(e){return JA(e,(()=>e.createTexture()),"Unable to create WebGLTexture.")}(e),o=e.TEXTURE_2D;return WA(e,(()=>e.bindTexture(o,i))),WA(e,(()=>e.texParameteri(o,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE))),WA(e,(()=>e.texParameteri(o,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE))),WA(e,(()=>e.texParameteri(o,e.TEXTURE_MIN_FILTER,e.NEAREST))),WA(e,(()=>e.texParameteri(o,e.TEXTURE_MAG_FILTER,e.NEAREST))),1===X().getNumber("WEBGL_VERSION")?WA(e,(()=>e.texImage2D(o,0,s,t,n,0,r,a,null))):WA(e,(()=>e.texStorage2D(o,1,s,t,n))),WA(e,(()=>e.bindTexture(e.TEXTURE_2D,null))),{texture:i,texShape:[n,t]}}function XR(e){return e.internalFormatFloat}function YR(e){return e.internalFormatHalfFloat}function ZR(e){return e.downloadTextureFormat}function JR(e){return e.internalFormatPackedFloat}function QR(e){return e.internalFormatPackedHalfFloat}function e_(e,t,n,s,r,a,i,o){const l=e,u=new Float32Array(function(e,t){const[n,s]=PA(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}class t_{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.itemsToPoll=[];const t=X().getNumber("WEBGL_VERSION");if(null!=e?(this.gl=e,function(e,t){RA[e]=t}(t,e)):this.gl=FA(t),e=this.gl,2===X().getNumber("WEBGL_VERSION")){const t=e;this.createVertexArray=()=>WA(t,(()=>t.createVertexArray())),this.bindVertexArray=e=>WA(t,(()=>t.bindVertexArray(e))),this.deleteVertexArray=e=>WA(t,(()=>t.deleteVertexArray(e))),this.getVertexArray=()=>WA(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=()=>WA(e,(()=>t.createVertexArrayOES())),this.bindVertexArray=n=>WA(e,(()=>t.bindVertexArrayOES(n))),this.deleteVertexArray=n=>WA(e,(()=>t.deleteVertexArrayOES(n))),this.getVertexArray=()=>WA(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===X().getNumber("WEBGL_VERSION")){const e="OES_texture_float",t="OES_texture_half_float";if(this.textureFloatExtension=UA(this.gl,e),oR(this.gl,t))this.textureHalfFloatExtension=UA(this.gl,t);else if(X().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),oR(this.gl,s))this.colorBufferHalfFloatExtension=UA(this.gl,s);else if(X().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",oR(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else{if(!oR(this.gl,s))throw new Error("GL context does not support color renderable floats");this.colorBufferHalfFloatExtension=this.gl.getExtension(s)}this.vertexBuffer=jR(this.gl),this.indexBuffer=qR(this.gl),this.framebuffer=function(e){return JA(e,(()=>e.createFramebuffer()),"Unable to create WebGLFramebuffer.")}(this.gl),this.textureConfig=BA(this.gl,this.textureHalfFloatExtension)}get debug(){return X().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;WA(e,(()=>e.finish())),WA(e,(()=>e.bindFramebuffer(e.FRAMEBUFFER,null))),WA(e,(()=>e.deleteFramebuffer(this.framebuffer))),WA(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,null))),WA(e,(()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null))),WA(e,(()=>e.deleteBuffer(this.indexBuffer))),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,s){const[r,a]=LA(t,n);return KR(e,r,a,XR(s),s.textureFormatFloat,e.FLOAT)}(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,s){const[r,a]=LA(t,n);return KR(e,r,a,YR(s),s.textureFormatFloat,s.textureTypeHalfFloat)}(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,s){const[r,a]=LA(t,n);return KR(e,r,a,ZR(s),e.RGBA,e.UNSIGNED_BYTE)}(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),function(e,t,n){WA(e,(()=>e.bindTexture(e.TEXTURE_2D,t))),n.data instanceof Uint8Array?2===X().getNumber("WEBGL_VERSION")?WA(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n.width,n.height,e.RGBA,e.UNSIGNED_BYTE,n.data))):WA(e,(()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data))):2===X().getNumber("WEBGL_VERSION")?WA(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,n))):WA(e,(()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n))),WA(e,(()=>e.bindTexture(e.TEXTURE_2D,null)))}(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,s){this.throwIfDisposed(),function(e,t,n,s,r,a){let i,o,l;WA(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===X().getNumber("WEBGL_VERSION")?WA(e,(()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,s,e.RGBA,o,i))):WA(e,(()=>e.texImage2D(e.TEXTURE_2D,0,l,n,s,0,e.RGBA,o,i))),WA(e,(()=>e.bindTexture(e.TEXTURE_2D,null)))}(this.gl,e,t,n,s,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,s){const[r,a]=PA(t,n);return KR(e,r,a,QR(s),e.RGBA,s.textureTypeHalfFloat)}(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),function(e,t,n,s){const[r,a]=PA(t,n);return KR(e,r,a,JR(s),e.RGBA,e.FLOAT)}(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(YA(this.gl,this.framebuffer),this.outputTexture=null),WA(this.gl,(()=>this.gl.deleteTexture(e)))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,(()=>function(e,t,n,s){const[r,a]=LA(t,n),i=new Uint8Array(t*n*4);return WA(e,(()=>e.readPixels(0,0,r,a,s.downloadTextureFormat,e.UNSIGNED_BYTE,i))),new Float32Array(i.buffer)}(this.gl,t,n,this.textureConfig)))}downloadPackedMatrixFromBuffer(e,t,n,s,r,a){return e_(this.gl,e,0,0,0,r,a,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return function(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}(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);const s=function(e,t,n,s){const r=e.createBuffer();WA(e,(()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,r)));const a=16*t*n;return WA(e,(()=>e.bufferData(e.PIXEL_PACK_BUFFER,a,e.STREAM_READ))),WA(e,(()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0))),WA(e,(()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null))),r}(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(X().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 X().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,X().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,(()=>function(e,t,n){const s=new Float32Array(t*n*4);return WA(e,(()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,s))),s}(this.gl,t,n)))}createProgram(e){this.throwIfDisposed();const t=this.gl;null==this.vertexShader&&(this.vertexShader=HR(t));const n=function(e){return JA(e,(()=>e.createProgram()),"Unable to create WebGLProgram.")}(t);let s;return WA(t,(()=>t.attachShader(n,this.vertexShader))),WA(t,(()=>t.attachShader(n,e))),function(e,t){if(WA(e,(()=>e.linkProgram(t))),!X().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.")}(t,n),s=Object.assign(n,{vao:this.createVertexArray()}),this.bindVertexArray(s.vao),WA(t,(()=>t.bindBuffer(t.ELEMENT_ARRAY_BUFFER,this.indexBuffer))),console.assert(function(e,t,n){return WA(e,(()=>e.bindBuffer(e.ARRAY_BUFFER,n))),qA(e,t,"clipSpacePos",n,3,20,0)&&qA(e,t,"uv",n,2,20,12)}(t,s,this.vertexBuffer),"gpgpu_util.bindVertexProgramAttributeStreams not fully successful."),this.debug&&jA(t,s),this.setProgram(s),s}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),null!=e&&(WA(this.gl,(()=>this.gl.deleteProgram(e))),this.deleteVertexArray(e.vao))}setProgram(e){this.throwIfDisposed(),this.program=e,null!=this.program&&(this.bindVertexArray(this.program.vao),this.debug&&jA(this.gl,this.program)),WA(this.gl,(()=>this.gl.useProgram(e)))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?function(e,t,n){return JA(e,(()=>e.getUniformLocation(t,n)),'uniform "'+n+'" not present in program.')}(this.gl,e,t):function(e,t,n){return e.getUniformLocation(t,n)}(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),WA(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(),KA(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();const[s,r]=PA(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&&jA(this.gl,this.program),ZA(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()}WA(e,(()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0)))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),WA(this.gl,(()=>this.gl.finish()))}getQueryTimerExtension(){return null==this.disjointQueryTimerExtension&&(this.disjointQueryTimerExtension=UA(this.gl,2===X().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===X().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===X().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 b((()=>this.disposed||this.isQueryAvailable(e,X().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")))),this.getQueryTime(e,X().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 X().platform&&(n=X().platform.setTimeoutCustom.bind(X().platform)),b((()=>(this.pollItems(),0===this.itemsToPoll.length)),(()=>0),null,n)}bindTextureToFrameBuffer(e){this.throwIfDisposed(),XA(this.gl,e,this.framebuffer),this.debug&&ZA(this.gl)}unbindTextureToFrameBuffer(){null!=this.outputTexture?(XA(this.gl,this.outputTexture,this.framebuffer),this.debug&&ZA(this.gl)):YA(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;XA(s,e,this.framebuffer),this.debug&&ZA(s),this.outputTexture=e,WA(s,(()=>s.viewport(0,0,t,n))),WA(s,(()=>s.scissor(0,0,t,n)))}setOutputMatrixWriteRegionDriver(e,t,n,s){this.throwIfDisposed(),WA(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:n_,bincountImpl:s_,bincountReduceImpl:r_,castImpl:a_,ceilImpl:i_,concatImpl:o_,equalImpl:l_,expImpl:u_,expm1Impl:c_,floorImpl:h_,gatherNdImpl:p_,gatherV2Impl:d_,greaterImpl:f_,greaterEqualImpl:m_,lessImpl:g_,lessEqualImpl:y_,linSpaceImpl:b_,logImpl:x_,maxImpl:w_,maximumImpl:v_,minimumImpl:k_,multiplyImpl:N_,negImpl:I_,notEqualImpl:S_,prodImpl:T_,raggedGatherImpl:C_,raggedRangeImpl:$_,raggedTensorToTensorImpl:E_,rangeImpl:A_,rsqrtImpl:R_,scatterImpl:__,sigmoidImpl:F_,simpleAbsImpl:D_,sliceImpl:O_,sparseFillEmptyRowsImpl:M_,sparseReshapeImpl:L_,sparseSegmentReductionImpl:z_,sqrtImpl:P_,stridedSliceImpl:B_,stringNGramsImpl:W_,stringSplitImpl:V_,stringToHashBucketFastImpl:U_,subImpl:G_,tileImpl:H_,topKImpl:j_,transposeImpl:q_,uniqueImpl:K_}=_T;function X_(e,t){return["x","y","z","w","u","v"].slice(0,t).map((t=>`${e}.${t}`))}function Y_(e,t){return 1===t?[e]:X_(e,t)}class Z_{constructor(e){if(this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.enableShapeUniforms=LR(this.outputShape.length),0===this.rank)this.userCode="\n void main() {\n setOutput(vec4(getA(), 0., 0., 0.));\n }\n ";else{const e=Y_("rc",this.rank),t=AR(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 J_{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=LR(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?gR(["r","c","d"],"inputShape"):fR(["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":yR(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 Q_{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}acquireTexture(e,t,n){const s=tF(t,n),r=nF(e,s,n);r in this.freeTextures||(this.freeTextures[r]=[]),r in this.usedTextures||(this.usedTextures[r]=[]);const a=eF(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].shift();return this.usedTextures[r].push(e),e}let i;return s===MA.PACKED_2X2_FLOAT32?i=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):s===MA.PACKED_2X2_FLOAT16?i=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):s===MA.UNPACKED_FLOAT32?i=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):s===MA.UNPACKED_FLOAT16?i=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):s===MA.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=tF(n,s),a=nF(t,r,s);a in this.freeTextures||(this.freeTextures[a]=[]);const i=eF(t,r,this.gpgpu.gl,this.gpgpu.textureConfig,s),o=X().get("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.indexOf(e);if(u<0)throw new Error("Cannot release a texture that was never provided by this texture manager");l.splice(u,1),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 eF(e,t,n,s,r){const a=function(e,t){switch(e){case MA.PACKED_2X2_FLOAT32:return JR(t);case MA.PACKED_2X2_FLOAT16:return QR(t);case MA.UNPACKED_FLOAT32:return XR(t);case MA.UNPACKED_FLOAT16:return YR(t);case MA.PACKED_4X1_UNSIGNED_BYTE:return ZR(t);default:throw new Error(`Unknown physical texture type ${e}`)}}(t,s);let i;if(r){const[t,n]=PA(e[0],e[1]);i=t*n}else{const[t,n]=LA(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 tF(e,t){if(e===OA.UPLOAD)return MA.PACKED_2X2_FLOAT32;if(e===OA.RENDER||null==e)return function(e){return X().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?MA.PACKED_2X2_FLOAT32:MA.UNPACKED_FLOAT32:e?MA.PACKED_2X2_FLOAT16:MA.UNPACKED_FLOAT16}(t);if(e===OA.DOWNLOAD||e===OA.PIXELS)return MA.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function nF(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}class sF{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=LR(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 rF="return abs(x);";const aF="return x;";class iF{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=LR(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 oF{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=LR(this.outputShape.length);const t=e.length,n=Y_("rc",t),s=AR(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 lF=Ah,uF={};const cF=X().getNumber("CPU_HANDOFF_SIZE_THRESHOLD");class hF extends n{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,!X().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");let n;if(null!=e){if(e instanceof t_)n=e;else{const t=FA(X().getNumber("WEBGL_VERSION"),e);n=new t_(t)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{const e=FA(X().getNumber("WEBGL_VERSION"));n=new t_(e),this.binaryCache=((s=X().getNumber("WEBGL_VERSION"))in uF||(uF[s]={}),uF[s]),this.gpgpuCreatedLocally=!0}var s;this.gpgpu=n,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new Q_(this.gpgpu),this.numMBBeforeWarning=null==X().global.screen?1024:X().global.screen.height*X().global.screen.width*window.devicePixelRatio*600/1024/1024,this.texData=new t(this,vi())}nextDataId(){return hF.nextDataId++}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=nR(t),u=new UR(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((X().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||X().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:OA.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(X().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:OA.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 iF(i,aF):new sF(i,aF);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=rr()),"complex64"===s){c=Dd(this.readSync(r.real.dataId),this.readSync(r.imag.dataId))}else c=this.getValuesFromTexture(e);return l&&(this.downloadWaitMs+=rr()-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 iF(s,aF):new sF(s,aF);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(X().getBool("DEBUG")&&!X().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&2===X().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&&X().get("WEBGL_BUFFER_SUPPORTED")){l=this.decode(e);const t=this.texData.get(l.dataId);c=this.gpgpu.createBufferFromTexture(t.texture.texture,...zA(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=Dd(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;WA(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)&&vi().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 iF(r,aF):new sF(r,aF);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=vi().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=>or(e)));return Za(e.shape,e.dtype,n)}catch(e){throw new Error("Failed to decode encoded string bytes into utf-8")}return Za(e.shape,e.dtype,t)}checkNumericalProblems(e){if(null!=e)for(let t=0;t<e.length;t++){const n=e[t];if(!VA(n)){if(X().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(X().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){const n=this.decode(e),s=this.texData.get(n.dataId),a=this.gpgpu.downloadMatrixFromPackedTexture(s.texture.texture,...zA(t)).subarray(0,r);return this.disposeIntermediateTensorInfo(n),a}const a=X().getBool("WEBGL_PACK")&&!0===s,i=a?nR(t):t,o=a?new WR(i):new BR(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 X().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=p(this.activeTimers.map((e=>e.query))).filter((e=>null!=e)),a=p(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(X().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){const e=await Promise.all(r);i.kernelMs=l(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 X().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:rr(),endMs:null}}endTimer(e){return X().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=rr(),e)}async getQueryTime(e){if(X().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=cF){return X().getBool("WEBGL_CPU_FORWARD")&&e.every((e=>null==this.texData.get(e.dataId).texture&&d(e.shape)<t))}getGPGPUContext(){return this.gpgpu}where(e){us("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");const t=e.dataSync();return lF(e.shape,t)}packedUnaryOp(e,t,n){const s=new iF(e.shape,t),r=this.compileAndRun(s,[e],n);return vi().makeTensorFromTensorInfo(r)}abs(e){if(this.shouldExecuteOnCPU([e])&&"complex64"!==e.dtype){const t=D_(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,t)}if(X().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,rF,e.dtype);const t=new sF(e.shape,rF),n=this.compileAndRun(t,[e]);return vi().makeTensorFromTensorInfo(n)}makeTensorInfo(e,t,n){let s;if("string"===t&&null!=n&&n.length>0&&A(n[0])){const r=n.map((e=>ir(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 vi().makeTensorFromTensorInfo(this.makeTensorInfo(e,t,n),this)}unpackTensor(e){const t=new oF(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){const t=new Z_(e.shape);return this.runWebGLProgram(t,[e],e.dtype,null,!0)}packedReshape(e,t){const n=[eR(e.shape),...tR(e.shape)],s={dtype:e.dtype,shape:n,dataId:e.dataId},r=[eR(t),...tR(t)],a=new J_(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){u(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=nR(r);let o;o=s?new PR(i):new zR(i);const l=[null!=t?t:zA(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===DA.DENSE){const t=null!=a?a:zA(e.outputShape);o.texShape=t.map((e=>2*e))}if(null!=e.outTexUsage&&(o.usage=e.outTexUsage),0===d(i.shape))return o.values=k(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)<=X().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&&!rR(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}=RR(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,m=2===o.length&&f(t.shape,a),g=1===d(t.shape),y=Oi(t.shape,n.shape),b=!e.packedInputs&&p===n.shape.length&&f(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}_${m}_${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+`${X().getNumber("WEBGL_VERSION")}`,a}(e,u,c),p=this.getAndSaveBinary(h,(()=>DR(this.gpgpu,e,u,c))),m=null!=this.activeTimers;let g;m&&(g=this.startTimer()),X().get("ENGINE_COMPILE_ONLY")||function(e,t,n,s,r){t.program.enableShapeUniforms||(MR(t.inShapeInfos,n),MR([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),1===X().getNumber("WEBGL_VERSION")&&null!==t.infLoc&&e.gl.uniform1f(t.infLoc,1/0),null!==t.nanLoc&&e.gl.uniform1f(t.nanLoc,NaN),n.forEach(((n,s)=>{const r=t.program.variableNames[s],a=t.uniformLocations[r],i=t.uniformLocations[`offset${r}`],o=t.inShapesLocations[`${r}Shape`],l=t.inTexShapesLocations[`${r}TexShape`];if(o){const{uniformShape:s}=RR(t.program.packedInputs,n.shape,n.texData.texShape);switch(s.length){case 1:e.gl.uniform1iv(o,new Int32Array(s));break;case 2:e.gl.uniform2iv(o,new Int32Array(s));break;case 3:e.gl.uniform3iv(o,new Int32Array(s));break;case 4:e.gl.uniform4iv(o,new Int32Array(s))}}if(l&&e.gl.uniform2i(l,n.texData.texShape[0],n.texData.texShape[1]),null!=a)if(n.isUniform)if(d(n.shape)<2)e.gl.uniform1f(a,n.uniformValues[0]);else{let t=n.uniformValues;t instanceof Float32Array||(t=new Float32Array(t)),e.gl.uniform1fv(a,t)}else null!=n.texData.slice&&null!=i&&e.gl.uniform1i(i,n.texData.slice.flatOffset),e.setInputMatrixTexture(n.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))}}t.outTexShapeLocation&&e.gl.uniform2i(t.outTexShapeLocation,s.texData.texShape[0],s.texData.texShape[1]),t.program.customUniforms&&r&&t.program.customUniforms.forEach(((n,s)=>{const a=t.customUniformLocations[s],i=r[s];if("float"===n.type)e.gl.uniform1fv(a,i);else if("vec2"===n.type)e.gl.uniform2fv(a,i);else if("vec3"===n.type)e.gl.uniform3fv(a,i);else if("vec4"===n.type)e.gl.uniform4fv(a,i);else if("int"===n.type)e.gl.uniform1iv(a,i);else if("ivec2"===n.type)e.gl.uniform2iv(a,i);else if("ivec3"===n.type)e.gl.uniform3iv(a,i);else{if("ivec4"!==n.type)throw Error(`uniform type ${n.type} is not supported yet.`);e.gl.uniform4iv(a,i)}})),e.executeProgram()}(this.gpgpu,p,u,c,s),l.forEach((e=>this.disposeIntermediateTensorInfo(e))),m&&(g=this.endTimer(g),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(g)}));const y=X().get("WEBGL_FLUSH_THRESHOLD");if(y>0){const e=rr();e-this.lastGlFlushTime>y&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=e)}if(!X().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(!X().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=Ni((()=>{if(!X().get("WEBGL_RENDER_FLOAT32_ENABLED")){const e=X().getBool("DEBUG");X().set("DEBUG",!1);const t=this.abs(au(1e-8)).dataSync()[0];if(X().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:o,isPacked:l}=t;if(null!=a)return;const u=null!=this.activeTimers;let c;u&&(c=rr());let h=t.texShape;if(null==h&&(h=function(e,t=!1){let n=X().getNumber("WEBGL_MAX_TEXTURE_SIZE"),s=X().getNumber("WEBGL_MAX_SIZE_FOR_NARROW_TEXTURE");if(s===1/0&&X().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?i(e[n]):e[n]))).length&&(e=[2,e[0]])),2!==e.length){const t=v(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 o=null!=a&&Math.max(...a)>s&&Math.min(...a)<=(t?2:1)&&Math.min(...a)>0;if(null==a||o)if(t){const t=eR(e);let n=2,s=2;e.length&&([n,s]=tR(e)),r=t*(n/2)*(s/2),a=g(r).map((e=>2*e))}else a=g(r);return a}(n,l),t.texShape=h),null!=r){const e=nR(n);let a,i=h[1],o=h[0];const p=r instanceof Uint8Array||r instanceof Uint8ClampedArray;!l&&p||([i,o]=PA(h[0],h[1])),a=l?new GR(e,p):new UR(e,p);const d=p?[o,i]:h,f=this.makeTensorInfo(d,s),m=this.texData.get(f.dataId);m.usage=p?OA.PIXELS:OA.UPLOAD,m.texShape=d,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(f.dataId),i,o,r);const g=[[o,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,X().get("ENGINE_COMPILE_ONLY")?this.disposeData(b.dataId):(t.texture=x.texture,t.values=null,this.texData.delete(b.dataId)),this.disposeIntermediateTensorInfo(f),u&&(this.uploadWaitMs+=rr()-c)}else{const e=this.acquireTexture(h,o,s,l);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 hd(),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 HA(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.entries(this.binaryCache)){const{uniformLocations:t,customUniformLocations:n,infLoc:s,nanLoc:r,inShapesLocations:a,inTexShapesLocations:i,outShapeLocation:o,outShapeStridesLocation:l,outTexShapeLocation:u}=OR(this.gpgpu,e.program,e.webGLProgram);e.uniformLocations=t,e.customUniformLocations=n,e.infLoc=s,e.nanLoc=r,e.inShapesLocations=a,e.inTexShapesLocations=i,e.outShapeLocation=o,e.outShapeStridesLocation=l,e.outTexShapeLocation=u}}createTensorFromTexture(e,t,n){const{texture:s,height:r,width:a,channels:i}=e,o=vi().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 vi().makeTensorFromDataId(l,t,n,o)}}hF.nextDataId=0;jr()&&Ci("webgl",(()=>new hF),2);class pF{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=Li(t,n),this.enableShapeUniforms=LR(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 `}}class dF{constructor(e,t,n,s=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=Li(t,n);const r=this.outputShape.length;this.enableShapeUniforms=LR(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 ${AR(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=Y_("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 fF(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 mF={kernelName:dt,backendName:"webgl",kernelFunc:fF};function gF(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=fF({inputs:{x:s},backend:n}),l=fF({inputs:{x:r},backend:n});return i.complexTensorInfos={real:o,imag:l},a}const yF={kernelName:Se,backendName:"webgl",kernelFunc:gF},bF="return (a < 0.) ? b * a : a;",xF="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n";const wF={kernelName:xt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{alpha:a}=s,i=n.makeTensorInfo([],"float32",nr(a,"float32")),o=X().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new dF(xF,r.shape,i.shape):new pF(bF,r.shape,i.shape),l=n.runWebGLProgram(o,[r,i],"float32");return n.disposeIntermediateTensorInfo(i),l}},vF="return (a < 0.) ? b * a : a;",kF="\n vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));\n return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);\n";const NF={kernelName:tn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:s,alpha:r}=t,a=X().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new dF(kF,s.shape,r.shape):new pF(vF,s.shape,r.shape);return n.runWebGLProgram(a,[s,r],"float32")}};function IF({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=X().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&null!=t?new iF(i.shape,t):new sF(i.shape,e),o.runWebGLProgram(u,[i],l)}}function SF({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 pF(e,l.shape,u.shape);return c.runWebGLProgram(i,[r,a],Ar(n.dtype,s.dtype))})),a=gF({inputs:{real:s,imag:r},backend:c});return c.disposeIntermediateTensorInfo(s),c.disposeIntermediateTensorInfo(r),a}const h=a||Ar(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?ff(e):e,s="string"===l.dtype?ff(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=X().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&null!=t?new dF(t,l.shape,u.shape,n):new pF(e,l.shape,u.shape),c.runWebGLProgram(p,[l,u],h)}}function TF(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?kF:vF;if("leakyrelu"===e)return t?xF:bF;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 CF{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=LR(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=`int(min(float(rc.x), ${e[0]-1}.))`:t[0]<e[0]&&(x=`int(min(float(rc.x), ${t[0]-1}.))`),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 for (int i = 0; i < ${c}; i++) {\n int batchA = ${b};\n int batchB = ${x};\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 $F="return areal * breal - aimag * bimag;",EF="return areal * bimag + aimag * breal;";class AF{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=Li(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 RF="return a * b;";function _F(e){const{inputs:t,backend:n}=e,{a:s,b:r}=t,a=Ar(s.dtype,r.dtype);if("complex64"===s.dtype){const e=n.texData.get(s.dataId),t=n.texData.get(r.dataId),a=new AF($F,s.shape,r.shape),i=new AF(EF,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=gF({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]=N_(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=X().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new dF(RF,s.shape,r.shape):new pF(RF,s.shape,r.shape),n.runWebGLProgram(i,[s,r],a)}const FF={kernelName:Gt,backendName:"webgl",kernelFunc:_F};function DF(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{shape:a}=s,i=n,o=d(r.shape),l=x(a,o),c=d(l);u(o===c,(()=>`The new shape (${l}) has ${c} 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||rR(r.shape,l)||null!==h.texture&&rR(h.shape,l)?(i.incRef(r.dataId),{dataId:r.dataId,shape:l,dtype:r.dtype}):function(e,t,n){const s=[eR(e.shape),...tR(e.shape)],r={dtype:e.dtype,shape:s,dataId:e.dataId},a=[eR(t),...tR(t)],i=new J_(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 OF={kernelName:hn,backendName:"webgl",kernelFunc:DF};class MF{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 * ${m(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 LF{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 zF(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=xd(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 MF({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:u},o):new MF({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:u}):new LF({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 PF{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=AR(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 BF{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=AR(this.rank),r=X_("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 WF(e,t,n){const s=X().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new BF(e.shape,t):new PF(e.shape,t);return n.runWebGLProgram(s,[e],e.dtype)}function VF(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=w(r,e.shape);let o=i;const l=Ql(o,a),u=null!=l;let c=e;u&&(c=WF(e,l,s),o=tu(o.length,a)),Jl("sum",o,a);const[h,p]=Yl(c.shape,o);let f=h;n&&(f=Zl(h,i));const m=d(p),g=DF({inputs:{x:c},attrs:{shape:[d(e.shape)/m,m]},backend:s}),y=zF(g,Rr(e.dtype),"sum",s),b=DF({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 UF={kernelName:Rn,backendName:"webgl",kernelFunc:VF};function GF(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=q_(e,r.shape,r.dtype,a,l);u=i.makeTensorInfo(l,r.dtype);i.texData.get(u.dataId).values=t}else u=WF(r,a,i);return u}const HF={kernelName:Jn,backendName:"webgl",kernelFunc:GF};function jF({a:e,b:t,transposeA:n,transposeB:s,backend:r,bias:a=null,preluActivationWeights:i=null,leakyreluAlpha:o=0,activation:l=null}){const c=e.shape.length,h=t.shape.length,p=n?e.shape[c-2]:e.shape[c-1],f=s?t.shape[h-1]:t.shape[h-2],m=n?e.shape[c-1]:e.shape[c-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=Li(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([m,g]);u(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=DF({inputs:{x:e},backend:r,attrs:{shape:k}}),S=DF({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?TF(l,!0):null;let F;if((1===m||1===g)&&$>1e3&&!1===(E||A||R||null!=_)){let e=I,t=S;n&&(e=GF({inputs:{x:I},backend:r,attrs:{perm:[0,2,1]}}),T.push(e)),s&&(t=GF({inputs:{x:S},backend:r,attrs:{perm:[0,2,1]}}),T.push(t));const a=1===g;let i=e;1!==g&&(i=DF({inputs:{x:e},backend:r,attrs:{shape:[C,$,1]}}),T.push(i));const o=1===g?2:1;let l=t;a&&(l=DF({inputs:{x:t},backend:r,attrs:{shape:[C,1,$]}}),T.push(l));const u=_F({inputs:{a:i,b:l},backend:r});F=VF({inputs:{x:u},backend:r,attrs:{axis:o,keepDims:!0}}),T.push(u)}else{const l=Ar(e.dtype,t.dtype),u=new CF(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",nr(o,"float32"));c.push(e),T.push(e)}F=r.runWebGLProgram(u,c,l)}const D=DF({inputs:{x:F},backend:r,attrs:{shape:v}});T.push(F);for(const e of T)r.disposeIntermediateTensorInfo(e);return D}const qF={kernelName:is,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 jF({a:r,b:a,transposeA:l,transposeB:u,backend:n,bias:i,preluActivationWeights:o,leakyreluAlpha:h,activation:c})}},KF="return abs(x);";const XF={kernelName:Q,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=D_(e.values);return n.makeTensorInfo(s.shape,s.dtype,t)}let r;return r=X().getBool("WEBGL_PACK_UNARY_OPERATIONS")?new iF(s.shape,KF):new sF(s.shape,KF),n.runWebGLProgram(r,[s],s.dtype)}},YF=IF({opSnippet:"if (isnan(x)) return x;\n if (abs(x) > 1.) {\n return NAN;\n }\n return acos(x);\n"}),ZF={kernelName:ee,backendName:"webgl",kernelFunc:YF},JF=IF({opSnippet:"if (isnan(x)) return x;\n if (x < 1.0) return NAN;\nreturn log(x + sqrt(x * x - 1.0));"}),QF={kernelName:te,backendName:"webgl",kernelFunc:JF},eD="return a + b;",tD=SF({opSnippet:eD,packedOpSnippet:eD,supportsComplex:!0,cpuKernelImpl:n_}),nD={kernelName:ne,backendName:"webgl",kernelFunc:tD};class sD{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 rD{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 aD={kernelName:se,backendName:"webgl",kernelFunc:function e(t){const{inputs:n,backend:s}=t,r=n;if(1===r.length)return fF({inputs:{x:r[0]},backend:s});if(r.length>X().get("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)=>Ar(e,t))),i=r.map((e=>e.shape)),o=X().getBool("WEBGL_PACK")?new rD(r[0].shape,i):new sD(r[0].shape,i);return s.runWebGLProgram(o,r,a)}};const iD={kernelName:re,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=w(a,r.shape);let u=l;const c=Ql(u,o);let h=r;null!=c&&(h=GF({inputs:{x:r},backend:n,attrs:{perm:c}}),u=tu(u.length,o)),Jl("all",u,o);const[p,f]=Yl(h.shape,u),m=DF({inputs:{x:h},backend:n,attrs:{shape:[-1,d(f)]}}),g=zF(m,m.dtype,"all",n);let y;if(i){y=DF({inputs:{x:g},backend:n,attrs:{shape:Zl(p,l)}})}else y=DF({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),null!=c&&n.disposeIntermediateTensorInfo(h),y}};const oD={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=w(a,r.shape);let u=l;const c=Ql(u,o);let h=r;null!=c&&(h=GF({inputs:{x:r},backend:n,attrs:{perm:c}}),u=tu(u.length,o)),Jl("any",u,o);const[p,f]=Yl(h.shape,u),m=DF({inputs:{x:h},backend:n,attrs:{shape:[-1,d(f)]}}),g=zF(m,m.dtype,"any",n);let y;if(i){y=DF({inputs:{x:g},backend:n,attrs:{shape:Zl(p,l)}})}else y=DF({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),null!=c&&n.disposeIntermediateTensorInfo(h),y}};class lD{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 uD{constructor(e,t,n,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,u(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=AR(o),c=Y_("coords",o);let h,p;if(1===a){p=o+1;const e=AR(p);h=`\n ${e} sourceLocR = ${e}(${c.join()}, 0);\n ++${c[o-1]};\n ${e} sourceLocG = ${e}(${c.join()}, 0);\n ++${c[o-2]};\n ${e} sourceLocA = ${e}(${c.join()}, 0);\n --${c[o-1]};\n ${e} sourceLocB = ${e}(${c.join()}, 0);\n --${c[o-2]};`}else p=o,h=`\n ${l} sourceLocR = coords;\n ++${c[o-1]};\n ${l} sourceLocG = coords;\n ++${c[o-2]};\n ${l} sourceLocA = coords;\n --${c[o-1]};\n ${l} sourceLocB = coords;\n --${c[o-2]};`;const d=["x","y","z","w","u","v"].slice(0,p),f="."+d[p-1],m=d.map((e=>"int "+e)),g=Y_("sourceLocR",p-1).concat("inIdx.r"),y=Y_("sourceLocG",p-1).concat("inIdx.g"),b=Y_("sourceLocB",p-1).concat("inIdx.b"),x=Y_("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 = ${c[o-1]} < ${i[o-1]-1};\n bool hasNextRow = ${c[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 cD(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=xd(a),o={windowSize:i,inSize:a,batchSize:r,outSize:Math.ceil(a/i)},l=new lD(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=cD(e,t,n,c);return e.disposeIntermediateTensorInfo(c),h}function hD(e,t,n,s=null){const r=null!=s?s.shape:t.shape,a=xd(r[r.length-1]),i=new uD(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=hD(e,t,n,l);return e.disposeIntermediateTensorInfo(l),s}return l}function pD(e,t,n,s){const r=[n];if(Jl("arg"+s.charAt(0).toUpperCase()+s.slice(1),r,t.shape.length),!X().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]=Yl(i.shape,r),u=d(l),c=DF({inputs:{x:i},backend:e,attrs:{shape:[-1,u]}});n.push(c);const h=cD(e,c,s);n.push(h);const p=DF({inputs:{x:h},backend:e,attrs:{shape:o}});return n.forEach((t=>e.disposeIntermediateTensorInfo(t))),p}return hD(e,t,s)}const dD={kernelName:ie,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s;let i=w(a,r.shape);const o=Ql(i,r.shape.length);let l=r;const u=[];null!=o&&(l=GF({inputs:{x:r},backend:n,attrs:{perm:o}}),u.push(l),i=tu(i.length,l.shape.length)),Jl("argMax",[i[0]],l.shape.length);const c=pD(n,l,i[0],"max");return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),c}};const fD={kernelName:oe,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a}=s;let i=w(a,r.shape);const o=Ql(i,r.shape.length);let l=r;const u=[];null!=o&&(l=GF({inputs:{x:r},backend:n,attrs:{perm:o}}),u.push(l),i=tu(i.length,l.shape.length)),Jl("argMin",[i[0]],l.shape.length);const c=pD(n,l,i[0],"min");return u.forEach((e=>n.disposeIntermediateTensorInfo(e))),c}},mD=IF({opSnippet:"if (isnan(x)) return x;\n if (abs(x) > 1.) {\n return NAN;\n }\n return asin(x);\n"}),gD={kernelName:le,backendName:"webgl",kernelFunc:mD},yD=IF({opSnippet:"if (isnan(x)) return x;return log(x + sqrt(x * x + 1.0));"}),bD={kernelName:ue,backendName:"webgl",kernelFunc:yD},xD=IF({opSnippet:"if (isnan(x)) return x;\n return atan(x);\n"}),wD={kernelName:ce,backendName:"webgl",kernelFunc:xD},vD=SF({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"}),kD={kernelName:pe,backendName:"webgl",kernelFunc:vD},ND=IF({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;"}),ID={kernelName:he,backendName:"webgl",kernelFunc:ND};class SD{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 / count");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 TD{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 / count");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 setOutput(${w});\n }\n }\n `}}const CD={kernelName:de,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t;hR(r,"avgPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:l}=s;u(Jo(i,1),(()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const c=Vo(r.shape,a,i,1,o,l);if(1===c.filterWidth&&1===c.filterHeight&&f(c.inShape,c.outShape))return fF({inputs:{x:r},backend:n});const h=new SD(c,"avg",!1);return n.runWebGLProgram(h,[r],"float32")}};const $D={kernelName:me,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=Uo(r.shape,a,i,[1,1,1],o,l,u),h=new TD(c,"avg",!1);return n.runWebGLProgram(h,[r],"float32")}};class ED{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 AD{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 RD={kernelName:ge,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=Uo(i.shape,o,l,[1,1,1],u,c),p=new AD(h);return n.runWebGLProgram(p,[r],i.dtype)}};const _D={kernelName:fe,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a}=t,i=a;hR([r,a],"avgPoolGrad");const{filterSize:o,strides:l,pad:u}=s,c=Vo(i.shape,o,l,1,u),h=new ED(c);return n.runWebGLProgram(h,[r],i.dtype)}};const FD={kernelName:ye,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{a:r,b:a}=t,{transposeA:i,transposeB:o}=s;return jF({a:r,b:a,transposeA:i,transposeB:o,backend:n})}};class DD{constructor(e,t,n,s,r,a){this.outputShape=[],this.variableNames=["x","mean","variance"],Li(e,t),Li(e,n);let i="0.0";null!=s&&(Li(e,s),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="1.0";null!=r&&(Li(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 OD{constructor(e,t,n,s,r,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],Li(e,t),Li(e,n);let i="vec4(0.0)";null!=s&&(Li(e,s),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="vec4(1.0)";null!=r&&(Li(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 MD={kernelName:lt,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s,mean:r,variance:a,offset:i,scale:o}=e;u(r.shape.length===a.shape.length,(()=>"Batch normalization gradient requires mean and variance to have equal ranks.")),u(null==i||r.shape.length===i.shape.length,(()=>"Batch normalization gradient requires mean and offset to have equal ranks.")),u(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 c=[s,r,a];let h=null;null!=i&&(h=i.shape,c.push(i));let p=null;null!=o&&(p=o.shape,c.push(o));const d=X().getBool("WEBGL_PACK_NORMALIZATION")?new OD(s.shape,r.shape,a.shape,h,p,l):new DD(s.shape,r.shape,a.shape,h,p,l);return t.runWebGLProgram(d,c,c[0].dtype)}};class LD{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;const t=AR(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];const n=function(e){if(1===e)return"sourceLoc";if(e<=6)return zD.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.${zD[t]} = start[${t}] + coords.${zD[t]};`)).join("\n")}\n `,this.userCode=`\n void main() {\n ${s}\n setOutput(getSource(${n}));\n }\n `}}const zD=["x","y","z","w","u","v"];class PD{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=AR(this.rank),n=Y_("coords",this.rank),s=Y_("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 BD(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{begin:a,size:i}=s,[o,l]=uo(r,a,i);if(Zi(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=O_(e.values,o,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,t)}const{isPacked:u}=n.texData.get(r.dataId),c=oo(r.shape,o,l);if(u||!c){const e=X().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new PD(l):new LD(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=lo(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 WD={kernelName:In,backendName:"webgl",kernelFunc:BD},VD={kernelName:be,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,crops:i}=s;u(r.shape.length<=4,(()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet"));const o=a.reduce(((e,t)=>e*t)),l=vd(r.shape,a,o),c=kd(l.length,a.length),h=Nd(r.shape,a,o),p=Id(i,a.length),d=Sd(h,i,a.length),f=[],m=DF({inputs:{x:r},backend:n,attrs:{shape:l}}),g=GF({inputs:{x:m},backend:n,attrs:{perm:c}}),y=DF({inputs:{x:g},backend:n,attrs:{shape:h}}),b=BD({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 UD={kernelName:xe,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=s_(o,l,a.dtype,a.shape,i);return n.makeTensorInfo([i],a.dtype,u)}};const GD={kernelName:ve,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=Li(Array.from(a),Array.from(i));return n.makeTensorInfo([o.length],"int32",Int32Array.from(o))}},HD=SF({opSnippet:"return float(a != b);",cpuKernelImpl:S_,dtype:"bool"}),jD={kernelName:jt,backendName:"webgl",kernelFunc:HD};function qD(e){const{inputs:t,backend:n}=e,{input:s}=t;return fF({inputs:{x:n.texData.get(s.dataId).complexTensorInfos.real},backend:n})}const KD={kernelName:ln,backendName:"webgl",kernelFunc:qD};const XD={kernelName:ke,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 fF({inputs:{x:a},backend:s});const t=Zu(a.shape),n=e({inputs:{x:a},backend:s,attrs:{dtype:"float32"}}),r=gF({inputs:{real:n,imag:t},backend:s});return t.dispose(),s.disposeIntermediateTensorInfo(n),r}if("complex64"===a.dtype){const t=qD({inputs:{input:a},backend:s}),n=e({inputs:{x:t},backend:s,attrs:{dtype:i}});return s.disposeIntermediateTensorInfo(t),n}if(!T(a.dtype,i)){const e=fF({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]=a_(e,a.shape,a.dtype,i);return s.makeTensorInfo(t,n,r)}if("int32"===i)return function(e,t){const n=new sF(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",k("bool",1)),t=HD({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}`)}},YD="return ceil(x);",ZD=IF({opSnippet:YD,packedOpSnippet:YD,cpuKernelImpl:i_}),JD={kernelName:Ne,backendName:"webgl",kernelFunc:ZD};class QD{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 eO{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 tO={kernelName:Ie,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{clipValueMin:a,clipValueMax:i}=s;let o;o=X().getBool("WEBGL_PACK_CLIP")?new eO(r.shape):new QD(r.shape);const l=[[a],[i]];return n.runWebGLProgram(o,[r],r.dtype,l)}};class nO{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 sO(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}const rO={kernelName:Te,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:s}=t,r=n.texData.get(s.dataId),a=new nO(s.shape),i=[sO(s,r.complexTensorInfos.real),sO(s,r.complexTensorInfos.imag)];return n.runWebGLProgram(a,i,i[0].dtype)}};class aO{constructor(e){this.outputShape=[],this.outputShape=dd(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 iO{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=dd(e,t);const n=this.outputShape,s=n.length,r=AR(s),a=Y_("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}(${oO(i,l,t)}),\n vec2(${oO(u,l,t)}));\n }`}const p=o.length,d=o[o.length-1];h+=`\n return getChannel(\n getT${p}(${oO(i,l,d)}),\n vec2(${oO(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 oO(e,t,n){const s=e.indexOf(t);return e.map(((e,t)=>t===s?`${e} - ${n}`:e)).join()}function lO(e){const{inputs:t,backend:n}=e,{input:s}=t;return fF({inputs:{x:n.texData.get(s.dataId).complexTensorInfos.imag},backend:n})}const uO={kernelName:mt,backendName:"webgl",kernelFunc:lO};function cO(e,t,n){const s=e[0].dtype;if("complex64"===s){const s=e.map((e=>qD({inputs:{input:e},backend:n}))),r=e.map((e=>lO({inputs:{input:e},backend:n}))),a=cO(s,t,n),i=cO(r,t,n),o=gF({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 DF({inputs:{x:e},backend:n,attrs:{shape:[-1,s]}})})),a=r.map((e=>({vals:n.readSync(e.dataId),shape:e.shape}))),i=dd(r.map((e=>e.shape)),1),o=1===r[0].shape[0],l=o_(a,i,s,o),u=dd(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=X().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&a[0].shape.length>1;if(1===a.length){const t=i?new sF(e[0].shape,aF):new iF(e[0].shape,aF);return n.runWebGLProgram(t,e,s)}const o=X().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(cO(r,t,n))}const s=cO(e,t,n);for(const t of e)n.disposeIntermediateTensorInfo(t);return s}if(i){const e=new iO(a.map((e=>e.shape)),t);return n.runWebGLProgram(e,a,s)}const{tensors2D:l,outShape:u}=function(e,t,n){const s=dd(e.map((e=>e.shape)),t);return{tensors2D:e.map((e=>DF({inputs:{x:e},attrs:{shape:[-1,d(e.shape.slice(t))]},backend:n}))),outShape:s}}(a,t,n),c=new aO(l.map((e=>e.shape))),h=n.runWebGLProgram(c,l,s);l.forEach((e=>n.disposeIntermediateTensorInfo(e)));const p=DF({inputs:{x:h},attrs:{shape:u},backend:n});return n.disposeIntermediateTensorInfo(h),p}function hO(e){const{inputs:t,backend:n,attrs:s}=e,{axis:r}=s,a=w(r,t[0].shape)[0];pd(t.map((e=>e.shape)),a);const i=dd(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?fF({inputs:{x:o[0]},backend:n}):cO(o,a,n)}const pO={kernelName:Ce,backendName:"webgl",kernelFunc:hO};class dO{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 fO{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 mO{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=LR(this.outputShape.length);const a=e.padInfo.left,o=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===o){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?i(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 gO{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=LR(this.outputShape.length);const{dataFormat:n}=t,s=dR(),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 yO(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 bO({x:e,filter:t,convInfo:n,backend:s,bias:r=null,preluActivationWeights:a=null,leakyreluAlpha:i=0,activation:o=null}){const l=e.shape,c=s.texData.get(e.dataId),h=n.inChannels,p=l[0]*l[1]*l[2],d=n.outChannels,m="channelsLast"===n.dataFormat;let g;const y=[];if(null!=a){const e=yO(a.shape,m);null!=e&&(a=DF({inputs:{x:a},backend:s,attrs:{shape:e}}),y.push(a))}if(null!=r){const e=yO(r.shape,m);null!=e&&(r=DF({inputs:{x:r},backend:s,attrs:{shape:e}}),y.push(r))}if(!((1===p||1===d)&&h>1e3)&&c.isPacked&&m&&null!=c.texture&&l[2]%2!=0&&f(c.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=c.shape;c.shape=c.shape.slice(),c.shape[c.shape.length-2]++,u(rR(c.shape,p.shape),(()=>`packed reshape ${c.shape} to ${p.shape} isn't free`));const f=DF({inputs:{x:t},backend:s,attrs:{shape:[1,n.inChannels,n.outChannels]}});y.push(f);const m=jF({a:p,b:f,backend:s,transposeA:false,transposeB:false,bias:r,activation:o,preluActivationWeights:a,leakyreluAlpha:i}),b=s.texData.get(m.dataId);u(b.isPacked,(()=>"batchMatMul result is expected to be packed")),c.shape=d,b.shape=n.outShape,g=fF({inputs:{x:m},backend:s}),g.shape=n.outShape,y.push(m)}else{const l=n.outHeight*n.outWidth,u=DF({inputs:{x:e},backend:s,attrs:{shape:m?[n.batchSize,l,n.inChannels]:[n.batchSize,n.inChannels,l]}}),c=DF({inputs:{x:t},backend:s,attrs:{shape:[1,n.inChannels,n.outChannels]}}),h=jF({a:m?u:c,b:m?c:u,transposeA:!m,transposeB:false,backend:s,bias:r,activation:o,preluActivationWeights:a,leakyreluAlpha:i});g=DF({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 xO({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=yO(a.shape,m);null!=e&&(a=DF({inputs:{x:a},backend:s,attrs:{shape:e}}),x.push(a))}if(null!=r){const e=yO(r.shape,m);null!=e&&(r=DF({inputs:{x:r},backend:s,attrs:{shape:e}}),x.push(r))}const w=DF({inputs:{x:t},backend:s,attrs:{shape:[1,g,d(t.shape)/g]}});x.push(w);const v=new gO(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=DF({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?TF(o,!0):null,E=new CF(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",nr(i,"float32"));A.push(e),x.push(e)}const R=s.runWebGLProgram(E,A,"float32"),_=DF({inputs:{x:R},backend:s,attrs:{shape:n.outShape}});x.push(R);for(const e of x)s.disposeIntermediateTensorInfo(e);return _}const wO={kernelName:$e,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=Qo(l),p=Go(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&&X().getBool("WEBGL_EXP_CONV")){const e=new mO(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(X().getBool("WEBGL_CONV_IM2COL"))d=xO({x:r,filter:a,convInfo:p,backend:n});else{const e=new dO(p);d=n.runWebGLProgram(e,[r,a],"float32")}else d=bO({x:r,filter:a,convInfo:p,backend:n});const f=DF({inputs:{x:d},backend:n,attrs:{shape:p.outShape}});return n.disposeIntermediateTensorInfo(d),f}};class vO{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 if (${a}) {\n float dyValue = getDy(b, yR, yC, d2);\n float xValue = getX(b, xR, xC, d1);\n dotProd += (xValue * dyValue);\n } else {\n float dyValue = getDy(b, d2, yR, yC);\n float xValue = getX(b, d1, xR, xC);\n dotProd += (xValue * dyValue);\n }\n\n }\n }\n }\n setOutput(dotProd);\n }\n `}}class kO{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 NO{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 IO{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 SO={kernelName:Ee,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=Qo(l),p=Go(r.shape,c,i,1,o,u,!1,h),d=new vO(p);return n.runWebGLProgram(d,[r,a],"float32")}};const TO={kernelName:Ae,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=Qo(u),p=Go(i,a.shape,o,1,l,c,!1,h),d=new kO(p);return n.runWebGLProgram(d,[r,a],"float32")}};const CO={kernelName:Re,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=Ho(r.shape,a.shape,i,l,o),c=new fO(u);return n.runWebGLProgram(c,[r,a],"float32")}};const $O={kernelName:_e,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=Ho(r.shape,l,i,1,o),c=new NO(u);return n.runWebGLProgram(c,[r,a],"float32")}};const EO={kernelName:Fe,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=Ho(l,a.shape,o,1,i),c=new IO(u);return n.runWebGLProgram(c,[r,a],"float32")}},AO=IF({opSnippet:"if (isnan(x)) return x;\n return cos(x);\n"}),RO={kernelName:De,backendName:"webgl",kernelFunc:AO},_O=IF({opSnippet:"\n float e2x = exp(-x);\n return (e2x + 1.0 / e2x) / 2.0;\n"}),FO={kernelName:Oe,backendName:"webgl",kernelFunc:_O};class DO{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 OO={kernelName:ze,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 DO(r.shape,a.shape,o,l,u);return n.runWebGLProgram(c,[r,a,i],"float32")}};var MO;!function(e){e.Prod="*",e.Sum="+"}(MO||(MO={}));class LO{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===MO.Prod?"1.0":"0.0",i=n?a:`getX(${zO(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 ${AR(r)} coords = getOutputCoords();\n int end = ${PO(r,"coords",this.op)};\n float val = ${i};\n int pow2 = int(pow(2.0, index));\n if (${l}) {\n int idx = ${u};\n ${PO(r,"coords",this.op)} = idx;\n val ${this.op}= getX(${zO(r,"coords",this.op)});\n }\n setOutput(val);\n }\n `}}function zO(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 PO(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 BO(e,t,n,s,r,a){const i=t.shape.length,o=Ql([s],i);let l=t;null!=o&&(l=GF({inputs:{x:t},backend:n,attrs:{perm:o}}));const u=tu(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=fF({inputs:{x:l},backend:n});for(let t=0;t<=Math.ceil(Math.log2(c))-1;t++){const s=new LO(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 LO(e,l.shape,r,a),s=h;h=n.runWebGLProgram(t,[h],h.dtype),n.disposeIntermediateTensorInfo(s)}if(null!=o){const e=GF({inputs:{x:h},backend:n,attrs:{perm:eu(o)}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(l),e}return h}const WO={kernelName:Me,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,exclusive:i,reverse:o}=s;return BO(MO.Prod,r,n,a,i,o)}};const VO={kernelName:Le,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{axis:a,exclusive:i,reverse:o}=s;return BO(MO.Sum,r,n,a,i,o)}};const UO={kernelName:Pe,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=s_(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=r_(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 GO{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 HO={kernelName:Be,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 GO("NHWC"===i?[o,l,u,c]:[o,c,l,u],a,i);return n.runWebGLProgram(h,[r],r.dtype)}};class jO{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=LR(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 qO{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=LR(this.outputShape.length);const a=e.outChannels/e.inChannels,o=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&&(o%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=o%2==0?i(u):u;u%2==0&&o%2==1||u%2!=0&&o%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&&(o%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 KO={kernelName:We,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:c}=s;let h=l;null==h&&(h=[1,1]),u(Jo(i,h),(()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${h}'`));const p=Go(r.shape,a.shape,i,h,o,c,!0);let d;d=X().getBool("WEBGL_PACK_DEPTHWISECONV")&&p.strideWidth<=2&&p.outChannels/p.inChannels==1?new qO(p):new jO(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 XO{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 YO{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 ZO={kernelName:Ve,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=Go(r.shape,c,i,o,l,u,!0),p=new XO(h);return n.runWebGLProgram(p,[r,a],"float32")}};const JO={kernelName:Ue,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=Go(c,a.shape,i,o,l,u,!0),p=new YO(h);return n.runWebGLProgram(p,[r,a],"float32")}};class QO{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 eM={kernelName:Ge,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{x:s}=t,r=[...s.shape,...s.shape],a=d(s.shape),i=DF({inputs:{x:s},backend:n,attrs:{shape:[a]}}),o=new QO(a),l=n.runWebGLProgram(o,[i],i.dtype),u=DF({inputs:{x:l},backend:n,attrs:{shape:r}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),u}};class tM{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 nM={kernelName:He,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=Wo(r.shape,a.shape,i,o,"NHWC",l);let c;const h=new tM(u);c=n.runWebGLProgram(h,[r,a],"float32");const p=DF({inputs:{x:c},backend:n,attrs:{shape:u.outShape}});return n.disposeIntermediateTensorInfo(c),p}};const sM={kernelName:Xe,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{equation:r}=s,a=t,{allDims:i,summedDims:o,idDims:l}=Gd(r,a.length);jd(i.length,l,a);const{path:u,steps:c}=qd(o,l),h=c.length;let p=null,d=i.length;const m=[];for(let e=0;e<h;++e){for(const t of c[e]){const{permutationIndices:e,expandDims:s}=Hd(d,l[t]);let r;Kd(e)?r=a[t]:(r=GF({inputs:{x:a[t]},backend:n,attrs:{perm:e}}),m.push(r));const i=r.shape.slice();for(let e=0;e<s.length;++e)i.splice(s[e],0,1);f(r.shape,i)||(r=DF({inputs:{x:r},backend:n,attrs:{shape:i}}),m.push(r)),null===p?p=r:(p=_F({inputs:{a:r,b:p},backend:n}),m.push(p))}e<h-1&&(u[e]>=0&&(p=VF({inputs:{x:p},backend:n,attrs:{axis:u[e]-(i.length-d),keepDims:!1}}),m.push(p)),d--)}for(const e of m)e!==p&&n.disposeIntermediateTensorInfo(e);return p}},rM=IF({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"}),aM={kernelName:Ye,backendName:"webgl",kernelFunc:rM},iM={kernelName:Ze,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n}=e,{dy:s,y:r}=t,a=X().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new dF("\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 pF("return (b >= 1.0) ? a : a * (b + 1.0);",s.shape,r.shape);return n.runWebGLProgram(a,[s,r],s.dtype)}},oM=SF({opSnippet:"return float(a == b);",packedOpSnippet:"\n return vec4(equal(a, b));\n",dtype:"bool",cpuKernelImpl:l_}),lM={kernelName:Qe,backendName:"webgl",kernelFunc:oM},uM=IF({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 = ${$d};\n float a1 = ${Ed};\n float a2 = ${Ad};\n float a3 = ${Rd};\n float a4 = ${_d};\n float a5 = ${Fd};\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`}),cM={kernelName:Je,backendName:"webgl",kernelFunc:uM},hM=IF({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:u_,dtype:"float32"}),pM={kernelName:et,backendName:"webgl",kernelFunc:hM};function dM(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&&(u(-(i+1)<=r,(()=>`Axis must be in the interval [${-(i+1)}, ${i}]`)),l=i+r+1),o.splice(l,0,1),DF({inputs:{x:a},backend:s,attrs:{shape:o}})}const fM={kernelName:tt,backendName:"webgl",kernelFunc:dM},mM="return exp(x) - 1.0;",gM=IF({opSnippet:mM,packedOpSnippet:mM,cpuKernelImpl:c_}),yM={kernelName:nt,backendName:"webgl",kernelFunc:gM};class bM{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 xM(e,t,n){const s=n.texData.get(e.dataId),r=d(e.shape),a=e.shape[e.shape.length-1],i=DF({inputs:{x:e},backend:n,attrs:{shape:[r/a,a]}}),o=i.shape,l=new bM("real",o,t),u=new bM("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=gF({inputs:{real:h,imag:p},backend:n});n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(p);const m=DF({inputs:{x:f},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(f),m}const wM={kernelName:st,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:s}=t;return xM(s,!1,n)}};class vM{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 kM(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=N(a,d(s));return e.fill(r),t.makeTensorInfo(s,a,e)}{const e=new vM(s,r),n=[[r]];return t.runWebGLProgram(e,[],a,n)}}const NM={kernelName:rt,backendName:"webgl",kernelFunc:kM};class IM{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 SM={kernelName:at,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{const{image:n}=e,s=t,r=new IM(n.shape);return s.runWebGLProgram(r,[n],n.dtype)}},TM="return floor(x);",CM=IF({opSnippet:TM,packedOpSnippet:TM,cpuKernelImpl:h_}),$M={kernelName:it,backendName:"webgl",kernelFunc:CM},EM=SF({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"}),AM={kernelName:ot,backendName:"webgl",kernelFunc:EM};class RM{constructor(e){this.variableNames=["A"];const t=dR(),[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 _M{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;const t=dR(),[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 FM={kernelName:rs,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=X().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");null!=DM&&e===OM||(OM=e,DM=document.createElement("canvas").getContext("2d",{willReadFrequently:OM})),DM.canvas.width=l,DM.canvas.height=u,DM.drawImage(r,0,0,l,u),r=DM.canvas}const p=n.makeTensorInfo(c,"int32");n.texData.get(p.dataId).usage=OA.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(p.dataId),r);const d=X().getBool("WEBGL_PACK")?new _M(h):new RM(h),f=n.runWebGLProgram(d,[p],"int32");return n.disposeData(p.dataId),f}};let DM,OM=X().getBool("CANVAS2D_WILL_READ_FREQUENTLY_FOR_GPU");const MM={kernelName:os,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=Qo(c),g=Go(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=DF({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",nr(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&&X().getBool("WEBGL_EXP_CONV")){const e=d?TF(d,!0):null,t=new mO(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(X().getBool("WEBGL_CONV_IM2COL"))y=xO({x:r,filter:a,convInfo:g,backend:n,bias:i,activation:d,preluActivationWeights:o,leakyreluAlpha:f});else{const e=d?TF(d,!1):null,t=new dO(g,x,e,w,v),s=k();y=n.runWebGLProgram(t,s,"float32")}else y=bO({x:r,filter:a,convInfo:g,backend:n,bias:i,activation:d,preluActivationWeights:o,leakyreluAlpha:f});const N=DF({inputs:{x:y},backend:n,attrs:{shape:g.outShape}});return b.push(y),b.forEach((e=>n.disposeIntermediateTensorInfo(e))),N}};const LM={kernelName:ls,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:c,dilations:h,dimRoundingMode:p,activation:d,leakyreluAlpha:f}=s,m=[];let g=h;null==g&&(g=[1,1]),u(Jo(l,g),(()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${g}'`));const y=Go(r.shape,a.shape,l,g,c,p,!0),b=X().getBool("WEBGL_PACK_DEPTHWISECONV")&&y.strideWidth<=2&&y.outChannels/y.inChannels==1,x=d?TF(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",nr(f,"float32"));w.push(e),m.push(e)}let I;I=b?new qO(y,v,x,k,N):new jO(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 zM{constructor(e,t,n,s){this.sliceDim=e,this.strides=t,this.paramsShape=s,this.variableNames=["x","indices"],this.outputShape=n;const r=AR(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 PM={kernelName:ct,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]=Hi(s,r),p=DF({inputs:{x:r},backend:n,attrs:{shape:[u,i]}}),f=DF({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=p_(e,t,s.dtype,u,i,c,h,s.shape,o);return n.makeTensorInfo(l,s.dtype,a.values)}const m=new zM(i,h,[u,c],s.shape),g=n.runWebGLProgram(m,[f,p],f.dtype),y=DF({inputs:{x:g},backend:n,attrs:{shape:l}});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(g),y}};class BM{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;const n=AR(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 WM(e){const{inputs:t,backend:n,attrs:s}=e,{x:r,indices:a}=t,{axis:i,batchDims:o}=s,l=w(i,r.shape)[0];if(X().get("DEBUG")){const e=n.readSync(a.dataId),t=r.shape[l];for(let n=0;n<e.length;++n){const s=e[n];u(s<=t-1&&s>=0,(()=>`GatherV2: the index value ${s} is not in [0, ${t-1}]`))}}const c=pf(r,a,l,o),h=d(a.shape),p=[],f=DF({inputs:{x:r},backend:n,attrs:{shape:[c.batchSize,c.outerSize,c.dimSize,c.sliceSize]}}),m=DF({inputs:{x:a},backend:n,attrs:{shape:[c.batchSize,h/c.batchSize]}});p.push(f),p.push(m);const g=[c.batchSize,c.outerSize,h/c.batchSize,c.sliceSize];if(n.shouldExecuteOnCPU([r,a])||"string"===r.dtype){const e=n.bufferSync(m),t=n.bufferSync(f),s=d_(t,e,g);return p.forEach((e=>n.disposeIntermediateTensorInfo(e))),n.makeTensorInfo(c.outputShape,s.dtype,s.values)}const y=new BM(f.shape,g),b=n.runWebGLProgram(y,[f,m],f.dtype);p.push(b);const x=DF({inputs:{x:b},backend:n,attrs:{shape:c.outputShape}});return p.forEach((e=>n.disposeIntermediateTensorInfo(e))),x}const VM={kernelName:ut,backendName:"webgl",kernelFunc:WM},UM=SF({opSnippet:"return float(a > b);",packedOpSnippet:"\n return vec4(greaterThan(a, b));\n",cpuKernelImpl:f_,dtype:"bool"}),GM={kernelName:ht,backendName:"webgl",kernelFunc:UM},HM=SF({opSnippet:"return float(a >= b);",packedOpSnippet:"\n return vec4(greaterThanEqual(a, b));\n",dtype:"bool",cpuKernelImpl:m_}),jM={kernelName:pt,backendName:"webgl",kernelFunc:HM};const qM={kernelName:ft,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{input:s}=t;return xM(s,!0,n)}},KM=IF({opSnippet:"return float(!isnan(x) && !isinf(x));",dtype:"bool"}),XM={kernelName:gt,backendName:"webgl",kernelFunc:KM},YM=IF({opSnippet:"return float(isinf(x));",dtype:"bool"}),ZM={kernelName:yt,backendName:"webgl",kernelFunc:YM},JM=IF({opSnippet:"return float(isnan(x));",dtype:"bool"}),QM={kernelName:bt,backendName:"webgl",kernelFunc:JM},eL=SF({opSnippet:"return float(a < b);",packedOpSnippet:"\n return vec4(lessThan(a, b));\n",cpuKernelImpl:g_,dtype:"bool"}),tL={kernelName:wt,backendName:"webgl",kernelFunc:eL},nL=SF({opSnippet:"return float(a <= b);",packedOpSnippet:"\n return vec4(lessThanEqual(a, b));\n",cpuKernelImpl:y_,dtype:"bool"}),sL={kernelName:vt,backendName:"webgl",kernelFunc:nL};const rL={kernelName:kt,backendName:"webgl",kernelFunc:function(e){const{backend:t,attrs:n}=e,{start:s,stop:r,num:a}=n,i=b_(s,r,a);return t.makeTensorInfo([i.length],"float32",i)}},aL=IF({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:x_}),iL={kernelName:Nt,backendName:"webgl",kernelFunc:aL},oL=IF({opSnippet:"if (isnan(x)) return x;\n return log(1.0 + x);\n"}),lL={kernelName:It,backendName:"webgl",kernelFunc:oL},uL=SF({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"}),cL={kernelName:St,backendName:"webgl",kernelFunc:uL},hL=IF({opSnippet:"return float(!(x >= 1.0));"}),pL={kernelName:Tt,backendName:"webgl",kernelFunc:hL},dL=SF({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"}),fL={kernelName:Ct,backendName:"webgl",kernelFunc:dL};class mL{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 gL{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 yL={kernelName:Et,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=X().getBool("WEBGL_PACK_NORMALIZATION")?new gL(r.shape,a,i,o,l):new mL(r.shape,a,i,o,l);return n.runWebGLProgram(u,[r],r.dtype)}};class bL{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 xL={kernelName:At,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 bL(r.shape,o,l,u,c);return n.runWebGLProgram(h,[r,a,i],r.dtype)}};function wL(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{reductionIndices:a,keepDims:i}=s,o=r.shape.length,l=w(a,r.shape);let u=l;const c=Ql(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=q_(e,r.shape,r.dtype,c,t);f=n.makeTensorInfo(t,r.dtype);n.texData.get(f.dataId).values=s}else f=WF(r,c,n);u=tu(u.length,o)}Jl("max",u,o);const[m,g]=Yl(f.shape,u);let y,b=m;if(i&&(b=Zl(m,l)),p){const e=n.texData.get(f.dataId).values,t=w_(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=DF({inputs:{x:e},attrs:{shape:[d(e.shape)/r,r]},backend:s}),i=zF(a,e.dtype,"max",s),o=DF({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 vL={kernelName:Rt,backendName:"webgl",kernelFunc:wL},kL=SF({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:v_}),NL={kernelName:_t,backendName:"webgl",kernelFunc:kL};const IL={kernelName:Ft,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t;hR(r,"maxPool");const{filterSize:a,strides:i,pad:o,dimRoundingMode:l}=s;u(Jo(i,1),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '1'`));const c=Vo(r.shape,a,i,1,o,l);if(1===c.filterWidth&&1===c.filterHeight&&f(c.inShape,c.outShape))return fF({inputs:{x:r},backend:n});const h=new SD(c,"max",!1);return n.runWebGLProgram(h,[r],r.dtype)}};const SL={kernelName:Ot,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=Uo(r.shape,a,i,[1,1,1],o,u,l),h=new TD(c,"max",!1);return n.runWebGLProgram(h,[r],r.dtype)}};class TL{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 CL{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 $L={kernelName:Mt,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=Uo(i.shape,o,l,[1,1,1],u,c),p=new TD(h,"max",!0),d=n.runWebGLProgram(p,[i],i.dtype),f=new CL(h),m=n.runWebGLProgram(f,[r,d],i.dtype);return n.disposeIntermediateTensorInfo(d),m}};const EL={kernelName:Dt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{dy:r,input:a,output:i}=t,o=a;hR([a,i],"maxPoolGrad");const{filterSize:l,strides:u,pad:c,dimRoundingMode:h}=s,p=Vo(o.shape,l,u,1,c,h),d=new SD(p,"max",!0),f=n.runWebGLProgram(d,[o],o.dtype),m=new TL(p),g=n.runWebGLProgram(m,[r,f],o.dtype);return n.disposeIntermediateTensorInfo(f),g}};const AL={kernelName:Lt,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{x:s}=e,{filterSize:r,strides:a,pad:i,includeBatchInIndex:o}=t,l=n;u(4===s.shape.length,(()=>`Error in maxPool: input must be rank 4 but got rank ${s.shape.length}.`));const c=[1,1];u(Jo(a,c),(()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${c}'`));const h=Vo(s.shape,r,a,c,i),[p,d]=function(e,t,n,s){let r=new SD(n,"max",!1);const a=s.runWebGLProgram(r,[e],"float32");return r=new SD(n,"max",!0,!0,t),[a,s.runWebGLProgram(r,[e],"float32")]}(s,o,h,l);return[p,d]}};const RL={kernelName:zt,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=w(a,s.shape);let u=l;const c=Ql(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=q_(e,s.shape,s.dtype,c,t);m=i.makeTensorInfo(t,s.dtype);i.texData.get(m.dataId).values=n}else m=WF(s,c,i);f.push(m),u=tu(u.length,o)}Jl("sum",u,o);const[g,y]=Yl(m.shape,u);let b=g;r&&(b=Zl(g,l));const x=function(e,t,n,s){const r=d(t),a=DF({inputs:{x:e},attrs:{shape:[d(e.shape)/r,r]},backend:s}),i=zF(a,"float32","mean",s),o=DF({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 _L={kernelName:Pt,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=w(a,r.shape);let u=l;const c=Ql(u,o);let h=r;null!=c&&(h=GF({inputs:{x:r},backend:n,attrs:{perm:c}}),u=tu(u.length,r.shape.length)),Jl("min",u,o);const[p,f]=Yl(h.shape,u),m=DF({inputs:{x:h},backend:n,attrs:{shape:[-1,d(f)]}}),g=zF(m,m.dtype,"min",n);let y;if(i){y=DF({inputs:{x:g},backend:n,attrs:{shape:Zl(p,l)}})}else y=DF({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),null!=c&&n.disposeIntermediateTensorInfo(h),y}},FL=SF({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:k_}),DL={kernelName:Bt,backendName:"webgl",kernelFunc:FL};class OL{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map(((t,n)=>t[0]+e[n]+t[1]));const s=e.length,r=AR(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 ML{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=AR(s),a=t.map((e=>e[0])).join(","),i=t.map(((t,n)=>t[0]+e[n])).join(","),o=Y_("rc",s),l=Y_("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 LL={kernelName:Wt,backendName:"webgl",kernelFunc:({inputs:e,backend:t,attrs:n})=>{const{x:s}=e,{paddings:r,mode:a}=n,i=X().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new ML(s.shape,r,a):new OL(s.shape,r,a);return t.runWebGLProgram(i,[s],s.dtype)}},zL=SF({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"}),PL={kernelName:Vt,backendName:"webgl",kernelFunc:zL};class BL{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 WL=SF({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}),VL={kernelName:Ke,backendName:"webgl",kernelFunc:WL},UL="return a - b;",GL=SF({opSnippet:UL,packedOpSnippet:UL,supportsComplex:!0,cpuKernelImpl:G_}),HL={kernelName:jn,backendName:"webgl",kernelFunc:GL};function jL(e){const{inputs:t,backend:n,attrs:s}=e,{logits:r}=t,{dim:a}=s,i=w([a],r.shape),o=wL({inputs:{x:r},backend:n,attrs:{reductionIndices:i,keepDims:!1}}),l=Zl(o.shape,i),u=DF({inputs:{x:o},backend:n,attrs:{shape:l}}),c=GL({inputs:{a:r,b:u},backend:n}),h=hM({inputs:{x:c},backend:n}),p=VF({inputs:{x:h},backend:n,attrs:{axis:i,keepDims:!1}}),d=DF({inputs:{x:p},backend:n,attrs:{shape:l}}),f=WL({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 qL={kernelName:Dn,backendName:"webgl",kernelFunc:jL};const KL={kernelName:Ut,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:jL({inputs:{logits:r},backend:n,attrs:{dim:r.shape.length-1}}),u=l.shape[0],c=l.shape[1],h=new BL(u,c,a),p=[[i]],d=n.runWebGLProgram(h,[l],"int32",p);return o||n.disposeIntermediateTensorInfo(l),d}};const XL={kernelName:Ht,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]=I_(e.values,s.shape,s.dtype);return n.makeTensorInfo(r,s.dtype,t)}let r;return r=X().getBool("WEBGL_PACK_UNARY_OPERATIONS")?new iF(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 sF(s.shape,"if (isnan(x)) return x;\n return -x;\n"),n.runWebGLProgram(r,[s],s.dtype)}},YL=cp;const ZL={kernelName:qt,backendName:"webgl",kernelFunc:function(e){us("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}=YL(u,c,i,o,l);return n.makeTensorInfo([h.length],"int32",new Int32Array(h))}},JL=hp;const QL={kernelName:Kt,backendName:"webgl",kernelFunc:function(e){us("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}=JL(c,h,i,o,l,u);return[n.makeTensorInfo([p.length],"int32",new Int32Array(p)),n.makeTensorInfo([],"int32",new Int32Array([d]))]}},ez=pp;const tz={kernelName:Xt,backendName:"webgl",kernelFunc:function(e){us("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}=ez(c,h,p,d,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}};class nz{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 sz={kernelName:Zt,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 nz(u,i,o,l),h=DF({inputs:{x:r},backend:n,attrs:{shape:[u]}}),p=n.runWebGLProgram(c,[h],a);n.disposeIntermediateTensorInfo(h);const f=DF({inputs:{x:p},backend:n,attrs:{shape:[...r.shape,i]}});return n.disposeIntermediateTensorInfo(p),f}};function rz(e){const{inputs:t,backend:n}=e,{x:s}=t;if("complex64"===s.dtype){const e=qD({inputs:{input:s},backend:n}),t=rz({inputs:{x:e},backend:n}),r=lO({inputs:{input:s},backend:n}),a=rz({inputs:{x:r},backend:n}),i=gF({inputs:{real:t,imag:a},backend:n});return n.disposeIntermediateTensorInfo(e),n.disposeIntermediateTensorInfo(t),n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(a),i}return kM({attrs:{shape:s.shape,dtype:s.dtype,value:"string"===s.dtype?"":0},backend:n})}const az={kernelName:ns,backendName:"webgl",kernelFunc:rz};const iz={kernelName:Yt,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=qD({inputs:{input:r},backend:s}),n=e({inputs:{x:t},backend:s}),a=lO({inputs:{input:r},backend:s}),i=rz({inputs:{x:a},backend:s}),o=gF({inputs:{real:n,imag:i},backend:s});return s.disposeIntermediateTensorInfo(t),s.disposeIntermediateTensorInfo(n),s.disposeIntermediateTensorInfo(a),s.disposeIntermediateTensorInfo(i),o}return kM({attrs:{shape:r.shape,dtype:r.dtype,value:1},backend:s})}};const oz={kernelName:Jt,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{axis:r}=s;if(1===t.length)return dM({inputs:{input:t[0]},backend:n,attrs:{dim:r}});const a=t[0].shape,i=t[0].dtype;t.forEach((e=>{c(a,e.shape,"All tensors passed to stack must have matching shapes"),u(i===e.dtype,(()=>"All tensors passed to stack must have matching dtypes"))}));const o=[],l=hO({inputs:t.map((e=>{const t=dM({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 lz{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=AR(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 uz{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=AR(s),a=t.map((e=>e[0])).join(","),i=t.map(((t,n)=>t[0]+e[n])).join(","),o=Y_("rc",s),l=Y_("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 cz=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 kM({backend:n,attrs:{shape:e,value:i,dtype:r.dtype}})}const o=X().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new uz(r.shape,a,i):new lz(r.shape,a,i),l=[[i]];return n.runWebGLProgram(o,[r],r.dtype,l)},hz={kernelName:Qt,backendName:"webgl",kernelFunc:cz},pz=SF({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"}),dz={kernelName:en,backendName:"webgl",kernelFunc:pz};const fz={kernelName:nn,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=w(a,r.shape);let c=u;const h=Ql(c,o);let p,f=r;if(null!=h&&(f=GF({inputs:{x:r},backend:n,attrs:{perm:h}}),c=tu(c.length,o),l.push(f)),Jl("prod",c,o),n.shouldExecuteOnCPU([f])){const e=n.texData.get(f.dataId).values,{outVals:t,outShape:s,outDtype:r}=T_(f.shape,f.dtype,e,c);p=n.makeTensorInfo(s,r,t)}else{const[e,t]=Yl(f.shape,c),s=d(t),a=DF({inputs:{x:f},backend:n,attrs:{shape:[-1,s]}}),i=zF(a,Rr(r.dtype),"prod",n);p=DF({inputs:{x:i},backend:n,attrs:{shape:e}}),l.push(a),l.push(i)}if(i){l.push(p);const e=Zl(p.shape,u);p=DF({inputs:{x:p},backend:n,attrs:{shape:e}})}return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),p}};const mz={kernelName:sn,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]=C_(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 gz={kernelName:rn,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]=$_(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 yz={kernelName:an,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]=E_(u,r.shape,c,a.shape,a.dtype,h,i.shape,p,d,l);return n.makeTensorInfo(f,a.dtype,m)}},bz=e=>{const{backend:t,attrs:n}=e,{start:s,stop:r,step:a,dtype:i}=n,o=A_(s,r,a,i);return t.makeTensorInfo([o.length],i,o)},xz={kernelName:on,backendName:"webgl",kernelFunc:bz},wz=IF({opSnippet:"return 1.0 / x;"}),vz={kernelName:un,backendName:"webgl",kernelFunc:wz},kz=IF({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"}),Nz={kernelName:cn,backendName:"webgl",kernelFunc:kz},Iz=IF({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"}),Sz={kernelName:gn,backendName:"webgl",kernelFunc:Iz};class Tz{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 Cz{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 $z={kernelName:fn,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=X().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new Cz(r.shape,l,u,a,i):new Tz(r.shape,l,u,a,i);return n.runWebGLProgram(c,[r],"float32")}};class Ez{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 Az={kernelName:mn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{images:r,dy:a}=t,{alignCorners:i}=s,o=new Ez(a.shape,r.shape,i);return n.runWebGLProgram(o,[a],a.dtype)}};class Rz{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 _z{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 Fz={kernelName:pn,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=X().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new _z(r.shape,l,u,a,i):new Rz(r.shape,l,u,a,i);return n.runWebGLProgram(c,[r],r.dtype)}};class Dz{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 Oz={kernelName:dn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{images:r,dy:a}=t,{alignCorners:i}=s,o=new Dz(a.shape,r.shape,i);return n.runWebGLProgram(o,[a],a.dtype)}};class Mz{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=AR(n);this.userCode=`\n void main() {\n ${r} coords = getOutputCoords();\n setOutput(getX(${s}));\n }\n `}}class Lz{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=Y_("rc",n),r=`${s[n-1]} + 1 < ${this.outputShape[n-1]}`,a=`${s[n-2]} + 1 < ${this.outputShape[n-2]}`,i=AR(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 zz={kernelName:yn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{dims:a}=s,i=r.shape.length,o=w(a,r.shape);if(0===i)return fF({inputs:{x:r},backend:n});const l=X().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Lz(r.shape,o):new Mz(r.shape,o);return n.runWebGLProgram(l,[r],r.dtype)}};class Pz{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 Bz={kernelName:as,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{const{image:s}=e,{radians:r,fillValue:a,center:i}=t,o=n,l=new Pz(s.shape,a),[u,c]=wd(i,s.shape[1],s.shape[2]),h=[[u,c,Math.sin(r),Math.cos(r)]];return o.runWebGLProgram(l,[s],s.dtype,h)}},Wz=IF({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"}),Vz={kernelName:bn,backendName:"webgl",kernelFunc:Wz},Uz=IF({opSnippet:"return inversesqrt(x);",cpuKernelImpl:R_}),Gz={kernelName:xn,backendName:"webgl",kernelFunc:Uz};class Hz{constructor(e,t,n,s,r,a,i=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;const o=AR(r.length),l=AR(a.length);let u="";1===n?u="i":2===n&&(u="i, j");const c=`getIndices(${u})`;let h="";1===s?h="i":2===s&&(h="i, coords[1]");const p=`getUpdates(${h})`,d=t>1?"strides[j]":"strides";this.userCode=`\n ${o} strides = ${o}(${r});\n\n void main() {\n ${l} 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(${c});\n flattenedIndex += index * ${d};\n }\n if (flattenedIndex == coords[0]) {\n sum += ${p};\n found = true;\n }\n }\n setOutput(mix(getDefaultValue(), sum, float(found)));\n }\n `}}const jz={kernelName:wn,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}=Xi(0,r,i),p=[h/u,u];if(0===h)return n.makeTensorInfo(i,r.dtype);const d=DF({inputs:{x:r},backend:n,attrs:{shape:[l,o]}}),f=DF({inputs:{x:a},backend:n,attrs:{shape:[l,u]}}),m=n.makeTensorInfo([],"float32",new Float32Array([0])),g=new Hz(l,o,d.shape.length,f.shape.length,c,p),y=n.runWebGLProgram(g,[f,d,m],f.dtype),b=DF({inputs:{x:y},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(m),b}};class qz{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===X().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 Kz={kernelName:vn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{sortedSequence:r,values:a}=t,{side:i}=s,o=new qz(r.shape[0],r.shape[1],a.shape[1],i),l=[[r.shape[1]]];return n.runWebGLProgram(o,[r,a],"int32",l)}};class Xz{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=AR(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 Yz={kernelName:kn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n}=e,{condition:s,t:r,e:a}=t,i=new Xz(s.shape.length,r.shape,r.shape.length);return n.runWebGLProgram(i,[s,r,a],Ar(r.dtype,a.dtype))}},Zz=IF({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 = ${Cd};\n return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);\n`}),Jz={kernelName:Nn,backendName:"webgl",kernelFunc:Zz},Qz=IF({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:F_}),eP={kernelName:$n,backendName:"webgl",kernelFunc:Qz},tP=IF({opSnippet:"\n if (isnan(x)) { return 0.0; }\n return sign(x);\n"}),nP={kernelName:Cn,backendName:"webgl",kernelFunc:tP},sP=IF({opSnippet:"if (isnan(x)) return x;\n return sin(x);\n"}),rP={kernelName:Sn,backendName:"webgl",kernelFunc:sP},aP=IF({opSnippet:"\n float e2x = exp(x);\n return (e2x - 1.0 / e2x) / 2.0;\n"}),iP={kernelName:Tn,backendName:"webgl",kernelFunc:aP},oP=IF({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"}),lP={kernelName:En,backendName:"webgl",kernelFunc:oP},uP={kernelName:_n,backendName:"webgl",kernelFunc:e=>{const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{blockShape:a,paddings:i}=s;u(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 c=[],h=cz({inputs:{x:r},backend:n,attrs:{paddings:l,constantValue:0}}),p=vd(h.shape,a,o,!1),d=kd(p.length,a.length,!1),f=Nd(h.shape,a,o,!1),m=DF({inputs:{x:h},backend:n,attrs:{shape:p}}),g=GF({inputs:{x:m},backend:n,attrs:{perm:d}}),y=DF({inputs:{x:g},backend:n,attrs:{shape:f}});return c.push(h),c.push(m),c.push(g),c.forEach((e=>n.disposeIntermediateTensorInfo(e))),y}};const cP={kernelName:On,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]=M_(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 hP={kernelName:Mn,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]=L_(o,s.shape,s.dtype,i,l);return[n.makeTensorInfo(c,s.dtype,u),n.makeTensorInfo([h.length],a.dtype,new Int32Array(h))]}};const pP={kernelName:Ln,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]=z_(i,s.shape,s.dtype,o,l,!0);return n.makeTensorInfo(c,s.dtype,u)}};const dP={kernelName:zn,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]=z_(i,s.shape,s.dtype,o,l);return n.makeTensorInfo(c,s.dtype,u)}};const fP={kernelName:Pn,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}=Xi(0,r,o);if("string"===a.dtype){const e=n.bufferSync(r),t=n.bufferSync(a),s=or(n.readSync(i.dataId)[0]),d=__(e,t,o,p,c,u,l,h,s,false);return n.makeTensorInfo(o,d.dtype,d.values)}const d=new Hz(u,l,r.shape.length,a.shape.length,h,[p,1],false),f=n.runWebGLProgram(d,[a,r,i],a.dtype),m=DF({inputs:{x:f},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(f),m}};const mP={kernelName:Fn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{numOrSizeSplits:a,axis:i}=s,o=w(i,r.shape)[0],l=Yd(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=BD({inputs:{x:r},backend:n,attrs:{begin:c,size:t}});return c[o]+=e,s}))}},gP="return sqrt(x);",yP=IF({opSnippet:gP,packedOpSnippet:gP,cpuKernelImpl:P_}),bP={kernelName:An,backendName:"webgl",kernelFunc:yP},xP={kernelName:Wn,backendName:"webgl",kernelFunc:IF({opSnippet:"return x * x;"})},wP="return (a - b) * (a - b);",vP=SF({opSnippet:wP,packedOpSnippet:wP}),kP={kernelName:Bn,backendName:"webgl",kernelFunc:vP};const NP={kernelName:ss,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 sF(s.shape,r);return n.runWebGLProgram(a,[s],s.dtype)}};class IP{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;const s=n.length,r=AR(n.length),a=AR(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 SP={kernelName:Vn,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:c,ellipsisMask:h,newAxisMask:p,shrinkAxisMask:d}=s,{finalShapeSparse:f,finalShape:m,isIdentity:g,sliceDim0:y,isSimpleSlice:b,begin:x,end:w,strides:v}=co(r.shape,a,i,o,l,c,h,p,d);let k;if(g)k=DF({inputs:{x:r},backend:n,attrs:{shape:m}});else if(y||b){u(r.shape.length>=1,(()=>`Input must have rank at least 1, got: ${r.shape.length}`));const e=Ji(x,w,v),t=BD({inputs:{x:r},backend:n,attrs:{begin:x,size:e}});k=DF({inputs:{x:t},backend:n,attrs:{shape:m}}),n.disposeIntermediateTensorInfo(t)}else{if(n.shouldExecuteOnCPU([r])){const e=n.readSync(r.dataId),t=Za(r.shape,r.dtype,e),s=B_(f,t,v,x);k=n.makeTensorInfo(m,r.dtype,s.values)}else{const e=new IP(x,v,f);k=n.runWebGLProgram(e,[r],r.dtype)}}const N=DF({inputs:{x:k},backend:n,attrs:{shape:m}});return n.disposeIntermediateTensorInfo(k),N}};const TP={kernelName:Un,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]=W_(p,d,r,a,i,o,l,u);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(h.shape,"int32",m)]}};const CP={kernelName:Gn,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]=V_(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 $P={kernelName:Hn,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=U_(i,r);return n.makeTensorInfo(a.shape,"int32",o)}},EP=IF({opSnippet:"return tan(x);"}),AP={kernelName:qn,backendName:"webgl",kernelFunc:EP},RP=IF({opSnippet:"\n float e2x = exp(-2.0 * abs(x));\n return sign(x) * (1.0 - e2x) / (1.0 + e2x);\n"}),_P={kernelName:Kn,backendName:"webgl",kernelFunc:RP};class FP{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=AR(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 DP(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=>or(e))):e,s=Za(r.shape,r.dtype,t),i=H_(s,a);return n.makeTensorInfo(i.shape,i.dtype,i.values)}const i=new FP(r.shape,a);return n.runWebGLProgram(i,[r],r.dtype)}const OP={kernelName:Xn,backendName:"webgl",kernelFunc:DP};class MP{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 LP{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 zP(e,t){null!==t&&e.disposeIntermediateTensorInfo(t)}function PP(e){let t=1;for(;t<e;)t*=2;return t}const BP={kernelName:Yn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,backend:n,attrs:s}=e,{x:r}=t,{k:a,sorted:i}=s,o=X().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"),l=X().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]=j_(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,kM({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=DF({inputs:{x:f},attrs:{shape:[m,c]},backend:n});p&&zP(n,f);const y=PP(a),b=PP(c);let x=null;const w=()=>null===x?[g,g]:[g,x],v=(e,t,s)=>{const r=w(),a=new MP(s),i=[[c],[null===x?1:0],[Number.NEGATIVE_INFINITY],[e],[t]],o=x;x=n.runWebGLProgram(a,r,"int32",i),zP(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 LP([m,e/2]),r=[[c],[null===x?1:0],[y]],a=x;x=n.runWebGLProgram(s,t,"int32",r),zP(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=BD({inputs:{x:x},backend:n,attrs:{begin:0,size:[m,a]}}),zP(n,k);let N=WM({inputs:{x:g,indices:x},backend:n,attrs:{axis:1,batchDims:1}});zP(n,g);const I=u.slice(0,-1);I.push(a),k=x,x=DF({inputs:{x:x},attrs:{shape:I},backend:n}),zP(n,k);const S=N;return N=DF({inputs:{x:N},attrs:{shape:I},backend:n}),zP(n,S),[N,x]}};class WP{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 VP={kernelName:Zn,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 WP(h,p,i,o,l,[c,f,m,d]);return n.runWebGLProgram(g,[r,a],"float32")}};const UP={kernelName:Qn,backendName:"webgl",kernelFunc:function(e){const{inputs:t,attrs:n,backend:s}=e,{axis:r}=n,{x:a}=t;hR(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}=K_(i,r,a.shape,a.dtype);return[s.makeTensorInfo(l,a.dtype,o),s.makeTensorInfo([u.length],"int32",u)]}};const GP={kernelName:es,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=BD({inputs:{x:i},backend:n,attrs:{begin:p,size:d}}),s=DF({inputs:{x:t},backend:n,attrs:{shape:u}});f[e]=s,h.push(t)}return h.forEach((e=>n.disposeIntermediateTensorInfo(e))),f}};class HP{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 jP={kernelName:ts,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=Ql([u],o);let h=r;null!=c&&(h=GF({inputs:{x:r},backend:n,attrs:{perm:c}}),l.push(h),u=tu(1,o)[0]);const p=hf(h.shape,u,i),f=d([h.shape[u]]),m=DF({inputs:{x:h},backend:n,attrs:{shape:[-1,f]}});l.push(m);const g=Rr(r.dtype),y=(e,t,s,r,a)=>{const i=e.shape[0],o=e.shape[1],u=cf(o,a),c=new HP({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=bz({backend:n,attrs:{start:0,stop:a,step:1,dtype:"float32"}}),d=DP({inputs:{x:p},backend:n,attrs:{reps:[o/u]}});l.push(p),l.push(d);return y(h,t,d,r,a)},b=DF({inputs:{x:y(m,"unsortedSegmentSum",a,g,i)},backend:n,attrs:{shape:p}});let x=b;if(null!=c){l.push(b);const e=eu(c);x=GF({inputs:{x:x},backend:n,attrs:{perm:e}})}return l.forEach((e=>n.disposeIntermediateTensorInfo(e))),x}},qP=[qF,XF,ZF,QF,nD,aD,iD,oD,dD,fD,gD,bD,wD,kD,ID,CD,$D,RD,_D,FD,MD,VD,UD,GD,XD,JD,tO,yF,rO,pO,wO,SO,TO,CO,$O,EO,RO,FO,OO,WO,VO,UO,HO,KO,ZO,JO,eM,nM,sM,aM,iM,lM,cM,pM,fM,yM,wM,NM,SM,$M,AM,FM,MM,LM,PM,VM,GM,jM,mF,qM,uO,XM,ZM,QM,wF,tL,sL,rL,iL,lL,cL,pL,fL,yL,xL,vL,NL,IL,SL,$L,EL,AL,RL,_L,DL,LL,PL,KL,FF,XL,ZL,QL,tz,jD,sz,iz,oz,hz,dz,NF,fz,mz,gz,yz,xz,KD,VL,vz,Nz,Sz,OF,$z,Az,Fz,Oz,zz,Bz,Vz,Gz,jz,Kz,Yz,Jz,eP,nP,rP,iP,WD,qL,lP,uP,cP,hP,pP,dP,fP,mP,bP,xP,kP,NP,SP,TP,CP,$P,HL,UF,AP,_P,OP,BP,VP,HF,UP,GP,jP,az];for(const e of qP)ms(e);const KP={"tfjs-core":No,"tfjs-backend-cpu":"4.1.0","tfjs-backend-webgl":"4.1.0","tfjs-data":cI,"tfjs-layers":Ub,"tfjs-converter":oN,tfjs:"4.1.0"};e.Abs=Q,e.Acos=ee,e.Acosh=te,e.AdadeltaOptimizer=td,e.AdagradOptimizer=nd,e.AdamOptimizer=sd,e.AdamaxOptimizer=rd,e.Add=ne,e.AddN=se,e.All=re,e.Any=ae,e.ArgMax=ie,e.ArgMin=oe,e.Asin=le,e.Asinh=ue,e.Atan=ce,e.Atan2=pe,e.Atanh=he,e.AvgPool=de,e.AvgPool3D=me,e.AvgPool3DGrad=ge,e.AvgPoolGrad=fe,e.BatchMatMul=ye,e.BatchToSpaceND=be,e.Bincount=xe,e.BroadcastArgs=ve,e.BroadcastTo=we,e.Callback=Wv,e.CallbackList=tb,e.Cast=ke,e.Ceil=Ne,e.ClipByValue=Ie,e.Complex=Se,e.ComplexAbs=Te,e.Concat=Ce,e.Conv2D=$e,e.Conv2DBackpropFilter=Ee,e.Conv2DBackpropInput=Ae,e.Conv3D=Re,e.Conv3DBackpropFilterV2=_e,e.Conv3DBackpropInputV2=Fe,e.Cos=De,e.Cosh=Oe,e.CropAndResize=ze,e.Cumprod=Me,e.Cumsum=Le,e.CustomCallback=rb,e.DataStorage=t,e.DenseBincount=Pe,e.DepthToSpace=Be,e.DepthwiseConv2dNative=We,e.DepthwiseConv2dNativeBackpropFilter=Ve,e.DepthwiseConv2dNativeBackpropInput=Ue,e.Diag=Ge,e.Dilation2D=He,e.Dilation2DBackpropFilter=qe,e.Dilation2DBackpropInput=je,e.EarlyStopping=Gv,e.Einsum=Xe,e.Elu=Ye,e.EluGrad=Ze,e.Environment=q,e.Equal=Qe,e.Erf=Je,e.Exp=et,e.ExpandDims=tt,e.Expm1=nt,e.FFT=st,e.Fill=rt,e.FlipLeftRight=at,e.Floor=it,e.FloorDiv=ot,e.FromPixels=rs,e.FusedBatchNorm=lt,e.FusedConv2D=os,e.FusedDepthwiseConv2D=ls,e.GatherNd=ct,e.GatherV2=ut,e.GraphModel=iN,e.Greater=ht,e.GreaterEqual=pt,e.History=sb,e.IFFT=ft,e.Identity=dt,e.Imag=mt,e.InputSpec=Ny,e.IsFinite=gt,e.IsInf=yt,e.IsNan=bt,e.KernelBackend=n,e.LRN=Et,e.LRNGrad=At,e.LayerVariable=wy,e.LayersModel=ux,e.LeakyRelu=xt,e.Less=wt,e.LessEqual=vt,e.LinSpace=kt,e.Log=Nt,e.Log1p=It,e.LogSoftmax=$t,e.LogicalAnd=St,e.LogicalNot=Tt,e.LogicalOr=Ct,e.LogicalXor="LogicalXor",e.LowerBound="LowerBound",e.Max=Rt,e.MaxPool=Ft,e.MaxPool3D=Ot,e.MaxPool3DGrad=Mt,e.MaxPoolGrad=Dt,e.MaxPoolWithArgmax=Lt,e.Maximum=_t,e.Mean=zt,e.Min=Pt,e.Minimum=Bt,e.MirrorPad=Wt,e.Mod=Vt,e.MomentumOptimizer=id,e.Multinomial=Ut,e.Multiply=Gt,e.Neg=Ht,e.NonMaxSuppressionV3=qt,e.NonMaxSuppressionV4=Kt,e.NonMaxSuppressionV5=Xt,e.NotEqual=jt,e.OP_SCOPE_SUFFIX=ea,e.OneHot=Zt,e.OnesLike=Yt,e.Optimizer=ed,e.OptimizerConstructors=ld,e.Pack=Jt,e.PadV2=Qt,e.Pool="Pool",e.Pow=en,e.Prelu=tn,e.Prod=nn,e.RMSPropOptimizer=od,e.RNN=pw,e.RaggedGather=sn,e.RaggedRange=rn,e.RaggedTensorToTensor=an,e.Range=on,e.Real=ln,e.RealDiv=Ke,e.Reciprocal=un,e.Relu=cn,e.Relu6=gn,e.Reshape=hn,e.ResizeBilinear=fn,e.ResizeBilinearGrad=mn,e.ResizeNearestNeighbor=pn,e.ResizeNearestNeighborGrad=dn,e.Reverse=yn,e.RotateWithOffset=as,e.Round=bn,e.Rsqrt=xn,e.SGDOptimizer=ad,e.ScatterNd=wn,e.SearchSorted=vn,e.Select=kn,e.Selu=Nn,e.Sequential=hx,e.Sigmoid=$n,e.Sign=Cn,e.Sin=Sn,e.Sinh=Tn,e.Slice=In,e.Softmax=Dn,e.Softplus=En,e.SpaceToBatchND=_n,e.SparseFillEmptyRows=On,e.SparseReshape=Mn,e.SparseSegmentMean=Ln,e.SparseSegmentSum=zn,e.SparseToDense=Pn,e.SplitV=Fn,e.Sqrt=An,e.Square=Wn,e.SquaredDifference=Bn,e.Step=ss,e.StridedSlice=Vn,e.StringNGrams=Un,e.StringSplit=Gn,e.StringToHashBucketFast=Hn,e.Sub=jn,e.Sum=Rn,e.SymbolicTensor=Iy,e.Tan=qn,e.Tanh=Kn,e.Tensor=vr,e.TensorBuffer=yr,e.Tile=Xn,e.TopK=Yn,e.Transform=Zn,e.Transpose=Jn,e.Unique=Qn,e.Unpack=es,e.UnsortedSegmentSum=ts,e.UpperBound="UpperBound",e.Variable=Nr,e.ZerosLike=ns,e._FusedMatMul=is,e.abs=$o,e.acos=Eo,e.acosh=Ao,e.add=Io,e.addN=Ro,e.all=_o,e.any=Fo,e.argMax=Do,e.argMin=Oo,e.asin=Mo,e.asinh=Lo,e.atan=zo,e.atan2=Po,e.atanh=Bo,e.avgPool=nl,e.avgPool3d=sl,e.backend=$i,e.backend_util=gf,e.basicLSTMCell=ll,e.batchNorm=cl,e.batchNorm2d=hl,e.batchNorm3d=pl,e.batchNorm4d=dl,e.batchToSpaceND=ul,e.bincount=fl,e.booleanMaskAsync=_h,e.broadcastArgs=ml,e.broadcastTo=gl,e.broadcast_util=zi,e.browser=Gi,e.buffer=Za,e.callbacks=Hv,e.cast=Ja,e.ceil=yl,e.clipByValue=xl,e.clone=Qa,e.complex=na,e.concat=rl,e.concat1d=wl,e.concat2d=vl,e.concat3d=kl,e.concat4d=Nl,e.constraints=Xy,e.conv1d=Sl,e.conv2d=Il,e.conv2dTranspose=Cl,e.conv3d=$l,e.conv3dTranspose=Al,e.copyRegisteredKernels=function(e,t){fs(e).forEach((e=>{ms(Object.assign({},e,{backendName:t}))}))},e.cos=Rl,e.cosh=_l,e.cosineWindow=Ph,e.cumprod=Fl,e.cumsum=Dl,e.customGrad=_u,e.data=hI,e.denseBincount=Ol,e.deprecationWarn=wi,e.depthToSpace=Ml,e.depthwiseConv2d=Ll,e.deregisterOp=function(e){delete Kv[e]},e.device_util=qr,e.diag=zl,e.dilation2d=Pl,e.disableDeprecationWarnings=function(){X().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")},e.dispose=Ii,e.disposeVariables=function(){Vr.disposeVariables()},e.div=To,e.divNoNan=Ul,e.dot=Gl,e.dropout=Lh,e.einsum=Hl,e.elu=jl,e.enableDebugMode=function(){X().set("DEBUG",!0)},e.enableProdMode=function(){X().set("PROD",!0)},e.enclosingPowerOfTwo=zh,e.engine=vi,e.env=X,e.equal=Bl,e.erf=ql,e.euclideanNorm=hu,e.exp=pu,e.expandDims=du,e.expm1=fu,e.eye=gu,e.fft=oh,e.fill=bl,e.findBackend=function(e){return Vr.findBackend(e)},e.findBackendFactory=function(e){return Vr.findBackendFactory(e)},e.floor=yu,e.floorDiv=So,e.fused=Zh,e.gather=bu,e.gatherND=Mh,e.gather_util=ji,e.getBackend=function(){return Vr.backendName},e.getGradient=ds,e.getKernel=ps,e.getKernelsForBackend=fs,e.grad=function(e){return u(D(e),(()=>"The f passed in grad(f) must be a function")),(t,n)=>{const s=Jr(t,"x","tf.grad","string_or_numeric"),r=null!=n?Jr(n,"dy","tf.grad"):null;return Vr.tidy((()=>{const{value:t,grads:n}=Vr.gradients((()=>e(s)),[s],r);return null!=r&&c(t.shape,r.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Fu(n),n[0]}))}},e.grads=function(e){return u(D(e),(()=>"The f passed in grads(f) must be a function")),(t,n)=>{u(Array.isArray(t),(()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s"));const s=Qr(t,"args","tf.grads","string_or_numeric"),r=null!=n?Jr(n,"dy","tf.grads"):null;return Vr.tidy((()=>{const{value:t,grads:n}=Vr.gradients((()=>e(...s)),s,r);return null!=r&&c(t.shape,r.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Fu(n),n}))}},e.greater=xu,e.greaterEqual=wu,e.ifft=lh,e.imag=Ei,e.image=Xp,e.inTopKAsync=Bh,e.initializers=Zy,e.input=px,e.io=yi,e.irfft=uh,e.isFinite=vu,e.isInf=ku,e.isNaN=Nu,e.keep=Si,e.kernel_impls=yf,e.layers=Lv,e.leakyRelu=Iu,e.less=Su,e.lessEqual=Tu,e.linalg=Yp,e.linspace=Cu,e.loadGraphModel=async function(e,t={},n=yi){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 iN(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=gi(fa(n,ya(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=gi(e)}const n=new iN(t);return n.load(),n},e.loadLayersModel=async function(e,t){if(null==t&&(t={}),"string"==typeof e){const n=va(e,t);if(0===n.length)n.push(pi(e,t));else if(n.length>1)throw new Mm(`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 Mm("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=lb(Wb(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 Mm("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=oa(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),Ii(e),Ii(t.map((e=>e.tensor)))}return o}(e,void 0,t)},e.localResponseNormalization=$u,e.log=Eu,e.log1p=Au,e.logSigmoid=Ou,e.logSoftmax=Lu,e.logSumExp=zu,e.logicalAnd=Pu,e.logicalNot=Bu,e.logicalOr=Wu,e.logicalXor=Vu,e.losses=Zp,e.lowerBound=Hu,e.matMul=bi,e.math=Di,e.max=nu,e.maxPool=ju,e.maxPool3d=qu,e.maxPoolWithArgmax=Ku,e.maximum=Xu,e.mean=Yu,e.memory=ki,e.meshgrid=Qu,e.metrics=zv,e.min=su,e.minimum=ec,e.mirrorPad=tc,e.mod=nc,e.model=function(e){return new ux(e)},e.models=Pv,e.moments=sc,e.movingAverage=Fh,e.mul=Co,e.multiRNNCell=rc,e.multinomial=ac,e.neg=Ai,e.nextFrame=hd,e.norm=cu,e.notEqual=ic,e.oneHot=xi,e.ones=Ju,e.onesLike=oc,e.op=ta,e.outerProduct=lc,e.pad=uc,e.pad1d=cc,e.pad2d=hc,e.pad3d=pc,e.pad4d=dc,e.pool=mc,e.pow=ru,e.prelu=gc,e.print=ei,e.prod=yc,e.profile=function(e){return Vr.profile(e)},e.raggedGather=bc,e.raggedRange=xc,e.raggedTensorToTensor=wc,e.rand=vc,e.randomGamma=Oc,e.randomNormal=Mc,e.randomStandardNormal=Lc,e.randomUniform=zc,e.range=Pc,e.ready=function(){return Vr.ready()},e.real=Ri,e.reciprocal=Bc,e.registerBackend=Ci,e.registerCallbackConstructor=function(e,t){ib.registerCallbackConstructor(e,t)},e.registerGradient=gs,e.registerKernel=ms,e.registerOp=function(e,t){const n={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};Kv[e]=n},e.regularizers=Bv,e.relu=Wc,e.relu6=Vc,e.removeBackend=function(e){Vr.removeBackend(e)},e.reshape=tl,e.reverse=Uc,e.reverse1d=Gc,e.reverse2d=Hc,e.reverse3d=jc,e.reverse4d=qc,e.rfft=hh,e.round=Kc,e.rsqrt=Xc,e.scalar=au,e.scatterND=Dh,e.scatter_util=Yi,e.searchSorted=Gu,e.selu=Yc,e.separableConv2d=Zc,e.sequential=function(e){return new hx(e)},e.serialization=yo,e.setBackend=Ti,e.setPlatform=function(e,t){X().setPlatform(e,t)},e.setdiff1dAsync=Jc,e.sigmoid=al,e.sign=Qc,e.signal=Kp,e.sin=eh,e.sinh=th,e.slice=il,e.slice1d=nh,e.slice2d=sh,e.slice3d=rh,e.slice4d=ah,e.slice_util=po,e.softmax=ih,e.softplus=Du,e.spaceToBatchND=fc,e.sparse=Jp,e.sparseToDense=Oh,e.spectral=qp,e.split=ch,e.sqrt=iu,e.square=ou,e.squaredDifference=ph,e.squeeze=dh,e.stack=fh,e.step=mh,e.stridedSlice=gh,e.string=Qp,e.sub=Mu,e.sum=lu,e.sumOutType=Rr,e.tan=yh,e.tanh=ol,e.tensor=ra,e.tensor1d=bh,e.tensor2d=xh,e.tensor3d=Pi,e.tensor4d=wh,e.tensor5d=vh,e.tensor6d=kh,e.tensor_util=Lr,e.test_util=ko,e.tidy=Ni,e.tile=mu,e.time=function(e){return Vr.time(e)},e.topk=Nh,e.train=ud,e.transpose=_i,e.truncatedNormal=Ih,e.unique=Sh,e.unregisterGradient=function(e){if(!hs.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);hs.delete(e)},e.unregisterKernel=function(e,t){const n=ys(e,t);if(!cs.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);cs.delete(n)},e.unsortedSegmentSum=Th,e.unstack=Ch,e.upcastType=Ar,e.upperBound=$h,e.util=lr,e.valueAndGrad=function(e){return u(D(e),(()=>"The f passed in valueAndGrad(f) must be a function")),(t,n)=>{u(t instanceof vr,(()=>"The x passed in valueAndGrad(f)(x) must be a tensor")),u(null==n||n instanceof vr,(()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor"));const{grads:s,value:r}=Vr.gradients((()=>e(t)),[t],n);return Fu(s),{grad:s[0],value:r}}},e.valueAndGrads=function(e){return u(D(e),(()=>"The f passed in valueAndGrads(f) must be a function")),(t,n)=>{u(Array.isArray(t)&&t.every((e=>e instanceof vr)),(()=>"The args passed in valueAndGrads(f)(args) must be array of tensors")),u(null==n||n instanceof vr,(()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor"));const s=Vr.gradients((()=>e(...t)),t,n);return null!=n&&c(s.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Fu(s.grads),s}},e.variable=Eh,e.variableGrads=Ru,e.version=KP,e.version_converter=oN,e.version_core=No,e.version_layers=Ub,e.where=Wl,e.whereAsync=Rh,e.zeros=Zu,e.zerosLike=Vl,Object.defineProperty(e,"__esModule",{value:!0})}));
18//# sourceMappingURL=tf.es2017.min.js.map